1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/BasicAliasAnalysis.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.h"
5 #include "llvm/ExecutionEngine/MCJIT.h"
6 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
7 #include "llvm/IR/DataLayout.h"
8 #include "llvm/IR/DerivedTypes.h"
9 #include "llvm/IR/IRBuilder.h"
10 #include "llvm/IR/LLVMContext.h"
11 #include "llvm/IR/LegacyPassManager.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Transforms/Scalar.h"
23 //===----------------------------------------------------------------------===//
25 //===----------------------------------------------------------------------===//
27 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
28 // of these for known things.
52 static std::string IdentifierStr; // Filled in if tok_identifier
53 static double NumVal; // Filled in if tok_number
55 /// gettok - Return the next token from standard input.
57 static int LastChar = ' ';
59 // Skip any whitespace.
60 while (isspace(LastChar))
63 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
64 IdentifierStr = LastChar;
65 while (isalnum((LastChar = getchar())))
66 IdentifierStr += LastChar;
68 if (IdentifierStr == "def")
70 if (IdentifierStr == "extern")
72 if (IdentifierStr == "if")
74 if (IdentifierStr == "then")
76 if (IdentifierStr == "else")
78 if (IdentifierStr == "for")
80 if (IdentifierStr == "in")
82 if (IdentifierStr == "binary")
84 if (IdentifierStr == "unary")
86 return tok_identifier;
89 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
94 } while (isdigit(LastChar) || LastChar == '.');
96 NumVal = strtod(NumStr.c_str(), 0);
100 if (LastChar == '#') {
101 // Comment until end of line.
103 LastChar = getchar();
104 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
110 // Check for end of file. Don't eat the EOF.
114 // Otherwise, just return the character as its ascii value.
115 int ThisChar = LastChar;
116 LastChar = getchar();
120 //===----------------------------------------------------------------------===//
121 // Abstract Syntax Tree (aka Parse Tree)
122 //===----------------------------------------------------------------------===//
124 /// ExprAST - Base class for all expression nodes.
127 virtual ~ExprAST() {}
128 virtual Value *Codegen() = 0;
131 /// NumberExprAST - Expression class for numeric literals like "1.0".
132 class NumberExprAST : public ExprAST {
135 NumberExprAST(double Val) : Val(Val) {}
136 Value *Codegen() override;
139 /// VariableExprAST - Expression class for referencing a variable, like "a".
140 class VariableExprAST : public ExprAST {
143 VariableExprAST(const std::string &Name) : Name(Name) {}
144 Value *Codegen() override;
147 /// UnaryExprAST - Expression class for a unary operator.
148 class UnaryExprAST : public ExprAST {
150 std::unique_ptr<ExprAST> Operand;
153 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
154 : Opcode(Opcode), Operand(std::move(Operand)) {}
155 Value *Codegen() override;
158 /// BinaryExprAST - Expression class for a binary operator.
159 class BinaryExprAST : public ExprAST {
161 std::unique_ptr<ExprAST> LHS, RHS;
163 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
164 std::unique_ptr<ExprAST> RHS)
165 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
166 Value *Codegen() override;
169 /// CallExprAST - Expression class for function calls.
170 class CallExprAST : public ExprAST {
172 std::vector<std::unique_ptr<ExprAST>> Args;
174 CallExprAST(const std::string &Callee,
175 std::vector<std::unique_ptr<ExprAST>> Args)
176 : Callee(Callee), Args(std::move(Args)) {}
177 Value *Codegen() override;
180 /// IfExprAST - Expression class for if/then/else.
181 class IfExprAST : public ExprAST {
182 std::unique_ptr<ExprAST> Cond, Then, Else;
184 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
185 std::unique_ptr<ExprAST> Else)
186 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
187 Value *Codegen() override;
190 /// ForExprAST - Expression class for for/in.
191 class ForExprAST : public ExprAST {
193 std::unique_ptr<ExprAST> Start, End, Step, Body;
195 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
196 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
197 std::unique_ptr<ExprAST> Body)
198 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
199 Step(std::move(Step)), Body(std::move(Body)) {}
200 Value *Codegen() override;
203 /// PrototypeAST - This class represents the "prototype" for a function,
204 /// which captures its name, and its argument names (thus implicitly the number
205 /// of arguments the function takes), as well as if it is an operator.
208 std::vector<std::string> Args;
210 unsigned Precedence; // Precedence if a binary op.
212 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
213 bool IsOperator = false, unsigned Prec = 0)
214 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
217 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
218 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
220 char getOperatorName() const {
221 assert(isUnaryOp() || isBinaryOp());
222 return Name[Name.size() - 1];
225 unsigned getBinaryPrecedence() const { return Precedence; }
230 /// FunctionAST - This class represents a function definition itself.
232 std::unique_ptr<PrototypeAST> Proto;
233 std::unique_ptr<ExprAST> Body;
235 FunctionAST(std::unique_ptr<PrototypeAST> Proto, std::unique_ptr<ExprAST> Body)
236 : Proto(std::move(Proto)), Body(std::move(Body)) {}
239 } // end anonymous namespace
241 //===----------------------------------------------------------------------===//
243 //===----------------------------------------------------------------------===//
245 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
246 /// token the parser is looking at. getNextToken reads another token from the
247 /// lexer and updates CurTok with its results.
249 static int getNextToken() { return CurTok = gettok(); }
251 /// BinopPrecedence - This holds the precedence for each binary operator that is
253 static std::map<char, int> BinopPrecedence;
255 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
256 static int GetTokPrecedence() {
257 if (!isascii(CurTok))
260 // Make sure it's a declared binop.
261 int TokPrec = BinopPrecedence[CurTok];
267 /// Error* - These are little helper functions for error handling.
268 std::unique_ptr<ExprAST> Error(const char *Str) {
269 fprintf(stderr, "Error: %s\n", Str);
272 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
276 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
281 static std::unique_ptr<ExprAST> ParseExpression();
285 /// ::= identifier '(' expression* ')'
286 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
287 std::string IdName = IdentifierStr;
289 getNextToken(); // eat identifier.
291 if (CurTok != '(') // Simple variable ref.
292 return llvm::make_unique<VariableExprAST>(IdName);
295 getNextToken(); // eat (
296 std::vector<std::unique_ptr<ExprAST>> Args;
299 if (auto Arg = ParseExpression())
300 Args.push_back(std::move(Arg));
308 return Error("Expected ')' or ',' in argument list");
316 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
319 /// numberexpr ::= number
320 static std::unique_ptr<ExprAST> ParseNumberExpr() {
321 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
322 getNextToken(); // consume the number
323 return std::move(Result);
326 /// parenexpr ::= '(' expression ')'
327 static std::unique_ptr<ExprAST> ParseParenExpr() {
328 getNextToken(); // eat (.
329 auto V = ParseExpression();
334 return Error("expected ')'");
335 getNextToken(); // eat ).
339 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
340 static std::unique_ptr<ExprAST> ParseIfExpr() {
341 getNextToken(); // eat the if.
344 auto Cond = ParseExpression();
348 if (CurTok != tok_then)
349 return Error("expected then");
350 getNextToken(); // eat the then
352 auto Then = ParseExpression();
356 if (CurTok != tok_else)
357 return Error("expected else");
361 auto Else = ParseExpression();
365 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
369 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
370 static std::unique_ptr<ExprAST> ParseForExpr() {
371 getNextToken(); // eat the for.
373 if (CurTok != tok_identifier)
374 return Error("expected identifier after for");
376 std::string IdName = IdentifierStr;
377 getNextToken(); // eat identifier.
380 return Error("expected '=' after for");
381 getNextToken(); // eat '='.
383 auto Start = ParseExpression();
387 return Error("expected ',' after for start value");
390 auto End = ParseExpression();
394 // The step value is optional.
395 std::unique_ptr<ExprAST> Step;
398 Step = ParseExpression();
403 if (CurTok != tok_in)
404 return Error("expected 'in' after for");
405 getNextToken(); // eat 'in'.
407 auto Body = ParseExpression();
411 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
412 std::move(Step), std::move(Body));
416 /// ::= identifierexpr
421 static std::unique_ptr<ExprAST> ParsePrimary() {
424 return Error("unknown token when expecting an expression");
426 return ParseIdentifierExpr();
428 return ParseNumberExpr();
430 return ParseParenExpr();
432 return ParseIfExpr();
434 return ParseForExpr();
441 static std::unique_ptr<ExprAST> ParseUnary() {
442 // If the current token is not an operator, it must be a primary expr.
443 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
444 return ParsePrimary();
446 // If this is a unary operator, read it.
449 if (auto Operand = ParseUnary())
450 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
456 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS) {
457 // If this is a binop, find its precedence.
459 int TokPrec = GetTokPrecedence();
461 // If this is a binop that binds at least as tightly as the current binop,
462 // consume it, otherwise we are done.
463 if (TokPrec < ExprPrec)
466 // Okay, we know this is a binop.
468 getNextToken(); // eat binop
470 // Parse the unary expression after the binary operator.
471 auto RHS = ParseUnary();
475 // If BinOp binds less tightly with RHS than the operator after RHS, let
476 // the pending operator take RHS as its LHS.
477 int NextPrec = GetTokPrecedence();
478 if (TokPrec < NextPrec) {
479 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
485 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
490 /// ::= unary binoprhs
492 static std::unique_ptr<ExprAST> ParseExpression() {
493 auto LHS = ParseUnary();
497 return ParseBinOpRHS(0, std::move(LHS));
501 /// ::= id '(' id* ')'
502 /// ::= binary LETTER number? (id, id)
503 /// ::= unary LETTER (id)
504 static std::unique_ptr<PrototypeAST> ParsePrototype() {
507 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
508 unsigned BinaryPrecedence = 30;
512 return ErrorP("Expected function name in prototype");
514 FnName = IdentifierStr;
520 if (!isascii(CurTok))
521 return ErrorP("Expected unary operator");
523 FnName += (char)CurTok;
529 if (!isascii(CurTok))
530 return ErrorP("Expected binary operator");
532 FnName += (char)CurTok;
536 // Read the precedence if present.
537 if (CurTok == tok_number) {
538 if (NumVal < 1 || NumVal > 100)
539 return ErrorP("Invalid precedecnce: must be 1..100");
540 BinaryPrecedence = (unsigned)NumVal;
547 return ErrorP("Expected '(' in prototype");
549 std::vector<std::string> ArgNames;
550 while (getNextToken() == tok_identifier)
551 ArgNames.push_back(IdentifierStr);
553 return ErrorP("Expected ')' in prototype");
556 getNextToken(); // eat ')'.
558 // Verify right number of names for operator.
559 if (Kind && ArgNames.size() != Kind)
560 return ErrorP("Invalid number of operands for operator");
562 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
566 /// definition ::= 'def' prototype expression
567 static std::unique_ptr<FunctionAST> ParseDefinition() {
568 getNextToken(); // eat def.
569 auto Proto = ParsePrototype();
573 if (auto E = ParseExpression())
574 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
578 /// toplevelexpr ::= expression
579 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
580 if (auto E = ParseExpression()) {
581 // Make an anonymous proto.
582 auto Proto = llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
583 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
588 /// external ::= 'extern' prototype
589 static std::unique_ptr<PrototypeAST> ParseExtern() {
590 getNextToken(); // eat extern.
591 return ParsePrototype();
594 //===----------------------------------------------------------------------===//
596 //===----------------------------------------------------------------------===//
598 static Module *TheModule;
599 static IRBuilder<> Builder(getGlobalContext());
600 static std::map<std::string, Value *> NamedValues;
601 static legacy::FunctionPassManager *TheFPM;
603 Value *ErrorV(const char *Str) {
608 Value *NumberExprAST::Codegen() {
609 return ConstantFP::get(getGlobalContext(), APFloat(Val));
612 Value *VariableExprAST::Codegen() {
613 // Look this variable up in the function.
614 Value *V = NamedValues[Name];
615 return V ? V : ErrorV("Unknown variable name");
618 Value *UnaryExprAST::Codegen() {
619 Value *OperandV = Operand->Codegen();
623 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
625 return ErrorV("Unknown unary operator");
627 return Builder.CreateCall(F, OperandV, "unop");
630 Value *BinaryExprAST::Codegen() {
631 Value *L = LHS->Codegen();
632 Value *R = RHS->Codegen();
638 return Builder.CreateFAdd(L, R, "addtmp");
640 return Builder.CreateFSub(L, R, "subtmp");
642 return Builder.CreateFMul(L, R, "multmp");
644 L = Builder.CreateFCmpULT(L, R, "cmptmp");
645 // Convert bool 0/1 to double 0.0 or 1.0
646 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
652 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
654 Function *F = TheModule->getFunction(std::string("binary") + Op);
655 assert(F && "binary operator not found!");
657 Value *Ops[] = { L, R };
658 return Builder.CreateCall(F, Ops, "binop");
661 Value *CallExprAST::Codegen() {
662 // Look up the name in the global module table.
663 Function *CalleeF = TheModule->getFunction(Callee);
665 return ErrorV("Unknown function referenced");
667 // If argument mismatch error.
668 if (CalleeF->arg_size() != Args.size())
669 return ErrorV("Incorrect # arguments passed");
671 std::vector<Value *> ArgsV;
672 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
673 ArgsV.push_back(Args[i]->Codegen());
678 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
681 Value *IfExprAST::Codegen() {
682 Value *CondV = Cond->Codegen();
686 // Convert condition to a bool by comparing equal to 0.0.
687 CondV = Builder.CreateFCmpONE(
688 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
690 Function *TheFunction = Builder.GetInsertBlock()->getParent();
692 // Create blocks for the then and else cases. Insert the 'then' block at the
693 // end of the function.
695 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
696 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
697 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
699 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
702 Builder.SetInsertPoint(ThenBB);
704 Value *ThenV = Then->Codegen();
708 Builder.CreateBr(MergeBB);
709 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
710 ThenBB = Builder.GetInsertBlock();
713 TheFunction->getBasicBlockList().push_back(ElseBB);
714 Builder.SetInsertPoint(ElseBB);
716 Value *ElseV = Else->Codegen();
720 Builder.CreateBr(MergeBB);
721 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
722 ElseBB = Builder.GetInsertBlock();
725 TheFunction->getBasicBlockList().push_back(MergeBB);
726 Builder.SetInsertPoint(MergeBB);
728 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
730 PN->addIncoming(ThenV, ThenBB);
731 PN->addIncoming(ElseV, ElseBB);
735 Value *ForExprAST::Codegen() {
741 // variable = phi [start, loopheader], [nextvariable, loopend]
747 // nextvariable = variable + step
749 // br endcond, loop, endloop
752 // Emit the start code first, without 'variable' in scope.
753 Value *StartVal = Start->Codegen();
757 // Make the new basic block for the loop header, inserting after current
759 Function *TheFunction = Builder.GetInsertBlock()->getParent();
760 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
762 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
764 // Insert an explicit fall through from the current block to the LoopBB.
765 Builder.CreateBr(LoopBB);
767 // Start insertion in LoopBB.
768 Builder.SetInsertPoint(LoopBB);
770 // Start the PHI node with an entry for Start.
771 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
773 Variable->addIncoming(StartVal, PreheaderBB);
775 // Within the loop, the variable is defined equal to the PHI node. If it
776 // shadows an existing variable, we have to restore it, so save it now.
777 Value *OldVal = NamedValues[VarName];
778 NamedValues[VarName] = Variable;
780 // Emit the body of the loop. This, like any other expr, can change the
781 // current BB. Note that we ignore the value computed by the body, but don't
783 if (!Body->Codegen())
786 // Emit the step value.
789 StepVal = Step->Codegen();
793 // If not specified, use 1.0.
794 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
797 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
799 // Compute the end condition.
800 Value *EndCond = End->Codegen();
804 // Convert condition to a bool by comparing equal to 0.0.
805 EndCond = Builder.CreateFCmpONE(
806 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
808 // Create the "after loop" block and insert it.
809 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
810 BasicBlock *AfterBB =
811 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
813 // Insert the conditional branch into the end of LoopEndBB.
814 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
816 // Any new code will be inserted in AfterBB.
817 Builder.SetInsertPoint(AfterBB);
819 // Add a new entry to the PHI node for the backedge.
820 Variable->addIncoming(NextVar, LoopEndBB);
822 // Restore the unshadowed variable.
824 NamedValues[VarName] = OldVal;
826 NamedValues.erase(VarName);
828 // for expr always returns 0.0.
829 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
832 Function *PrototypeAST::Codegen() {
833 // Make the function type: double(double,double) etc.
834 std::vector<Type *> Doubles(Args.size(),
835 Type::getDoubleTy(getGlobalContext()));
837 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
840 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
842 // If F conflicted, there was already something named 'Name'. If it has a
843 // body, don't allow redefinition or reextern.
844 if (F->getName() != Name) {
845 // Delete the one we just made and get the existing one.
846 F->eraseFromParent();
847 F = TheModule->getFunction(Name);
849 // If F already has a body, reject this.
851 ErrorF("redefinition of function");
855 // If F took a different number of args, reject.
856 if (F->arg_size() != Args.size()) {
857 ErrorF("redefinition of function with different # args");
862 // Set names for all arguments.
864 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
866 AI->setName(Args[Idx]);
868 // Add arguments to variable symbol table.
869 NamedValues[Args[Idx]] = AI;
875 Function *FunctionAST::Codegen() {
878 Function *TheFunction = Proto->Codegen();
882 // If this is an operator, install it.
883 if (Proto->isBinaryOp())
884 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
886 // Create a new basic block to start insertion into.
887 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
888 Builder.SetInsertPoint(BB);
890 if (Value *RetVal = Body->Codegen()) {
891 // Finish off the function.
892 Builder.CreateRet(RetVal);
894 // Validate the generated code, checking for consistency.
895 verifyFunction(*TheFunction);
897 // Optimize the function.
898 TheFPM->run(*TheFunction);
903 // Error reading body, remove function.
904 TheFunction->eraseFromParent();
906 if (Proto->isBinaryOp())
907 BinopPrecedence.erase(Proto->getOperatorName());
911 //===----------------------------------------------------------------------===//
912 // Top-Level parsing and JIT Driver
913 //===----------------------------------------------------------------------===//
915 static ExecutionEngine *TheExecutionEngine;
917 static void HandleDefinition() {
918 if (auto FnAST = ParseDefinition()) {
919 if (auto *FnIR = FnAST->Codegen()) {
920 fprintf(stderr, "Read function definition:");
924 // Skip token for error recovery.
929 static void HandleExtern() {
930 if (auto ProtoAST = ParseExtern()) {
931 if (auto *FnIR = ProtoAST->Codegen()) {
932 fprintf(stderr, "Read extern: ");
936 // Skip token for error recovery.
941 static void HandleTopLevelExpression() {
942 // Evaluate a top-level expression into an anonymous function.
943 if (auto FnAST = ParseTopLevelExpr()) {
944 if (auto *FnIR = FnAST->Codegen()) {
945 TheExecutionEngine->finalizeObject();
946 // JIT the function, returning a function pointer.
947 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
949 // Cast it to the right type (takes no arguments, returns a double) so we
950 // can call it as a native function.
951 double (*FP)() = (double (*)())(intptr_t)FPtr;
952 fprintf(stderr, "Evaluated to %f\n", FP());
955 // Skip token for error recovery.
960 /// top ::= definition | external | expression | ';'
961 static void MainLoop() {
963 fprintf(stderr, "ready> ");
969 break; // ignore top-level semicolons.
977 HandleTopLevelExpression();
983 //===----------------------------------------------------------------------===//
984 // "Library" functions that can be "extern'd" from user code.
985 //===----------------------------------------------------------------------===//
987 /// putchard - putchar that takes a double and returns 0.
988 extern "C" double putchard(double X) {
993 /// printd - printf that takes a double prints it as "%f\n", returning 0.
994 extern "C" double printd(double X) {
999 //===----------------------------------------------------------------------===//
1000 // Main driver code.
1001 //===----------------------------------------------------------------------===//
1004 InitializeNativeTarget();
1005 InitializeNativeTargetAsmPrinter();
1006 InitializeNativeTargetAsmParser();
1007 LLVMContext &Context = getGlobalContext();
1009 // Install standard binary operators.
1010 // 1 is lowest precedence.
1011 BinopPrecedence['<'] = 10;
1012 BinopPrecedence['+'] = 20;
1013 BinopPrecedence['-'] = 20;
1014 BinopPrecedence['*'] = 40; // highest.
1016 // Prime the first token.
1017 fprintf(stderr, "ready> ");
1020 // Make the module, which holds all the code.
1021 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1022 TheModule = Owner.get();
1024 // Create the JIT. This takes ownership of the module.
1026 TheExecutionEngine =
1027 EngineBuilder(std::move(Owner))
1028 .setErrorStr(&ErrStr)
1029 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1031 if (!TheExecutionEngine) {
1032 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1036 legacy::FunctionPassManager OurFPM(TheModule);
1038 // Set up the optimizer pipeline. Start with registering info about how the
1039 // target lays out data structures.
1040 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1041 // Provide basic AliasAnalysis support for GVN.
1042 OurFPM.add(createBasicAliasAnalysisPass());
1043 // Do simple "peephole" optimizations and bit-twiddling optzns.
1044 OurFPM.add(createInstructionCombiningPass());
1045 // Reassociate expressions.
1046 OurFPM.add(createReassociatePass());
1047 // Eliminate Common SubExpressions.
1048 OurFPM.add(createGVNPass());
1049 // Simplify the control flow graph (deleting unreachable blocks, etc).
1050 OurFPM.add(createCFGSimplificationPass());
1052 OurFPM.doInitialization();
1054 // Set the global so the code gen can use this.
1057 // Run the main "interpreter loop" now.
1062 // Print out all of the generated code.