1 //===-- BrainF.cpp - BrainF compiler example ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===--------------------------------------------------------------------===//
10 // This class compiles the BrainF language into LLVM assembly.
12 // The BrainF language has 8 commands:
13 // Command Equivalent C Action
14 // ------- ------------ ------
15 // , *h=getchar(); Read a character from stdin, 255 on EOF
16 // . putchar(*h); Write a character to stdout
17 // - --*h; Decrement tape
18 // + ++*h; Increment tape
19 // < --h; Move head left
20 // > ++h; Move head right
21 // [ while(*h) { Start loop
24 //===--------------------------------------------------------------------===//
27 #include "llvm/Constants.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/ADT/STLExtras.h"
33 //Set the constants for naming
34 const char *BrainF::tapereg = "tape";
35 const char *BrainF::headreg = "head";
36 const char *BrainF::label = "brainf";
37 const char *BrainF::testreg = "test";
39 Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf,
40 const LLVMContext& Context) {
51 void BrainF::header(const LLVMContext& C) {
52 module = new Module("BrainF", C);
56 //declare void @llvm.memset.i32(i8 *, i8, i32, i32)
57 const Type *Tys[] = { Type::Int32Ty };
58 Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset,
61 //declare i32 @getchar()
62 getchar_func = cast<Function>(module->
63 getOrInsertFunction("getchar", IntegerType::Int32Ty, NULL));
65 //declare i32 @putchar(i32)
66 putchar_func = cast<Function>(module->
67 getOrInsertFunction("putchar", IntegerType::Int32Ty,
68 IntegerType::Int32Ty, NULL));
73 //define void @brainf()
74 brainf_func = cast<Function>(module->
75 getOrInsertFunction("brainf", Type::VoidTy, NULL));
77 builder = new IRBuilder<>(BasicBlock::Create(label, brainf_func));
79 //%arr = malloc i8, i32 %d
80 ConstantInt *val_mem = ConstantInt::get(APInt(32, memtotal));
81 ptr_arr = builder->CreateMalloc(IntegerType::Int8Ty, val_mem, "arr");
83 //call void @llvm.memset.i32(i8 *%arr, i8 0, i32 %d, i32 1)
85 Value *memset_params[] = {
87 ConstantInt::get(APInt(8, 0)),
89 ConstantInt::get(APInt(32, 1))
92 CallInst *memset_call = builder->
93 CreateCall(memset_func, memset_params, array_endof(memset_params));
94 memset_call->setTailCall(false);
97 //%arrmax = getelementptr i8 *%arr, i32 %d
98 if (comflag & flag_arraybounds) {
99 ptr_arrmax = builder->
100 CreateGEP(ptr_arr, ConstantInt::get(APInt(32, memtotal)), "arrmax");
103 //%head.%d = getelementptr i8 *%arr, i32 %d
104 curhead = builder->CreateGEP(ptr_arr,
105 ConstantInt::get(APInt(32, memtotal/2)),
113 endbb = BasicBlock::Create(label, brainf_func);
116 new FreeInst(ptr_arr, endbb);
119 ReturnInst::Create(endbb);
123 //Error block for array out of bounds
124 if (comflag & flag_arraybounds)
126 //@aberrormsg = internal constant [%d x i8] c"\00"
127 Constant *msg_0 = ConstantArray::
128 get("Error: The head has left the tape.", true);
130 GlobalVariable *aberrormsg = new GlobalVariable(
133 GlobalValue::InternalLinkage,
138 //declare i32 @puts(i8 *)
139 Function *puts_func = cast<Function>(module->
140 getOrInsertFunction("puts", IntegerType::Int32Ty,
141 PointerType::getUnqual(IntegerType::Int8Ty), NULL));
144 aberrorbb = BasicBlock::Create(label, brainf_func);
146 //call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0))
148 Constant *zero_32 = Constant::getNullValue(IntegerType::Int32Ty);
150 Constant *gep_params[] = {
155 Constant *msgptr = ConstantExpr::
156 getGetElementPtr(aberrormsg, gep_params,
157 array_lengthof(gep_params));
159 Value *puts_params[] = {
163 CallInst *puts_call =
164 CallInst::Create(puts_func,
165 puts_params, array_endof(puts_params),
167 puts_call->setTailCall(false);
170 //br label %brainf.end
171 BranchInst::Create(endbb, aberrorbb);
175 void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb) {
176 Symbol cursym = SYM_NONE;
178 Symbol nextsym = SYM_NONE;
184 while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) {
185 // Write out commands
193 //%tape.%d = call i32 @getchar()
194 CallInst *getchar_call = builder->CreateCall(getchar_func, tapereg);
195 getchar_call->setTailCall(false);
196 Value *tape_0 = getchar_call;
198 //%tape.%d = trunc i32 %tape.%d to i8
199 Value *tape_1 = builder->
200 CreateTrunc(tape_0, IntegerType::Int8Ty, tapereg);
202 //store i8 %tape.%d, i8 *%head.%d
203 builder->CreateStore(tape_1, curhead);
209 //%tape.%d = load i8 *%head.%d
210 LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
212 //%tape.%d = sext i8 %tape.%d to i32
213 Value *tape_1 = builder->
214 CreateSExt(tape_0, IntegerType::Int32Ty, tapereg);
216 //call i32 @putchar(i32 %tape.%d)
217 Value *putchar_params[] = {
220 CallInst *putchar_call = builder->
221 CreateCall(putchar_func,
222 putchar_params, array_endof(putchar_params));
223 putchar_call->setTailCall(false);
229 //%head.%d = getelementptr i8 *%head.%d, i32 %d
231 CreateGEP(curhead, ConstantInt::get(APInt(32, curvalue)),
234 //Error block for array out of bounds
235 if (comflag & flag_arraybounds)
237 //%test.%d = icmp uge i8 *%head.%d, %arrmax
238 Value *test_0 = builder->
239 CreateICmpUGE(curhead, ptr_arrmax, testreg);
241 //%test.%d = icmp ult i8 *%head.%d, %arr
242 Value *test_1 = builder->
243 CreateICmpULT(curhead, ptr_arr, testreg);
245 //%test.%d = or i1 %test.%d, %test.%d
246 Value *test_2 = builder->
247 CreateOr(test_0, test_1, testreg);
249 //br i1 %test.%d, label %main.%d, label %main.%d
250 BasicBlock *nextbb = BasicBlock::Create(label, brainf_func);
251 builder->CreateCondBr(test_2, aberrorbb, nextbb);
254 builder->SetInsertPoint(nextbb);
261 //%tape.%d = load i8 *%head.%d
262 LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
264 //%tape.%d = add i8 %tape.%d, %d
265 Value *tape_1 = builder->
266 CreateAdd(tape_0, ConstantInt::get(APInt(8, curvalue)), tapereg);
268 //store i8 %tape.%d, i8 *%head.%d\n"
269 builder->CreateStore(tape_1, curhead);
276 BasicBlock *testbb = BasicBlock::Create(label, brainf_func);
277 builder->CreateBr(testbb);
280 BasicBlock *bb_0 = builder->GetInsertBlock();
281 BasicBlock *bb_1 = BasicBlock::Create(label, brainf_func);
282 builder->SetInsertPoint(bb_1);
284 // Make part of PHI instruction now, wait until end of loop to finish
286 PHINode::Create(PointerType::getUnqual(IntegerType::Int8Ty),
288 phi_0->reserveOperandSpace(2);
289 phi_0->addIncoming(curhead, bb_0);
292 readloop(phi_0, bb_1, testbb);
297 std::cerr << "Error: Unknown symbol.\n";
303 curvalue = nextvalue;
306 // Reading stdin loop
307 loop = (cursym == SYM_NONE)
308 || (cursym == SYM_MOVE)
309 || (cursym == SYM_CHANGE);
313 if (cursym == SYM_NONE) {
327 if (cursym == SYM_CHANGE) {
328 curvalue += direction;
331 if (cursym == SYM_NONE) {
333 curvalue = direction;
336 nextsym = SYM_CHANGE;
337 nextvalue = direction;
348 if (cursym == SYM_MOVE) {
349 curvalue += direction;
352 if (cursym == SYM_NONE) {
354 curvalue = direction;
358 nextvalue = direction;
365 if (cursym == SYM_NONE) {
374 if (cursym == SYM_NONE) {
383 if (cursym == SYM_NONE) {
392 if (cursym == SYM_NONE) {
393 cursym = SYM_ENDLOOP;
395 nextsym = SYM_ENDLOOP;
400 // Ignore other characters
408 if (cursym == SYM_ENDLOOP) {
410 std::cerr << "Error: Extra ']'\n";
417 builder->CreateBr(testbb);
421 //%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d]
422 //Finish phi made at beginning of loop
423 phi->addIncoming(curhead, builder->GetInsertBlock());
426 //%tape.%d = load i8 *%head.%d
427 LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb);
429 //%test.%d = icmp eq i8 %tape.%d, 0
430 ICmpInst *test_0 = new ICmpInst(ICmpInst::ICMP_EQ, tape_0,
431 ConstantInt::get(APInt(8, 0)), testreg,
434 //br i1 %test.%d, label %main.%d, label %main.%d
435 BasicBlock *bb_0 = BasicBlock::Create(label, brainf_func);
436 BranchInst::Create(bb_0, oldbb, test_0, testbb);
439 builder->SetInsertPoint(bb_0);
441 //%head.%d = phi i8 *[%head.%d, %main.%d]
442 PHINode *phi_1 = builder->
443 CreatePHI(PointerType::getUnqual(IntegerType::Int8Ty), headreg);
444 phi_1->reserveOperandSpace(1);
445 phi_1->addIncoming(head_0, testbb);
452 //End of the program, so go to return block
453 builder->CreateBr(endbb);
456 std::cerr << "Error: Missing ']'\n";