1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/JIT.h"
4 #include "llvm/IR/DataLayout.h"
5 #include "llvm/IR/DerivedTypes.h"
6 #include "llvm/IR/IRBuilder.h"
7 #include "llvm/IR/LLVMContext.h"
8 #include "llvm/IR/Module.h"
9 #include "llvm/IR/Verifier.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 /// NumberExprAST - Expression class for numeric literals like "1.0".
99 class NumberExprAST : public ExprAST {
102 NumberExprAST(double val) : Val(val) {}
103 virtual Value *Codegen();
106 /// VariableExprAST - Expression class for referencing a variable, like "a".
107 class VariableExprAST : public ExprAST {
110 VariableExprAST(const std::string &name) : Name(name) {}
111 virtual Value *Codegen();
114 /// BinaryExprAST - Expression class for a binary operator.
115 class BinaryExprAST : public ExprAST {
119 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
120 : Op(op), LHS(lhs), RHS(rhs) {}
121 virtual Value *Codegen();
124 /// CallExprAST - Expression class for function calls.
125 class CallExprAST : public ExprAST {
127 std::vector<ExprAST*> Args;
129 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
130 : Callee(callee), Args(args) {}
131 virtual Value *Codegen();
134 /// PrototypeAST - This class represents the "prototype" for a function,
135 /// which captures its name, and its argument names (thus implicitly the number
136 /// of arguments the function takes).
139 std::vector<std::string> Args;
141 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
142 : Name(name), Args(args) {}
147 /// FunctionAST - This class represents a function definition itself.
152 FunctionAST(PrototypeAST *proto, ExprAST *body)
153 : Proto(proto), Body(body) {}
157 } // end anonymous namespace
159 //===----------------------------------------------------------------------===//
161 //===----------------------------------------------------------------------===//
163 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
164 /// token the parser is looking at. getNextToken reads another token from the
165 /// lexer and updates CurTok with its results.
167 static int getNextToken() {
168 return CurTok = gettok();
171 /// BinopPrecedence - This holds the precedence for each binary operator that is
173 static std::map<char, int> BinopPrecedence;
175 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
176 static int GetTokPrecedence() {
177 if (!isascii(CurTok))
180 // Make sure it's a declared binop.
181 int TokPrec = BinopPrecedence[CurTok];
182 if (TokPrec <= 0) return -1;
186 /// Error* - These are little helper functions for error handling.
187 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
188 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
189 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
191 static ExprAST *ParseExpression();
195 /// ::= identifier '(' expression* ')'
196 static ExprAST *ParseIdentifierExpr() {
197 std::string IdName = IdentifierStr;
199 getNextToken(); // eat identifier.
201 if (CurTok != '(') // Simple variable ref.
202 return new VariableExprAST(IdName);
205 getNextToken(); // eat (
206 std::vector<ExprAST*> Args;
209 ExprAST *Arg = ParseExpression();
213 if (CurTok == ')') break;
216 return Error("Expected ')' or ',' in argument list");
224 return new CallExprAST(IdName, Args);
227 /// numberexpr ::= number
228 static ExprAST *ParseNumberExpr() {
229 ExprAST *Result = new NumberExprAST(NumVal);
230 getNextToken(); // consume the number
234 /// parenexpr ::= '(' expression ')'
235 static ExprAST *ParseParenExpr() {
236 getNextToken(); // eat (.
237 ExprAST *V = ParseExpression();
241 return Error("expected ')'");
242 getNextToken(); // eat ).
247 /// ::= identifierexpr
250 static ExprAST *ParsePrimary() {
252 default: return Error("unknown token when expecting an expression");
253 case tok_identifier: return ParseIdentifierExpr();
254 case tok_number: return ParseNumberExpr();
255 case '(': return ParseParenExpr();
260 /// ::= ('+' primary)*
261 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
262 // If this is a binop, find its precedence.
264 int TokPrec = GetTokPrecedence();
266 // If this is a binop that binds at least as tightly as the current binop,
267 // consume it, otherwise we are done.
268 if (TokPrec < ExprPrec)
271 // Okay, we know this is a binop.
273 getNextToken(); // eat binop
275 // Parse the primary expression after the binary operator.
276 ExprAST *RHS = ParsePrimary();
279 // If BinOp binds less tightly with RHS than the operator after RHS, let
280 // the pending operator take RHS as its LHS.
281 int NextPrec = GetTokPrecedence();
282 if (TokPrec < NextPrec) {
283 RHS = ParseBinOpRHS(TokPrec+1, RHS);
284 if (RHS == 0) return 0;
288 LHS = new BinaryExprAST(BinOp, LHS, RHS);
293 /// ::= primary binoprhs
295 static ExprAST *ParseExpression() {
296 ExprAST *LHS = ParsePrimary();
299 return ParseBinOpRHS(0, LHS);
303 /// ::= id '(' id* ')'
304 static PrototypeAST *ParsePrototype() {
305 if (CurTok != tok_identifier)
306 return ErrorP("Expected function name in prototype");
308 std::string FnName = IdentifierStr;
312 return ErrorP("Expected '(' in prototype");
314 std::vector<std::string> ArgNames;
315 while (getNextToken() == tok_identifier)
316 ArgNames.push_back(IdentifierStr);
318 return ErrorP("Expected ')' in prototype");
321 getNextToken(); // eat ')'.
323 return new PrototypeAST(FnName, ArgNames);
326 /// definition ::= 'def' prototype expression
327 static FunctionAST *ParseDefinition() {
328 getNextToken(); // eat def.
329 PrototypeAST *Proto = ParsePrototype();
330 if (Proto == 0) return 0;
332 if (ExprAST *E = ParseExpression())
333 return new FunctionAST(Proto, E);
337 /// toplevelexpr ::= expression
338 static FunctionAST *ParseTopLevelExpr() {
339 if (ExprAST *E = ParseExpression()) {
340 // Make an anonymous proto.
341 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
342 return new FunctionAST(Proto, E);
347 /// external ::= 'extern' prototype
348 static PrototypeAST *ParseExtern() {
349 getNextToken(); // eat extern.
350 return ParsePrototype();
353 //===----------------------------------------------------------------------===//
355 //===----------------------------------------------------------------------===//
357 static Module *TheModule;
358 static IRBuilder<> Builder(getGlobalContext());
359 static std::map<std::string, Value*> NamedValues;
360 static FunctionPassManager *TheFPM;
362 Value *ErrorV(const char *Str) { Error(Str); return 0; }
364 Value *NumberExprAST::Codegen() {
365 return ConstantFP::get(getGlobalContext(), APFloat(Val));
368 Value *VariableExprAST::Codegen() {
369 // Look this variable up in the function.
370 Value *V = NamedValues[Name];
371 return V ? V : ErrorV("Unknown variable name");
374 Value *BinaryExprAST::Codegen() {
375 Value *L = LHS->Codegen();
376 Value *R = RHS->Codegen();
377 if (L == 0 || R == 0) return 0;
380 case '+': return Builder.CreateFAdd(L, R, "addtmp");
381 case '-': return Builder.CreateFSub(L, R, "subtmp");
382 case '*': return Builder.CreateFMul(L, R, "multmp");
384 L = Builder.CreateFCmpULT(L, R, "cmptmp");
385 // Convert bool 0/1 to double 0.0 or 1.0
386 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
388 default: return ErrorV("invalid binary operator");
392 Value *CallExprAST::Codegen() {
393 // Look up the name in the global module table.
394 Function *CalleeF = TheModule->getFunction(Callee);
396 return ErrorV("Unknown function referenced");
398 // If argument mismatch error.
399 if (CalleeF->arg_size() != Args.size())
400 return ErrorV("Incorrect # arguments passed");
402 std::vector<Value*> ArgsV;
403 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
404 ArgsV.push_back(Args[i]->Codegen());
405 if (ArgsV.back() == 0) return 0;
408 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
411 Function *PrototypeAST::Codegen() {
412 // Make the function type: double(double,double) etc.
413 std::vector<Type*> Doubles(Args.size(),
414 Type::getDoubleTy(getGlobalContext()));
415 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
418 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
420 // If F conflicted, there was already something named 'Name'. If it has a
421 // body, don't allow redefinition or reextern.
422 if (F->getName() != Name) {
423 // Delete the one we just made and get the existing one.
424 F->eraseFromParent();
425 F = TheModule->getFunction(Name);
427 // If F already has a body, reject this.
429 ErrorF("redefinition of function");
433 // If F took a different number of args, reject.
434 if (F->arg_size() != Args.size()) {
435 ErrorF("redefinition of function with different # args");
440 // Set names for all arguments.
442 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
444 AI->setName(Args[Idx]);
446 // Add arguments to variable symbol table.
447 NamedValues[Args[Idx]] = AI;
453 Function *FunctionAST::Codegen() {
456 Function *TheFunction = Proto->Codegen();
457 if (TheFunction == 0)
460 // Create a new basic block to start insertion into.
461 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
462 Builder.SetInsertPoint(BB);
464 if (Value *RetVal = Body->Codegen()) {
465 // Finish off the function.
466 Builder.CreateRet(RetVal);
468 // Validate the generated code, checking for consistency.
469 verifyFunction(*TheFunction);
471 // Optimize the function.
472 TheFPM->run(*TheFunction);
477 // Error reading body, remove function.
478 TheFunction->eraseFromParent();
482 //===----------------------------------------------------------------------===//
483 // Top-Level parsing and JIT Driver
484 //===----------------------------------------------------------------------===//
486 static ExecutionEngine *TheExecutionEngine;
488 static void HandleDefinition() {
489 if (FunctionAST *F = ParseDefinition()) {
490 if (Function *LF = F->Codegen()) {
491 fprintf(stderr, "Read function definition:");
495 // Skip token for error recovery.
500 static void HandleExtern() {
501 if (PrototypeAST *P = ParseExtern()) {
502 if (Function *F = P->Codegen()) {
503 fprintf(stderr, "Read extern: ");
507 // Skip token for error recovery.
512 static void HandleTopLevelExpression() {
513 // Evaluate a top-level expression into an anonymous function.
514 if (FunctionAST *F = ParseTopLevelExpr()) {
515 if (Function *LF = F->Codegen()) {
516 // JIT the function, returning a function pointer.
517 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
519 // Cast it to the right type (takes no arguments, returns a double) so we
520 // can call it as a native function.
521 double (*FP)() = (double (*)())(intptr_t)FPtr;
522 fprintf(stderr, "Evaluated to %f\n", FP());
525 // Skip token for error recovery.
530 /// top ::= definition | external | expression | ';'
531 static void MainLoop() {
533 fprintf(stderr, "ready> ");
535 case tok_eof: return;
536 case ';': getNextToken(); break; // ignore top-level semicolons.
537 case tok_def: HandleDefinition(); break;
538 case tok_extern: HandleExtern(); break;
539 default: HandleTopLevelExpression(); break;
544 //===----------------------------------------------------------------------===//
545 // "Library" functions that can be "extern'd" from user code.
546 //===----------------------------------------------------------------------===//
548 /// putchard - putchar that takes a double and returns 0.
550 double putchard(double X) {
555 //===----------------------------------------------------------------------===//
557 //===----------------------------------------------------------------------===//
560 InitializeNativeTarget();
561 LLVMContext &Context = getGlobalContext();
563 // Install standard binary operators.
564 // 1 is lowest precedence.
565 BinopPrecedence['<'] = 10;
566 BinopPrecedence['+'] = 20;
567 BinopPrecedence['-'] = 20;
568 BinopPrecedence['*'] = 40; // highest.
570 // Prime the first token.
571 fprintf(stderr, "ready> ");
574 // Make the module, which holds all the code.
575 TheModule = new Module("my cool jit", Context);
577 // Create the JIT. This takes ownership of the module.
579 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
580 if (!TheExecutionEngine) {
581 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
585 FunctionPassManager OurFPM(TheModule);
587 // Set up the optimizer pipeline. Start with registering info about how the
588 // target lays out data structures.
589 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
590 OurFPM.add(new DataLayoutPass(TheModule));
591 // Provide basic AliasAnalysis support for GVN.
592 OurFPM.add(createBasicAliasAnalysisPass());
593 // Do simple "peephole" optimizations and bit-twiddling optzns.
594 OurFPM.add(createInstructionCombiningPass());
595 // Reassociate expressions.
596 OurFPM.add(createReassociatePass());
597 // Eliminate Common SubExpressions.
598 OurFPM.add(createGVNPass());
599 // Simplify the control flow graph (deleting unreachable blocks, etc).
600 OurFPM.add(createCFGSimplificationPass());
602 OurFPM.doInitialization();
604 // Set the global so the code gen can use this.
607 // Run the main "interpreter loop" now.
612 // Print out all of the generated code.