1 #include "llvm/DerivedTypes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/JIT.h"
4 #include "llvm/LLVMContext.h"
5 #include "llvm/Module.h"
6 #include "llvm/PassManager.h"
7 #include "llvm/Analysis/Verifier.h"
8 #include "llvm/Target/TargetData.h"
9 #include "llvm/Target/TargetSelect.h"
10 #include "llvm/Transforms/Scalar.h"
11 #include "llvm/Support/IRBuilder.h"
18 //===----------------------------------------------------------------------===//
20 //===----------------------------------------------------------------------===//
22 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
23 // of these for known things.
28 tok_def = -2, tok_extern = -3,
31 tok_identifier = -4, tok_number = -5
34 static std::string IdentifierStr; // Filled in if tok_identifier
35 static double NumVal; // Filled in if tok_number
37 /// gettok - Return the next token from standard input.
39 static int LastChar = ' ';
41 // Skip any whitespace.
42 while (isspace(LastChar))
45 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
46 IdentifierStr = LastChar;
47 while (isalnum((LastChar = getchar())))
48 IdentifierStr += LastChar;
50 if (IdentifierStr == "def") return tok_def;
51 if (IdentifierStr == "extern") return tok_extern;
52 return tok_identifier;
55 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
60 } while (isdigit(LastChar) || LastChar == '.');
62 NumVal = strtod(NumStr.c_str(), 0);
66 if (LastChar == '#') {
67 // Comment until end of line.
68 do LastChar = getchar();
69 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
75 // Check for end of file. Don't eat the EOF.
79 // Otherwise, just return the character as its ascii value.
80 int ThisChar = LastChar;
85 //===----------------------------------------------------------------------===//
86 // Abstract Syntax Tree (aka Parse Tree)
87 //===----------------------------------------------------------------------===//
89 /// ExprAST - Base class for all expression nodes.
93 virtual Value *Codegen() = 0;
96 /// NumberExprAST - Expression class for numeric literals like "1.0".
97 class NumberExprAST : public ExprAST {
100 NumberExprAST(double val) : Val(val) {}
101 virtual Value *Codegen();
104 /// VariableExprAST - Expression class for referencing a variable, like "a".
105 class VariableExprAST : public ExprAST {
108 VariableExprAST(const std::string &name) : Name(name) {}
109 virtual Value *Codegen();
112 /// BinaryExprAST - Expression class for a binary operator.
113 class BinaryExprAST : public ExprAST {
117 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
118 : Op(op), LHS(lhs), RHS(rhs) {}
119 virtual Value *Codegen();
122 /// CallExprAST - Expression class for function calls.
123 class CallExprAST : public ExprAST {
125 std::vector<ExprAST*> Args;
127 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
128 : Callee(callee), Args(args) {}
129 virtual Value *Codegen();
132 /// PrototypeAST - This class represents the "prototype" for a function,
133 /// which captures its name, and its argument names (thus implicitly the number
134 /// of arguments the function takes).
137 std::vector<std::string> Args;
139 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
140 : Name(name), Args(args) {}
145 /// FunctionAST - This class represents a function definition itself.
150 FunctionAST(PrototypeAST *proto, ExprAST *body)
151 : Proto(proto), Body(body) {}
156 //===----------------------------------------------------------------------===//
158 //===----------------------------------------------------------------------===//
160 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
161 /// token the parser is looking at. getNextToken reads another token from the
162 /// lexer and updates CurTok with its results.
164 static int getNextToken() {
165 return CurTok = gettok();
168 /// BinopPrecedence - This holds the precedence for each binary operator that is
170 static std::map<char, int> BinopPrecedence;
172 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
173 static int GetTokPrecedence() {
174 if (!isascii(CurTok))
177 // Make sure it's a declared binop.
178 int TokPrec = BinopPrecedence[CurTok];
179 if (TokPrec <= 0) return -1;
183 /// Error* - These are little helper functions for error handling.
184 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
185 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
186 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
188 static ExprAST *ParseExpression();
192 /// ::= identifier '(' expression* ')'
193 static ExprAST *ParseIdentifierExpr() {
194 std::string IdName = IdentifierStr;
196 getNextToken(); // eat identifier.
198 if (CurTok != '(') // Simple variable ref.
199 return new VariableExprAST(IdName);
202 getNextToken(); // eat (
203 std::vector<ExprAST*> Args;
206 ExprAST *Arg = ParseExpression();
210 if (CurTok == ')') break;
213 return Error("Expected ')' or ',' in argument list");
221 return new CallExprAST(IdName, Args);
224 /// numberexpr ::= number
225 static ExprAST *ParseNumberExpr() {
226 ExprAST *Result = new NumberExprAST(NumVal);
227 getNextToken(); // consume the number
231 /// parenexpr ::= '(' expression ')'
232 static ExprAST *ParseParenExpr() {
233 getNextToken(); // eat (.
234 ExprAST *V = ParseExpression();
238 return Error("expected ')'");
239 getNextToken(); // eat ).
244 /// ::= identifierexpr
247 static ExprAST *ParsePrimary() {
249 default: return Error("unknown token when expecting an expression");
250 case tok_identifier: return ParseIdentifierExpr();
251 case tok_number: return ParseNumberExpr();
252 case '(': return ParseParenExpr();
257 /// ::= ('+' primary)*
258 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
259 // If this is a binop, find its precedence.
261 int TokPrec = GetTokPrecedence();
263 // If this is a binop that binds at least as tightly as the current binop,
264 // consume it, otherwise we are done.
265 if (TokPrec < ExprPrec)
268 // Okay, we know this is a binop.
270 getNextToken(); // eat binop
272 // Parse the primary expression after the binary operator.
273 ExprAST *RHS = ParsePrimary();
276 // If BinOp binds less tightly with RHS than the operator after RHS, let
277 // the pending operator take RHS as its LHS.
278 int NextPrec = GetTokPrecedence();
279 if (TokPrec < NextPrec) {
280 RHS = ParseBinOpRHS(TokPrec+1, RHS);
281 if (RHS == 0) return 0;
285 LHS = new BinaryExprAST(BinOp, LHS, RHS);
290 /// ::= primary binoprhs
292 static ExprAST *ParseExpression() {
293 ExprAST *LHS = ParsePrimary();
296 return ParseBinOpRHS(0, LHS);
300 /// ::= id '(' id* ')'
301 static PrototypeAST *ParsePrototype() {
302 if (CurTok != tok_identifier)
303 return ErrorP("Expected function name in prototype");
305 std::string FnName = IdentifierStr;
309 return ErrorP("Expected '(' in prototype");
311 std::vector<std::string> ArgNames;
312 while (getNextToken() == tok_identifier)
313 ArgNames.push_back(IdentifierStr);
315 return ErrorP("Expected ')' in prototype");
318 getNextToken(); // eat ')'.
320 return new PrototypeAST(FnName, ArgNames);
323 /// definition ::= 'def' prototype expression
324 static FunctionAST *ParseDefinition() {
325 getNextToken(); // eat def.
326 PrototypeAST *Proto = ParsePrototype();
327 if (Proto == 0) return 0;
329 if (ExprAST *E = ParseExpression())
330 return new FunctionAST(Proto, E);
334 /// toplevelexpr ::= expression
335 static FunctionAST *ParseTopLevelExpr() {
336 if (ExprAST *E = ParseExpression()) {
337 // Make an anonymous proto.
338 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
339 return new FunctionAST(Proto, E);
344 /// external ::= 'extern' prototype
345 static PrototypeAST *ParseExtern() {
346 getNextToken(); // eat extern.
347 return ParsePrototype();
350 //===----------------------------------------------------------------------===//
352 //===----------------------------------------------------------------------===//
354 static Module *TheModule;
355 static IRBuilder<> Builder(getGlobalContext());
356 static std::map<std::string, Value*> NamedValues;
357 static FunctionPassManager *TheFPM;
359 Value *ErrorV(const char *Str) { Error(Str); return 0; }
361 Value *NumberExprAST::Codegen() {
362 return ConstantFP::get(getGlobalContext(), APFloat(Val));
365 Value *VariableExprAST::Codegen() {
366 // Look this variable up in the function.
367 Value *V = NamedValues[Name];
368 return V ? V : ErrorV("Unknown variable name");
371 Value *BinaryExprAST::Codegen() {
372 Value *L = LHS->Codegen();
373 Value *R = RHS->Codegen();
374 if (L == 0 || R == 0) return 0;
377 case '+': return Builder.CreateAdd(L, R, "addtmp");
378 case '-': return Builder.CreateSub(L, R, "subtmp");
379 case '*': return Builder.CreateMul(L, R, "multmp");
381 L = Builder.CreateFCmpULT(L, R, "cmptmp");
382 // Convert bool 0/1 to double 0.0 or 1.0
383 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
385 default: return ErrorV("invalid binary operator");
389 Value *CallExprAST::Codegen() {
390 // Look up the name in the global module table.
391 Function *CalleeF = TheModule->getFunction(Callee);
393 return ErrorV("Unknown function referenced");
395 // If argument mismatch error.
396 if (CalleeF->arg_size() != Args.size())
397 return ErrorV("Incorrect # arguments passed");
399 std::vector<Value*> ArgsV;
400 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
401 ArgsV.push_back(Args[i]->Codegen());
402 if (ArgsV.back() == 0) return 0;
405 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
408 Function *PrototypeAST::Codegen() {
409 // Make the function type: double(double,double) etc.
410 std::vector<const Type*> Doubles(Args.size(),
411 Type::getDoubleTy(getGlobalContext()));
412 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
415 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
417 // If F conflicted, there was already something named 'Name'. If it has a
418 // body, don't allow redefinition or reextern.
419 if (F->getName() != Name) {
420 // Delete the one we just made and get the existing one.
421 F->eraseFromParent();
422 F = TheModule->getFunction(Name);
424 // If F already has a body, reject this.
426 ErrorF("redefinition of function");
430 // If F took a different number of args, reject.
431 if (F->arg_size() != Args.size()) {
432 ErrorF("redefinition of function with different # args");
437 // Set names for all arguments.
439 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
441 AI->setName(Args[Idx]);
443 // Add arguments to variable symbol table.
444 NamedValues[Args[Idx]] = AI;
450 Function *FunctionAST::Codegen() {
453 Function *TheFunction = Proto->Codegen();
454 if (TheFunction == 0)
457 // Create a new basic block to start insertion into.
458 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
459 Builder.SetInsertPoint(BB);
461 if (Value *RetVal = Body->Codegen()) {
462 // Finish off the function.
463 Builder.CreateRet(RetVal);
465 // Validate the generated code, checking for consistency.
466 verifyFunction(*TheFunction);
468 // Optimize the function.
469 TheFPM->run(*TheFunction);
474 // Error reading body, remove function.
475 TheFunction->eraseFromParent();
479 //===----------------------------------------------------------------------===//
480 // Top-Level parsing and JIT Driver
481 //===----------------------------------------------------------------------===//
483 static ExecutionEngine *TheExecutionEngine;
485 static void HandleDefinition() {
486 if (FunctionAST *F = ParseDefinition()) {
487 if (Function *LF = F->Codegen()) {
488 fprintf(stderr, "Read function definition:");
492 // Skip token for error recovery.
497 static void HandleExtern() {
498 if (PrototypeAST *P = ParseExtern()) {
499 if (Function *F = P->Codegen()) {
500 fprintf(stderr, "Read extern: ");
504 // Skip token for error recovery.
509 static void HandleTopLevelExpression() {
510 // Evaluate a top-level expression into an anonymous function.
511 if (FunctionAST *F = ParseTopLevelExpr()) {
512 if (Function *LF = F->Codegen()) {
513 // JIT the function, returning a function pointer.
514 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
516 // Cast it to the right type (takes no arguments, returns a double) so we
517 // can call it as a native function.
518 double (*FP)() = (double (*)())(intptr_t)FPtr;
519 fprintf(stderr, "Evaluated to %f\n", FP());
522 // Skip token for error recovery.
527 /// top ::= definition | external | expression | ';'
528 static void MainLoop() {
530 fprintf(stderr, "ready> ");
532 case tok_eof: return;
533 case ';': getNextToken(); break; // ignore top-level semicolons.
534 case tok_def: HandleDefinition(); break;
535 case tok_extern: HandleExtern(); break;
536 default: HandleTopLevelExpression(); break;
541 //===----------------------------------------------------------------------===//
542 // "Library" functions that can be "extern'd" from user code.
543 //===----------------------------------------------------------------------===//
545 /// putchard - putchar that takes a double and returns 0.
547 double putchard(double X) {
552 //===----------------------------------------------------------------------===//
554 //===----------------------------------------------------------------------===//
557 InitializeNativeTarget();
558 LLVMContext &Context = getGlobalContext();
560 // Install standard binary operators.
561 // 1 is lowest precedence.
562 BinopPrecedence['<'] = 10;
563 BinopPrecedence['+'] = 20;
564 BinopPrecedence['-'] = 20;
565 BinopPrecedence['*'] = 40; // highest.
567 // Prime the first token.
568 fprintf(stderr, "ready> ");
571 // Make the module, which holds all the code.
572 TheModule = new Module("my cool jit", Context);
574 // Create the JIT. This takes ownership of the module.
576 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
577 if (!TheExecutionEngine) {
578 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
582 FunctionPassManager OurFPM(TheModule);
584 // Set up the optimizer pipeline. Start with registering info about how the
585 // target lays out data structures.
586 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
587 // Do simple "peephole" optimizations and bit-twiddling optzns.
588 OurFPM.add(createInstructionCombiningPass());
589 // Reassociate expressions.
590 OurFPM.add(createReassociatePass());
591 // Eliminate Common SubExpressions.
592 OurFPM.add(createGVNPass());
593 // Simplify the control flow graph (deleting unreachable blocks, etc).
594 OurFPM.add(createCFGSimplificationPass());
596 OurFPM.doInitialization();
598 // Set the global so the code gen can use this.
601 // Run the main "interpreter loop" now.
606 // Print out all of the generated code.