blob: 4d56c0f2dfbed7c62476c5a3f672e18e748ebc44 [file] [log] [blame]
Chandler Carruth4ca7e092012-12-04 10:16:57 +00001#include "llvm/Analysis/Passes.h"
2#include "llvm/Analysis/Verifier.h"
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +00003#include "llvm/ExecutionEngine/ExecutionEngine.h"
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +00004#include "llvm/ExecutionEngine/JIT.h"
Chandler Carruth0a084602013-01-02 11:56:33 +00005#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"
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000010#include "llvm/PassManager.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000011#include "llvm/Support/TargetSelect.h"
Chandler Carruth4ca7e092012-12-04 10:16:57 +000012#include "llvm/Transforms/Scalar.h"
Will Dietze3ba15c2013-10-12 00:55:57 +000013#include <cctype>
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000014#include <cstdio>
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000015#include <map>
Chandler Carruth4ca7e092012-12-04 10:16:57 +000016#include <string>
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000017#include <vector>
18using namespace llvm;
19
20//===----------------------------------------------------------------------===//
21// Lexer
22//===----------------------------------------------------------------------===//
23
24// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25// of these for known things.
26enum Token {
27 tok_eof = -1,
28
29 // commands
30 tok_def = -2, tok_extern = -3,
31
32 // primary
33 tok_identifier = -4, tok_number = -5
34};
35
36static std::string IdentifierStr; // Filled in if tok_identifier
37static double NumVal; // Filled in if tok_number
38
39/// gettok - Return the next token from standard input.
40static int gettok() {
41 static int LastChar = ' ';
42
43 // Skip any whitespace.
44 while (isspace(LastChar))
45 LastChar = getchar();
46
47 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
48 IdentifierStr = LastChar;
49 while (isalnum((LastChar = getchar())))
50 IdentifierStr += LastChar;
51
52 if (IdentifierStr == "def") return tok_def;
53 if (IdentifierStr == "extern") return tok_extern;
54 return tok_identifier;
55 }
56
57 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
58 std::string NumStr;
59 do {
60 NumStr += LastChar;
61 LastChar = getchar();
62 } while (isdigit(LastChar) || LastChar == '.');
63
64 NumVal = strtod(NumStr.c_str(), 0);
65 return tok_number;
66 }
67
68 if (LastChar == '#') {
69 // Comment until end of line.
70 do LastChar = getchar();
71 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
72
73 if (LastChar != EOF)
74 return gettok();
75 }
76
77 // Check for end of file. Don't eat the EOF.
78 if (LastChar == EOF)
79 return tok_eof;
80
81 // Otherwise, just return the character as its ascii value.
82 int ThisChar = LastChar;
83 LastChar = getchar();
84 return ThisChar;
85}
86
87//===----------------------------------------------------------------------===//
88// Abstract Syntax Tree (aka Parse Tree)
89//===----------------------------------------------------------------------===//
90
91/// ExprAST - Base class for all expression nodes.
92class ExprAST {
93public:
Juergen Ributzka35436252013-11-19 00:57:56 +000094 virtual ~ExprAST();
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000095 virtual Value *Codegen() = 0;
96};
97
Juergen Ributzka35436252013-11-19 00:57:56 +000098// Provide out-of-line definition to prevent weak vtable.
99ExprAST::~ExprAST() {}
100
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000101/// NumberExprAST - Expression class for numeric literals like "1.0".
102class NumberExprAST : public ExprAST {
103 double Val;
104public:
105 NumberExprAST(double val) : Val(val) {}
106 virtual Value *Codegen();
107};
108
109/// VariableExprAST - Expression class for referencing a variable, like "a".
110class VariableExprAST : public ExprAST {
111 std::string Name;
112public:
113 VariableExprAST(const std::string &name) : Name(name) {}
114 virtual Value *Codegen();
115};
116
117/// BinaryExprAST - Expression class for a binary operator.
118class BinaryExprAST : public ExprAST {
119 char Op;
120 ExprAST *LHS, *RHS;
121public:
122 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
123 : Op(op), LHS(lhs), RHS(rhs) {}
124 virtual Value *Codegen();
125};
126
127/// CallExprAST - Expression class for function calls.
128class CallExprAST : public ExprAST {
129 std::string Callee;
130 std::vector<ExprAST*> Args;
131public:
132 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
133 : Callee(callee), Args(args) {}
134 virtual Value *Codegen();
135};
136
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).
140class PrototypeAST {
141 std::string Name;
142 std::vector<std::string> Args;
143public:
144 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
145 : Name(name), Args(args) {}
146
147 Function *Codegen();
148};
149
150/// FunctionAST - This class represents a function definition itself.
151class FunctionAST {
152 PrototypeAST *Proto;
153 ExprAST *Body;
154public:
155 FunctionAST(PrototypeAST *proto, ExprAST *body)
156 : Proto(proto), Body(body) {}
157
158 Function *Codegen();
159};
160
161//===----------------------------------------------------------------------===//
162// Parser
163//===----------------------------------------------------------------------===//
164
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.
168static int CurTok;
169static int getNextToken() {
170 return CurTok = gettok();
171}
172
173/// BinopPrecedence - This holds the precedence for each binary operator that is
174/// defined.
175static std::map<char, int> BinopPrecedence;
176
177/// GetTokPrecedence - Get the precedence of the pending binary operator token.
178static int GetTokPrecedence() {
179 if (!isascii(CurTok))
180 return -1;
181
182 // Make sure it's a declared binop.
183 int TokPrec = BinopPrecedence[CurTok];
184 if (TokPrec <= 0) return -1;
185 return TokPrec;
186}
187
188/// Error* - These are little helper functions for error handling.
189ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
190PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
191FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
192
193static ExprAST *ParseExpression();
194
195/// identifierexpr
196/// ::= identifier
197/// ::= identifier '(' expression* ')'
198static ExprAST *ParseIdentifierExpr() {
199 std::string IdName = IdentifierStr;
200
201 getNextToken(); // eat identifier.
202
203 if (CurTok != '(') // Simple variable ref.
204 return new VariableExprAST(IdName);
205
206 // Call.
207 getNextToken(); // eat (
208 std::vector<ExprAST*> Args;
209 if (CurTok != ')') {
210 while (1) {
211 ExprAST *Arg = ParseExpression();
212 if (!Arg) return 0;
213 Args.push_back(Arg);
214
215 if (CurTok == ')') break;
216
217 if (CurTok != ',')
218 return Error("Expected ')' or ',' in argument list");
219 getNextToken();
220 }
221 }
222
223 // Eat the ')'.
224 getNextToken();
225
226 return new CallExprAST(IdName, Args);
227}
228
229/// numberexpr ::= number
230static ExprAST *ParseNumberExpr() {
231 ExprAST *Result = new NumberExprAST(NumVal);
232 getNextToken(); // consume the number
233 return Result;
234}
235
236/// parenexpr ::= '(' expression ')'
237static ExprAST *ParseParenExpr() {
238 getNextToken(); // eat (.
239 ExprAST *V = ParseExpression();
240 if (!V) return 0;
241
242 if (CurTok != ')')
243 return Error("expected ')'");
244 getNextToken(); // eat ).
245 return V;
246}
247
248/// primary
249/// ::= identifierexpr
250/// ::= numberexpr
251/// ::= parenexpr
252static ExprAST *ParsePrimary() {
253 switch (CurTok) {
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();
258 }
259}
260
261/// binoprhs
262/// ::= ('+' primary)*
263static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
264 // If this is a binop, find its precedence.
265 while (1) {
266 int TokPrec = GetTokPrecedence();
267
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)
271 return LHS;
272
273 // Okay, we know this is a binop.
274 int BinOp = CurTok;
275 getNextToken(); // eat binop
276
277 // Parse the primary expression after the binary operator.
278 ExprAST *RHS = ParsePrimary();
279 if (!RHS) return 0;
280
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;
287 }
288
289 // Merge LHS/RHS.
290 LHS = new BinaryExprAST(BinOp, LHS, RHS);
291 }
292}
293
294/// expression
295/// ::= primary binoprhs
296///
297static ExprAST *ParseExpression() {
298 ExprAST *LHS = ParsePrimary();
299 if (!LHS) return 0;
300
301 return ParseBinOpRHS(0, LHS);
302}
303
304/// prototype
305/// ::= id '(' id* ')'
306static PrototypeAST *ParsePrototype() {
307 if (CurTok != tok_identifier)
308 return ErrorP("Expected function name in prototype");
309
310 std::string FnName = IdentifierStr;
311 getNextToken();
312
313 if (CurTok != '(')
314 return ErrorP("Expected '(' in prototype");
315
316 std::vector<std::string> ArgNames;
317 while (getNextToken() == tok_identifier)
318 ArgNames.push_back(IdentifierStr);
319 if (CurTok != ')')
320 return ErrorP("Expected ')' in prototype");
321
322 // success.
323 getNextToken(); // eat ')'.
324
325 return new PrototypeAST(FnName, ArgNames);
326}
327
328/// definition ::= 'def' prototype expression
329static FunctionAST *ParseDefinition() {
330 getNextToken(); // eat def.
331 PrototypeAST *Proto = ParsePrototype();
332 if (Proto == 0) return 0;
333
334 if (ExprAST *E = ParseExpression())
335 return new FunctionAST(Proto, E);
336 return 0;
337}
338
339/// toplevelexpr ::= expression
340static 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);
345 }
346 return 0;
347}
348
349/// external ::= 'extern' prototype
350static PrototypeAST *ParseExtern() {
351 getNextToken(); // eat extern.
352 return ParsePrototype();
353}
354
355//===----------------------------------------------------------------------===//
356// Code Generation
357//===----------------------------------------------------------------------===//
358
359static Module *TheModule;
360static IRBuilder<> Builder(getGlobalContext());
361static std::map<std::string, Value*> NamedValues;
362static FunctionPassManager *TheFPM;
363
364Value *ErrorV(const char *Str) { Error(Str); return 0; }
365
366Value *NumberExprAST::Codegen() {
367 return ConstantFP::get(getGlobalContext(), APFloat(Val));
368}
369
370Value *VariableExprAST::Codegen() {
371 // Look this variable up in the function.
372 Value *V = NamedValues[Name];
373 return V ? V : ErrorV("Unknown variable name");
374}
375
376Value *BinaryExprAST::Codegen() {
377 Value *L = LHS->Codegen();
378 Value *R = RHS->Codegen();
379 if (L == 0 || R == 0) return 0;
380
381 switch (Op) {
Eric Christopher2632bbf2010-06-14 06:03:16 +0000382 case '+': return Builder.CreateFAdd(L, R, "addtmp");
383 case '-': return Builder.CreateFSub(L, R, "subtmp");
384 case '*': return Builder.CreateFMul(L, R, "multmp");
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000385 case '<':
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()),
389 "booltmp");
390 default: return ErrorV("invalid binary operator");
391 }
392}
393
394Value *CallExprAST::Codegen() {
395 // Look up the name in the global module table.
396 Function *CalleeF = TheModule->getFunction(Callee);
397 if (CalleeF == 0)
398 return ErrorV("Unknown function referenced");
399
400 // If argument mismatch error.
401 if (CalleeF->arg_size() != Args.size())
402 return ErrorV("Incorrect # arguments passed");
403
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;
408 }
409
Francois Pichet0bd9d3a2011-07-15 10:59:52 +0000410 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000411}
412
413Function *PrototypeAST::Codegen() {
414 // Make the function type: double(double,double) etc.
John Wiegleyd1c2bd82011-07-11 22:39:46 +0000415 std::vector<Type*> Doubles(Args.size(),
416 Type::getDoubleTy(getGlobalContext()));
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000417 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
418 Doubles, false);
419
420 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
421
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);
428
429 // If F already has a body, reject this.
430 if (!F->empty()) {
431 ErrorF("redefinition of function");
432 return 0;
433 }
434
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");
438 return 0;
439 }
440 }
441
442 // Set names for all arguments.
443 unsigned Idx = 0;
444 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
445 ++AI, ++Idx) {
446 AI->setName(Args[Idx]);
447
448 // Add arguments to variable symbol table.
449 NamedValues[Args[Idx]] = AI;
450 }
451
452 return F;
453}
454
455Function *FunctionAST::Codegen() {
456 NamedValues.clear();
457
458 Function *TheFunction = Proto->Codegen();
459 if (TheFunction == 0)
460 return 0;
461
462 // Create a new basic block to start insertion into.
463 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
464 Builder.SetInsertPoint(BB);
465
466 if (Value *RetVal = Body->Codegen()) {
467 // Finish off the function.
468 Builder.CreateRet(RetVal);
469
470 // Validate the generated code, checking for consistency.
471 verifyFunction(*TheFunction);
472
473 // Optimize the function.
474 TheFPM->run(*TheFunction);
475
476 return TheFunction;
477 }
478
479 // Error reading body, remove function.
480 TheFunction->eraseFromParent();
481 return 0;
482}
483
484//===----------------------------------------------------------------------===//
485// Top-Level parsing and JIT Driver
486//===----------------------------------------------------------------------===//
487
488static ExecutionEngine *TheExecutionEngine;
489
490static void HandleDefinition() {
491 if (FunctionAST *F = ParseDefinition()) {
492 if (Function *LF = F->Codegen()) {
493 fprintf(stderr, "Read function definition:");
494 LF->dump();
495 }
496 } else {
497 // Skip token for error recovery.
498 getNextToken();
499 }
500}
501
502static void HandleExtern() {
503 if (PrototypeAST *P = ParseExtern()) {
504 if (Function *F = P->Codegen()) {
505 fprintf(stderr, "Read extern: ");
506 F->dump();
507 }
508 } else {
509 // Skip token for error recovery.
510 getNextToken();
511 }
512}
513
514static 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);
520
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());
525 }
526 } else {
527 // Skip token for error recovery.
528 getNextToken();
529 }
530}
531
532/// top ::= definition | external | expression | ';'
533static void MainLoop() {
534 while (1) {
535 fprintf(stderr, "ready> ");
536 switch (CurTok) {
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;
542 }
543 }
544}
545
546//===----------------------------------------------------------------------===//
547// "Library" functions that can be "extern'd" from user code.
548//===----------------------------------------------------------------------===//
549
550/// putchard - putchar that takes a double and returns 0.
551extern "C"
552double putchard(double X) {
553 putchar((char)X);
554 return 0;
555}
556
557//===----------------------------------------------------------------------===//
558// Main driver code.
559//===----------------------------------------------------------------------===//
560
561int main() {
562 InitializeNativeTarget();
563 LLVMContext &Context = getGlobalContext();
564
565 // Install standard binary operators.
566 // 1 is lowest precedence.
567 BinopPrecedence['<'] = 10;
568 BinopPrecedence['+'] = 20;
569 BinopPrecedence['-'] = 20;
570 BinopPrecedence['*'] = 40; // highest.
571
572 // Prime the first token.
573 fprintf(stderr, "ready> ");
574 getNextToken();
575
576 // Make the module, which holds all the code.
577 TheModule = new Module("my cool jit", Context);
578
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000579 // Create the JIT. This takes ownership of the module.
Jeffrey Yasskin42fc5582010-02-11 19:15:20 +0000580 std::string ErrStr;
581 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
582 if (!TheExecutionEngine) {
583 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
584 exit(1);
585 }
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000586
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000587 FunctionPassManager OurFPM(TheModule);
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000588
589 // Set up the optimizer pipeline. Start with registering info about how the
590 // target lays out data structures.
Micah Villmow2b4b44e2012-10-08 16:37:04 +0000591 OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
Dan Gohmandfa1a792010-11-15 18:41:10 +0000592 // Provide basic AliasAnalysis support for GVN.
593 OurFPM.add(createBasicAliasAnalysisPass());
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000594 // 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());
602
603 OurFPM.doInitialization();
604
605 // Set the global so the code gen can use this.
606 TheFPM = &OurFPM;
607
608 // Run the main "interpreter loop" now.
609 MainLoop();
610
611 TheFPM = 0;
612
613 // Print out all of the generated code.
614 TheModule->dump();
615
616 return 0;
617}