1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
|
#include "cps/RuntimeCheck.h"
#include "cps/ExceptionHandler.h"
#include "cps/TypeSystem.h" // kEnumOrdinalBase
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/GlobalVariable.h"
using namespace llvm;
using namespace cps;
RuntimeCheck::RuntimeCheck(Module &M, LLVMContext &C, IRBuilder<> &B, ExceptionHandler &EH)
: TheModule(M), TheContext(C), Builder(B), Exceptions(EH) {
UserLine = new GlobalVariable(TheModule, Builder.getInt32Ty(), false,
GlobalValue::ExternalLinkage, Builder.getInt32(0), "__cps_user_line");
setupExternalFunctions();
}
Value *RuntimeCheck::lineValue(int Line) {
return LibraryMode ? Builder.CreateLoad(Builder.getInt32Ty(), UserLine, "user_line")
: static_cast<Value *>(Builder.getInt32(Line));
}
void RuntimeCheck::setUserLine(int Line) {
Builder.CreateStore(Builder.getInt32(Line), UserLine);
}
void RuntimeCheck::setupExternalFunctions() {
Type *PtrTy = PointerType::getUnqual(TheContext);
Type *I32 = Type::getInt32Ty(TheContext);
FprintfFunc = TheModule.getOrInsertFunction(
"fprintf", FunctionType::get(I32, {PtrTy, PtrTy}, true));
// The stderr FILE* is a platform-specific symbol; host and target match.
#if defined(_WIN32)
StderrFunc = TheModule.getOrInsertFunction(
"__acrt_iob_func", FunctionType::get(PtrTy, {I32}, false));
#else
#if defined(__APPLE__)
const char *StderrName = "__stderrp";
#else
const char *StderrName = "stderr";
#endif
StderrVar = new GlobalVariable(TheModule, PtrTy, false, GlobalValue::ExternalLinkage,
nullptr, StderrName);
#endif
DivZeroMsg = Builder.CreateGlobalString("[Fatal] line %d: Division by zero\n", "err_div_zero", 0, &TheModule);
OutOfBoundsMsg = Builder.CreateGlobalString("[Fatal] line %d: Array index out of bounds\n", "err_bounds", 0, &TheModule);lass="hl sng">"strcpy", StrCpyType);
StrCatFunc = Module.getOrInsertFunction("strcat", StrCpyType);
StrCmpFunc = Module.getOrInsertFunction("strcmp",
FunctionType::get(Type::getInt32Ty(Context),
{PointerType::getUnqual(Context), PointerType::getUnqual(Context)}, false));
FunctionType *CharCaseType = FunctionType::get(Type::getInt32Ty(Context), {Type::getInt32Ty(Context)}, false);
ToUpperFunc = Module.getOrInsertFunction("toupper", CharCaseType);
ToLowerFunc = Module.getOrInsertFunction("tolower", CharCaseType);
}
Value *StringHandler::createLiteral(const std::string &Val) {
return Builder.CreateGlobalStringPtr(Val);
}
Value *StringHandler::emitLength(Value *Str) {
if (!Str) return nullptr;
return Builder.CreateCall(StrLenFunc, Str, "len");
}
Value *StringHandler::emitConcat(Value *LHS, Value *RHS) {
if (!LHS || !RHS) return nullptr;
Value *LLen = Builder.CreateCall(StrLenFunc, {LHS}, "llen");
Value *RLen = Builder.CreateCall(StrLenFunc, {RHS}, "rlen");
Value *TotalLen = Builder.CreateAdd(LLen, RLen, "totallen");
Value *AllocSize = Builder.CreateAdd(TotalLen, ConstantInt::get(Type::getInt64Ty(Context), 1), "allocsize");
Value *NewStr = Builder.CreateCall(MallocFunc, {AllocSize}, "concat_str");
Builder.CreateCall(StrCpyFunc, {NewStr, LHS});
Builder.CreateCall(StrCatFunc, {NewStr, RHS});
return NewStr;
}
Value *StringHandler::emitCompare(int Op, Value *LHS, Value *RHS) {
if (!LHS || !RHS) return nullptr;
CmpInst::Predicate Pred;
switch (Op) {
case tok_eq: Pred = CmpInst::ICMP_EQ; break;
case tok_ne: Pred = CmpInst::ICMP_NE; break;
case '<': Pred = CmpInst::ICMP_SLT; break;
case '>': Pred = CmpInst::ICMP_SGT; break;
case tok_le: Pred = CmpInst::ICMP_SLE; break;
case tok_ge: Pred = CmpInst::ICMP_SGE; break;
default: return nullptr;
}
Value *Cmp = Builder.CreateCall(StrCmpFunc, {LHS, RHS}, "strcmp_result");
return Builder.CreateICmp(Pred, Cmp, ConstantInt::get(Type::getInt32Ty(Context), 0), "str_compare");
}
// malloc(Len + 1), copy Len bytes from Src + StartIdx, NUL-terminate.
// Clamping is each caller's business — MID/RIGHT/LEFT clamp different things.
Value *StringHandler::allocCopySubstring(Value *Src, Value *StartIdx, Value *Len) {
Value *One = ConstantInt::get(Context, APInt(64, 1));
Value *AllocSize = Builder.CreateAdd(Len, One);
Value *NewStr = Builder.CreateCall(MallocFunc, AllocSize, "substr_mem");
Value *SrcPtr = Builder.CreateInBoundsGEP(Type::getInt8Ty(Context), Src, StartIdx);
Builder.CreateCall(MemCpyFunc, {NewStr, SrcPtr, Len});
Value *NullTermPtr = Builder.CreateInBoundsGEP(Type::getInt8Ty(Context), NewStr, Len);
Builder.CreateStore(ConstantInt::get(Type::getInt8Ty(Context), 0), NullTermPtr);
return NewStr;
}
Value *StringHandler::emitMid(Value *Str, Value *Start, Value *Len) {
Value *FullLen = emitLength(Str);
Value *One = ConstantInt::get(Context, APInt(64, 1));
Value *Zero = ConstantInt::get(Context, APInt(64, 0));
Value *StartZeroBased = Builder.CreateSub(Start, One, "start_idx");
Value *IsNeg = Builder.CreateICmpSLT(StartZeroBased, Zero);
StartZeroBased = Builder.CreateSelect(IsNeg, Zero, StartZeroBased);
Value *IsTooBig = Builder.CreateICmpSGT(StartZeroBased, FullLen);
StartZeroBased = Builder.CreateSelect(IsTooBig, FullLen, StartZeroBased);
Value *RemLen = Builder.CreateSub(FullLen, StartZeroBased);
Value *IsLenTooBig = Builder.CreateICmpSGT(Len, RemLen);
Value *ActualLen = Builder.CreateSelect(IsLenTooBig, RemLen, Len);
Value *IsLenNeg = Builder.CreateICmpSLT(ActualLen, Zero);
ActualLen = Builder.CreateSelect(IsLenNeg, Zero, ActualLen);
return allocCopySubstring(Str, StartZeroBased, ActualLen);
}
Value *StringHandler::emitRight(Value *Str, Value *Len) {
Value *FullLen = emitLength(Str);
Value *StartIdx = Builder.CreateSub(FullLen, Len, "right_start");
Value *Zero = ConstantInt::get(Context, APInt(64, 0));
Value *IsNeg = Builder.CreateICmpSLT(StartIdx, Zero);
StartIdx = Builder.CreateSelect(IsNeg, Zero, StartIdx);
Value *ActualLen = Builder.CreateSub(FullLen, StartIdx);
return allocCopySubstring(Str, StartIdx, ActualLen);
}
Value *StringHandler::emitLeft(Value *Str, Value *Len) {
Value *FullLen = emitLength(Str);
Value *Zero = ConstantInt::get(Context, APInt(64, 0));
Value *IsNeg = Builder.CreateICmpSLT(Len, Zero);
Value *SafeLen = Builder.CreateSelect(IsNeg, Zero, Len);
Value *IsTooBig = Builder.CreateICmpSGT(SafeLen, FullLen);
Value *ActualLen = Builder.CreateSelect(IsTooBig, FullLen, SafeLen);
return allocCopySubstring(Str, Zero, ActualLen);
}
// Shared loop for LCASE/UCASE: malloc a copy of Str with every byte run
// through CaseFn (tolower/toupper).
Value *StringHandler::emitCaseConvert(Value *Str, FunctionCallee CaseFn) {
if (!Str) return nullptr;
Value *Len = emitLength(Str);
Value *One = ConstantInt::get(Context, APInt(64, 1));
Value *AllocSize = Builder.CreateAdd(Len, One);
Value *NewStr = Builder.CreateCall(MallocFunc, AllocSize, "case_str");
Function *TheFunction = Builder.GetInsertBlock()->getParent();
BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", TheFunction);
BasicBlock *AfterBB = BasicBlock::Create(Context, "afterloop", TheFunction);
IRBuilder<> TmpB(&TheFunction->getEntryBlock(), TheFunction->getEntryBlock().begin());
AllocaInst *IdxVar = TmpB.CreateAlloca(Type::getInt64Ty(Context), nullptr, "idx");
Builder.CreateStore(ConstantInt::get(Context, APInt(64, 0)), IdxVar);
Builder.CreateBr(LoopBB);
Builder.SetInsertPoint(LoopBB);
Value *CurIdx = Builder.CreateLoad(Type::getInt64Ty(Context), IdxVar);
Value *Cond = Builder.CreateICmpSLT(CurIdx, Len);
BasicBlock *BodyBB = BasicBlock::Create(Context, "body", TheFunction);
Builder.CreateCondBr(Cond, BodyBB, AfterBB);
Builder.SetInsertPoint(BodyBB);
Value *SrcPtr = Builder.CreateInBoundsGEP(Type::getInt8Ty(Context), Str, CurIdx);
Value *CharVal = Builder.CreateLoad(Type::getInt8Ty(Context), SrcPtr);
Value *ExtChar = Builder.CreateSExt(CharVal, Type::getInt32Ty(Context));
Value *ConvChar = Builder.CreateCall(CaseFn, ExtChar);
Value *TruncChar = Builder.CreateTrunc(ConvChar, Type::getInt8Ty(Context));
Value *DestPtr = Builder.CreateInBoundsGEP(Type::getInt8Ty(Context), NewStr, CurIdx);
Builder.CreateStore(TruncChar, DestPtr);
Value *NextIdx = Builder.CreateAdd(CurIdx, One);
Builder.CreateStore(NextIdx, IdxVar);
Builder.CreateBr(LoopBB);
Builder.SetInsertPoint(AfterBB);
Value *NullPtr = Builder.CreateInBoundsGEP(Type::getInt8Ty(Context), NewStr, Len);
Builder.CreateStore(ConstantInt::get(Type::getInt8Ty(Context), 0), NullPtr);
return NewStr;
}
Value *StringHandler::emitLCase(Value *Str) {
return emitCaseConvert(Str, ToLowerFunc);
}
Value *StringHandler::emitUCase(Value *Str) {
return emitCaseConvert(Str, ToUpperFunc);
}
|