1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/Analysis/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 tok_binary = -11, tok_unary = -12
43 static std::string IdentifierStr; // Filled in if tok_identifier
44 static double NumVal; // Filled in if tok_number
46 /// gettok - Return the next token from standard input.
48 static int LastChar = ' ';
50 // Skip any whitespace.
51 while (isspace(LastChar))
54 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
55 IdentifierStr = LastChar;
56 while (isalnum((LastChar = getchar())))
57 IdentifierStr += LastChar;
59 if (IdentifierStr == "def") return tok_def;
60 if (IdentifierStr == "extern") return tok_extern;
61 if (IdentifierStr == "if") return tok_if;
62 if (IdentifierStr == "then") return tok_then;
63 if (IdentifierStr == "else") return tok_else;
64 if (IdentifierStr == "for") return tok_for;
65 if (IdentifierStr == "in") return tok_in;
66 if (IdentifierStr == "binary") return tok_binary;
67 if (IdentifierStr == "unary") return tok_unary;
68 return tok_identifier;
71 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
76 } while (isdigit(LastChar) || LastChar == '.');
78 NumVal = strtod(NumStr.c_str(), 0);
82 if (LastChar == '#') {
83 // Comment until end of line.
84 do LastChar = getchar();
85 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
91 // Check for end of file. Don't eat the EOF.
95 // Otherwise, just return the character as its ascii value.
96 int ThisChar = LastChar;
101 //===----------------------------------------------------------------------===//
102 // Abstract Syntax Tree (aka Parse Tree)
103 //===----------------------------------------------------------------------===//
105 /// ExprAST - Base class for all expression nodes.
109 virtual Value *Codegen() = 0;
112 // Provide out-of-line definition to prevent weak vtable.
113 ExprAST::~ExprAST() {}
115 /// NumberExprAST - Expression class for numeric literals like "1.0".
116 class NumberExprAST : public ExprAST {
119 NumberExprAST(double val) : Val(val) {}
120 virtual Value *Codegen();
123 /// VariableExprAST - Expression class for referencing a variable, like "a".
124 class VariableExprAST : public ExprAST {
127 VariableExprAST(const std::string &name) : Name(name) {}
128 virtual Value *Codegen();
131 /// UnaryExprAST - Expression class for a unary operator.
132 class UnaryExprAST : public ExprAST {
136 UnaryExprAST(char opcode, ExprAST *operand)
137 : Opcode(opcode), Operand(operand) {}
138 virtual Value *Codegen();
141 /// BinaryExprAST - Expression class for a binary operator.
142 class BinaryExprAST : public ExprAST {
146 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
147 : Op(op), LHS(lhs), RHS(rhs) {}
148 virtual Value *Codegen();
151 /// CallExprAST - Expression class for function calls.
152 class CallExprAST : public ExprAST {
154 std::vector<ExprAST*> Args;
156 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
157 : Callee(callee), Args(args) {}
158 virtual Value *Codegen();
161 /// IfExprAST - Expression class for if/then/else.
162 class IfExprAST : public ExprAST {
163 ExprAST *Cond, *Then, *Else;
165 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
166 : Cond(cond), Then(then), Else(_else) {}
167 virtual Value *Codegen();
170 /// ForExprAST - Expression class for for/in.
171 class ForExprAST : public ExprAST {
173 ExprAST *Start, *End, *Step, *Body;
175 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
176 ExprAST *step, ExprAST *body)
177 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
178 virtual Value *Codegen();
181 /// PrototypeAST - This class represents the "prototype" for a function,
182 /// which captures its name, and its argument names (thus implicitly the number
183 /// of arguments the function takes), as well as if it is an operator.
186 std::vector<std::string> Args;
188 unsigned Precedence; // Precedence if a binary op.
190 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
191 bool isoperator = false, unsigned prec = 0)
192 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
194 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
195 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
197 char getOperatorName() const {
198 assert(isUnaryOp() || isBinaryOp());
199 return Name[Name.size()-1];
202 unsigned getBinaryPrecedence() const { return Precedence; }
207 /// FunctionAST - This class represents a function definition itself.
212 FunctionAST(PrototypeAST *proto, ExprAST *body)
213 : Proto(proto), Body(body) {}
218 //===----------------------------------------------------------------------===//
220 //===----------------------------------------------------------------------===//
222 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
223 /// token the parser is looking at. getNextToken reads another token from the
224 /// lexer and updates CurTok with its results.
226 static int getNextToken() {
227 return CurTok = gettok();
230 /// BinopPrecedence - This holds the precedence for each binary operator that is
232 static std::map<char, int> BinopPrecedence;
234 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
235 static int GetTokPrecedence() {
236 if (!isascii(CurTok))
239 // Make sure it's a declared binop.
240 int TokPrec = BinopPrecedence[CurTok];
241 if (TokPrec <= 0) return -1;
245 /// Error* - These are little helper functions for error handling.
246 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
247 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
248 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
250 static ExprAST *ParseExpression();
254 /// ::= identifier '(' expression* ')'
255 static ExprAST *ParseIdentifierExpr() {
256 std::string IdName = IdentifierStr;
258 getNextToken(); // eat identifier.
260 if (CurTok != '(') // Simple variable ref.
261 return new VariableExprAST(IdName);
264 getNextToken(); // eat (
265 std::vector<ExprAST*> Args;
268 ExprAST *Arg = ParseExpression();
272 if (CurTok == ')') break;
275 return Error("Expected ')' or ',' in argument list");
283 return new CallExprAST(IdName, Args);
286 /// numberexpr ::= number
287 static ExprAST *ParseNumberExpr() {
288 ExprAST *Result = new NumberExprAST(NumVal);
289 getNextToken(); // consume the number
293 /// parenexpr ::= '(' expression ')'
294 static ExprAST *ParseParenExpr() {
295 getNextToken(); // eat (.
296 ExprAST *V = ParseExpression();
300 return Error("expected ')'");
301 getNextToken(); // eat ).
305 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
306 static ExprAST *ParseIfExpr() {
307 getNextToken(); // eat the if.
310 ExprAST *Cond = ParseExpression();
313 if (CurTok != tok_then)
314 return Error("expected then");
315 getNextToken(); // eat the then
317 ExprAST *Then = ParseExpression();
318 if (Then == 0) return 0;
320 if (CurTok != tok_else)
321 return Error("expected else");
325 ExprAST *Else = ParseExpression();
328 return new IfExprAST(Cond, Then, Else);
331 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
332 static ExprAST *ParseForExpr() {
333 getNextToken(); // eat the for.
335 if (CurTok != tok_identifier)
336 return Error("expected identifier after for");
338 std::string IdName = IdentifierStr;
339 getNextToken(); // eat identifier.
342 return Error("expected '=' after for");
343 getNextToken(); // eat '='.
346 ExprAST *Start = ParseExpression();
347 if (Start == 0) return 0;
349 return Error("expected ',' after for start value");
352 ExprAST *End = ParseExpression();
353 if (End == 0) return 0;
355 // The step value is optional.
359 Step = ParseExpression();
360 if (Step == 0) return 0;
363 if (CurTok != tok_in)
364 return Error("expected 'in' after for");
365 getNextToken(); // eat 'in'.
367 ExprAST *Body = ParseExpression();
368 if (Body == 0) return 0;
370 return new ForExprAST(IdName, Start, End, Step, Body);
374 /// ::= identifierexpr
379 static ExprAST *ParsePrimary() {
381 default: return Error("unknown token when expecting an expression");
382 case tok_identifier: return ParseIdentifierExpr();
383 case tok_number: return ParseNumberExpr();
384 case '(': return ParseParenExpr();
385 case tok_if: return ParseIfExpr();
386 case tok_for: return ParseForExpr();
393 static ExprAST *ParseUnary() {
394 // If the current token is not an operator, it must be a primary expr.
395 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
396 return ParsePrimary();
398 // If this is a unary operator, read it.
401 if (ExprAST *Operand = ParseUnary())
402 return new UnaryExprAST(Opc, Operand);
408 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
409 // If this is a binop, find its precedence.
411 int TokPrec = GetTokPrecedence();
413 // If this is a binop that binds at least as tightly as the current binop,
414 // consume it, otherwise we are done.
415 if (TokPrec < ExprPrec)
418 // Okay, we know this is a binop.
420 getNextToken(); // eat binop
422 // Parse the unary expression after the binary operator.
423 ExprAST *RHS = ParseUnary();
426 // If BinOp binds less tightly with RHS than the operator after RHS, let
427 // the pending operator take RHS as its LHS.
428 int NextPrec = GetTokPrecedence();
429 if (TokPrec < NextPrec) {
430 RHS = ParseBinOpRHS(TokPrec+1, RHS);
431 if (RHS == 0) return 0;
435 LHS = new BinaryExprAST(BinOp, LHS, RHS);
440 /// ::= unary binoprhs
442 static ExprAST *ParseExpression() {
443 ExprAST *LHS = ParseUnary();
446 return ParseBinOpRHS(0, LHS);
450 /// ::= id '(' id* ')'
451 /// ::= binary LETTER number? (id, id)
452 /// ::= unary LETTER (id)
453 static PrototypeAST *ParsePrototype() {
456 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
457 unsigned BinaryPrecedence = 30;
461 return ErrorP("Expected function name in prototype");
463 FnName = IdentifierStr;
469 if (!isascii(CurTok))
470 return ErrorP("Expected unary operator");
472 FnName += (char)CurTok;
478 if (!isascii(CurTok))
479 return ErrorP("Expected binary operator");
481 FnName += (char)CurTok;
485 // Read the precedence if present.
486 if (CurTok == tok_number) {
487 if (NumVal < 1 || NumVal > 100)
488 return ErrorP("Invalid precedecnce: must be 1..100");
489 BinaryPrecedence = (unsigned)NumVal;
496 return ErrorP("Expected '(' in prototype");
498 std::vector<std::string> ArgNames;
499 while (getNextToken() == tok_identifier)
500 ArgNames.push_back(IdentifierStr);
502 return ErrorP("Expected ')' in prototype");
505 getNextToken(); // eat ')'.
507 // Verify right number of names for operator.
508 if (Kind && ArgNames.size() != Kind)
509 return ErrorP("Invalid number of operands for operator");
511 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
514 /// definition ::= 'def' prototype expression
515 static FunctionAST *ParseDefinition() {
516 getNextToken(); // eat def.
517 PrototypeAST *Proto = ParsePrototype();
518 if (Proto == 0) return 0;
520 if (ExprAST *E = ParseExpression())
521 return new FunctionAST(Proto, E);
525 /// toplevelexpr ::= expression
526 static FunctionAST *ParseTopLevelExpr() {
527 if (ExprAST *E = ParseExpression()) {
528 // Make an anonymous proto.
529 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
530 return new FunctionAST(Proto, E);
535 /// external ::= 'extern' prototype
536 static PrototypeAST *ParseExtern() {
537 getNextToken(); // eat extern.
538 return ParsePrototype();
541 //===----------------------------------------------------------------------===//
543 //===----------------------------------------------------------------------===//
545 static Module *TheModule;
546 static IRBuilder<> Builder(getGlobalContext());
547 static std::map<std::string, Value*> NamedValues;
548 static FunctionPassManager *TheFPM;
550 Value *ErrorV(const char *Str) { Error(Str); return 0; }
552 Value *NumberExprAST::Codegen() {
553 return ConstantFP::get(getGlobalContext(), APFloat(Val));
556 Value *VariableExprAST::Codegen() {
557 // Look this variable up in the function.
558 Value *V = NamedValues[Name];
559 return V ? V : ErrorV("Unknown variable name");
562 Value *UnaryExprAST::Codegen() {
563 Value *OperandV = Operand->Codegen();
564 if (OperandV == 0) return 0;
566 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
568 return ErrorV("Unknown unary operator");
570 return Builder.CreateCall(F, OperandV, "unop");
573 Value *BinaryExprAST::Codegen() {
574 Value *L = LHS->Codegen();
575 Value *R = RHS->Codegen();
576 if (L == 0 || R == 0) return 0;
579 case '+': return Builder.CreateFAdd(L, R, "addtmp");
580 case '-': return Builder.CreateFSub(L, R, "subtmp");
581 case '*': return Builder.CreateFMul(L, R, "multmp");
583 L = Builder.CreateFCmpULT(L, R, "cmptmp");
584 // Convert bool 0/1 to double 0.0 or 1.0
585 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
590 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
592 Function *F = TheModule->getFunction(std::string("binary")+Op);
593 assert(F && "binary operator not found!");
595 Value *Ops[] = { L, R };
596 return Builder.CreateCall(F, Ops, "binop");
599 Value *CallExprAST::Codegen() {
600 // Look up the name in the global module table.
601 Function *CalleeF = TheModule->getFunction(Callee);
603 return ErrorV("Unknown function referenced");
605 // If argument mismatch error.
606 if (CalleeF->arg_size() != Args.size())
607 return ErrorV("Incorrect # arguments passed");
609 std::vector<Value*> ArgsV;
610 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
611 ArgsV.push_back(Args[i]->Codegen());
612 if (ArgsV.back() == 0) return 0;
615 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
618 Value *IfExprAST::Codegen() {
619 Value *CondV = Cond->Codegen();
620 if (CondV == 0) return 0;
622 // Convert condition to a bool by comparing equal to 0.0.
623 CondV = Builder.CreateFCmpONE(CondV,
624 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
627 Function *TheFunction = Builder.GetInsertBlock()->getParent();
629 // Create blocks for the then and else cases. Insert the 'then' block at the
630 // end of the function.
631 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
632 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
633 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
635 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
638 Builder.SetInsertPoint(ThenBB);
640 Value *ThenV = Then->Codegen();
641 if (ThenV == 0) return 0;
643 Builder.CreateBr(MergeBB);
644 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
645 ThenBB = Builder.GetInsertBlock();
648 TheFunction->getBasicBlockList().push_back(ElseBB);
649 Builder.SetInsertPoint(ElseBB);
651 Value *ElseV = Else->Codegen();
652 if (ElseV == 0) return 0;
654 Builder.CreateBr(MergeBB);
655 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
656 ElseBB = Builder.GetInsertBlock();
659 TheFunction->getBasicBlockList().push_back(MergeBB);
660 Builder.SetInsertPoint(MergeBB);
661 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
664 PN->addIncoming(ThenV, ThenBB);
665 PN->addIncoming(ElseV, ElseBB);
669 Value *ForExprAST::Codegen() {
675 // variable = phi [start, loopheader], [nextvariable, loopend]
681 // nextvariable = variable + step
683 // br endcond, loop, endloop
686 // Emit the start code first, without 'variable' in scope.
687 Value *StartVal = Start->Codegen();
688 if (StartVal == 0) return 0;
690 // Make the new basic block for the loop header, inserting after current
692 Function *TheFunction = Builder.GetInsertBlock()->getParent();
693 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
694 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
696 // Insert an explicit fall through from the current block to the LoopBB.
697 Builder.CreateBr(LoopBB);
699 // Start insertion in LoopBB.
700 Builder.SetInsertPoint(LoopBB);
702 // Start the PHI node with an entry for Start.
703 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
704 Variable->addIncoming(StartVal, PreheaderBB);
706 // Within the loop, the variable is defined equal to the PHI node. If it
707 // shadows an existing variable, we have to restore it, so save it now.
708 Value *OldVal = NamedValues[VarName];
709 NamedValues[VarName] = Variable;
711 // Emit the body of the loop. This, like any other expr, can change the
712 // current BB. Note that we ignore the value computed by the body, but don't
714 if (Body->Codegen() == 0)
717 // Emit the step value.
720 StepVal = Step->Codegen();
721 if (StepVal == 0) return 0;
723 // If not specified, use 1.0.
724 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
727 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
729 // Compute the end condition.
730 Value *EndCond = End->Codegen();
731 if (EndCond == 0) return EndCond;
733 // Convert condition to a bool by comparing equal to 0.0.
734 EndCond = Builder.CreateFCmpONE(EndCond,
735 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
738 // Create the "after loop" block and insert it.
739 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
740 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
742 // Insert the conditional branch into the end of LoopEndBB.
743 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
745 // Any new code will be inserted in AfterBB.
746 Builder.SetInsertPoint(AfterBB);
748 // Add a new entry to the PHI node for the backedge.
749 Variable->addIncoming(NextVar, LoopEndBB);
751 // Restore the unshadowed variable.
753 NamedValues[VarName] = OldVal;
755 NamedValues.erase(VarName);
758 // for expr always returns 0.0.
759 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
762 Function *PrototypeAST::Codegen() {
763 // Make the function type: double(double,double) etc.
764 std::vector<Type*> Doubles(Args.size(),
765 Type::getDoubleTy(getGlobalContext()));
766 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
769 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
771 // If F conflicted, there was already something named 'Name'. If it has a
772 // body, don't allow redefinition or reextern.
773 if (F->getName() != Name) {
774 // Delete the one we just made and get the existing one.
775 F->eraseFromParent();
776 F = TheModule->getFunction(Name);
778 // If F already has a body, reject this.
780 ErrorF("redefinition of function");
784 // If F took a different number of args, reject.
785 if (F->arg_size() != Args.size()) {
786 ErrorF("redefinition of function with different # args");
791 // Set names for all arguments.
793 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
795 AI->setName(Args[Idx]);
797 // Add arguments to variable symbol table.
798 NamedValues[Args[Idx]] = AI;
804 Function *FunctionAST::Codegen() {
807 Function *TheFunction = Proto->Codegen();
808 if (TheFunction == 0)
811 // If this is an operator, install it.
812 if (Proto->isBinaryOp())
813 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
815 // Create a new basic block to start insertion into.
816 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
817 Builder.SetInsertPoint(BB);
819 if (Value *RetVal = Body->Codegen()) {
820 // Finish off the function.
821 Builder.CreateRet(RetVal);
823 // Validate the generated code, checking for consistency.
824 verifyFunction(*TheFunction);
826 // Optimize the function.
827 TheFPM->run(*TheFunction);
832 // Error reading body, remove function.
833 TheFunction->eraseFromParent();
835 if (Proto->isBinaryOp())
836 BinopPrecedence.erase(Proto->getOperatorName());
840 //===----------------------------------------------------------------------===//
841 // Top-Level parsing and JIT Driver
842 //===----------------------------------------------------------------------===//
844 static ExecutionEngine *TheExecutionEngine;
846 static void HandleDefinition() {
847 if (FunctionAST *F = ParseDefinition()) {
848 if (Function *LF = F->Codegen()) {
849 fprintf(stderr, "Read function definition:");
853 // Skip token for error recovery.
858 static void HandleExtern() {
859 if (PrototypeAST *P = ParseExtern()) {
860 if (Function *F = P->Codegen()) {
861 fprintf(stderr, "Read extern: ");
865 // Skip token for error recovery.
870 static void HandleTopLevelExpression() {
871 // Evaluate a top-level expression into an anonymous function.
872 if (FunctionAST *F = ParseTopLevelExpr()) {
873 if (Function *LF = F->Codegen()) {
874 // JIT the function, returning a function pointer.
875 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
877 // Cast it to the right type (takes no arguments, returns a double) so we
878 // can call it as a native function.
879 double (*FP)() = (double (*)())(intptr_t)FPtr;
880 fprintf(stderr, "Evaluated to %f\n", FP());
883 // Skip token for error recovery.
888 /// top ::= definition | external | expression | ';'
889 static void MainLoop() {
891 fprintf(stderr, "ready> ");
893 case tok_eof: return;
894 case ';': getNextToken(); break; // ignore top-level semicolons.
895 case tok_def: HandleDefinition(); break;
896 case tok_extern: HandleExtern(); break;
897 default: HandleTopLevelExpression(); break;
902 //===----------------------------------------------------------------------===//
903 // "Library" functions that can be "extern'd" from user code.
904 //===----------------------------------------------------------------------===//
906 /// putchard - putchar that takes a double and returns 0.
908 double putchard(double X) {
913 /// printd - printf that takes a double prints it as "%f\n", returning 0.
915 double printd(double X) {
920 //===----------------------------------------------------------------------===//
922 //===----------------------------------------------------------------------===//
925 InitializeNativeTarget();
926 LLVMContext &Context = getGlobalContext();
928 // Install standard binary operators.
929 // 1 is lowest precedence.
930 BinopPrecedence['<'] = 10;
931 BinopPrecedence['+'] = 20;
932 BinopPrecedence['-'] = 20;
933 BinopPrecedence['*'] = 40; // highest.
935 // Prime the first token.
936 fprintf(stderr, "ready> ");
939 // Make the module, which holds all the code.
940 TheModule = new Module("my cool jit", Context);
942 // Create the JIT. This takes ownership of the module.
944 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
945 if (!TheExecutionEngine) {
946 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
950 FunctionPassManager OurFPM(TheModule);
952 // Set up the optimizer pipeline. Start with registering info about how the
953 // target lays out data structures.
954 OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
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.