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