1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/IR/DataLayout.h"
4 #include "llvm/IR/DerivedTypes.h"
5 #include "llvm/IR/IRBuilder.h"
6 #include "llvm/IR/LLVMContext.h"
7 #include "llvm/IR/Module.h"
8 #include "llvm/IR/Verifier.h"
9 #include "llvm/PassManager.h"
10 #include "llvm/Support/TargetSelect.h"
11 #include "llvm/Transforms/Scalar.h"
19 //===----------------------------------------------------------------------===//
21 //===----------------------------------------------------------------------===//
23 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
24 // of these for known things.
29 tok_def = -2, tok_extern = -3,
32 tok_identifier = -4, tok_number = -5,
35 tok_if = -6, tok_then = -7, tok_else = -8,
36 tok_for = -9, tok_in = -10,
39 tok_binary = -11, tok_unary = -12
42 static std::string IdentifierStr; // Filled in if tok_identifier
43 static double NumVal; // Filled in if tok_number
45 /// gettok - Return the next token from standard input.
47 static int LastChar = ' ';
49 // Skip any whitespace.
50 while (isspace(LastChar))
53 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
54 IdentifierStr = LastChar;
55 while (isalnum((LastChar = getchar())))
56 IdentifierStr += LastChar;
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 return tok_identifier;
70 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
75 } while (isdigit(LastChar) || LastChar == '.');
77 NumVal = strtod(NumStr.c_str(), 0);
81 if (LastChar == '#') {
82 // Comment until end of line.
83 do LastChar = getchar();
84 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
90 // Check for end of file. Don't eat the EOF.
94 // Otherwise, just return the character as its ascii value.
95 int ThisChar = LastChar;
100 //===----------------------------------------------------------------------===//
101 // Abstract Syntax Tree (aka Parse Tree)
102 //===----------------------------------------------------------------------===//
104 /// ExprAST - Base class for all expression nodes.
107 virtual ~ExprAST() {}
108 virtual Value *Codegen() = 0;
111 /// NumberExprAST - Expression class for numeric literals like "1.0".
112 class NumberExprAST : public ExprAST {
115 NumberExprAST(double val) : Val(val) {}
116 virtual Value *Codegen();
119 /// VariableExprAST - Expression class for referencing a variable, like "a".
120 class VariableExprAST : public ExprAST {
123 VariableExprAST(const std::string &name) : Name(name) {}
124 virtual Value *Codegen();
127 /// UnaryExprAST - Expression class for a unary operator.
128 class UnaryExprAST : public ExprAST {
132 UnaryExprAST(char opcode, ExprAST *operand)
133 : Opcode(opcode), Operand(operand) {}
134 virtual Value *Codegen();
137 /// BinaryExprAST - Expression class for a binary operator.
138 class BinaryExprAST : public ExprAST {
142 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
143 : Op(op), LHS(lhs), RHS(rhs) {}
144 virtual Value *Codegen();
147 /// CallExprAST - Expression class for function calls.
148 class CallExprAST : public ExprAST {
150 std::vector<ExprAST*> Args;
152 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
153 : Callee(callee), Args(args) {}
154 virtual Value *Codegen();
157 /// IfExprAST - Expression class for if/then/else.
158 class IfExprAST : public ExprAST {
159 ExprAST *Cond, *Then, *Else;
161 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
162 : Cond(cond), Then(then), Else(_else) {}
163 virtual Value *Codegen();
166 /// ForExprAST - Expression class for for/in.
167 class ForExprAST : public ExprAST {
169 ExprAST *Start, *End, *Step, *Body;
171 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
172 ExprAST *step, ExprAST *body)
173 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
174 virtual Value *Codegen();
177 /// PrototypeAST - This class represents the "prototype" for a function,
178 /// which captures its name, and its argument names (thus implicitly the number
179 /// of arguments the function takes), as well as if it is an operator.
182 std::vector<std::string> Args;
184 unsigned Precedence; // Precedence if a binary op.
186 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
187 bool isoperator = false, unsigned prec = 0)
188 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
190 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
191 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
193 char getOperatorName() const {
194 assert(isUnaryOp() || isBinaryOp());
195 return Name[Name.size()-1];
198 unsigned getBinaryPrecedence() const { return Precedence; }
203 /// FunctionAST - This class represents a function definition itself.
208 FunctionAST(PrototypeAST *proto, ExprAST *body)
209 : Proto(proto), Body(body) {}
213 } // end anonymous namespace
215 //===----------------------------------------------------------------------===//
217 //===----------------------------------------------------------------------===//
219 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
220 /// token the parser is looking at. getNextToken reads another token from the
221 /// lexer and updates CurTok with its results.
223 static int getNextToken() {
224 return CurTok = gettok();
227 /// BinopPrecedence - This holds the precedence for each binary operator that is
229 static std::map<char, int> BinopPrecedence;
231 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
232 static int GetTokPrecedence() {
233 if (!isascii(CurTok))
236 // Make sure it's a declared binop.
237 int TokPrec = BinopPrecedence[CurTok];
238 if (TokPrec <= 0) return -1;
242 /// Error* - These are little helper functions for error handling.
243 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
244 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
245 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
247 static ExprAST *ParseExpression();
251 /// ::= identifier '(' expression* ')'
252 static ExprAST *ParseIdentifierExpr() {
253 std::string IdName = IdentifierStr;
255 getNextToken(); // eat identifier.
257 if (CurTok != '(') // Simple variable ref.
258 return new VariableExprAST(IdName);
261 getNextToken(); // eat (
262 std::vector<ExprAST*> Args;
265 ExprAST *Arg = ParseExpression();
269 if (CurTok == ')') break;
272 return Error("Expected ')' or ',' in argument list");
280 return new CallExprAST(IdName, Args);
283 /// numberexpr ::= number
284 static ExprAST *ParseNumberExpr() {
285 ExprAST *Result = new NumberExprAST(NumVal);
286 getNextToken(); // consume the number
290 /// parenexpr ::= '(' expression ')'
291 static ExprAST *ParseParenExpr() {
292 getNextToken(); // eat (.
293 ExprAST *V = ParseExpression();
297 return Error("expected ')'");
298 getNextToken(); // eat ).
302 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
303 static ExprAST *ParseIfExpr() {
304 getNextToken(); // eat the if.
307 ExprAST *Cond = ParseExpression();
310 if (CurTok != tok_then)
311 return Error("expected then");
312 getNextToken(); // eat the then
314 ExprAST *Then = ParseExpression();
315 if (Then == 0) return 0;
317 if (CurTok != tok_else)
318 return Error("expected else");
322 ExprAST *Else = ParseExpression();
325 return new IfExprAST(Cond, Then, Else);
328 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
329 static ExprAST *ParseForExpr() {
330 getNextToken(); // eat the for.
332 if (CurTok != tok_identifier)
333 return Error("expected identifier after for");
335 std::string IdName = IdentifierStr;
336 getNextToken(); // eat identifier.
339 return Error("expected '=' after for");
340 getNextToken(); // eat '='.
343 ExprAST *Start = ParseExpression();
344 if (Start == 0) return 0;
346 return Error("expected ',' after for start value");
349 ExprAST *End = ParseExpression();
350 if (End == 0) return 0;
352 // The step value is optional.
356 Step = ParseExpression();
357 if (Step == 0) return 0;
360 if (CurTok != tok_in)
361 return Error("expected 'in' after for");
362 getNextToken(); // eat 'in'.
364 ExprAST *Body = ParseExpression();
365 if (Body == 0) return 0;
367 return new ForExprAST(IdName, Start, End, Step, Body);
371 /// ::= identifierexpr
376 static ExprAST *ParsePrimary() {
378 default: return Error("unknown token when expecting an expression");
379 case tok_identifier: return ParseIdentifierExpr();
380 case tok_number: return ParseNumberExpr();
381 case '(': return ParseParenExpr();
382 case tok_if: return ParseIfExpr();
383 case tok_for: return ParseForExpr();
390 static ExprAST *ParseUnary() {
391 // If the current token is not an operator, it must be a primary expr.
392 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
393 return ParsePrimary();
395 // If this is a unary operator, read it.
398 if (ExprAST *Operand = ParseUnary())
399 return new UnaryExprAST(Opc, Operand);
405 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
406 // If this is a binop, find its precedence.
408 int TokPrec = GetTokPrecedence();
410 // If this is a binop that binds at least as tightly as the current binop,
411 // consume it, otherwise we are done.
412 if (TokPrec < ExprPrec)
415 // Okay, we know this is a binop.
417 getNextToken(); // eat binop
419 // Parse the unary expression after the binary operator.
420 ExprAST *RHS = ParseUnary();
423 // If BinOp binds less tightly with RHS than the operator after RHS, let
424 // the pending operator take RHS as its LHS.
425 int NextPrec = GetTokPrecedence();
426 if (TokPrec < NextPrec) {
427 RHS = ParseBinOpRHS(TokPrec+1, RHS);
428 if (RHS == 0) return 0;
432 LHS = new BinaryExprAST(BinOp, LHS, RHS);
437 /// ::= unary binoprhs
439 static ExprAST *ParseExpression() {
440 ExprAST *LHS = ParseUnary();
443 return ParseBinOpRHS(0, LHS);
447 /// ::= id '(' id* ')'
448 /// ::= binary LETTER number? (id, id)
449 /// ::= unary LETTER (id)
450 static PrototypeAST *ParsePrototype() {
453 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
454 unsigned BinaryPrecedence = 30;
458 return ErrorP("Expected function name in prototype");
460 FnName = IdentifierStr;
466 if (!isascii(CurTok))
467 return ErrorP("Expected unary operator");
469 FnName += (char)CurTok;
475 if (!isascii(CurTok))
476 return ErrorP("Expected binary operator");
478 FnName += (char)CurTok;
482 // Read the precedence if present.
483 if (CurTok == tok_number) {
484 if (NumVal < 1 || NumVal > 100)
485 return ErrorP("Invalid precedecnce: must be 1..100");
486 BinaryPrecedence = (unsigned)NumVal;
493 return ErrorP("Expected '(' in prototype");
495 std::vector<std::string> ArgNames;
496 while (getNextToken() == tok_identifier)
497 ArgNames.push_back(IdentifierStr);
499 return ErrorP("Expected ')' in prototype");
502 getNextToken(); // eat ')'.
504 // Verify right number of names for operator.
505 if (Kind && ArgNames.size() != Kind)
506 return ErrorP("Invalid number of operands for operator");
508 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
511 /// definition ::= 'def' prototype expression
512 static FunctionAST *ParseDefinition() {
513 getNextToken(); // eat def.
514 PrototypeAST *Proto = ParsePrototype();
515 if (Proto == 0) return 0;
517 if (ExprAST *E = ParseExpression())
518 return new FunctionAST(Proto, E);
522 /// toplevelexpr ::= expression
523 static FunctionAST *ParseTopLevelExpr() {
524 if (ExprAST *E = ParseExpression()) {
525 // Make an anonymous proto.
526 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
527 return new FunctionAST(Proto, E);
532 /// external ::= 'extern' prototype
533 static PrototypeAST *ParseExtern() {
534 getNextToken(); // eat extern.
535 return ParsePrototype();
538 //===----------------------------------------------------------------------===//
540 //===----------------------------------------------------------------------===//
542 static Module *TheModule;
543 static IRBuilder<> Builder(getGlobalContext());
544 static std::map<std::string, Value*> NamedValues;
545 static FunctionPassManager *TheFPM;
547 Value *ErrorV(const char *Str) { Error(Str); return 0; }
549 Value *NumberExprAST::Codegen() {
550 return ConstantFP::get(getGlobalContext(), APFloat(Val));
553 Value *VariableExprAST::Codegen() {
554 // Look this variable up in the function.
555 Value *V = NamedValues[Name];
556 return V ? V : ErrorV("Unknown variable name");
559 Value *UnaryExprAST::Codegen() {
560 Value *OperandV = Operand->Codegen();
561 if (OperandV == 0) return 0;
563 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
565 return ErrorV("Unknown unary operator");
567 return Builder.CreateCall(F, OperandV, "unop");
570 Value *BinaryExprAST::Codegen() {
571 Value *L = LHS->Codegen();
572 Value *R = RHS->Codegen();
573 if (L == 0 || R == 0) return 0;
576 case '+': return Builder.CreateFAdd(L, R, "addtmp");
577 case '-': return Builder.CreateFSub(L, R, "subtmp");
578 case '*': return Builder.CreateFMul(L, R, "multmp");
580 L = Builder.CreateFCmpULT(L, R, "cmptmp");
581 // Convert bool 0/1 to double 0.0 or 1.0
582 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
587 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
589 Function *F = TheModule->getFunction(std::string("binary")+Op);
590 assert(F && "binary operator not found!");
592 Value *Ops[] = { L, R };
593 return Builder.CreateCall(F, Ops, "binop");
596 Value *CallExprAST::Codegen() {
597 // Look up the name in the global module table.
598 Function *CalleeF = TheModule->getFunction(Callee);
600 return ErrorV("Unknown function referenced");
602 // If argument mismatch error.
603 if (CalleeF->arg_size() != Args.size())
604 return ErrorV("Incorrect # arguments passed");
606 std::vector<Value*> ArgsV;
607 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
608 ArgsV.push_back(Args[i]->Codegen());
609 if (ArgsV.back() == 0) return 0;
612 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
615 Value *IfExprAST::Codegen() {
616 Value *CondV = Cond->Codegen();
617 if (CondV == 0) return 0;
619 // Convert condition to a bool by comparing equal to 0.0.
620 CondV = Builder.CreateFCmpONE(CondV,
621 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
624 Function *TheFunction = Builder.GetInsertBlock()->getParent();
626 // Create blocks for the then and else cases. Insert the 'then' block at the
627 // end of the function.
628 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
629 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
630 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
632 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
635 Builder.SetInsertPoint(ThenBB);
637 Value *ThenV = Then->Codegen();
638 if (ThenV == 0) return 0;
640 Builder.CreateBr(MergeBB);
641 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
642 ThenBB = Builder.GetInsertBlock();
645 TheFunction->getBasicBlockList().push_back(ElseBB);
646 Builder.SetInsertPoint(ElseBB);
648 Value *ElseV = Else->Codegen();
649 if (ElseV == 0) return 0;
651 Builder.CreateBr(MergeBB);
652 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
653 ElseBB = Builder.GetInsertBlock();
656 TheFunction->getBasicBlockList().push_back(MergeBB);
657 Builder.SetInsertPoint(MergeBB);
658 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
661 PN->addIncoming(ThenV, ThenBB);
662 PN->addIncoming(ElseV, ElseBB);
666 Value *ForExprAST::Codegen() {
672 // variable = phi [start, loopheader], [nextvariable, loopend]
678 // nextvariable = variable + step
680 // br endcond, loop, endloop
683 // Emit the start code first, without 'variable' in scope.
684 Value *StartVal = Start->Codegen();
685 if (StartVal == 0) return 0;
687 // Make the new basic block for the loop header, inserting after current
689 Function *TheFunction = Builder.GetInsertBlock()->getParent();
690 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
691 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
693 // Insert an explicit fall through from the current block to the LoopBB.
694 Builder.CreateBr(LoopBB);
696 // Start insertion in LoopBB.
697 Builder.SetInsertPoint(LoopBB);
699 // Start the PHI node with an entry for Start.
700 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
701 Variable->addIncoming(StartVal, PreheaderBB);
703 // Within the loop, the variable is defined equal to the PHI node. If it
704 // shadows an existing variable, we have to restore it, so save it now.
705 Value *OldVal = NamedValues[VarName];
706 NamedValues[VarName] = Variable;
708 // Emit the body of the loop. This, like any other expr, can change the
709 // current BB. Note that we ignore the value computed by the body, but don't
711 if (Body->Codegen() == 0)
714 // Emit the step value.
717 StepVal = Step->Codegen();
718 if (StepVal == 0) return 0;
720 // If not specified, use 1.0.
721 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
724 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
726 // Compute the end condition.
727 Value *EndCond = End->Codegen();
728 if (EndCond == 0) return EndCond;
730 // Convert condition to a bool by comparing equal to 0.0.
731 EndCond = Builder.CreateFCmpONE(EndCond,
732 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
735 // Create the "after loop" block and insert it.
736 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
737 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
739 // Insert the conditional branch into the end of LoopEndBB.
740 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
742 // Any new code will be inserted in AfterBB.
743 Builder.SetInsertPoint(AfterBB);
745 // Add a new entry to the PHI node for the backedge.
746 Variable->addIncoming(NextVar, LoopEndBB);
748 // Restore the unshadowed variable.
750 NamedValues[VarName] = OldVal;
752 NamedValues.erase(VarName);
755 // for expr always returns 0.0.
756 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
759 Function *PrototypeAST::Codegen() {
760 // Make the function type: double(double,double) etc.
761 std::vector<Type*> Doubles(Args.size(),
762 Type::getDoubleTy(getGlobalContext()));
763 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
766 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
768 // If F conflicted, there was already something named 'Name'. If it has a
769 // body, don't allow redefinition or reextern.
770 if (F->getName() != Name) {
771 // Delete the one we just made and get the existing one.
772 F->eraseFromParent();
773 F = TheModule->getFunction(Name);
775 // If F already has a body, reject this.
777 ErrorF("redefinition of function");
781 // If F took a different number of args, reject.
782 if (F->arg_size() != Args.size()) {
783 ErrorF("redefinition of function with different # args");
788 // Set names for all arguments.
790 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
792 AI->setName(Args[Idx]);
794 // Add arguments to variable symbol table.
795 NamedValues[Args[Idx]] = AI;
801 Function *FunctionAST::Codegen() {
804 Function *TheFunction = Proto->Codegen();
805 if (TheFunction == 0)
808 // If this is an operator, install it.
809 if (Proto->isBinaryOp())
810 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
812 // Create a new basic block to start insertion into.
813 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
814 Builder.SetInsertPoint(BB);
816 if (Value *RetVal = Body->Codegen()) {
817 // Finish off the function.
818 Builder.CreateRet(RetVal);
820 // Validate the generated code, checking for consistency.
821 verifyFunction(*TheFunction);
823 // Optimize the function.
824 TheFPM->run(*TheFunction);
829 // Error reading body, remove function.
830 TheFunction->eraseFromParent();
832 if (Proto->isBinaryOp())
833 BinopPrecedence.erase(Proto->getOperatorName());
837 //===----------------------------------------------------------------------===//
838 // Top-Level parsing and JIT Driver
839 //===----------------------------------------------------------------------===//
841 static ExecutionEngine *TheExecutionEngine;
843 static void HandleDefinition() {
844 if (FunctionAST *F = ParseDefinition()) {
845 if (Function *LF = F->Codegen()) {
846 fprintf(stderr, "Read function definition:");
850 // Skip token for error recovery.
855 static void HandleExtern() {
856 if (PrototypeAST *P = ParseExtern()) {
857 if (Function *F = P->Codegen()) {
858 fprintf(stderr, "Read extern: ");
862 // Skip token for error recovery.
867 static void HandleTopLevelExpression() {
868 // Evaluate a top-level expression into an anonymous function.
869 if (FunctionAST *F = ParseTopLevelExpr()) {
870 if (Function *LF = F->Codegen()) {
871 // JIT the function, returning a function pointer.
872 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
874 // Cast it to the right type (takes no arguments, returns a double) so we
875 // can call it as a native function.
876 double (*FP)() = (double (*)())(intptr_t)FPtr;
877 fprintf(stderr, "Evaluated to %f\n", FP());
880 // Skip token for error recovery.
885 /// top ::= definition | external | expression | ';'
886 static void MainLoop() {
888 fprintf(stderr, "ready> ");
890 case tok_eof: return;
891 case ';': getNextToken(); break; // ignore top-level semicolons.
892 case tok_def: HandleDefinition(); break;
893 case tok_extern: HandleExtern(); break;
894 default: HandleTopLevelExpression(); break;
899 //===----------------------------------------------------------------------===//
900 // "Library" functions that can be "extern'd" from user code.
901 //===----------------------------------------------------------------------===//
903 /// putchard - putchar that takes a double and returns 0.
905 double putchard(double X) {
910 /// printd - printf that takes a double prints it as "%f\n", returning 0.
912 double printd(double X) {
917 //===----------------------------------------------------------------------===//
919 //===----------------------------------------------------------------------===//
922 InitializeNativeTarget();
923 LLVMContext &Context = getGlobalContext();
925 // Install standard binary operators.
926 // 1 is lowest precedence.
927 BinopPrecedence['<'] = 10;
928 BinopPrecedence['+'] = 20;
929 BinopPrecedence['-'] = 20;
930 BinopPrecedence['*'] = 40; // highest.
932 // Prime the first token.
933 fprintf(stderr, "ready> ");
936 // Make the module, which holds all the code.
937 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
938 TheModule = Owner.get();
940 // Create the JIT. This takes ownership of the module.
943 EngineBuilder(std::move(Owner)).setErrorStr(&ErrStr).create();
944 if (!TheExecutionEngine) {
945 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
949 FunctionPassManager OurFPM(TheModule);
951 // Set up the optimizer pipeline. Start with registering info about how the
952 // target lays out data structures.
953 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
954 OurFPM.add(new DataLayoutPass());
955 // Provide basic AliasAnalysis support for GVN.
956 OurFPM.add(createBasicAliasAnalysisPass());
957 // Do simple "peephole" optimizations and bit-twiddling optzns.
958 OurFPM.add(createInstructionCombiningPass());
959 // Reassociate expressions.
960 OurFPM.add(createReassociatePass());
961 // Eliminate Common SubExpressions.
962 OurFPM.add(createGVNPass());
963 // Simplify the control flow graph (deleting unreachable blocks, etc).
964 OurFPM.add(createCFGSimplificationPass());
966 OurFPM.doInitialization();
968 // Set the global so the code gen can use this.
971 // Run the main "interpreter loop" now.
976 // Print out all of the generated code.