1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/IR/DataLayout.h"
4 #include "llvm/IR/DerivedTypes.h"
5 #include "llvm/IR/IRBuilder.h"
6 #include "llvm/IR/LLVMContext.h"
7 #include "llvm/IR/Module.h"
8 #include "llvm/IR/Verifier.h"
9 #include "llvm/PassManager.h"
10 #include "llvm/Support/TargetSelect.h"
11 #include "llvm/Transforms/Scalar.h"
19 //===----------------------------------------------------------------------===//
21 //===----------------------------------------------------------------------===//
23 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
24 // of these for known things.
29 tok_def = -2, tok_extern = -3,
32 tok_identifier = -4, tok_number = -5
35 static std::string IdentifierStr; // Filled in if tok_identifier
36 static double NumVal; // Filled in if tok_number
38 /// gettok - Return the next token from standard input.
40 static int LastChar = ' ';
42 // Skip any whitespace.
43 while (isspace(LastChar))
46 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
47 IdentifierStr = LastChar;
48 while (isalnum((LastChar = getchar())))
49 IdentifierStr += LastChar;
51 if (IdentifierStr == "def") return tok_def;
52 if (IdentifierStr == "extern") return tok_extern;
53 return tok_identifier;
56 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
61 } while (isdigit(LastChar) || LastChar == '.');
63 NumVal = strtod(NumStr.c_str(), 0);
67 if (LastChar == '#') {
68 // Comment until end of line.
69 do LastChar = getchar();
70 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
76 // Check for end of file. Don't eat the EOF.
80 // Otherwise, just return the character as its ascii value.
81 int ThisChar = LastChar;
86 //===----------------------------------------------------------------------===//
87 // Abstract Syntax Tree (aka Parse Tree)
88 //===----------------------------------------------------------------------===//
90 /// ExprAST - Base class for all expression nodes.
94 virtual Value *Codegen() = 0;
97 /// NumberExprAST - Expression class for numeric literals like "1.0".
98 class NumberExprAST : public ExprAST {
101 NumberExprAST(double val) : Val(val) {}
102 virtual Value *Codegen();
105 /// VariableExprAST - Expression class for referencing a variable, like "a".
106 class VariableExprAST : public ExprAST {
109 VariableExprAST(const std::string &name) : Name(name) {}
110 virtual Value *Codegen();
113 /// BinaryExprAST - Expression class for a binary operator.
114 class BinaryExprAST : public ExprAST {
118 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
119 : Op(op), LHS(lhs), RHS(rhs) {}
120 virtual Value *Codegen();
123 /// CallExprAST - Expression class for function calls.
124 class CallExprAST : public ExprAST {
126 std::vector<ExprAST*> Args;
128 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
129 : Callee(callee), Args(args) {}
130 virtual Value *Codegen();
133 /// PrototypeAST - This class represents the "prototype" for a function,
134 /// which captures its name, and its argument names (thus implicitly the number
135 /// of arguments the function takes).
138 std::vector<std::string> Args;
140 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
141 : Name(name), Args(args) {}
146 /// FunctionAST - This class represents a function definition itself.
151 FunctionAST(PrototypeAST *proto, ExprAST *body)
152 : Proto(proto), Body(body) {}
156 } // end anonymous namespace
158 //===----------------------------------------------------------------------===//
160 //===----------------------------------------------------------------------===//
162 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
163 /// token the parser is looking at. getNextToken reads another token from the
164 /// lexer and updates CurTok with its results.
166 static int getNextToken() {
167 return CurTok = gettok();
170 /// BinopPrecedence - This holds the precedence for each binary operator that is
172 static std::map<char, int> BinopPrecedence;
174 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
175 static int GetTokPrecedence() {
176 if (!isascii(CurTok))
179 // Make sure it's a declared binop.
180 int TokPrec = BinopPrecedence[CurTok];
181 if (TokPrec <= 0) return -1;
185 /// Error* - These are little helper functions for error handling.
186 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
187 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
188 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
190 static ExprAST *ParseExpression();
194 /// ::= identifier '(' expression* ')'
195 static ExprAST *ParseIdentifierExpr() {
196 std::string IdName = IdentifierStr;
198 getNextToken(); // eat identifier.
200 if (CurTok != '(') // Simple variable ref.
201 return new VariableExprAST(IdName);
204 getNextToken(); // eat (
205 std::vector<ExprAST*> Args;
208 ExprAST *Arg = ParseExpression();
212 if (CurTok == ')') break;
215 return Error("Expected ')' or ',' in argument list");
223 return new CallExprAST(IdName, Args);
226 /// numberexpr ::= number
227 static ExprAST *ParseNumberExpr() {
228 ExprAST *Result = new NumberExprAST(NumVal);
229 getNextToken(); // consume the number
233 /// parenexpr ::= '(' expression ')'
234 static ExprAST *ParseParenExpr() {
235 getNextToken(); // eat (.
236 ExprAST *V = ParseExpression();
240 return Error("expected ')'");
241 getNextToken(); // eat ).
246 /// ::= identifierexpr
249 static ExprAST *ParsePrimary() {
251 default: return Error("unknown token when expecting an expression");
252 case tok_identifier: return ParseIdentifierExpr();
253 case tok_number: return ParseNumberExpr();
254 case '(': return ParseParenExpr();
259 /// ::= ('+' primary)*
260 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
261 // If this is a binop, find its precedence.
263 int TokPrec = GetTokPrecedence();
265 // If this is a binop that binds at least as tightly as the current binop,
266 // consume it, otherwise we are done.
267 if (TokPrec < ExprPrec)
270 // Okay, we know this is a binop.
272 getNextToken(); // eat binop
274 // Parse the primary expression after the binary operator.
275 ExprAST *RHS = ParsePrimary();
278 // If BinOp binds less tightly with RHS than the operator after RHS, let
279 // the pending operator take RHS as its LHS.
280 int NextPrec = GetTokPrecedence();
281 if (TokPrec < NextPrec) {
282 RHS = ParseBinOpRHS(TokPrec+1, RHS);
283 if (RHS == 0) return 0;
287 LHS = new BinaryExprAST(BinOp, LHS, RHS);
292 /// ::= primary binoprhs
294 static ExprAST *ParseExpression() {
295 ExprAST *LHS = ParsePrimary();
298 return ParseBinOpRHS(0, LHS);
302 /// ::= id '(' id* ')'
303 static PrototypeAST *ParsePrototype() {
304 if (CurTok != tok_identifier)
305 return ErrorP("Expected function name in prototype");
307 std::string FnName = IdentifierStr;
311 return ErrorP("Expected '(' in prototype");
313 std::vector<std::string> ArgNames;
314 while (getNextToken() == tok_identifier)
315 ArgNames.push_back(IdentifierStr);
317 return ErrorP("Expected ')' in prototype");
320 getNextToken(); // eat ')'.
322 return new PrototypeAST(FnName, ArgNames);
325 /// definition ::= 'def' prototype expression
326 static FunctionAST *ParseDefinition() {
327 getNextToken(); // eat def.
328 PrototypeAST *Proto = ParsePrototype();
329 if (Proto == 0) return 0;
331 if (ExprAST *E = ParseExpression())
332 return new FunctionAST(Proto, E);
336 /// toplevelexpr ::= expression
337 static FunctionAST *ParseTopLevelExpr() {
338 if (ExprAST *E = ParseExpression()) {
339 // Make an anonymous proto.
340 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
341 return new FunctionAST(Proto, E);
346 /// external ::= 'extern' prototype
347 static PrototypeAST *ParseExtern() {
348 getNextToken(); // eat extern.
349 return ParsePrototype();
352 //===----------------------------------------------------------------------===//
354 //===----------------------------------------------------------------------===//
356 static Module *TheModule;
357 static IRBuilder<> Builder(getGlobalContext());
358 static std::map<std::string, Value*> NamedValues;
359 static FunctionPassManager *TheFPM;
361 Value *ErrorV(const char *Str) { Error(Str); return 0; }
363 Value *NumberExprAST::Codegen() {
364 return ConstantFP::get(getGlobalContext(), APFloat(Val));
367 Value *VariableExprAST::Codegen() {
368 // Look this variable up in the function.
369 Value *V = NamedValues[Name];
370 return V ? V : ErrorV("Unknown variable name");
373 Value *BinaryExprAST::Codegen() {
374 Value *L = LHS->Codegen();
375 Value *R = RHS->Codegen();
376 if (L == 0 || R == 0) return 0;
379 case '+': return Builder.CreateFAdd(L, R, "addtmp");
380 case '-': return Builder.CreateFSub(L, R, "subtmp");
381 case '*': return Builder.CreateFMul(L, R, "multmp");
383 L = Builder.CreateFCmpULT(L, R, "cmptmp");
384 // Convert bool 0/1 to double 0.0 or 1.0
385 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
387 default: return ErrorV("invalid binary operator");
391 Value *CallExprAST::Codegen() {
392 // Look up the name in the global module table.
393 Function *CalleeF = TheModule->getFunction(Callee);
395 return ErrorV("Unknown function referenced");
397 // If argument mismatch error.
398 if (CalleeF->arg_size() != Args.size())
399 return ErrorV("Incorrect # arguments passed");
401 std::vector<Value*> ArgsV;
402 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
403 ArgsV.push_back(Args[i]->Codegen());
404 if (ArgsV.back() == 0) return 0;
407 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
410 Function *PrototypeAST::Codegen() {
411 // Make the function type: double(double,double) etc.
412 std::vector<Type*> Doubles(Args.size(),
413 Type::getDoubleTy(getGlobalContext()));
414 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
417 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
419 // If F conflicted, there was already something named 'Name'. If it has a
420 // body, don't allow redefinition or reextern.
421 if (F->getName() != Name) {
422 // Delete the one we just made and get the existing one.
423 F->eraseFromParent();
424 F = TheModule->getFunction(Name);
426 // If F already has a body, reject this.
428 ErrorF("redefinition of function");
432 // If F took a different number of args, reject.
433 if (F->arg_size() != Args.size()) {
434 ErrorF("redefinition of function with different # args");
439 // Set names for all arguments.
441 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
443 AI->setName(Args[Idx]);
445 // Add arguments to variable symbol table.
446 NamedValues[Args[Idx]] = AI;
452 Function *FunctionAST::Codegen() {
455 Function *TheFunction = Proto->Codegen();
456 if (TheFunction == 0)
459 // Create a new basic block to start insertion into.
460 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
461 Builder.SetInsertPoint(BB);
463 if (Value *RetVal = Body->Codegen()) {
464 // Finish off the function.
465 Builder.CreateRet(RetVal);
467 // Validate the generated code, checking for consistency.
468 verifyFunction(*TheFunction);
470 // Optimize the function.
471 TheFPM->run(*TheFunction);
476 // Error reading body, remove function.
477 TheFunction->eraseFromParent();
481 //===----------------------------------------------------------------------===//
482 // Top-Level parsing and JIT Driver
483 //===----------------------------------------------------------------------===//
485 static ExecutionEngine *TheExecutionEngine;
487 static void HandleDefinition() {
488 if (FunctionAST *F = ParseDefinition()) {
489 if (Function *LF = F->Codegen()) {
490 fprintf(stderr, "Read function definition:");
494 // Skip token for error recovery.
499 static void HandleExtern() {
500 if (PrototypeAST *P = ParseExtern()) {
501 if (Function *F = P->Codegen()) {
502 fprintf(stderr, "Read extern: ");
506 // Skip token for error recovery.
511 static void HandleTopLevelExpression() {
512 // Evaluate a top-level expression into an anonymous function.
513 if (FunctionAST *F = ParseTopLevelExpr()) {
514 if (Function *LF = F->Codegen()) {
515 // JIT the function, returning a function pointer.
516 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
518 // Cast it to the right type (takes no arguments, returns a double) so we
519 // can call it as a native function.
520 double (*FP)() = (double (*)())(intptr_t)FPtr;
521 fprintf(stderr, "Evaluated to %f\n", FP());
524 // Skip token for error recovery.
529 /// top ::= definition | external | expression | ';'
530 static void MainLoop() {
532 fprintf(stderr, "ready> ");
534 case tok_eof: return;
535 case ';': getNextToken(); break; // ignore top-level semicolons.
536 case tok_def: HandleDefinition(); break;
537 case tok_extern: HandleExtern(); break;
538 default: HandleTopLevelExpression(); break;
543 //===----------------------------------------------------------------------===//
544 // "Library" functions that can be "extern'd" from user code.
545 //===----------------------------------------------------------------------===//
547 /// putchard - putchar that takes a double and returns 0.
549 double putchard(double X) {
554 //===----------------------------------------------------------------------===//
556 //===----------------------------------------------------------------------===//
559 InitializeNativeTarget();
560 LLVMContext &Context = getGlobalContext();
562 // Install standard binary operators.
563 // 1 is lowest precedence.
564 BinopPrecedence['<'] = 10;
565 BinopPrecedence['+'] = 20;
566 BinopPrecedence['-'] = 20;
567 BinopPrecedence['*'] = 40; // highest.
569 // Prime the first token.
570 fprintf(stderr, "ready> ");
573 // Make the module, which holds all the code.
574 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
575 TheModule = Owner.get();
577 // Create the JIT. This takes ownership of the module.
580 EngineBuilder(std::move(Owner)).setErrorStr(&ErrStr).create();
581 if (!TheExecutionEngine) {
582 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
586 FunctionPassManager OurFPM(TheModule);
588 // Set up the optimizer pipeline. Start with registering info about how the
589 // target lays out data structures.
590 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
591 OurFPM.add(new DataLayoutPass(TheModule));
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.