1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/Passes.h"
3 #include "llvm/ExecutionEngine/ExecutionEngine.h"
4 #include "llvm/ExecutionEngine/MCJIT.h"
5 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
6 #include "llvm/IR/DataLayout.h"
7 #include "llvm/IR/DerivedTypes.h"
8 #include "llvm/IR/IRBuilder.h"
9 #include "llvm/IR/LLVMContext.h"
10 #include "llvm/IR/LegacyPassManager.h"
11 #include "llvm/IR/Module.h"
12 #include "llvm/IR/Verifier.h"
13 #include "llvm/Support/TargetSelect.h"
14 #include "llvm/Transforms/Scalar.h"
22 //===----------------------------------------------------------------------===//
24 //===----------------------------------------------------------------------===//
26 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
27 // of these for known things.
51 static std::string IdentifierStr; // Filled in if tok_identifier
52 static double NumVal; // Filled in if tok_number
54 /// gettok - Return the next token from standard input.
56 static int LastChar = ' ';
58 // Skip any whitespace.
59 while (isspace(LastChar))
62 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
63 IdentifierStr = LastChar;
64 while (isalnum((LastChar = getchar())))
65 IdentifierStr += LastChar;
67 if (IdentifierStr == "def")
69 if (IdentifierStr == "extern")
71 if (IdentifierStr == "if")
73 if (IdentifierStr == "then")
75 if (IdentifierStr == "else")
77 if (IdentifierStr == "for")
79 if (IdentifierStr == "in")
81 if (IdentifierStr == "binary")
83 if (IdentifierStr == "unary")
85 return tok_identifier;
88 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
93 } while (isdigit(LastChar) || LastChar == '.');
95 NumVal = strtod(NumStr.c_str(), 0);
99 if (LastChar == '#') {
100 // Comment until end of line.
102 LastChar = getchar();
103 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
109 // Check for end of file. Don't eat the EOF.
113 // Otherwise, just return the character as its ascii value.
114 int ThisChar = LastChar;
115 LastChar = getchar();
119 //===----------------------------------------------------------------------===//
120 // Abstract Syntax Tree (aka Parse Tree)
121 //===----------------------------------------------------------------------===//
123 /// ExprAST - Base class for all expression nodes.
126 virtual ~ExprAST() {}
127 virtual Value *Codegen() = 0;
130 /// NumberExprAST - Expression class for numeric literals like "1.0".
131 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 {
144 VariableExprAST(const std::string &name) : Name(name) {}
145 Value *Codegen() override;
148 /// UnaryExprAST - Expression class for a unary operator.
149 class UnaryExprAST : public ExprAST {
154 UnaryExprAST(char opcode, ExprAST *operand)
155 : Opcode(opcode), Operand(operand) {}
156 Value *Codegen() override;
159 /// BinaryExprAST - Expression class for a binary operator.
160 class BinaryExprAST : public ExprAST {
165 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
166 : Op(op), LHS(lhs), RHS(rhs) {}
167 Value *Codegen() override;
170 /// CallExprAST - Expression class for function calls.
171 class CallExprAST : public ExprAST {
173 std::vector<ExprAST *> Args;
176 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
177 : Callee(callee), Args(args) {}
178 Value *Codegen() override;
181 /// IfExprAST - Expression class for if/then/else.
182 class IfExprAST : public ExprAST {
183 ExprAST *Cond, *Then, *Else;
186 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
187 : Cond(cond), Then(then), Else(_else) {}
188 Value *Codegen() override;
191 /// ForExprAST - Expression class for for/in.
192 class ForExprAST : public ExprAST {
194 ExprAST *Start, *End, *Step, *Body;
197 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
198 ExprAST *step, ExprAST *body)
199 : VarName(varname), Start(start), End(end), Step(step), Body(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, const std::vector<std::string> &args,
213 bool isoperator = false, unsigned prec = 0)
214 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
216 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
217 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
219 char getOperatorName() const {
220 assert(isUnaryOp() || isBinaryOp());
221 return Name[Name.size() - 1];
224 unsigned getBinaryPrecedence() const { return Precedence; }
229 /// FunctionAST - This class represents a function definition itself.
235 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(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 ExprAST *Error(const char *Str) {
269 fprintf(stderr, "Error: %s\n", Str);
272 PrototypeAST *ErrorP(const char *Str) {
276 FunctionAST *ErrorF(const char *Str) {
281 static ExprAST *ParseExpression();
285 /// ::= identifier '(' expression* ')'
286 static ExprAST *ParseIdentifierExpr() {
287 std::string IdName = IdentifierStr;
289 getNextToken(); // eat identifier.
291 if (CurTok != '(') // Simple variable ref.
292 return new VariableExprAST(IdName);
295 getNextToken(); // eat (
296 std::vector<ExprAST *> Args;
299 ExprAST *Arg = ParseExpression();
308 return Error("Expected ')' or ',' in argument list");
316 return new CallExprAST(IdName, Args);
319 /// numberexpr ::= number
320 static ExprAST *ParseNumberExpr() {
321 ExprAST *Result = new NumberExprAST(NumVal);
322 getNextToken(); // consume the number
326 /// parenexpr ::= '(' expression ')'
327 static ExprAST *ParseParenExpr() {
328 getNextToken(); // eat (.
329 ExprAST *V = ParseExpression();
334 return Error("expected ')'");
335 getNextToken(); // eat ).
339 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
340 static ExprAST *ParseIfExpr() {
341 getNextToken(); // eat the if.
344 ExprAST *Cond = ParseExpression();
348 if (CurTok != tok_then)
349 return Error("expected then");
350 getNextToken(); // eat the then
352 ExprAST *Then = ParseExpression();
356 if (CurTok != tok_else)
357 return Error("expected else");
361 ExprAST *Else = ParseExpression();
365 return new IfExprAST(Cond, Then, Else);
368 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
369 static ExprAST *ParseForExpr() {
370 getNextToken(); // eat the for.
372 if (CurTok != tok_identifier)
373 return Error("expected identifier after for");
375 std::string IdName = IdentifierStr;
376 getNextToken(); // eat identifier.
379 return Error("expected '=' after for");
380 getNextToken(); // eat '='.
382 ExprAST *Start = ParseExpression();
386 return Error("expected ',' after for start value");
389 ExprAST *End = ParseExpression();
393 // The step value is optional.
397 Step = ParseExpression();
402 if (CurTok != tok_in)
403 return Error("expected 'in' after for");
404 getNextToken(); // eat 'in'.
406 ExprAST *Body = ParseExpression();
410 return new ForExprAST(IdName, Start, End, Step, Body);
414 /// ::= identifierexpr
419 static ExprAST *ParsePrimary() {
422 return Error("unknown token when expecting an expression");
424 return ParseIdentifierExpr();
426 return ParseNumberExpr();
428 return ParseParenExpr();
430 return ParseIfExpr();
432 return ParseForExpr();
439 static ExprAST *ParseUnary() {
440 // If the current token is not an operator, it must be a primary expr.
441 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
442 return ParsePrimary();
444 // If this is a unary operator, read it.
447 if (ExprAST *Operand = ParseUnary())
448 return new UnaryExprAST(Opc, Operand);
454 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
455 // If this is a binop, find its precedence.
457 int TokPrec = GetTokPrecedence();
459 // If this is a binop that binds at least as tightly as the current binop,
460 // consume it, otherwise we are done.
461 if (TokPrec < ExprPrec)
464 // Okay, we know this is a binop.
466 getNextToken(); // eat binop
468 // Parse the unary expression after the binary operator.
469 ExprAST *RHS = ParseUnary();
473 // If BinOp binds less tightly with RHS than the operator after RHS, let
474 // the pending operator take RHS as its LHS.
475 int NextPrec = GetTokPrecedence();
476 if (TokPrec < NextPrec) {
477 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
483 LHS = new BinaryExprAST(BinOp, LHS, RHS);
488 /// ::= unary binoprhs
490 static ExprAST *ParseExpression() {
491 ExprAST *LHS = ParseUnary();
495 return ParseBinOpRHS(0, LHS);
499 /// ::= id '(' id* ')'
500 /// ::= binary LETTER number? (id, id)
501 /// ::= unary LETTER (id)
502 static PrototypeAST *ParsePrototype() {
505 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
506 unsigned BinaryPrecedence = 30;
510 return ErrorP("Expected function name in prototype");
512 FnName = IdentifierStr;
518 if (!isascii(CurTok))
519 return ErrorP("Expected unary operator");
521 FnName += (char)CurTok;
527 if (!isascii(CurTok))
528 return ErrorP("Expected binary operator");
530 FnName += (char)CurTok;
534 // Read the precedence if present.
535 if (CurTok == tok_number) {
536 if (NumVal < 1 || NumVal > 100)
537 return ErrorP("Invalid precedecnce: must be 1..100");
538 BinaryPrecedence = (unsigned)NumVal;
545 return ErrorP("Expected '(' in prototype");
547 std::vector<std::string> ArgNames;
548 while (getNextToken() == tok_identifier)
549 ArgNames.push_back(IdentifierStr);
551 return ErrorP("Expected ')' in prototype");
554 getNextToken(); // eat ')'.
556 // Verify right number of names for operator.
557 if (Kind && ArgNames.size() != Kind)
558 return ErrorP("Invalid number of operands for operator");
560 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
563 /// definition ::= 'def' prototype expression
564 static FunctionAST *ParseDefinition() {
565 getNextToken(); // eat def.
566 PrototypeAST *Proto = ParsePrototype();
570 if (ExprAST *E = ParseExpression())
571 return new FunctionAST(Proto, E);
575 /// toplevelexpr ::= expression
576 static FunctionAST *ParseTopLevelExpr() {
577 if (ExprAST *E = ParseExpression()) {
578 // Make an anonymous proto.
579 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
580 return new FunctionAST(Proto, E);
585 /// external ::= 'extern' prototype
586 static PrototypeAST *ParseExtern() {
587 getNextToken(); // eat extern.
588 return ParsePrototype();
591 //===----------------------------------------------------------------------===//
593 //===----------------------------------------------------------------------===//
595 static Module *TheModule;
596 static IRBuilder<> Builder(getGlobalContext());
597 static std::map<std::string, Value *> NamedValues;
598 static legacy::FunctionPassManager *TheFPM;
600 Value *ErrorV(const char *Str) {
605 Value *NumberExprAST::Codegen() {
606 return ConstantFP::get(getGlobalContext(), APFloat(Val));
609 Value *VariableExprAST::Codegen() {
610 // Look this variable up in the function.
611 Value *V = NamedValues[Name];
612 return V ? V : ErrorV("Unknown variable name");
615 Value *UnaryExprAST::Codegen() {
616 Value *OperandV = Operand->Codegen();
620 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
622 return ErrorV("Unknown unary operator");
624 return Builder.CreateCall(F, OperandV, "unop");
627 Value *BinaryExprAST::Codegen() {
628 Value *L = LHS->Codegen();
629 Value *R = RHS->Codegen();
630 if (L == 0 || R == 0)
635 return Builder.CreateFAdd(L, R, "addtmp");
637 return Builder.CreateFSub(L, R, "subtmp");
639 return Builder.CreateFMul(L, R, "multmp");
641 L = Builder.CreateFCmpULT(L, R, "cmptmp");
642 // Convert bool 0/1 to double 0.0 or 1.0
643 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
649 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
651 Function *F = TheModule->getFunction(std::string("binary") + Op);
652 assert(F && "binary operator not found!");
654 Value *Ops[] = { L, R };
655 return Builder.CreateCall(F, Ops, "binop");
658 Value *CallExprAST::Codegen() {
659 // Look up the name in the global module table.
660 Function *CalleeF = TheModule->getFunction(Callee);
662 return ErrorV("Unknown function referenced");
664 // If argument mismatch error.
665 if (CalleeF->arg_size() != Args.size())
666 return ErrorV("Incorrect # arguments passed");
668 std::vector<Value *> ArgsV;
669 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
670 ArgsV.push_back(Args[i]->Codegen());
671 if (ArgsV.back() == 0)
675 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
678 Value *IfExprAST::Codegen() {
679 Value *CondV = Cond->Codegen();
683 // Convert condition to a bool by comparing equal to 0.0.
684 CondV = Builder.CreateFCmpONE(
685 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
687 Function *TheFunction = Builder.GetInsertBlock()->getParent();
689 // Create blocks for the then and else cases. Insert the 'then' block at the
690 // end of the function.
692 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
693 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
694 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
696 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
699 Builder.SetInsertPoint(ThenBB);
701 Value *ThenV = Then->Codegen();
705 Builder.CreateBr(MergeBB);
706 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
707 ThenBB = Builder.GetInsertBlock();
710 TheFunction->getBasicBlockList().push_back(ElseBB);
711 Builder.SetInsertPoint(ElseBB);
713 Value *ElseV = Else->Codegen();
717 Builder.CreateBr(MergeBB);
718 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
719 ElseBB = Builder.GetInsertBlock();
722 TheFunction->getBasicBlockList().push_back(MergeBB);
723 Builder.SetInsertPoint(MergeBB);
725 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
727 PN->addIncoming(ThenV, ThenBB);
728 PN->addIncoming(ElseV, ElseBB);
732 Value *ForExprAST::Codegen() {
738 // variable = phi [start, loopheader], [nextvariable, loopend]
744 // nextvariable = variable + step
746 // br endcond, loop, endloop
749 // Emit the start code first, without 'variable' in scope.
750 Value *StartVal = Start->Codegen();
754 // Make the new basic block for the loop header, inserting after current
756 Function *TheFunction = Builder.GetInsertBlock()->getParent();
757 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
759 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
761 // Insert an explicit fall through from the current block to the LoopBB.
762 Builder.CreateBr(LoopBB);
764 // Start insertion in LoopBB.
765 Builder.SetInsertPoint(LoopBB);
767 // Start the PHI node with an entry for Start.
768 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
770 Variable->addIncoming(StartVal, PreheaderBB);
772 // Within the loop, the variable is defined equal to the PHI node. If it
773 // shadows an existing variable, we have to restore it, so save it now.
774 Value *OldVal = NamedValues[VarName];
775 NamedValues[VarName] = Variable;
777 // Emit the body of the loop. This, like any other expr, can change the
778 // current BB. Note that we ignore the value computed by the body, but don't
780 if (Body->Codegen() == 0)
783 // Emit the step value.
786 StepVal = Step->Codegen();
790 // If not specified, use 1.0.
791 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
794 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
796 // Compute the end condition.
797 Value *EndCond = End->Codegen();
801 // Convert condition to a bool by comparing equal to 0.0.
802 EndCond = Builder.CreateFCmpONE(
803 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
805 // Create the "after loop" block and insert it.
806 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
807 BasicBlock *AfterBB =
808 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
810 // Insert the conditional branch into the end of LoopEndBB.
811 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
813 // Any new code will be inserted in AfterBB.
814 Builder.SetInsertPoint(AfterBB);
816 // Add a new entry to the PHI node for the backedge.
817 Variable->addIncoming(NextVar, LoopEndBB);
819 // Restore the unshadowed variable.
821 NamedValues[VarName] = OldVal;
823 NamedValues.erase(VarName);
825 // for expr always returns 0.0.
826 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
829 Function *PrototypeAST::Codegen() {
830 // Make the function type: double(double,double) etc.
831 std::vector<Type *> Doubles(Args.size(),
832 Type::getDoubleTy(getGlobalContext()));
834 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
837 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
839 // If F conflicted, there was already something named 'Name'. If it has a
840 // body, don't allow redefinition or reextern.
841 if (F->getName() != Name) {
842 // Delete the one we just made and get the existing one.
843 F->eraseFromParent();
844 F = TheModule->getFunction(Name);
846 // If F already has a body, reject this.
848 ErrorF("redefinition of function");
852 // If F took a different number of args, reject.
853 if (F->arg_size() != Args.size()) {
854 ErrorF("redefinition of function with different # args");
859 // Set names for all arguments.
861 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
863 AI->setName(Args[Idx]);
865 // Add arguments to variable symbol table.
866 NamedValues[Args[Idx]] = AI;
872 Function *FunctionAST::Codegen() {
875 Function *TheFunction = Proto->Codegen();
876 if (TheFunction == 0)
879 // If this is an operator, install it.
880 if (Proto->isBinaryOp())
881 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
883 // Create a new basic block to start insertion into.
884 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
885 Builder.SetInsertPoint(BB);
887 if (Value *RetVal = Body->Codegen()) {
888 // Finish off the function.
889 Builder.CreateRet(RetVal);
891 // Validate the generated code, checking for consistency.
892 verifyFunction(*TheFunction);
894 // Optimize the function.
895 TheFPM->run(*TheFunction);
900 // Error reading body, remove function.
901 TheFunction->eraseFromParent();
903 if (Proto->isBinaryOp())
904 BinopPrecedence.erase(Proto->getOperatorName());
908 //===----------------------------------------------------------------------===//
909 // Top-Level parsing and JIT Driver
910 //===----------------------------------------------------------------------===//
912 static ExecutionEngine *TheExecutionEngine;
914 static void HandleDefinition() {
915 if (FunctionAST *F = ParseDefinition()) {
916 if (Function *LF = F->Codegen()) {
917 fprintf(stderr, "Read function definition:");
921 // Skip token for error recovery.
926 static void HandleExtern() {
927 if (PrototypeAST *P = ParseExtern()) {
928 if (Function *F = P->Codegen()) {
929 fprintf(stderr, "Read extern: ");
933 // Skip token for error recovery.
938 static void HandleTopLevelExpression() {
939 // Evaluate a top-level expression into an anonymous function.
940 if (FunctionAST *F = ParseTopLevelExpr()) {
941 if (Function *LF = F->Codegen()) {
942 TheExecutionEngine->finalizeObject();
943 // JIT the function, returning a function pointer.
944 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
946 // Cast it to the right type (takes no arguments, returns a double) so we
947 // can call it as a native function.
948 double (*FP)() = (double (*)())(intptr_t)FPtr;
949 fprintf(stderr, "Evaluated to %f\n", FP());
952 // Skip token for error recovery.
957 /// top ::= definition | external | expression | ';'
958 static void MainLoop() {
960 fprintf(stderr, "ready> ");
966 break; // ignore top-level semicolons.
974 HandleTopLevelExpression();
980 //===----------------------------------------------------------------------===//
981 // "Library" functions that can be "extern'd" from user code.
982 //===----------------------------------------------------------------------===//
984 /// putchard - putchar that takes a double and returns 0.
985 extern "C" double putchard(double X) {
990 /// printd - printf that takes a double prints it as "%f\n", returning 0.
991 extern "C" double printd(double X) {
996 //===----------------------------------------------------------------------===//
998 //===----------------------------------------------------------------------===//
1001 InitializeNativeTarget();
1002 InitializeNativeTargetAsmPrinter();
1003 InitializeNativeTargetAsmParser();
1004 LLVMContext &Context = getGlobalContext();
1006 // Install standard binary operators.
1007 // 1 is lowest precedence.
1008 BinopPrecedence['<'] = 10;
1009 BinopPrecedence['+'] = 20;
1010 BinopPrecedence['-'] = 20;
1011 BinopPrecedence['*'] = 40; // highest.
1013 // Prime the first token.
1014 fprintf(stderr, "ready> ");
1017 // Make the module, which holds all the code.
1018 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1019 TheModule = Owner.get();
1021 // Create the JIT. This takes ownership of the module.
1023 TheExecutionEngine =
1024 EngineBuilder(std::move(Owner))
1025 .setErrorStr(&ErrStr)
1026 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1028 if (!TheExecutionEngine) {
1029 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1033 legacy::FunctionPassManager OurFPM(TheModule);
1035 // Set up the optimizer pipeline. Start with registering info about how the
1036 // target lays out data structures.
1037 TheModule->setDataLayout(*TheExecutionEngine->getDataLayout());
1038 // Provide basic AliasAnalysis support for GVN.
1039 OurFPM.add(createBasicAliasAnalysisPass());
1040 // Do simple "peephole" optimizations and bit-twiddling optzns.
1041 OurFPM.add(createInstructionCombiningPass());
1042 // Reassociate expressions.
1043 OurFPM.add(createReassociatePass());
1044 // Eliminate Common SubExpressions.
1045 OurFPM.add(createGVNPass());
1046 // Simplify the control flow graph (deleting unreachable blocks, etc).
1047 OurFPM.add(createCFGSimplificationPass());
1049 OurFPM.doInitialization();
1051 // Set the global so the code gen can use this.
1054 // Run the main "interpreter loop" now.
1059 // Print out all of the generated code.