llvm.org GIT mirror llvm / 9f85634
Add Kaleidoscope to examples/ so that it gets built regularly and we'll notice if an API change causes it to be out of date. The code is copied out of LangImpl7.html. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@68912 91177308-0d34-0410-b5e6-96231b3b80d8 Nick Lewycky 11 years ago
5 changed file(s) with 1159 addition(s) and 1 deletion(s). Raw diff Collapse all Expand all
0 add_subdirectory(BrainF)
11 add_subdirectory(Fibonacci)
22 add_subdirectory(HowToUseJIT)
3 add_subdirectory(Kaleidoscope)
34 add_subdirectory(ModuleMaker)
45
56 include(CheckIncludeFile)
0 set(LLVM_LINK_COMPONENTS core jit native)
1
2 add_llvm_example(Kaleidoscope
3 toy.cpp
4 )
0 ##===- examples/Kaleidoscope/Makefile ----------------------*- Makefile -*-===##
1 #
2 # The LLVM Compiler Infrastructure
3 #
4 # This file is distributed under the University of Illinois Open Source
5 # License. See LICENSE.TXT for details.
6 #
7 ##===----------------------------------------------------------------------===##
8 LEVEL = ../..
9 TOOLNAME = Kaleidoscope
10 EXAMPLE_TOOL = 1
11
12 LINK_COMPONENTS := core jit native
13
14 include $(LEVEL)/Makefile.common
0 #include "llvm/DerivedTypes.h"
1 #include "llvm/ExecutionEngine/ExecutionEngine.h"
2 #include "llvm/Module.h"
3 #include "llvm/ModuleProvider.h"
4 #include "llvm/PassManager.h"
5 #include "llvm/Analysis/Verifier.h"
6 #include "llvm/Target/TargetData.h"
7 #include "llvm/Transforms/Scalar.h"
8 #include "llvm/Support/IRBuilder.h"
9 #include
10 #include
11 #include
12 #include
13 using namespace llvm;
14
15 //===----------------------------------------------------------------------===//
16 // Lexer
17 //===----------------------------------------------------------------------===//
18
19 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
20 // of these for known things.
21 enum Token {
22 tok_eof = -1,
23
24 // commands
25 tok_def = -2, tok_extern = -3,
26
27 // primary
28 tok_identifier = -4, tok_number = -5,
29
30 // control
31 tok_if = -6, tok_then = -7, tok_else = -8,
32 tok_for = -9, tok_in = -10,
33
34 // operators
35 tok_binary = -11, tok_unary = -12,
36
37 // var definition
38 tok_var = -13
39 };
40
41 static std::string IdentifierStr; // Filled in if tok_identifier
42 static double NumVal; // Filled in if tok_number
43
44 /// gettok - Return the next token from standard input.
45 static int gettok() {
46 static int LastChar = ' ';
47
48 // Skip any whitespace.
49 while (isspace(LastChar))
50 LastChar = getchar();
51
52 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
53 IdentifierStr = LastChar;
54 while (isalnum((LastChar = getchar())))
55 IdentifierStr += LastChar;
56
57 if (IdentifierStr == "def") return tok_def;
58 if (IdentifierStr == "extern") return tok_extern;
59 if (IdentifierStr == "if") return tok_if;
60 if (IdentifierStr == "then") return tok_then;
61 if (IdentifierStr == "else") return tok_else;
62 if (IdentifierStr == "for") return tok_for;
63 if (IdentifierStr == "in") return tok_in;
64 if (IdentifierStr == "binary") return tok_binary;
65 if (IdentifierStr == "unary") return tok_unary;
66 if (IdentifierStr == "var") return tok_var;
67 return tok_identifier;
68 }
69
70 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
71 std::string NumStr;
72 do {
73 NumStr += LastChar;
74 LastChar = getchar();
75 } while (isdigit(LastChar) || LastChar == '.');
76
77 NumVal = strtod(NumStr.c_str(), 0);
78 return tok_number;
79 }
80
81 if (LastChar == '#') {
82 // Comment until end of line.
83 do LastChar = getchar();
84 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
85
86 if (LastChar != EOF)
87 return gettok();
88 }
89
90 // Check for end of file. Don't eat the EOF.
91 if (LastChar == EOF)
92 return tok_eof;
93
94 // Otherwise, just return the character as its ascii value.
95 int ThisChar = LastChar;
96 LastChar = getchar();
97 return ThisChar;
98 }
99
100 //===----------------------------------------------------------------------===//
101 // Abstract Syntax Tree (aka Parse Tree)
102 //===----------------------------------------------------------------------===//
103
104 /// ExprAST - Base class for all expression nodes.
105 class ExprAST {
106 public:
107 virtual ~ExprAST() {}
108 virtual Value *Codegen() = 0;
109 };
110
111 /// NumberExprAST - Expression class for numeric literals like "1.0".
112 class NumberExprAST : public ExprAST {
113 double Val;
114 public:
115 NumberExprAST(double val) : Val(val) {}
116 virtual Value *Codegen();
117 };
118
119 /// VariableExprAST - Expression class for referencing a variable, like "a".
120 class VariableExprAST : public ExprAST {
121 std::string Name;
122 public:
123 VariableExprAST(const std::string &name) : Name(name) {}
124 const std::string &getName() const { return Name; }
125 virtual Value *Codegen();
126 };
127
128 /// UnaryExprAST - Expression class for a unary operator.
129 class UnaryExprAST : public ExprAST {
130 char Opcode;
131 ExprAST *Operand;
132 public:
133 UnaryExprAST(char opcode, ExprAST *operand)
134 : Opcode(opcode), Operand(operand) {}
135 virtual Value *Codegen();
136 };
137
138 /// BinaryExprAST - Expression class for a binary operator.
139 class BinaryExprAST : public ExprAST {
140 char Op;
141 ExprAST *LHS, *RHS;
142 public:
143 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
144 : Op(op), LHS(lhs), RHS(rhs) {}
145 virtual Value *Codegen();
146 };
147
148 /// CallExprAST - Expression class for function calls.
149 class CallExprAST : public ExprAST {
150 std::string Callee;
151 std::vector Args;
152 public:
153 CallExprAST(const std::string &callee, std::vector &args)
154 : Callee(callee), Args(args) {}
155 virtual Value *Codegen();
156 };
157
158 /// IfExprAST - Expression class for if/then/else.
159 class IfExprAST : public ExprAST {
160 ExprAST *Cond, *Then, *Else;
161 public:
162 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
163 : Cond(cond), Then(then), Else(_else) {}
164 virtual Value *Codegen();
165 };
166
167 /// ForExprAST - Expression class for for/in.
168 class ForExprAST : public ExprAST {
169 std::string VarName;
170 ExprAST *Start, *End, *Step, *Body;
171 public:
172 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
173 ExprAST *step, ExprAST *body)
174 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
175 virtual Value *Codegen();
176 };
177
178 /// VarExprAST - Expression class for var/in
179 class VarExprAST : public ExprAST {
180 std::vector > VarNames;
181 ExprAST *Body;
182 public:
183 VarExprAST(const std::vector > &varnames,
184 ExprAST *body)
185 : VarNames(varnames), Body(body) {}
186
187 virtual Value *Codegen();
188 };
189
190 /// PrototypeAST - This class represents the "prototype" for a function,
191 /// which captures its argument names as well as if it is an operator.
192 class PrototypeAST {
193 std::string Name;
194 std::vector Args;
195 bool isOperator;
196 unsigned Precedence; // Precedence if a binary op.
197 public:
198 PrototypeAST(const std::string &name, const std::vector &args,
199 bool isoperator = false, unsigned prec = 0)
200 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
201
202 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
203 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
204
205 char getOperatorName() const {
206 assert(isUnaryOp() || isBinaryOp());
207 return Name[Name.size()-1];
208 }
209
210 unsigned getBinaryPrecedence() const { return Precedence; }
211
212 Function *Codegen();
213
214 void CreateArgumentAllocas(Function *F);
215 };
216
217 /// FunctionAST - This class represents a function definition itself.
218 class FunctionAST {
219 PrototypeAST *Proto;
220 ExprAST *Body;
221 public:
222 FunctionAST(PrototypeAST *proto, ExprAST *body)
223 : Proto(proto), Body(body) {}
224
225 Function *Codegen();
226 };
227
228 //===----------------------------------------------------------------------===//
229 // Parser
230 //===----------------------------------------------------------------------===//
231
232 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
233 /// token the parser it looking at. getNextToken reads another token from the
234 /// lexer and updates CurTok with its results.
235 static int CurTok;
236 static int getNextToken() {
237 return CurTok = gettok();
238 }
239
240 /// BinopPrecedence - This holds the precedence for each binary operator that is
241 /// defined.
242 static std::map BinopPrecedence;
243
244 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
245 static int GetTokPrecedence() {
246 if (!isascii(CurTok))
247 return -1;
248
249 // Make sure it's a declared binop.
250 int TokPrec = BinopPrecedence[CurTok];
251 if (TokPrec <= 0) return -1;
252 return TokPrec;
253 }
254
255 /// Error* - These are little helper functions for error handling.
256 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
257 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
258 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
259
260 static ExprAST *ParseExpression();
261
262 /// identifierexpr
263 /// ::= identifier
264 /// ::= identifier '(' expression* ')'
265 static ExprAST *ParseIdentifierExpr() {
266 std::string IdName = IdentifierStr;
267
268 getNextToken(); // eat identifier.
269
270 if (CurTok != '(') // Simple variable ref.
271 return new VariableExprAST(IdName);
272
273 // Call.
274 getNextToken(); // eat (
275 std::vector Args;
276 if (CurTok != ')') {
277 while (1) {
278 ExprAST *Arg = ParseExpression();
279 if (!Arg) return 0;
280 Args.push_back(Arg);
281
282 if (CurTok == ')') break;
283
284 if (CurTok != ',')
285 return Error("Expected ')' or ',' in argument list");
286 getNextToken();
287 }
288 }
289
290 // Eat the ')'.
291 getNextToken();
292
293 return new CallExprAST(IdName, Args);
294 }
295
296 /// numberexpr ::= number
297 static ExprAST *ParseNumberExpr() {
298 ExprAST *Result = new NumberExprAST(NumVal);
299 getNextToken(); // consume the number
300 return Result;
301 }
302
303 /// parenexpr ::= '(' expression ')'
304 static ExprAST *ParseParenExpr() {
305 getNextToken(); // eat (.
306 ExprAST *V = ParseExpression();
307 if (!V) return 0;
308
309 if (CurTok != ')')
310 return Error("expected ')'");
311 getNextToken(); // eat ).
312 return V;
313 }
314
315 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
316 static ExprAST *ParseIfExpr() {
317 getNextToken(); // eat the if.
318
319 // condition.
320 ExprAST *Cond = ParseExpression();
321 if (!Cond) return 0;
322
323 if (CurTok != tok_then)
324 return Error("expected then");
325 getNextToken(); // eat the then
326
327 ExprAST *Then = ParseExpression();
328 if (Then == 0) return 0;
329
330 if (CurTok != tok_else)
331 return Error("expected else");
332
333 getNextToken();
334
335 ExprAST *Else = ParseExpression();
336 if (!Else) return 0;
337
338 return new IfExprAST(Cond, Then, Else);
339 }
340
341 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
342 static ExprAST *ParseForExpr() {
343 getNextToken(); // eat the for.
344
345 if (CurTok != tok_identifier)
346 return Error("expected identifier after for");
347
348 std::string IdName = IdentifierStr;
349 getNextToken(); // eat identifier.
350
351 if (CurTok != '=')
352 return Error("expected '=' after for");
353 getNextToken(); // eat '='.
354
355
356 ExprAST *Start = ParseExpression();
357 if (Start == 0) return 0;
358 if (CurTok != ',')
359 return Error("expected ',' after for start value");
360 getNextToken();
361
362 ExprAST *End = ParseExpression();
363 if (End == 0) return 0;
364
365 // The step value is optional.
366 ExprAST *Step = 0;
367 if (CurTok == ',') {
368 getNextToken();
369 Step = ParseExpression();
370 if (Step == 0) return 0;
371 }
372
373 if (CurTok != tok_in)
374 return Error("expected 'in' after for");
375 getNextToken(); // eat 'in'.
376
377 ExprAST *Body = ParseExpression();
378 if (Body == 0) return 0;
379
380 return new ForExprAST(IdName, Start, End, Step, Body);
381 }
382
383 /// varexpr ::= 'var' identifier ('=' expression)?
384 // (',' identifier ('=' expression)?)* 'in' expression
385 static ExprAST *ParseVarExpr() {
386 getNextToken(); // eat the var.
387
388 std::vector > VarNames;
389
390 // At least one variable name is required.
391 if (CurTok != tok_identifier)
392 return Error("expected identifier after var");
393
394 while (1) {
395 std::string Name = IdentifierStr;
396 getNextToken(); // eat identifier.
397
398 // Read the optional initializer.
399 ExprAST *Init = 0;
400 if (CurTok == '=') {
401 getNextToken(); // eat the '='.
402
403 Init = ParseExpression();
404 if (Init == 0) return 0;
405 }
406
407 VarNames.push_back(std::make_pair(Name, Init));
408
409 // End of var list, exit loop.
410 if (CurTok != ',') break;
411 getNextToken(); // eat the ','.
412
413 if (CurTok != tok_identifier)
414 return Error("expected identifier list after var");
415 }
416
417 // At this point, we have to have 'in'.
418 if (CurTok != tok_in)
419 return Error("expected 'in' keyword after 'var'");
420 getNextToken(); // eat 'in'.
421
422 ExprAST *Body = ParseExpression();
423 if (Body == 0) return 0;
424
425 return new VarExprAST(VarNames, Body);
426 }
427
428
429 /// primary
430 /// ::= identifierexpr
431 /// ::= numberexpr
432 /// ::= parenexpr
433 /// ::= ifexpr
434 /// ::= forexpr
435 /// ::= varexpr
436 static ExprAST *ParsePrimary() {
437 switch (CurTok) {
438 default: return Error("unknown token when expecting an expression");
439 case tok_identifier: return ParseIdentifierExpr();
440 case tok_number: return ParseNumberExpr();
441 case '(': return ParseParenExpr();
442 case tok_if: return ParseIfExpr();
443 case tok_for: return ParseForExpr();
444 case tok_var: return ParseVarExpr();
445 }
446 }
447
448 /// unary
449 /// ::= primary
450 /// ::= '!' unary
451 static ExprAST *ParseUnary() {
452 // If the current token is not an operator, it must be a primary expr.
453 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
454 return ParsePrimary();
455
456 // If this is a unary operator, read it.
457 int Opc = CurTok;
458 getNextToken();
459 if (ExprAST *Operand = ParseUnary())
460 return new UnaryExprAST(Opc, Operand);
461 return 0;
462 }
463
464 /// binoprhs
465 /// ::= ('+' unary)*
466 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
467 // If this is a binop, find its precedence.
468 while (1) {
469 int TokPrec = GetTokPrecedence();
470
471 // If this is a binop that binds at least as tightly as the current binop,
472 // consume it, otherwise we are done.
473 if (TokPrec < ExprPrec)
474 return LHS;
475
476 // Okay, we know this is a binop.
477 int BinOp = CurTok;
478 getNextToken(); // eat binop
479
480 // Parse the unary expression after the binary operator.
481 ExprAST *RHS = ParseUnary();
482 if (!RHS) return 0;
483
484 // If BinOp binds less tightly with RHS than the operator after RHS, let
485 // the pending operator take RHS as its LHS.
486 int NextPrec = GetTokPrecedence();
487 if (TokPrec < NextPrec) {
488 RHS = ParseBinOpRHS(TokPrec+1, RHS);
489 if (RHS == 0) return 0;
490 }
491
492 // Merge LHS/RHS.
493 LHS = new BinaryExprAST(BinOp, LHS, RHS);
494 }
495 }
496
497 /// expression
498 /// ::= unary binoprhs
499 ///
500 static ExprAST *ParseExpression() {
501 ExprAST *LHS = ParseUnary();
502 if (!LHS) return 0;
503
504 return ParseBinOpRHS(0, LHS);
505 }
506
507 /// prototype
508 /// ::= id '(' id* ')'
509 /// ::= binary LETTER number? (id, id)
510 /// ::= unary LETTER (id)
511 static PrototypeAST *ParsePrototype() {
512 std::string FnName;
513
514 int Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
515 unsigned BinaryPrecedence = 30;
516
517 switch (CurTok) {
518 default:
519 return ErrorP("Expected function name in prototype");
520 case tok_identifier:
521 FnName = IdentifierStr;
522 Kind = 0;
523 getNextToken();
524 break;
525 case tok_unary:
526 getNextToken();
527 if (!isascii(CurTok))
528 return ErrorP("Expected unary operator");
529 FnName = "unary";
530 FnName += (char)CurTok;
531 Kind = 1;
532 getNextToken();
533 break;
534 case tok_binary:
535 getNextToken();
536 if (!isascii(CurTok))
537 return ErrorP("Expected binary operator");
538 FnName = "binary";
539 FnName += (char)CurTok;
540 Kind = 2;
541 getNextToken();
542
543 // Read the precedence if present.
544 if (CurTok == tok_number) {
545 if (NumVal < 1 || NumVal > 100)
546 return ErrorP("Invalid precedecnce: must be 1..100");
547 BinaryPrecedence = (unsigned)NumVal;
548 getNextToken();
549 }
550 break;
551 }
552
553 if (CurTok != '(')
554 return ErrorP("Expected '(' in prototype");
555
556 std::vector ArgNames;
557 while (getNextToken() == tok_identifier)
558 ArgNames.push_back(IdentifierStr);
559 if (CurTok != ')')
560 return ErrorP("Expected ')' in prototype");
561
562 // success.
563 getNextToken(); // eat ')'.
564
565 // Verify right number of names for operator.
566 if (Kind && ArgNames.size() != Kind)
567 return ErrorP("Invalid number of operands for operator");
568
569 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
570 }
571
572 /// definition ::= 'def' prototype expression
573 static FunctionAST *ParseDefinition() {
574 getNextToken(); // eat def.
575 PrototypeAST *Proto = ParsePrototype();
576 if (Proto == 0) return 0;
577
578 if (ExprAST *E = ParseExpression())
579 return new FunctionAST(Proto, E);
580 return 0;
581 }
582
583 /// toplevelexpr ::= expression
584 static FunctionAST *ParseTopLevelExpr() {
585 if (ExprAST *E = ParseExpression()) {
586 // Make an anonymous proto.
587 PrototypeAST *Proto = new PrototypeAST("", std::vector());
588 return new FunctionAST(Proto, E);
589 }
590 return 0;
591 }
592
593 /// external ::= 'extern' prototype
594 static PrototypeAST *ParseExtern() {
595 getNextToken(); // eat extern.
596 return ParsePrototype();
597 }
598
599 //===----------------------------------------------------------------------===//
600 // Code Generation
601 //===----------------------------------------------------------------------===//
602
603 static Module *TheModule;
604 static IRBuilder<> Builder;
605 static std::map NamedValues;
606 static FunctionPassManager *TheFPM;
607
608 Value *ErrorV(const char *Str) { Error(Str); return 0; }
609
610 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
611 /// the function. This is used for mutable variables etc.
612 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
613 const std::string &VarName) {
614 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
615 TheFunction->getEntryBlock().begin());
616 return TmpB.CreateAlloca(Type::DoubleTy, 0, VarName.c_str());
617 }
618
619
620 Value *NumberExprAST::Codegen() {
621 return ConstantFP::get(APFloat(Val));
622 }
623
624 Value *VariableExprAST::Codegen() {
625 // Look this variable up in the function.
626 Value *V = NamedValues[Name];
627 if (V == 0) return ErrorV("Unknown variable name");
628
629 // Load the value.
630 return Builder.CreateLoad(V, Name.c_str());
631 }
632
633 Value *UnaryExprAST::Codegen() {
634 Value *OperandV = Operand->Codegen();
635 if (OperandV == 0) return 0;
636
637 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
638 if (F == 0)
639 return ErrorV("Unknown unary operator");
640
641 return Builder.CreateCall(F, OperandV, "unop");
642 }
643
644
645 Value *BinaryExprAST::Codegen() {
646 // Special case '=' because we don't want to emit the LHS as an expression.
647 if (Op == '=') {
648 // Assignment requires the LHS to be an identifier.
649 VariableExprAST *LHSE = dynamic_cast(LHS);
650 if (!LHSE)
651 return ErrorV("destination of '=' must be a variable");
652 // Codegen the RHS.
653 Value *Val = RHS->Codegen();
654 if (Val == 0) return 0;
655
656 // Look up the name.
657 Value *Variable = NamedValues[LHSE->getName()];
658 if (Variable == 0) return ErrorV("Unknown variable name");
659
660 Builder.CreateStore(Val, Variable);
661 return Val;
662 }
663
664
665 Value *L = LHS->Codegen();
666 Value *R = RHS->Codegen();
667 if (L == 0 || R == 0) return 0;
668
669 switch (Op) {
670 case '+': return Builder.CreateAdd(L, R, "addtmp");
671 case '-': return Builder.CreateSub(L, R, "subtmp");
672 case '*': return Builder.CreateMul(L, R, "multmp");
673 case '<':
674 L = Builder.CreateFCmpULT(L, R, "cmptmp");
675 // Convert bool 0/1 to double 0.0 or 1.0
676 return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
677 default: break;
678 }
679
680 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
681 // a call to it.
682 Function *F = TheModule->getFunction(std::string("binary")+Op);
683 assert(F && "binary operator not found!");
684
685 Value *Ops[] = { L, R };
686 return Builder.CreateCall(F, Ops, Ops+2, "binop");
687 }
688
689 Value *CallExprAST::Codegen() {
690 // Look up the name in the global module table.
691 Function *CalleeF = TheModule->getFunction(Callee);
692 if (CalleeF == 0)
693 return ErrorV("Unknown function referenced");
694
695 // If argument mismatch error.
696 if (CalleeF->arg_size() != Args.size())
697 return ErrorV("Incorrect # arguments passed");
698
699 std::vector ArgsV;
700 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
701 ArgsV.push_back(Args[i]->Codegen());
702 if (ArgsV.back() == 0) return 0;
703 }
704
705 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
706 }
707
708 Value *IfExprAST::Codegen() {
709 Value *CondV = Cond->Codegen();
710 if (CondV == 0) return 0;
711
712 // Convert condition to a bool by comparing equal to 0.0.
713 CondV = Builder.CreateFCmpONE(CondV,
714 ConstantFP::get(APFloat(0.0)),
715 "ifcond");
716
717 Function *TheFunction = Builder.GetInsertBlock()->getParent();
718
719 // Create blocks for the then and else cases. Insert the 'then' block at the
720 // end of the function.
721 BasicBlock *ThenBB = BasicBlock::Create("then", TheFunction);
722 BasicBlock *ElseBB = BasicBlock::Create("else");
723 BasicBlock *MergeBB = BasicBlock::Create("ifcont");
724
725 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
726
727 // Emit then value.
728 Builder.SetInsertPoint(ThenBB);
729
730 Value *ThenV = Then->Codegen();
731 if (ThenV == 0) return 0;
732
733 Builder.CreateBr(MergeBB);
734 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
735 ThenBB = Builder.GetInsertBlock();
736
737 // Emit else block.
738 TheFunction->getBasicBlockList().push_back(ElseBB);
739 Builder.SetInsertPoint(ElseBB);
740
741 Value *ElseV = Else->Codegen();
742 if (ElseV == 0) return 0;
743
744 Builder.CreateBr(MergeBB);
745 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
746 ElseBB = Builder.GetInsertBlock();
747
748 // Emit merge block.
749 TheFunction->getBasicBlockList().push_back(MergeBB);
750 Builder.SetInsertPoint(MergeBB);
751 PHINode *PN = Builder.CreatePHI(Type::DoubleTy, "iftmp");
752
753 PN->addIncoming(ThenV, ThenBB);
754 PN->addIncoming(ElseV, ElseBB);
755 return PN;
756 }
757
758 Value *ForExprAST::Codegen() {
759 // Output this as:
760 // var = alloca double
761 // ...
762 // start = startexpr
763 // store start -> var
764 // goto loop
765 // loop:
766 // ...
767 // bodyexpr
768 // ...
769 // loopend:
770 // step = stepexpr
771 // endcond = endexpr
772 //
773 // curvar = load var
774 // nextvar = curvar + step
775 // store nextvar -> var
776 // br endcond, loop, endloop
777 // outloop:
778
779 Function *TheFunction = Builder.GetInsertBlock()->getParent();
780
781 // Create an alloca for the variable in the entry block.
782 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
783
784 // Emit the start code first, without 'variable' in scope.
785 Value *StartVal = Start->Codegen();
786 if (StartVal == 0) return 0;
787
788 // Store the value into the alloca.
789 Builder.CreateStore(StartVal, Alloca);
790
791 // Make the new basic block for the loop header, inserting after current
792 // block.
793 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
794 BasicBlock *LoopBB = BasicBlock::Create("loop", TheFunction);
795
796 // Insert an explicit fall through from the current block to the LoopBB.
797 Builder.CreateBr(LoopBB);
798
799 // Start insertion in LoopBB.
800 Builder.SetInsertPoint(LoopBB);
801
802 // Within the loop, the variable is defined equal to the PHI node. If it
803 // shadows an existing variable, we have to restore it, so save it now.
804 AllocaInst *OldVal = NamedValues[VarName];
805 NamedValues[VarName] = Alloca;
806
807 // Emit the body of the loop. This, like any other expr, can change the
808 // current BB. Note that we ignore the value computed by the body, but don't
809 // allow an error.
810 if (Body->Codegen() == 0)
811 return 0;
812
813 // Emit the step value.
814 Value *StepVal;
815 if (Step) {
816 StepVal = Step->Codegen();
817 if (StepVal == 0) return 0;
818 } else {
819 // If not specified, use 1.0.
820 StepVal = ConstantFP::get(APFloat(1.0));
821 }
822
823 // Compute the end condition.
824 Value *EndCond = End->Codegen();
825 if (EndCond == 0) return EndCond;
826
827 // Reload, increment, and restore the alloca. This handles the case where
828 // the body of the loop mutates the variable.
829 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
830 Value *NextVar = Builder.CreateAdd(CurVar, StepVal, "nextvar");
831 Builder.CreateStore(NextVar, Alloca);
832
833 // Convert condition to a bool by comparing equal to 0.0.
834 EndCond = Builder.CreateFCmpONE(EndCond,
835 ConstantFP::get(APFloat(0.0)),
836 "loopcond");
837
838 // Create the "after loop" block and insert it.
839 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
840 BasicBlock *AfterBB = BasicBlock::Create("afterloop", TheFunction);
841
842 // Insert the conditional branch into the end of LoopEndBB.
843 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
844
845 // Any new code will be inserted in AfterBB.
846 Builder.SetInsertPoint(AfterBB);
847
848 // Restore the unshadowed variable.
849 if (OldVal)
850 NamedValues[VarName] = OldVal;
851 else
852 NamedValues.erase(VarName);
853
854
855 // for expr always returns 0.0.
856 return Constant::getNullValue(Type::DoubleTy);
857 }
858
859 Value *VarExprAST::Codegen() {
860 std::vector OldBindings;
861
862 Function *TheFunction = Builder.GetInsertBlock()->getParent();
863
864 // Register all variables and emit their initializer.
865 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
866 const std::string &VarName = VarNames[i].first;
867 ExprAST *Init = VarNames[i].second;
868
869 // Emit the initializer before adding the variable to scope, this prevents
870 // the initializer from referencing the variable itself, and permits stuff
871 // like this:
872 // var a = 1 in
873 // var a = a in ... # refers to outer 'a'.
874 Value *InitVal;
875 if (Init) {
876 InitVal = Init->Codegen();
877 if (InitVal == 0) return 0;
878 } else { // If not specified, use 0.0.
879 InitVal = ConstantFP::get(APFloat(0.0));
880 }
881
882 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
883 Builder.CreateStore(InitVal, Alloca);
884
885 // Remember the old variable binding so that we can restore the binding when
886 // we unrecurse.
887 OldBindings.push_back(NamedValues[VarName]);
888
889 // Remember this binding.
890 NamedValues[VarName] = Alloca;
891 }
892
893 // Codegen the body, now that all vars are in scope.
894 Value *BodyVal = Body->Codegen();
895 if (BodyVal == 0) return 0;
896
897 // Pop all our variables from scope.
898 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
899 NamedValues[VarNames[i].first] = OldBindings[i];
900
901 // Return the body computation.
902 return BodyVal;
903 }
904
905
906 Function *PrototypeAST::Codegen() {
907 // Make the function type: double(double,double) etc.
908 std::vector Doubles(Args.size(), Type::DoubleTy);
909 FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
910
911 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
912
913 // If F conflicted, there was already something named 'Name'. If it has a
914 // body, don't allow redefinition or reextern.
915 if (F->getName() != Name) {
916 // Delete the one we just made and get the existing one.
917 F->eraseFromParent();
918 F = TheModule->getFunction(Name);
919
920 // If F already has a body, reject this.
921 if (!F->empty()) {
922 ErrorF("redefinition of function");
923 return 0;
924 }
925
926 // If F took a different number of args, reject.
927 if (F->arg_size() != Args.size()) {
928 ErrorF("redefinition of function with different # args");
929 return 0;
930 }
931 }
932
933 // Set names for all arguments.
934 unsigned Idx = 0;
935 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
936 ++AI, ++Idx)
937 AI->setName(Args[Idx]);
938
939 return F;
940 }
941
942 /// CreateArgumentAllocas - Create an alloca for each argument and register the
943 /// argument in the symbol table so that references to it will succeed.
944 void PrototypeAST::CreateArgumentAllocas(Function *F) {
945 Function::arg_iterator AI = F->arg_begin();
946 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
947 // Create an alloca for this variable.
948 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
949
950 // Store the initial value into the alloca.
951 Builder.CreateStore(AI, Alloca);
952
953 // Add arguments to variable symbol table.
954 NamedValues[Args[Idx]] = Alloca;
955 }
956 }
957
958
959 Function *FunctionAST::Codegen() {
960 NamedValues.clear();
961
962 Function *TheFunction = Proto->Codegen();
963 if (TheFunction == 0)
964 return 0;
965
966 // If this is an operator, install it.
967 if (Proto->isBinaryOp())
968 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
969
970 // Create a new basic block to start insertion into.
971 BasicBlock *BB = BasicBlock::Create("entry", TheFunction);
972 Builder.SetInsertPoint(BB);
973
974 // Add all arguments to the symbol table and create their allocas.
975 Proto->CreateArgumentAllocas(TheFunction);
976
977 if (Value *RetVal = Body->Codegen()) {
978 // Finish off the function.
979 Builder.CreateRet(RetVal);
980
981 // Validate the generated code, checking for consistency.
982 verifyFunction(*TheFunction);
983
984 // Optimize the function.
985 TheFPM->run(*TheFunction);
986
987 return TheFunction;
988 }
989
990 // Error reading body, remove function.
991 TheFunction->eraseFromParent();
992
993 if (Proto->isBinaryOp())
994 BinopPrecedence.erase(Proto->getOperatorName());
995 return 0;
996 }
997
998 //===----------------------------------------------------------------------===//
999 // Top-Level parsing and JIT Driver
1000 //===----------------------------------------------------------------------===//
1001
1002 static ExecutionEngine *TheExecutionEngine;
1003
1004 static void HandleDefinition() {
1005 if (FunctionAST *F = ParseDefinition()) {
1006 if (Function *LF = F->Codegen()) {
1007 fprintf(stderr, "Read function definition:");
1008 LF->dump();
1009 }
1010 } else {
1011 // Skip token for error recovery.
1012 getNextToken();
1013 }
1014 }
1015
1016 static void HandleExtern() {
1017 if (PrototypeAST *P = ParseExtern()) {
1018 if (Function *F = P->Codegen()) {
1019 fprintf(stderr, "Read extern: ");
1020 F->dump();
1021 }
1022 } else {
1023 // Skip token for error recovery.
1024 getNextToken();
1025 }
1026 }
1027
1028 static void HandleTopLevelExpression() {
1029 // Evaluate a top level expression into an anonymous function.
1030 if (FunctionAST *F = ParseTopLevelExpr()) {
1031 if (Function *LF = F->Codegen()) {
1032 // JIT the function, returning a function pointer.
1033 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1034
1035 // Cast it to the right type (takes no arguments, returns a double) so we
1036 // can call it as a native function.
1037 double (*FP)() = (double (*)())FPtr;
1038 fprintf(stderr, "Evaluated to %f\n", FP());
1039 }
1040 } else {
1041 // Skip token for error recovery.
1042 getNextToken();
1043 }
1044 }
1045
1046 /// top ::= definition | external | expression | ';'
1047 static void MainLoop() {
1048 while (1) {
1049 fprintf(stderr, "ready> ");
1050 switch (CurTok) {
1051 case tok_eof: return;
1052 case ';': getNextToken(); break; // ignore top level semicolons.
1053 case tok_def: HandleDefinition(); break;
1054 case tok_extern: HandleExtern(); break;
1055 default: HandleTopLevelExpression(); break;
1056 }
1057 }
1058 }
1059
1060
1061
1062 //===----------------------------------------------------------------------===//
1063 // "Library" functions that can be "extern'd" from user code.
1064 //===----------------------------------------------------------------------===//
1065
1066 /// putchard - putchar that takes a double and returns 0.
1067 extern "C"
1068 double putchard(double X) {
1069 putchar((char)X);
1070 return 0;
1071 }
1072
1073 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1074 extern "C"
1075 double printd(double X) {
1076 printf("%f\n", X);
1077 return 0;
1078 }
1079
1080 //===----------------------------------------------------------------------===//
1081 // Main driver code.
1082 //===----------------------------------------------------------------------===//
1083
1084 int main() {
1085 // Install standard binary operators.
1086 // 1 is lowest precedence.
1087 BinopPrecedence['='] = 2;
1088 BinopPrecedence['<'] = 10;
1089 BinopPrecedence['+'] = 20;
1090 BinopPrecedence['-'] = 20;
1091 BinopPrecedence['*'] = 40; // highest.
1092
1093 // Prime the first token.
1094 fprintf(stderr, "ready> ");
1095 getNextToken();
1096
1097 // Make the module, which holds all the code.
1098 TheModule = new Module("my cool jit");
1099
1100 // Create the JIT.
1101 TheExecutionEngine = ExecutionEngine::create(TheModule);
1102
1103 {
1104 ExistingModuleProvider OurModuleProvider(TheModule);
1105 FunctionPassManager OurFPM(&OurModuleProvider);
1106
1107 // Set up the optimizer pipeline. Start with registering info about how the
1108 // target lays out data structures.
1109 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
1110 // Promote allocas to registers.
1111 OurFPM.add(createPromoteMemoryToRegisterPass());
1112 // Do simple "peephole" optimizations and bit-twiddling optzns.
1113 OurFPM.add(createInstructionCombiningPass());
1114 // Reassociate expressions.
1115 OurFPM.add(createReassociatePass());
1116 // Eliminate Common SubExpressions.
1117 OurFPM.add(createGVNPass());
1118 // Simplify the control flow graph (deleting unreachable blocks, etc).
1119 OurFPM.add(createCFGSimplificationPass());
1120
1121 // Set the global so the code gen can use this.
1122 TheFPM = &OurFPM;
1123
1124 // Run the main "interpreter loop" now.
1125 MainLoop();
1126
1127 TheFPM = 0;
1128
1129 // Print out all of the generated code.
1130 TheModule->dump();
1131
1132 } // Free module provider (and thus the module) and pass manager.
1133
1134 return 0;
1135 }
1136
99
1010 include $(LEVEL)/Makefile.config
1111
12 PARALLEL_DIRS:= BrainF Fibonacci HowToUseJIT ModuleMaker
12 PARALLEL_DIRS:= BrainF Fibonacci HowToUseJIT Kaleidoscope ModuleMaker
1313
1414 ifeq ($(HAVE_PTHREAD),1)
1515 PARALLEL_DIRS += ParallelJIT