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 static std::string IdentifierStr; // Filled in if tok_identifier
37 static double NumVal; // Filled in if tok_number
39 /// gettok - Return the next token from standard input.
41 static int LastChar = ' ';
43 // Skip any whitespace.
44 while (isspace(LastChar))
47 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
48 IdentifierStr = LastChar;
49 while (isalnum((LastChar = getchar())))
50 IdentifierStr += LastChar;
52 if (IdentifierStr == "def") return tok_def;
53 if (IdentifierStr == "extern") return tok_extern;
54 return tok_identifier;
57 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
62 } while (isdigit(LastChar) || LastChar == '.');
64 NumVal = strtod(NumStr.c_str(), 0);
68 if (LastChar == '#') {
69 // Comment until end of line.
70 do LastChar = getchar();
71 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
77 // Check for end of file. Don't eat the EOF.
81 // Otherwise, just return the character as its ascii value.
82 int ThisChar = LastChar;
87 //===----------------------------------------------------------------------===//
88 // Abstract Syntax Tree (aka Parse Tree)
89 //===----------------------------------------------------------------------===//
91 /// ExprAST - Base class for all expression nodes.
95 virtual Value *Codegen() = 0;
98 // Provide out-of-line definition to prevent weak vtable.
99 ExprAST::~ExprAST() {}
101 /// NumberExprAST - Expression class for numeric literals like "1.0".
102 class NumberExprAST : public ExprAST {
105 NumberExprAST(double val) : Val(val) {}
106 virtual Value *Codegen();
109 /// VariableExprAST - Expression class for referencing a variable, like "a".
110 class VariableExprAST : public ExprAST {
113 VariableExprAST(const std::string &name) : Name(name) {}
114 virtual Value *Codegen();
117 /// BinaryExprAST - Expression class for a binary operator.
118 class BinaryExprAST : public ExprAST {
122 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
123 : Op(op), LHS(lhs), RHS(rhs) {}
124 virtual Value *Codegen();
127 /// CallExprAST - Expression class for function calls.
128 class CallExprAST : public ExprAST {
130 std::vector<ExprAST*> Args;
132 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
133 : Callee(callee), Args(args) {}
134 virtual Value *Codegen();
137 /// PrototypeAST - This class represents the "prototype" for a function,
138 /// which captures its name, and its argument names (thus implicitly the number
139 /// of arguments the function takes).
142 std::vector<std::string> Args;
144 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
145 : Name(name), Args(args) {}
150 /// FunctionAST - This class represents a function definition itself.
155 FunctionAST(PrototypeAST *proto, ExprAST *body)
156 : Proto(proto), Body(body) {}
161 //===----------------------------------------------------------------------===//
163 //===----------------------------------------------------------------------===//
165 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
166 /// token the parser is looking at. getNextToken reads another token from the
167 /// lexer and updates CurTok with its results.
169 static int getNextToken() {
170 return CurTok = gettok();
173 /// BinopPrecedence - This holds the precedence for each binary operator that is
175 static std::map<char, int> BinopPrecedence;
177 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
178 static int GetTokPrecedence() {
179 if (!isascii(CurTok))
182 // Make sure it's a declared binop.
183 int TokPrec = BinopPrecedence[CurTok];
184 if (TokPrec <= 0) return -1;
188 /// Error* - These are little helper functions for error handling.
189 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
190 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
191 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
193 static ExprAST *ParseExpression();
197 /// ::= identifier '(' expression* ')'
198 static ExprAST *ParseIdentifierExpr() {
199 std::string IdName = IdentifierStr;
201 getNextToken(); // eat identifier.
203 if (CurTok != '(') // Simple variable ref.
204 return new VariableExprAST(IdName);
207 getNextToken(); // eat (
208 std::vector<ExprAST*> Args;
211 ExprAST *Arg = ParseExpression();
215 if (CurTok == ')') break;
218 return Error("Expected ')' or ',' in argument list");
226 return new CallExprAST(IdName, Args);
229 /// numberexpr ::= number
230 static ExprAST *ParseNumberExpr() {
231 ExprAST *Result = new NumberExprAST(NumVal);
232 getNextToken(); // consume the number
236 /// parenexpr ::= '(' expression ')'
237 static ExprAST *ParseParenExpr() {
238 getNextToken(); // eat (.
239 ExprAST *V = ParseExpression();
243 return Error("expected ')'");
244 getNextToken(); // eat ).
249 /// ::= identifierexpr
252 static ExprAST *ParsePrimary() {
254 default: return Error("unknown token when expecting an expression");
255 case tok_identifier: return ParseIdentifierExpr();
256 case tok_number: return ParseNumberExpr();
257 case '(': return ParseParenExpr();
262 /// ::= ('+' primary)*
263 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
264 // If this is a binop, find its precedence.
266 int TokPrec = GetTokPrecedence();
268 // If this is a binop that binds at least as tightly as the current binop,
269 // consume it, otherwise we are done.
270 if (TokPrec < ExprPrec)
273 // Okay, we know this is a binop.
275 getNextToken(); // eat binop
277 // Parse the primary expression after the binary operator.
278 ExprAST *RHS = ParsePrimary();
281 // If BinOp binds less tightly with RHS than the operator after RHS, let
282 // the pending operator take RHS as its LHS.
283 int NextPrec = GetTokPrecedence();
284 if (TokPrec < NextPrec) {
285 RHS = ParseBinOpRHS(TokPrec+1, RHS);
286 if (RHS == 0) return 0;
290 LHS = new BinaryExprAST(BinOp, LHS, RHS);
295 /// ::= primary binoprhs
297 static ExprAST *ParseExpression() {
298 ExprAST *LHS = ParsePrimary();
301 return ParseBinOpRHS(0, LHS);
305 /// ::= id '(' id* ')'
306 static PrototypeAST *ParsePrototype() {
307 if (CurTok != tok_identifier)
308 return ErrorP("Expected function name in prototype");
310 std::string FnName = IdentifierStr;
314 return ErrorP("Expected '(' in prototype");
316 std::vector<std::string> ArgNames;
317 while (getNextToken() == tok_identifier)
318 ArgNames.push_back(IdentifierStr);
320 return ErrorP("Expected ')' in prototype");
323 getNextToken(); // eat ')'.
325 return new PrototypeAST(FnName, ArgNames);
328 /// definition ::= 'def' prototype expression
329 static FunctionAST *ParseDefinition() {
330 getNextToken(); // eat def.
331 PrototypeAST *Proto = ParsePrototype();
332 if (Proto == 0) return 0;
334 if (ExprAST *E = ParseExpression())
335 return new FunctionAST(Proto, E);
339 /// toplevelexpr ::= expression
340 static FunctionAST *ParseTopLevelExpr() {
341 if (ExprAST *E = ParseExpression()) {
342 // Make an anonymous proto.
343 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
344 return new FunctionAST(Proto, E);
349 /// external ::= 'extern' prototype
350 static PrototypeAST *ParseExtern() {
351 getNextToken(); // eat extern.
352 return ParsePrototype();
355 //===----------------------------------------------------------------------===//
357 //===----------------------------------------------------------------------===//
359 static Module *TheModule;
360 static IRBuilder<> Builder(getGlobalContext());
361 static std::map<std::string, Value*> NamedValues;
362 static FunctionPassManager *TheFPM;
364 Value *ErrorV(const char *Str) { Error(Str); return 0; }
366 Value *NumberExprAST::Codegen() {
367 return ConstantFP::get(getGlobalContext(), APFloat(Val));
370 Value *VariableExprAST::Codegen() {
371 // Look this variable up in the function.
372 Value *V = NamedValues[Name];
373 return V ? V : ErrorV("Unknown variable name");
376 Value *BinaryExprAST::Codegen() {
377 Value *L = LHS->Codegen();
378 Value *R = RHS->Codegen();
379 if (L == 0 || R == 0) return 0;
382 case '+': return Builder.CreateFAdd(L, R, "addtmp");
383 case '-': return Builder.CreateFSub(L, R, "subtmp");
384 case '*': return Builder.CreateFMul(L, R, "multmp");
386 L = Builder.CreateFCmpULT(L, R, "cmptmp");
387 // Convert bool 0/1 to double 0.0 or 1.0
388 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
390 default: return ErrorV("invalid binary operator");
394 Value *CallExprAST::Codegen() {
395 // Look up the name in the global module table.
396 Function *CalleeF = TheModule->getFunction(Callee);
398 return ErrorV("Unknown function referenced");
400 // If argument mismatch error.
401 if (CalleeF->arg_size() != Args.size())
402 return ErrorV("Incorrect # arguments passed");
404 std::vector<Value*> ArgsV;
405 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
406 ArgsV.push_back(Args[i]->Codegen());
407 if (ArgsV.back() == 0) return 0;
410 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
413 Function *PrototypeAST::Codegen() {
414 // Make the function type: double(double,double) etc.
415 std::vector<Type*> Doubles(Args.size(),
416 Type::getDoubleTy(getGlobalContext()));
417 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
420 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
422 // If F conflicted, there was already something named 'Name'. If it has a
423 // body, don't allow redefinition or reextern.
424 if (F->getName() != Name) {
425 // Delete the one we just made and get the existing one.
426 F->eraseFromParent();
427 F = TheModule->getFunction(Name);
429 // If F already has a body, reject this.
431 ErrorF("redefinition of function");
435 // If F took a different number of args, reject.
436 if (F->arg_size() != Args.size()) {
437 ErrorF("redefinition of function with different # args");
442 // Set names for all arguments.
444 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
446 AI->setName(Args[Idx]);
448 // Add arguments to variable symbol table.
449 NamedValues[Args[Idx]] = AI;
455 Function *FunctionAST::Codegen() {
458 Function *TheFunction = Proto->Codegen();
459 if (TheFunction == 0)
462 // Create a new basic block to start insertion into.
463 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
464 Builder.SetInsertPoint(BB);
466 if (Value *RetVal = Body->Codegen()) {
467 // Finish off the function.
468 Builder.CreateRet(RetVal);
470 // Validate the generated code, checking for consistency.
471 verifyFunction(*TheFunction);
473 // Optimize the function.
474 TheFPM->run(*TheFunction);
479 // Error reading body, remove function.
480 TheFunction->eraseFromParent();
484 //===----------------------------------------------------------------------===//
485 // Top-Level parsing and JIT Driver
486 //===----------------------------------------------------------------------===//
488 static ExecutionEngine *TheExecutionEngine;
490 static void HandleDefinition() {
491 if (FunctionAST *F = ParseDefinition()) {
492 if (Function *LF = F->Codegen()) {
493 fprintf(stderr, "Read function definition:");
497 // Skip token for error recovery.
502 static void HandleExtern() {
503 if (PrototypeAST *P = ParseExtern()) {
504 if (Function *F = P->Codegen()) {
505 fprintf(stderr, "Read extern: ");
509 // Skip token for error recovery.
514 static void HandleTopLevelExpression() {
515 // Evaluate a top-level expression into an anonymous function.
516 if (FunctionAST *F = ParseTopLevelExpr()) {
517 if (Function *LF = F->Codegen()) {
518 // JIT the function, returning a function pointer.
519 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
521 // Cast it to the right type (takes no arguments, returns a double) so we
522 // can call it as a native function.
523 double (*FP)() = (double (*)())(intptr_t)FPtr;
524 fprintf(stderr, "Evaluated to %f\n", FP());
527 // Skip token for error recovery.
532 /// top ::= definition | external | expression | ';'
533 static void MainLoop() {
535 fprintf(stderr, "ready> ");
537 case tok_eof: return;
538 case ';': getNextToken(); break; // ignore top-level semicolons.
539 case tok_def: HandleDefinition(); break;
540 case tok_extern: HandleExtern(); break;
541 default: HandleTopLevelExpression(); break;
546 //===----------------------------------------------------------------------===//
547 // "Library" functions that can be "extern'd" from user code.
548 //===----------------------------------------------------------------------===//
550 /// putchard - putchar that takes a double and returns 0.
552 double putchard(double X) {
557 //===----------------------------------------------------------------------===//
559 //===----------------------------------------------------------------------===//
562 InitializeNativeTarget();
563 LLVMContext &Context = getGlobalContext();
565 // Install standard binary operators.
566 // 1 is lowest precedence.
567 BinopPrecedence['<'] = 10;
568 BinopPrecedence['+'] = 20;
569 BinopPrecedence['-'] = 20;
570 BinopPrecedence['*'] = 40; // highest.
572 // Prime the first token.
573 fprintf(stderr, "ready> ");
576 // Make the module, which holds all the code.
577 TheModule = new Module("my cool jit", Context);
579 // Create the JIT. This takes ownership of the module.
581 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
582 if (!TheExecutionEngine) {
583 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
587 FunctionPassManager OurFPM(TheModule);
589 // Set up the optimizer pipeline. Start with registering info about how the
590 // target lays out data structures.
591 OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
592 // Provide basic AliasAnalysis support for GVN.
593 OurFPM.add(createBasicAliasAnalysisPass());
594 // Do simple "peephole" optimizations and bit-twiddling optzns.
595 OurFPM.add(createInstructionCombiningPass());
596 // Reassociate expressions.
597 OurFPM.add(createReassociatePass());
598 // Eliminate Common SubExpressions.
599 OurFPM.add(createGVNPass());
600 // Simplify the control flow graph (deleting unreachable blocks, etc).
601 OurFPM.add(createCFGSimplificationPass());
603 OurFPM.doInitialization();
605 // Set the global so the code gen can use this.
608 // Run the main "interpreter loop" now.
613 // Print out all of the generated code.