blob: a52b5552a291d185c81a918ae3d23de36b508305 [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 Ributzka5a364c52013-11-15 22:34:48 +000094 virtual ~ExprAST();
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000095 virtual Value *Codegen() = 0;
96};
97
Juergen Ributzka5a364c52013-11-15 22:34:48 +000098ExprAST::~ExprAST() {}
99
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000100/// NumberExprAST - Expression class for numeric literals like "1.0".
101class NumberExprAST : public ExprAST {
102 double Val;
103public:
104 NumberExprAST(double val) : Val(val) {}
105 virtual Value *Codegen();
106};
107
108/// VariableExprAST - Expression class for referencing a variable, like "a".
109class VariableExprAST : public ExprAST {
110 std::string Name;
111public:
112 VariableExprAST(const std::string &name) : Name(name) {}
113 virtual Value *Codegen();
114};
115
116/// BinaryExprAST - Expression class for a binary operator.
117class BinaryExprAST : public ExprAST {
118 char Op;
119 ExprAST *LHS, *RHS;
120public:
121 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
122 : Op(op), LHS(lhs), RHS(rhs) {}
123 virtual Value *Codegen();
124};
125
126/// CallExprAST - Expression class for function calls.
127class CallExprAST : public ExprAST {
128 std::string Callee;
129 std::vector<ExprAST*> Args;
130public:
131 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
132 : Callee(callee), Args(args) {}
133 virtual Value *Codegen();
134};
135
136/// PrototypeAST - This class represents the "prototype" for a function,
137/// which captures its name, and its argument names (thus implicitly the number
138/// of arguments the function takes).
139class PrototypeAST {
140 std::string Name;
141 std::vector<std::string> Args;
142public:
143 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
144 : Name(name), Args(args) {}
145
146 Function *Codegen();
147};
148
149/// FunctionAST - This class represents a function definition itself.
150class FunctionAST {
151 PrototypeAST *Proto;
152 ExprAST *Body;
153public:
154 FunctionAST(PrototypeAST *proto, ExprAST *body)
155 : Proto(proto), Body(body) {}
156
157 Function *Codegen();
158};
159
160//===----------------------------------------------------------------------===//
161// Parser
162//===----------------------------------------------------------------------===//
163
164/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
165/// token the parser is looking at. getNextToken reads another token from the
166/// lexer and updates CurTok with its results.
167static int CurTok;
168static int getNextToken() {
169 return CurTok = gettok();
170}
171
172/// BinopPrecedence - This holds the precedence for each binary operator that is
173/// defined.
174static std::map<char, int> BinopPrecedence;
175
176/// GetTokPrecedence - Get the precedence of the pending binary operator token.
177static int GetTokPrecedence() {
178 if (!isascii(CurTok))
179 return -1;
180
181 // Make sure it's a declared binop.
182 int TokPrec = BinopPrecedence[CurTok];
183 if (TokPrec <= 0) return -1;
184 return TokPrec;
185}
186
187/// Error* - These are little helper functions for error handling.
188ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
189PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
190FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
191
192static ExprAST *ParseExpression();
193
194/// identifierexpr
195/// ::= identifier
196/// ::= identifier '(' expression* ')'
197static ExprAST *ParseIdentifierExpr() {
198 std::string IdName = IdentifierStr;
199
200 getNextToken(); // eat identifier.
201
202 if (CurTok != '(') // Simple variable ref.
203 return new VariableExprAST(IdName);
204
205 // Call.
206 getNextToken(); // eat (
207 std::vector<ExprAST*> Args;
208 if (CurTok != ')') {
209 while (1) {
210 ExprAST *Arg = ParseExpression();
211 if (!Arg) return 0;
212 Args.push_back(Arg);
213
214 if (CurTok == ')') break;
215
216 if (CurTok != ',')
217 return Error("Expected ')' or ',' in argument list");
218 getNextToken();
219 }
220 }
221
222 // Eat the ')'.
223 getNextToken();
224
225 return new CallExprAST(IdName, Args);
226}
227
228/// numberexpr ::= number
229static ExprAST *ParseNumberExpr() {
230 ExprAST *Result = new NumberExprAST(NumVal);
231 getNextToken(); // consume the number
232 return Result;
233}
234
235/// parenexpr ::= '(' expression ')'
236static ExprAST *ParseParenExpr() {
237 getNextToken(); // eat (.
238 ExprAST *V = ParseExpression();
239 if (!V) return 0;
240
241 if (CurTok != ')')
242 return Error("expected ')'");
243 getNextToken(); // eat ).
244 return V;
245}
246
247/// primary
248/// ::= identifierexpr
249/// ::= numberexpr
250/// ::= parenexpr
251static ExprAST *ParsePrimary() {
252 switch (CurTok) {
253 default: return Error("unknown token when expecting an expression");
254 case tok_identifier: return ParseIdentifierExpr();
255 case tok_number: return ParseNumberExpr();
256 case '(': return ParseParenExpr();
257 }
258}
259
260/// binoprhs
261/// ::= ('+' primary)*
262static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
263 // If this is a binop, find its precedence.
264 while (1) {
265 int TokPrec = GetTokPrecedence();
266
267 // If this is a binop that binds at least as tightly as the current binop,
268 // consume it, otherwise we are done.
269 if (TokPrec < ExprPrec)
270 return LHS;
271
272 // Okay, we know this is a binop.
273 int BinOp = CurTok;
274 getNextToken(); // eat binop
275
276 // Parse the primary expression after the binary operator.
277 ExprAST *RHS = ParsePrimary();
278 if (!RHS) return 0;
279
280 // If BinOp binds less tightly with RHS than the operator after RHS, let
281 // the pending operator take RHS as its LHS.
282 int NextPrec = GetTokPrecedence();
283 if (TokPrec < NextPrec) {
284 RHS = ParseBinOpRHS(TokPrec+1, RHS);
285 if (RHS == 0) return 0;
286 }
287
288 // Merge LHS/RHS.
289 LHS = new BinaryExprAST(BinOp, LHS, RHS);
290 }
291}
292
293/// expression
294/// ::= primary binoprhs
295///
296static ExprAST *ParseExpression() {
297 ExprAST *LHS = ParsePrimary();
298 if (!LHS) return 0;
299
300 return ParseBinOpRHS(0, LHS);
301}
302
303/// prototype
304/// ::= id '(' id* ')'
305static PrototypeAST *ParsePrototype() {
306 if (CurTok != tok_identifier)
307 return ErrorP("Expected function name in prototype");
308
309 std::string FnName = IdentifierStr;
310 getNextToken();
311
312 if (CurTok != '(')
313 return ErrorP("Expected '(' in prototype");
314
315 std::vector<std::string> ArgNames;
316 while (getNextToken() == tok_identifier)
317 ArgNames.push_back(IdentifierStr);
318 if (CurTok != ')')
319 return ErrorP("Expected ')' in prototype");
320
321 // success.
322 getNextToken(); // eat ')'.
323
324 return new PrototypeAST(FnName, ArgNames);
325}
326
327/// definition ::= 'def' prototype expression
328static FunctionAST *ParseDefinition() {
329 getNextToken(); // eat def.
330 PrototypeAST *Proto = ParsePrototype();
331 if (Proto == 0) return 0;
332
333 if (ExprAST *E = ParseExpression())
334 return new FunctionAST(Proto, E);
335 return 0;
336}
337
338/// toplevelexpr ::= expression
339static FunctionAST *ParseTopLevelExpr() {
340 if (ExprAST *E = ParseExpression()) {
341 // Make an anonymous proto.
342 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
343 return new FunctionAST(Proto, E);
344 }
345 return 0;
346}
347
348/// external ::= 'extern' prototype
349static PrototypeAST *ParseExtern() {
350 getNextToken(); // eat extern.
351 return ParsePrototype();
352}
353
354//===----------------------------------------------------------------------===//
355// Code Generation
356//===----------------------------------------------------------------------===//
357
358static Module *TheModule;
359static IRBuilder<> Builder(getGlobalContext());
360static std::map<std::string, Value*> NamedValues;
361static FunctionPassManager *TheFPM;
362
363Value *ErrorV(const char *Str) { Error(Str); return 0; }
364
365Value *NumberExprAST::Codegen() {
366 return ConstantFP::get(getGlobalContext(), APFloat(Val));
367}
368
369Value *VariableExprAST::Codegen() {
370 // Look this variable up in the function.
371 Value *V = NamedValues[Name];
372 return V ? V : ErrorV("Unknown variable name");
373}
374
375Value *BinaryExprAST::Codegen() {
376 Value *L = LHS->Codegen();
377 Value *R = RHS->Codegen();
378 if (L == 0 || R == 0) return 0;
379
380 switch (Op) {
Eric Christopher2632bbf2010-06-14 06:03:16 +0000381 case '+': return Builder.CreateFAdd(L, R, "addtmp");
382 case '-': return Builder.CreateFSub(L, R, "subtmp");
383 case '*': return Builder.CreateFMul(L, R, "multmp");
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000384 case '<':
385 L = Builder.CreateFCmpULT(L, R, "cmptmp");
386 // Convert bool 0/1 to double 0.0 or 1.0
387 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
388 "booltmp");
389 default: return ErrorV("invalid binary operator");
390 }
391}
392
393Value *CallExprAST::Codegen() {
394 // Look up the name in the global module table.
395 Function *CalleeF = TheModule->getFunction(Callee);
396 if (CalleeF == 0)
397 return ErrorV("Unknown function referenced");
398
399 // If argument mismatch error.
400 if (CalleeF->arg_size() != Args.size())
401 return ErrorV("Incorrect # arguments passed");
402
403 std::vector<Value*> ArgsV;
404 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
405 ArgsV.push_back(Args[i]->Codegen());
406 if (ArgsV.back() == 0) return 0;
407 }
408
Francois Pichet0bd9d3a2011-07-15 10:59:52 +0000409 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000410}
411
412Function *PrototypeAST::Codegen() {
413 // Make the function type: double(double,double) etc.
John Wiegleyd1c2bd82011-07-11 22:39:46 +0000414 std::vector<Type*> Doubles(Args.size(),
415 Type::getDoubleTy(getGlobalContext()));
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000416 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
417 Doubles, false);
418
419 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
420
421 // If F conflicted, there was already something named 'Name'. If it has a
422 // body, don't allow redefinition or reextern.
423 if (F->getName() != Name) {
424 // Delete the one we just made and get the existing one.
425 F->eraseFromParent();
426 F = TheModule->getFunction(Name);
427
428 // If F already has a body, reject this.
429 if (!F->empty()) {
430 ErrorF("redefinition of function");
431 return 0;
432 }
433
434 // If F took a different number of args, reject.
435 if (F->arg_size() != Args.size()) {
436 ErrorF("redefinition of function with different # args");
437 return 0;
438 }
439 }
440
441 // Set names for all arguments.
442 unsigned Idx = 0;
443 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
444 ++AI, ++Idx) {
445 AI->setName(Args[Idx]);
446
447 // Add arguments to variable symbol table.
448 NamedValues[Args[Idx]] = AI;
449 }
450
451 return F;
452}
453
454Function *FunctionAST::Codegen() {
455 NamedValues.clear();
456
457 Function *TheFunction = Proto->Codegen();
458 if (TheFunction == 0)
459 return 0;
460
461 // Create a new basic block to start insertion into.
462 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
463 Builder.SetInsertPoint(BB);
464
465 if (Value *RetVal = Body->Codegen()) {
466 // Finish off the function.
467 Builder.CreateRet(RetVal);
468
469 // Validate the generated code, checking for consistency.
470 verifyFunction(*TheFunction);
471
472 // Optimize the function.
473 TheFPM->run(*TheFunction);
474
475 return TheFunction;
476 }
477
478 // Error reading body, remove function.
479 TheFunction->eraseFromParent();
480 return 0;
481}
482
483//===----------------------------------------------------------------------===//
484// Top-Level parsing and JIT Driver
485//===----------------------------------------------------------------------===//
486
487static ExecutionEngine *TheExecutionEngine;
488
489static void HandleDefinition() {
490 if (FunctionAST *F = ParseDefinition()) {
491 if (Function *LF = F->Codegen()) {
492 fprintf(stderr, "Read function definition:");
493 LF->dump();
494 }
495 } else {
496 // Skip token for error recovery.
497 getNextToken();
498 }
499}
500
501static void HandleExtern() {
502 if (PrototypeAST *P = ParseExtern()) {
503 if (Function *F = P->Codegen()) {
504 fprintf(stderr, "Read extern: ");
505 F->dump();
506 }
507 } else {
508 // Skip token for error recovery.
509 getNextToken();
510 }
511}
512
513static void HandleTopLevelExpression() {
514 // Evaluate a top-level expression into an anonymous function.
515 if (FunctionAST *F = ParseTopLevelExpr()) {
516 if (Function *LF = F->Codegen()) {
517 // JIT the function, returning a function pointer.
518 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
519
520 // Cast it to the right type (takes no arguments, returns a double) so we
521 // can call it as a native function.
522 double (*FP)() = (double (*)())(intptr_t)FPtr;
523 fprintf(stderr, "Evaluated to %f\n", FP());
524 }
525 } else {
526 // Skip token for error recovery.
527 getNextToken();
528 }
529}
530
531/// top ::= definition | external | expression | ';'
532static void MainLoop() {
533 while (1) {
534 fprintf(stderr, "ready> ");
535 switch (CurTok) {
536 case tok_eof: return;
537 case ';': getNextToken(); break; // ignore top-level semicolons.
538 case tok_def: HandleDefinition(); break;
539 case tok_extern: HandleExtern(); break;
540 default: HandleTopLevelExpression(); break;
541 }
542 }
543}
544
545//===----------------------------------------------------------------------===//
546// "Library" functions that can be "extern'd" from user code.
547//===----------------------------------------------------------------------===//
548
549/// putchard - putchar that takes a double and returns 0.
550extern "C"
551double putchard(double X) {
552 putchar((char)X);
553 return 0;
554}
555
556//===----------------------------------------------------------------------===//
557// Main driver code.
558//===----------------------------------------------------------------------===//
559
560int main() {
561 InitializeNativeTarget();
562 LLVMContext &Context = getGlobalContext();
563
564 // Install standard binary operators.
565 // 1 is lowest precedence.
566 BinopPrecedence['<'] = 10;
567 BinopPrecedence['+'] = 20;
568 BinopPrecedence['-'] = 20;
569 BinopPrecedence['*'] = 40; // highest.
570
571 // Prime the first token.
572 fprintf(stderr, "ready> ");
573 getNextToken();
574
575 // Make the module, which holds all the code.
576 TheModule = new Module("my cool jit", Context);
577
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000578 // Create the JIT. This takes ownership of the module.
Jeffrey Yasskin42fc5582010-02-11 19:15:20 +0000579 std::string ErrStr;
580 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
581 if (!TheExecutionEngine) {
582 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
583 exit(1);
584 }
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000585
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000586 FunctionPassManager OurFPM(TheModule);
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000587
588 // Set up the optimizer pipeline. Start with registering info about how the
589 // target lays out data structures.
Micah Villmow2b4b44e2012-10-08 16:37:04 +0000590 OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
Dan Gohmandfa1a792010-11-15 18:41:10 +0000591 // Provide basic AliasAnalysis support for GVN.
592 OurFPM.add(createBasicAliasAnalysisPass());
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000593 // 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());
601
602 OurFPM.doInitialization();
603
604 // Set the global so the code gen can use this.
605 TheFPM = &OurFPM;
606
607 // Run the main "interpreter loop" now.
608 MainLoop();
609
610 TheFPM = 0;
611
612 // Print out all of the generated code.
613 TheModule->dump();
614
615 return 0;
616}