1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/IR/Verifier.h"
3 #include "llvm/ExecutionEngine/ExecutionEngine.h"
4 #include "llvm/ExecutionEngine/JIT.h"
5 #include "llvm/IR/DataLayout.h"
6 #include "llvm/IR/DerivedTypes.h"
7 #include "llvm/IR/IRBuilder.h"
8 #include "llvm/IR/LLVMContext.h"
9 #include "llvm/IR/Module.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/Support/TargetSelect.h"
12 #include "llvm/Transforms/Scalar.h"
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
30 tok_def = -2, tok_extern = -3,
33 tok_identifier = -4, tok_number = -5,
36 tok_if = -6, tok_then = -7, tok_else = -8,
37 tok_for = -9, tok_in = -10
40 static std::string IdentifierStr; // Filled in if tok_identifier
41 static double NumVal; // Filled in if tok_number
43 /// gettok - Return the next token from standard input.
45 static int LastChar = ' ';
47 // Skip any whitespace.
48 while (isspace(LastChar))
51 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
52 IdentifierStr = LastChar;
53 while (isalnum((LastChar = getchar())))
54 IdentifierStr += LastChar;
56 if (IdentifierStr == "def") return tok_def;
57 if (IdentifierStr == "extern") return tok_extern;
58 if (IdentifierStr == "if") return tok_if;
59 if (IdentifierStr == "then") return tok_then;
60 if (IdentifierStr == "else") return tok_else;
61 if (IdentifierStr == "for") return tok_for;
62 if (IdentifierStr == "in") return tok_in;
63 return tok_identifier;
66 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
71 } while (isdigit(LastChar) || LastChar == '.');
73 NumVal = strtod(NumStr.c_str(), 0);
77 if (LastChar == '#') {
78 // Comment until end of line.
79 do LastChar = getchar();
80 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
86 // Check for end of file. Don't eat the EOF.
90 // Otherwise, just return the character as its ascii value.
91 int ThisChar = LastChar;
96 //===----------------------------------------------------------------------===//
97 // Abstract Syntax Tree (aka Parse Tree)
98 //===----------------------------------------------------------------------===//
100 /// ExprAST - Base class for all expression nodes.
103 virtual ~ExprAST() {}
104 virtual Value *Codegen() = 0;
107 /// NumberExprAST - Expression class for numeric literals like "1.0".
108 class NumberExprAST : public ExprAST {
111 NumberExprAST(double val) : Val(val) {}
112 virtual Value *Codegen();
115 /// VariableExprAST - Expression class for referencing a variable, like "a".
116 class VariableExprAST : public ExprAST {
119 VariableExprAST(const std::string &name) : Name(name) {}
120 virtual Value *Codegen();
123 /// BinaryExprAST - Expression class for a binary operator.
124 class BinaryExprAST : public ExprAST {
128 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
129 : Op(op), LHS(lhs), RHS(rhs) {}
130 virtual Value *Codegen();
133 /// CallExprAST - Expression class for function calls.
134 class CallExprAST : public ExprAST {
136 std::vector<ExprAST*> Args;
138 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
139 : Callee(callee), Args(args) {}
140 virtual Value *Codegen();
143 /// IfExprAST - Expression class for if/then/else.
144 class IfExprAST : public ExprAST {
145 ExprAST *Cond, *Then, *Else;
147 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
148 : Cond(cond), Then(then), Else(_else) {}
149 virtual Value *Codegen();
152 /// ForExprAST - Expression class for for/in.
153 class ForExprAST : public ExprAST {
155 ExprAST *Start, *End, *Step, *Body;
157 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
158 ExprAST *step, ExprAST *body)
159 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
160 virtual Value *Codegen();
163 /// PrototypeAST - This class represents the "prototype" for a function,
164 /// which captures its name, and its argument names (thus implicitly the number
165 /// of arguments the function takes).
168 std::vector<std::string> Args;
170 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
171 : Name(name), Args(args) {}
176 /// FunctionAST - This class represents a function definition itself.
181 FunctionAST(PrototypeAST *proto, ExprAST *body)
182 : Proto(proto), Body(body) {}
186 } // end anonymous namespace
188 //===----------------------------------------------------------------------===//
190 //===----------------------------------------------------------------------===//
192 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
193 /// token the parser is looking at. getNextToken reads another token from the
194 /// lexer and updates CurTok with its results.
196 static int getNextToken() {
197 return CurTok = gettok();
200 /// BinopPrecedence - This holds the precedence for each binary operator that is
202 static std::map<char, int> BinopPrecedence;
204 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
205 static int GetTokPrecedence() {
206 if (!isascii(CurTok))
209 // Make sure it's a declared binop.
210 int TokPrec = BinopPrecedence[CurTok];
211 if (TokPrec <= 0) return -1;
215 /// Error* - These are little helper functions for error handling.
216 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
217 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
218 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
220 static ExprAST *ParseExpression();
224 /// ::= identifier '(' expression* ')'
225 static ExprAST *ParseIdentifierExpr() {
226 std::string IdName = IdentifierStr;
228 getNextToken(); // eat identifier.
230 if (CurTok != '(') // Simple variable ref.
231 return new VariableExprAST(IdName);
234 getNextToken(); // eat (
235 std::vector<ExprAST*> Args;
238 ExprAST *Arg = ParseExpression();
242 if (CurTok == ')') break;
245 return Error("Expected ')' or ',' in argument list");
253 return new CallExprAST(IdName, Args);
256 /// numberexpr ::= number
257 static ExprAST *ParseNumberExpr() {
258 ExprAST *Result = new NumberExprAST(NumVal);
259 getNextToken(); // consume the number
263 /// parenexpr ::= '(' expression ')'
264 static ExprAST *ParseParenExpr() {
265 getNextToken(); // eat (.
266 ExprAST *V = ParseExpression();
270 return Error("expected ')'");
271 getNextToken(); // eat ).
275 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
276 static ExprAST *ParseIfExpr() {
277 getNextToken(); // eat the if.
280 ExprAST *Cond = ParseExpression();
283 if (CurTok != tok_then)
284 return Error("expected then");
285 getNextToken(); // eat the then
287 ExprAST *Then = ParseExpression();
288 if (Then == 0) return 0;
290 if (CurTok != tok_else)
291 return Error("expected else");
295 ExprAST *Else = ParseExpression();
298 return new IfExprAST(Cond, Then, Else);
301 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
302 static ExprAST *ParseForExpr() {
303 getNextToken(); // eat the for.
305 if (CurTok != tok_identifier)
306 return Error("expected identifier after for");
308 std::string IdName = IdentifierStr;
309 getNextToken(); // eat identifier.
312 return Error("expected '=' after for");
313 getNextToken(); // eat '='.
316 ExprAST *Start = ParseExpression();
317 if (Start == 0) return 0;
319 return Error("expected ',' after for start value");
322 ExprAST *End = ParseExpression();
323 if (End == 0) return 0;
325 // The step value is optional.
329 Step = ParseExpression();
330 if (Step == 0) return 0;
333 if (CurTok != tok_in)
334 return Error("expected 'in' after for");
335 getNextToken(); // eat 'in'.
337 ExprAST *Body = ParseExpression();
338 if (Body == 0) return 0;
340 return new ForExprAST(IdName, Start, End, Step, Body);
344 /// ::= identifierexpr
349 static ExprAST *ParsePrimary() {
351 default: return Error("unknown token when expecting an expression");
352 case tok_identifier: return ParseIdentifierExpr();
353 case tok_number: return ParseNumberExpr();
354 case '(': return ParseParenExpr();
355 case tok_if: return ParseIfExpr();
356 case tok_for: return ParseForExpr();
361 /// ::= ('+' primary)*
362 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
363 // If this is a binop, find its precedence.
365 int TokPrec = GetTokPrecedence();
367 // If this is a binop that binds at least as tightly as the current binop,
368 // consume it, otherwise we are done.
369 if (TokPrec < ExprPrec)
372 // Okay, we know this is a binop.
374 getNextToken(); // eat binop
376 // Parse the primary expression after the binary operator.
377 ExprAST *RHS = ParsePrimary();
380 // If BinOp binds less tightly with RHS than the operator after RHS, let
381 // the pending operator take RHS as its LHS.
382 int NextPrec = GetTokPrecedence();
383 if (TokPrec < NextPrec) {
384 RHS = ParseBinOpRHS(TokPrec+1, RHS);
385 if (RHS == 0) return 0;
389 LHS = new BinaryExprAST(BinOp, LHS, RHS);
394 /// ::= primary binoprhs
396 static ExprAST *ParseExpression() {
397 ExprAST *LHS = ParsePrimary();
400 return ParseBinOpRHS(0, LHS);
404 /// ::= id '(' id* ')'
405 static PrototypeAST *ParsePrototype() {
406 if (CurTok != tok_identifier)
407 return ErrorP("Expected function name in prototype");
409 std::string FnName = IdentifierStr;
413 return ErrorP("Expected '(' in prototype");
415 std::vector<std::string> ArgNames;
416 while (getNextToken() == tok_identifier)
417 ArgNames.push_back(IdentifierStr);
419 return ErrorP("Expected ')' in prototype");
422 getNextToken(); // eat ')'.
424 return new PrototypeAST(FnName, ArgNames);
427 /// definition ::= 'def' prototype expression
428 static FunctionAST *ParseDefinition() {
429 getNextToken(); // eat def.
430 PrototypeAST *Proto = ParsePrototype();
431 if (Proto == 0) return 0;
433 if (ExprAST *E = ParseExpression())
434 return new FunctionAST(Proto, E);
438 /// toplevelexpr ::= expression
439 static FunctionAST *ParseTopLevelExpr() {
440 if (ExprAST *E = ParseExpression()) {
441 // Make an anonymous proto.
442 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
443 return new FunctionAST(Proto, E);
448 /// external ::= 'extern' prototype
449 static PrototypeAST *ParseExtern() {
450 getNextToken(); // eat extern.
451 return ParsePrototype();
454 //===----------------------------------------------------------------------===//
456 //===----------------------------------------------------------------------===//
458 static Module *TheModule;
459 static IRBuilder<> Builder(getGlobalContext());
460 static std::map<std::string, Value*> NamedValues;
461 static FunctionPassManager *TheFPM;
463 Value *ErrorV(const char *Str) { Error(Str); return 0; }
465 Value *NumberExprAST::Codegen() {
466 return ConstantFP::get(getGlobalContext(), APFloat(Val));
469 Value *VariableExprAST::Codegen() {
470 // Look this variable up in the function.
471 Value *V = NamedValues[Name];
472 return V ? V : ErrorV("Unknown variable name");
475 Value *BinaryExprAST::Codegen() {
476 Value *L = LHS->Codegen();
477 Value *R = RHS->Codegen();
478 if (L == 0 || R == 0) return 0;
481 case '+': return Builder.CreateFAdd(L, R, "addtmp");
482 case '-': return Builder.CreateFSub(L, R, "subtmp");
483 case '*': return Builder.CreateFMul(L, R, "multmp");
485 L = Builder.CreateFCmpULT(L, R, "cmptmp");
486 // Convert bool 0/1 to double 0.0 or 1.0
487 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
489 default: return ErrorV("invalid binary operator");
493 Value *CallExprAST::Codegen() {
494 // Look up the name in the global module table.
495 Function *CalleeF = TheModule->getFunction(Callee);
497 return ErrorV("Unknown function referenced");
499 // If argument mismatch error.
500 if (CalleeF->arg_size() != Args.size())
501 return ErrorV("Incorrect # arguments passed");
503 std::vector<Value*> ArgsV;
504 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
505 ArgsV.push_back(Args[i]->Codegen());
506 if (ArgsV.back() == 0) return 0;
509 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
512 Value *IfExprAST::Codegen() {
513 Value *CondV = Cond->Codegen();
514 if (CondV == 0) return 0;
516 // Convert condition to a bool by comparing equal to 0.0.
517 CondV = Builder.CreateFCmpONE(CondV,
518 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
521 Function *TheFunction = Builder.GetInsertBlock()->getParent();
523 // Create blocks for the then and else cases. Insert the 'then' block at the
524 // end of the function.
525 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
526 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
527 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
529 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
532 Builder.SetInsertPoint(ThenBB);
534 Value *ThenV = Then->Codegen();
535 if (ThenV == 0) return 0;
537 Builder.CreateBr(MergeBB);
538 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
539 ThenBB = Builder.GetInsertBlock();
542 TheFunction->getBasicBlockList().push_back(ElseBB);
543 Builder.SetInsertPoint(ElseBB);
545 Value *ElseV = Else->Codegen();
546 if (ElseV == 0) return 0;
548 Builder.CreateBr(MergeBB);
549 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
550 ElseBB = Builder.GetInsertBlock();
553 TheFunction->getBasicBlockList().push_back(MergeBB);
554 Builder.SetInsertPoint(MergeBB);
555 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
558 PN->addIncoming(ThenV, ThenBB);
559 PN->addIncoming(ElseV, ElseBB);
563 Value *ForExprAST::Codegen() {
569 // variable = phi [start, loopheader], [nextvariable, loopend]
575 // nextvariable = variable + step
577 // br endcond, loop, endloop
580 // Emit the start code first, without 'variable' in scope.
581 Value *StartVal = Start->Codegen();
582 if (StartVal == 0) return 0;
584 // Make the new basic block for the loop header, inserting after current
586 Function *TheFunction = Builder.GetInsertBlock()->getParent();
587 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
588 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
590 // Insert an explicit fall through from the current block to the LoopBB.
591 Builder.CreateBr(LoopBB);
593 // Start insertion in LoopBB.
594 Builder.SetInsertPoint(LoopBB);
596 // Start the PHI node with an entry for Start.
597 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
598 Variable->addIncoming(StartVal, PreheaderBB);
600 // Within the loop, the variable is defined equal to the PHI node. If it
601 // shadows an existing variable, we have to restore it, so save it now.
602 Value *OldVal = NamedValues[VarName];
603 NamedValues[VarName] = Variable;
605 // Emit the body of the loop. This, like any other expr, can change the
606 // current BB. Note that we ignore the value computed by the body, but don't
608 if (Body->Codegen() == 0)
611 // Emit the step value.
614 StepVal = Step->Codegen();
615 if (StepVal == 0) return 0;
617 // If not specified, use 1.0.
618 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
621 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
623 // Compute the end condition.
624 Value *EndCond = End->Codegen();
625 if (EndCond == 0) return EndCond;
627 // Convert condition to a bool by comparing equal to 0.0.
628 EndCond = Builder.CreateFCmpONE(EndCond,
629 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
632 // Create the "after loop" block and insert it.
633 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
634 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
636 // Insert the conditional branch into the end of LoopEndBB.
637 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
639 // Any new code will be inserted in AfterBB.
640 Builder.SetInsertPoint(AfterBB);
642 // Add a new entry to the PHI node for the backedge.
643 Variable->addIncoming(NextVar, LoopEndBB);
645 // Restore the unshadowed variable.
647 NamedValues[VarName] = OldVal;
649 NamedValues.erase(VarName);
652 // for expr always returns 0.0.
653 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
656 Function *PrototypeAST::Codegen() {
657 // Make the function type: double(double,double) etc.
658 std::vector<Type*> Doubles(Args.size(),
659 Type::getDoubleTy(getGlobalContext()));
660 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
663 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
665 // If F conflicted, there was already something named 'Name'. If it has a
666 // body, don't allow redefinition or reextern.
667 if (F->getName() != Name) {
668 // Delete the one we just made and get the existing one.
669 F->eraseFromParent();
670 F = TheModule->getFunction(Name);
672 // If F already has a body, reject this.
674 ErrorF("redefinition of function");
678 // If F took a different number of args, reject.
679 if (F->arg_size() != Args.size()) {
680 ErrorF("redefinition of function with different # args");
685 // Set names for all arguments.
687 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
689 AI->setName(Args[Idx]);
691 // Add arguments to variable symbol table.
692 NamedValues[Args[Idx]] = AI;
698 Function *FunctionAST::Codegen() {
701 Function *TheFunction = Proto->Codegen();
702 if (TheFunction == 0)
705 // Create a new basic block to start insertion into.
706 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
707 Builder.SetInsertPoint(BB);
709 if (Value *RetVal = Body->Codegen()) {
710 // Finish off the function.
711 Builder.CreateRet(RetVal);
713 // Validate the generated code, checking for consistency.
714 verifyFunction(*TheFunction);
716 // Optimize the function.
717 TheFPM->run(*TheFunction);
722 // Error reading body, remove function.
723 TheFunction->eraseFromParent();
727 //===----------------------------------------------------------------------===//
728 // Top-Level parsing and JIT Driver
729 //===----------------------------------------------------------------------===//
731 static ExecutionEngine *TheExecutionEngine;
733 static void HandleDefinition() {
734 if (FunctionAST *F = ParseDefinition()) {
735 if (Function *LF = F->Codegen()) {
736 fprintf(stderr, "Read function definition:");
740 // Skip token for error recovery.
745 static void HandleExtern() {
746 if (PrototypeAST *P = ParseExtern()) {
747 if (Function *F = P->Codegen()) {
748 fprintf(stderr, "Read extern: ");
752 // Skip token for error recovery.
757 static void HandleTopLevelExpression() {
758 // Evaluate a top-level expression into an anonymous function.
759 if (FunctionAST *F = ParseTopLevelExpr()) {
760 if (Function *LF = F->Codegen()) {
761 // JIT the function, returning a function pointer.
762 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
764 // Cast it to the right type (takes no arguments, returns a double) so we
765 // can call it as a native function.
766 double (*FP)() = (double (*)())(intptr_t)FPtr;
767 fprintf(stderr, "Evaluated to %f\n", FP());
770 // Skip token for error recovery.
775 /// top ::= definition | external | expression | ';'
776 static void MainLoop() {
778 fprintf(stderr, "ready> ");
780 case tok_eof: return;
781 case ';': getNextToken(); break; // ignore top-level semicolons.
782 case tok_def: HandleDefinition(); break;
783 case tok_extern: HandleExtern(); break;
784 default: HandleTopLevelExpression(); break;
789 //===----------------------------------------------------------------------===//
790 // "Library" functions that can be "extern'd" from user code.
791 //===----------------------------------------------------------------------===//
793 /// putchard - putchar that takes a double and returns 0.
795 double putchard(double X) {
800 //===----------------------------------------------------------------------===//
802 //===----------------------------------------------------------------------===//
805 InitializeNativeTarget();
806 LLVMContext &Context = getGlobalContext();
808 // Install standard binary operators.
809 // 1 is lowest precedence.
810 BinopPrecedence['<'] = 10;
811 BinopPrecedence['+'] = 20;
812 BinopPrecedence['-'] = 20;
813 BinopPrecedence['*'] = 40; // highest.
815 // Prime the first token.
816 fprintf(stderr, "ready> ");
819 // Make the module, which holds all the code.
820 TheModule = new Module("my cool jit", Context);
822 // Create the JIT. This takes ownership of the module.
824 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
825 if (!TheExecutionEngine) {
826 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
830 FunctionPassManager OurFPM(TheModule);
832 // Set up the optimizer pipeline. Start with registering info about how the
833 // target lays out data structures.
834 OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
835 // Provide basic AliasAnalysis support for GVN.
836 OurFPM.add(createBasicAliasAnalysisPass());
837 // Do simple "peephole" optimizations and bit-twiddling optzns.
838 OurFPM.add(createInstructionCombiningPass());
839 // Reassociate expressions.
840 OurFPM.add(createReassociatePass());
841 // Eliminate Common SubExpressions.
842 OurFPM.add(createGVNPass());
843 // Simplify the control flow graph (deleting unreachable blocks, etc).
844 OurFPM.add(createCFGSimplificationPass());
846 OurFPM.doInitialization();
848 // Set the global so the code gen can use this.
851 // Run the main "interpreter loop" now.
856 // Print out all of the generated code.