blob: bd6d5f2e56c2645787f91b4919e0650641dd7291 [file] [log] [blame]
Chris Lattnerbef8e0b2007-09-12 18:24:00 +00001//===-- BrainF.cpp - BrainF compiler example ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerfc001bb2007-12-29 20:37:57 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbef8e0b2007-09-12 18:24:00 +00007//
8//===--------------------------------------------------------------------===//
9//
10// This class compiles the BrainF language into LLVM assembly.
11//
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
22// ] } End loop
23//
24//===--------------------------------------------------------------------===//
25
26#include "BrainF.h"
27#include "llvm/Constants.h"
Duncan Sandse2c43042008-04-07 13:45:04 +000028#include "llvm/Intrinsics.h"
Chris Lattnerbef8e0b2007-09-12 18:24:00 +000029#include "llvm/ADT/STLExtras.h"
30
31using namespace llvm;
32
33//Set the constants for naming
34const char *BrainF::tapereg = "tape";
35const char *BrainF::headreg = "head";
36const char *BrainF::label = "brainf";
37const char *BrainF::testreg = "test";
38
39Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf) {
40 in = in1;
41 memtotal = mem;
42 comflag = cf;
43
44 header();
45 readloop(0, 0, 0);
46 delete builder;
47 return module;
48}
49
50void BrainF::header() {
51 module = new Module("BrainF");
52
53 //Function prototypes
54
55 //declare void @llvm.memset.i32(i8 *, i8, i32, i32)
Duncan Sandse2c43042008-04-07 13:45:04 +000056 Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset_i32);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +000057
58 //declare i32 @getchar()
59 getchar_func = cast<Function>(module->
60 getOrInsertFunction("getchar", IntegerType::Int32Ty, NULL));
61
62 //declare i32 @putchar(i32)
63 putchar_func = cast<Function>(module->
64 getOrInsertFunction("putchar", IntegerType::Int32Ty,
65 IntegerType::Int32Ty, NULL));
66
67
68 //Function header
69
70 //define void @brainf()
71 brainf_func = cast<Function>(module->
72 getOrInsertFunction("brainf", Type::VoidTy, NULL));
73
Duncan Sands89f6d882008-04-13 06:22:09 +000074 builder = new IRBuilder(BasicBlock::Create(label, brainf_func));
Chris Lattnerbef8e0b2007-09-12 18:24:00 +000075
76 //%arr = malloc i8, i32 %d
77 ConstantInt *val_mem = ConstantInt::get(APInt(32, memtotal));
78 ptr_arr = builder->CreateMalloc(IntegerType::Int8Ty, val_mem, "arr");
79
80 //call void @llvm.memset.i32(i8 *%arr, i8 0, i32 %d, i32 1)
81 {
82 Value *memset_params[] = {
83 ptr_arr,
84 ConstantInt::get(APInt(8, 0)),
85 val_mem,
86 ConstantInt::get(APInt(32, 1))
87 };
88
89 CallInst *memset_call = builder->
90 CreateCall(memset_func, memset_params, array_endof(memset_params));
91 memset_call->setTailCall(false);
92 }
93
94 //%arrmax = getelementptr i8 *%arr, i32 %d
95 if (comflag & flag_arraybounds) {
96 ptr_arrmax = builder->
97 CreateGEP(ptr_arr, ConstantInt::get(APInt(32, memtotal)), "arrmax");
98 }
99
100 //%head.%d = getelementptr i8 *%arr, i32 %d
101 curhead = builder->CreateGEP(ptr_arr,
102 ConstantInt::get(APInt(32, memtotal/2)),
103 headreg);
104
105
106
107 //Function footer
108
109 //brainf.end:
Gabor Greif051a9502008-04-06 20:25:17 +0000110 endbb = BasicBlock::Create(label, brainf_func);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000111
112 //free i8 *%arr
113 new FreeInst(ptr_arr, endbb);
114
115 //ret void
Gabor Greif051a9502008-04-06 20:25:17 +0000116 ReturnInst::Create(endbb);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000117
118
119
120 //Error block for array out of bounds
121 if (comflag & flag_arraybounds)
122 {
123 //@aberrormsg = internal constant [%d x i8] c"\00"
124 Constant *msg_0 = ConstantArray::
125 get("Error: The head has left the tape.", true);
126
127 GlobalVariable *aberrormsg = new GlobalVariable(
128 msg_0->getType(),
129 true,
130 GlobalValue::InternalLinkage,
131 msg_0,
132 "aberrormsg",
133 module);
134
135 //declare i32 @puts(i8 *)
136 Function *puts_func = cast<Function>(module->
137 getOrInsertFunction("puts", IntegerType::Int32Ty,
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000138 PointerType::getUnqual(IntegerType::Int8Ty), NULL));
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000139
140 //brainf.aberror:
Gabor Greif051a9502008-04-06 20:25:17 +0000141 aberrorbb = BasicBlock::Create(label, brainf_func);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000142
143 //call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0))
144 {
145 Constant *zero_32 = Constant::getNullValue(IntegerType::Int32Ty);
146
147 Constant *gep_params[] = {
148 zero_32,
149 zero_32
150 };
151
152 Constant *msgptr = ConstantExpr::
153 getGetElementPtr(aberrormsg, gep_params,
154 array_lengthof(gep_params));
155
156 Value *puts_params[] = {
157 msgptr
158 };
159
160 CallInst *puts_call =
Gabor Greif051a9502008-04-06 20:25:17 +0000161 CallInst::Create(puts_func,
162 puts_params, array_endof(puts_params),
163 "", aberrorbb);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000164 puts_call->setTailCall(false);
165 }
166
167 //br label %brainf.end
Gabor Greif051a9502008-04-06 20:25:17 +0000168 BranchInst::Create(endbb, aberrorbb);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000169 }
170}
171
172void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb) {
173 Symbol cursym = SYM_NONE;
174 int curvalue = 0;
175 Symbol nextsym = SYM_NONE;
176 int nextvalue = 0;
177 char c;
178 int loop;
179 int direction;
180
181 while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) {
182 // Write out commands
183 switch(cursym) {
184 case SYM_NONE:
185 // Do nothing
186 break;
187
188 case SYM_READ:
189 {
190 //%tape.%d = call i32 @getchar()
191 CallInst *getchar_call = builder->CreateCall(getchar_func, tapereg);
192 getchar_call->setTailCall(false);
193 Value *tape_0 = getchar_call;
194
195 //%tape.%d = trunc i32 %tape.%d to i8
Duncan Sands89f6d882008-04-13 06:22:09 +0000196 Value *tape_1 = builder->
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000197 CreateTrunc(tape_0, IntegerType::Int8Ty, tapereg);
198
199 //store i8 %tape.%d, i8 *%head.%d
200 builder->CreateStore(tape_1, curhead);
201 }
202 break;
203
204 case SYM_WRITE:
205 {
206 //%tape.%d = load i8 *%head.%d
207 LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
208
209 //%tape.%d = sext i8 %tape.%d to i32
Duncan Sands89f6d882008-04-13 06:22:09 +0000210 Value *tape_1 = builder->
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000211 CreateSExt(tape_0, IntegerType::Int32Ty, tapereg);
212
213 //call i32 @putchar(i32 %tape.%d)
214 Value *putchar_params[] = {
215 tape_1
216 };
217 CallInst *putchar_call = builder->
218 CreateCall(putchar_func,
219 putchar_params, array_endof(putchar_params));
220 putchar_call->setTailCall(false);
221 }
222 break;
223
224 case SYM_MOVE:
225 {
226 //%head.%d = getelementptr i8 *%head.%d, i32 %d
227 curhead = builder->
228 CreateGEP(curhead, ConstantInt::get(APInt(32, curvalue)),
229 headreg);
230
231 //Error block for array out of bounds
232 if (comflag & flag_arraybounds)
233 {
234 //%test.%d = icmp uge i8 *%head.%d, %arrmax
Duncan Sands89f6d882008-04-13 06:22:09 +0000235 Value *test_0 = builder->
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000236 CreateICmpUGE(curhead, ptr_arrmax, testreg);
237
238 //%test.%d = icmp ult i8 *%head.%d, %arr
Duncan Sands89f6d882008-04-13 06:22:09 +0000239 Value *test_1 = builder->
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000240 CreateICmpULT(curhead, ptr_arr, testreg);
241
242 //%test.%d = or i1 %test.%d, %test.%d
Duncan Sands89f6d882008-04-13 06:22:09 +0000243 Value *test_2 = builder->
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000244 CreateOr(test_0, test_1, testreg);
245
246 //br i1 %test.%d, label %main.%d, label %main.%d
Gabor Greif051a9502008-04-06 20:25:17 +0000247 BasicBlock *nextbb = BasicBlock::Create(label, brainf_func);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000248 builder->CreateCondBr(test_2, aberrorbb, nextbb);
249
250 //main.%d:
251 builder->SetInsertPoint(nextbb);
252 }
253 }
254 break;
255
256 case SYM_CHANGE:
257 {
258 //%tape.%d = load i8 *%head.%d
259 LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
260
261 //%tape.%d = add i8 %tape.%d, %d
Duncan Sands89f6d882008-04-13 06:22:09 +0000262 Value *tape_1 = builder->
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000263 CreateAdd(tape_0, ConstantInt::get(APInt(8, curvalue)), tapereg);
264
265 //store i8 %tape.%d, i8 *%head.%d\n"
266 builder->CreateStore(tape_1, curhead);
267 }
268 break;
269
270 case SYM_LOOP:
271 {
272 //br label %main.%d
Gabor Greif051a9502008-04-06 20:25:17 +0000273 BasicBlock *testbb = BasicBlock::Create(label, brainf_func);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000274 builder->CreateBr(testbb);
275
276 //main.%d:
277 BasicBlock *bb_0 = builder->GetInsertBlock();
Gabor Greif051a9502008-04-06 20:25:17 +0000278 BasicBlock *bb_1 = BasicBlock::Create(label, brainf_func);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000279 builder->SetInsertPoint(bb_1);
280
281 //Make part of PHI instruction now, wait until end of loop to finish
Gabor Greif051a9502008-04-06 20:25:17 +0000282 PHINode *phi_0 = PHINode::Create(PointerType::getUnqual(IntegerType::Int8Ty),
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000283 headreg, testbb);
284 phi_0->reserveOperandSpace(2);
285 phi_0->addIncoming(curhead, bb_0);
286 curhead = phi_0;
287
288 readloop(phi_0, bb_1, testbb);
289 }
290 break;
291
292 default:
293 cerr<<"Error: Unknown symbol.\n";
294 abort();
295 break;
296 }
297
298 cursym = nextsym;
299 curvalue = nextvalue;
300 nextsym = SYM_NONE;
301
302 // Reading stdin loop
303 loop = (cursym == SYM_NONE)
304 || (cursym == SYM_MOVE)
305 || (cursym == SYM_CHANGE);
306 while(loop) {
307 *in>>c;
308 if (in->eof()) {
309 if (cursym == SYM_NONE) {
310 cursym = SYM_EOF;
311 } else {
312 nextsym = SYM_EOF;
313 }
314 loop = 0;
315 } else {
316 direction = 1;
317 switch(c) {
318 case '-':
319 direction = -1;
320 // Fall through
321
322 case '+':
323 if (cursym == SYM_CHANGE) {
324 curvalue += direction;
325 // loop = 1
326 } else {
327 if (cursym == SYM_NONE) {
328 cursym = SYM_CHANGE;
329 curvalue = direction;
330 // loop = 1
331 } else {
332 nextsym = SYM_CHANGE;
333 nextvalue = direction;
334 loop = 0;
335 }
336 }
337 break;
338
339 case '<':
340 direction = -1;
341 // Fall through
342
343 case '>':
344 if (cursym == SYM_MOVE) {
345 curvalue += direction;
346 // loop = 1
347 } else {
348 if (cursym == SYM_NONE) {
349 cursym = SYM_MOVE;
350 curvalue = direction;
351 // loop = 1
352 } else {
353 nextsym = SYM_MOVE;
354 nextvalue = direction;
355 loop = 0;
356 }
357 }
358 break;
359
360 case ',':
361 if (cursym == SYM_NONE) {
362 cursym = SYM_READ;
363 } else {
364 nextsym = SYM_READ;
365 }
366 loop = 0;
367 break;
368
369 case '.':
370 if (cursym == SYM_NONE) {
371 cursym = SYM_WRITE;
372 } else {
373 nextsym = SYM_WRITE;
374 }
375 loop = 0;
376 break;
377
378 case '[':
379 if (cursym == SYM_NONE) {
380 cursym = SYM_LOOP;
381 } else {
382 nextsym = SYM_LOOP;
383 }
384 loop = 0;
385 break;
386
387 case ']':
388 if (cursym == SYM_NONE) {
389 cursym = SYM_ENDLOOP;
390 } else {
391 nextsym = SYM_ENDLOOP;
392 }
393 loop = 0;
394 break;
395
396 // Ignore other characters
397 default:
398 break;
399 }
400 }
401 }
402 }
403
404 if (cursym == SYM_ENDLOOP) {
405 if (!phi) {
406 cerr<<"Error: Extra ']'\n";
407 abort();
408 }
409
410 // Write loop test
411 {
412 //br label %main.%d
413 builder->CreateBr(testbb);
414
415 //main.%d:
416
417 //%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d]
418 //Finish phi made at beginning of loop
419 phi->addIncoming(curhead, builder->GetInsertBlock());
420 Value *head_0 = phi;
421
422 //%tape.%d = load i8 *%head.%d
423 LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb);
424
425 //%test.%d = icmp eq i8 %tape.%d, 0
426 ICmpInst *test_0 = new ICmpInst(ICmpInst::ICMP_EQ, tape_0,
427 ConstantInt::get(APInt(8, 0)), testreg,
428 testbb);
429
430 //br i1 %test.%d, label %main.%d, label %main.%d
Gabor Greif051a9502008-04-06 20:25:17 +0000431 BasicBlock *bb_0 = BasicBlock::Create(label, brainf_func);
432 BranchInst::Create(bb_0, oldbb, test_0, testbb);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000433
434 //main.%d:
435 builder->SetInsertPoint(bb_0);
436
437 //%head.%d = phi i8 *[%head.%d, %main.%d]
438 PHINode *phi_1 = builder->
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000439 CreatePHI(PointerType::getUnqual(IntegerType::Int8Ty), headreg);
Chris Lattnerbef8e0b2007-09-12 18:24:00 +0000440 phi_1->reserveOperandSpace(1);
441 phi_1->addIncoming(head_0, testbb);
442 curhead = phi_1;
443 }
444
445 return;
446 }
447
448 //End of the program, so go to return block
449 builder->CreateBr(endbb);
450
451 if (phi) {
452 cerr<<"Error: Missing ']'\n";
453 abort();
454 }
455}