blob: d25aa5d4d7fee577616800512f7c6ae8ad958b65 [file] [log] [blame]
Chandler Carruth4ca7e092012-12-04 10:16:57 +00001#include "llvm/Analysis/Verifier.h"
Chandler Carruth0a084602013-01-02 11:56:33 +00002#include "llvm/IR/DerivedTypes.h"
3#include "llvm/IR/IRBuilder.h"
4#include "llvm/IR/LLVMContext.h"
5#include "llvm/IR/Module.h"
Will Dietze3ba15c2013-10-12 00:55:57 +00006#include <cctype>
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +00007#include <cstdio>
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +00008#include <map>
Chandler Carruth4ca7e092012-12-04 10:16:57 +00009#include <string>
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000010#include <vector>
11using namespace llvm;
12
13//===----------------------------------------------------------------------===//
14// Lexer
15//===----------------------------------------------------------------------===//
16
17// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
18// of these for known things.
19enum Token {
20 tok_eof = -1,
21
22 // commands
23 tok_def = -2, tok_extern = -3,
24
25 // primary
26 tok_identifier = -4, tok_number = -5
27};
28
29static std::string IdentifierStr; // Filled in if tok_identifier
30static double NumVal; // Filled in if tok_number
31
32/// gettok - Return the next token from standard input.
33static int gettok() {
34 static int LastChar = ' ';
35
36 // Skip any whitespace.
37 while (isspace(LastChar))
38 LastChar = getchar();
39
40 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
41 IdentifierStr = LastChar;
42 while (isalnum((LastChar = getchar())))
43 IdentifierStr += LastChar;
44
45 if (IdentifierStr == "def") return tok_def;
46 if (IdentifierStr == "extern") return tok_extern;
47 return tok_identifier;
48 }
49
50 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
51 std::string NumStr;
52 do {
53 NumStr += LastChar;
54 LastChar = getchar();
55 } while (isdigit(LastChar) || LastChar == '.');
56
57 NumVal = strtod(NumStr.c_str(), 0);
58 return tok_number;
59 }
60
61 if (LastChar == '#') {
62 // Comment until end of line.
63 do LastChar = getchar();
64 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
65
66 if (LastChar != EOF)
67 return gettok();
68 }
69
70 // Check for end of file. Don't eat the EOF.
71 if (LastChar == EOF)
72 return tok_eof;
73
74 // Otherwise, just return the character as its ascii value.
75 int ThisChar = LastChar;
76 LastChar = getchar();
77 return ThisChar;
78}
79
80//===----------------------------------------------------------------------===//
81// Abstract Syntax Tree (aka Parse Tree)
82//===----------------------------------------------------------------------===//
83
84/// ExprAST - Base class for all expression nodes.
85class ExprAST {
86public:
Juergen Ributzka5a364c52013-11-15 22:34:48 +000087 virtual ~ExprAST();
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000088 virtual Value *Codegen() = 0;
89};
90
Juergen Ributzka5a364c52013-11-15 22:34:48 +000091ExprAST::~ExprAST() {}
92
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +000093/// NumberExprAST - Expression class for numeric literals like "1.0".
94class NumberExprAST : public ExprAST {
95 double Val;
96public:
97 NumberExprAST(double val) : Val(val) {}
98 virtual Value *Codegen();
99};
100
101/// VariableExprAST - Expression class for referencing a variable, like "a".
102class VariableExprAST : public ExprAST {
103 std::string Name;
104public:
105 VariableExprAST(const std::string &name) : Name(name) {}
106 virtual Value *Codegen();
107};
108
109/// BinaryExprAST - Expression class for a binary operator.
110class BinaryExprAST : public ExprAST {
111 char Op;
112 ExprAST *LHS, *RHS;
113public:
114 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
115 : Op(op), LHS(lhs), RHS(rhs) {}
116 virtual Value *Codegen();
117};
118
119/// CallExprAST - Expression class for function calls.
120class CallExprAST : public ExprAST {
121 std::string Callee;
122 std::vector<ExprAST*> Args;
123public:
124 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
125 : Callee(callee), Args(args) {}
126 virtual Value *Codegen();
127};
128
129/// PrototypeAST - This class represents the "prototype" for a function,
130/// which captures its name, and its argument names (thus implicitly the number
131/// of arguments the function takes).
132class PrototypeAST {
133 std::string Name;
134 std::vector<std::string> Args;
135public:
136 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
137 : Name(name), Args(args) {}
138
139 Function *Codegen();
140};
141
142/// FunctionAST - This class represents a function definition itself.
143class FunctionAST {
144 PrototypeAST *Proto;
145 ExprAST *Body;
146public:
147 FunctionAST(PrototypeAST *proto, ExprAST *body)
148 : Proto(proto), Body(body) {}
149
150 Function *Codegen();
151};
152
153//===----------------------------------------------------------------------===//
154// Parser
155//===----------------------------------------------------------------------===//
156
157/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
158/// token the parser is looking at. getNextToken reads another token from the
159/// lexer and updates CurTok with its results.
160static int CurTok;
161static int getNextToken() {
162 return CurTok = gettok();
163}
164
165/// BinopPrecedence - This holds the precedence for each binary operator that is
166/// defined.
167static std::map<char, int> BinopPrecedence;
168
169/// GetTokPrecedence - Get the precedence of the pending binary operator token.
170static int GetTokPrecedence() {
171 if (!isascii(CurTok))
172 return -1;
173
174 // Make sure it's a declared binop.
175 int TokPrec = BinopPrecedence[CurTok];
176 if (TokPrec <= 0) return -1;
177 return TokPrec;
178}
179
180/// Error* - These are little helper functions for error handling.
181ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
182PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
183FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
184
185static ExprAST *ParseExpression();
186
187/// identifierexpr
188/// ::= identifier
189/// ::= identifier '(' expression* ')'
190static ExprAST *ParseIdentifierExpr() {
191 std::string IdName = IdentifierStr;
192
193 getNextToken(); // eat identifier.
194
195 if (CurTok != '(') // Simple variable ref.
196 return new VariableExprAST(IdName);
197
198 // Call.
199 getNextToken(); // eat (
200 std::vector<ExprAST*> Args;
201 if (CurTok != ')') {
202 while (1) {
203 ExprAST *Arg = ParseExpression();
204 if (!Arg) return 0;
205 Args.push_back(Arg);
206
207 if (CurTok == ')') break;
208
209 if (CurTok != ',')
210 return Error("Expected ')' or ',' in argument list");
211 getNextToken();
212 }
213 }
214
215 // Eat the ')'.
216 getNextToken();
217
218 return new CallExprAST(IdName, Args);
219}
220
221/// numberexpr ::= number
222static ExprAST *ParseNumberExpr() {
223 ExprAST *Result = new NumberExprAST(NumVal);
224 getNextToken(); // consume the number
225 return Result;
226}
227
228/// parenexpr ::= '(' expression ')'
229static ExprAST *ParseParenExpr() {
230 getNextToken(); // eat (.
231 ExprAST *V = ParseExpression();
232 if (!V) return 0;
233
234 if (CurTok != ')')
235 return Error("expected ')'");
236 getNextToken(); // eat ).
237 return V;
238}
239
240/// primary
241/// ::= identifierexpr
242/// ::= numberexpr
243/// ::= parenexpr
244static ExprAST *ParsePrimary() {
245 switch (CurTok) {
246 default: return Error("unknown token when expecting an expression");
247 case tok_identifier: return ParseIdentifierExpr();
248 case tok_number: return ParseNumberExpr();
249 case '(': return ParseParenExpr();
250 }
251}
252
253/// binoprhs
254/// ::= ('+' primary)*
255static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
256 // If this is a binop, find its precedence.
257 while (1) {
258 int TokPrec = GetTokPrecedence();
259
260 // If this is a binop that binds at least as tightly as the current binop,
261 // consume it, otherwise we are done.
262 if (TokPrec < ExprPrec)
263 return LHS;
264
265 // Okay, we know this is a binop.
266 int BinOp = CurTok;
267 getNextToken(); // eat binop
268
269 // Parse the primary expression after the binary operator.
270 ExprAST *RHS = ParsePrimary();
271 if (!RHS) return 0;
272
273 // If BinOp binds less tightly with RHS than the operator after RHS, let
274 // the pending operator take RHS as its LHS.
275 int NextPrec = GetTokPrecedence();
276 if (TokPrec < NextPrec) {
277 RHS = ParseBinOpRHS(TokPrec+1, RHS);
278 if (RHS == 0) return 0;
279 }
280
281 // Merge LHS/RHS.
282 LHS = new BinaryExprAST(BinOp, LHS, RHS);
283 }
284}
285
286/// expression
287/// ::= primary binoprhs
288///
289static ExprAST *ParseExpression() {
290 ExprAST *LHS = ParsePrimary();
291 if (!LHS) return 0;
292
293 return ParseBinOpRHS(0, LHS);
294}
295
296/// prototype
297/// ::= id '(' id* ')'
298static PrototypeAST *ParsePrototype() {
299 if (CurTok != tok_identifier)
300 return ErrorP("Expected function name in prototype");
301
302 std::string FnName = IdentifierStr;
303 getNextToken();
304
305 if (CurTok != '(')
306 return ErrorP("Expected '(' in prototype");
307
308 std::vector<std::string> ArgNames;
309 while (getNextToken() == tok_identifier)
310 ArgNames.push_back(IdentifierStr);
311 if (CurTok != ')')
312 return ErrorP("Expected ')' in prototype");
313
314 // success.
315 getNextToken(); // eat ')'.
316
317 return new PrototypeAST(FnName, ArgNames);
318}
319
320/// definition ::= 'def' prototype expression
321static FunctionAST *ParseDefinition() {
322 getNextToken(); // eat def.
323 PrototypeAST *Proto = ParsePrototype();
324 if (Proto == 0) return 0;
325
326 if (ExprAST *E = ParseExpression())
327 return new FunctionAST(Proto, E);
328 return 0;
329}
330
331/// toplevelexpr ::= expression
332static FunctionAST *ParseTopLevelExpr() {
333 if (ExprAST *E = ParseExpression()) {
334 // Make an anonymous proto.
335 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
336 return new FunctionAST(Proto, E);
337 }
338 return 0;
339}
340
341/// external ::= 'extern' prototype
342static PrototypeAST *ParseExtern() {
343 getNextToken(); // eat extern.
344 return ParsePrototype();
345}
346
347//===----------------------------------------------------------------------===//
348// Code Generation
349//===----------------------------------------------------------------------===//
350
351static Module *TheModule;
352static IRBuilder<> Builder(getGlobalContext());
353static std::map<std::string, Value*> NamedValues;
354
355Value *ErrorV(const char *Str) { Error(Str); return 0; }
356
357Value *NumberExprAST::Codegen() {
358 return ConstantFP::get(getGlobalContext(), APFloat(Val));
359}
360
361Value *VariableExprAST::Codegen() {
362 // Look this variable up in the function.
363 Value *V = NamedValues[Name];
364 return V ? V : ErrorV("Unknown variable name");
365}
366
367Value *BinaryExprAST::Codegen() {
368 Value *L = LHS->Codegen();
369 Value *R = RHS->Codegen();
370 if (L == 0 || R == 0) return 0;
371
372 switch (Op) {
Chris Lattnerb0e9ead2010-06-21 22:51:14 +0000373 case '+': return Builder.CreateFAdd(L, R, "addtmp");
374 case '-': return Builder.CreateFSub(L, R, "subtmp");
375 case '*': return Builder.CreateFMul(L, R, "multmp");
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000376 case '<':
377 L = Builder.CreateFCmpULT(L, R, "cmptmp");
378 // Convert bool 0/1 to double 0.0 or 1.0
379 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
380 "booltmp");
381 default: return ErrorV("invalid binary operator");
382 }
383}
384
385Value *CallExprAST::Codegen() {
386 // Look up the name in the global module table.
387 Function *CalleeF = TheModule->getFunction(Callee);
388 if (CalleeF == 0)
389 return ErrorV("Unknown function referenced");
390
391 // If argument mismatch error.
392 if (CalleeF->arg_size() != Args.size())
393 return ErrorV("Incorrect # arguments passed");
394
395 std::vector<Value*> ArgsV;
396 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
397 ArgsV.push_back(Args[i]->Codegen());
398 if (ArgsV.back() == 0) return 0;
399 }
400
Francois Pichet0bd9d3a2011-07-15 10:59:52 +0000401 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000402}
403
404Function *PrototypeAST::Codegen() {
405 // Make the function type: double(double,double) etc.
John Wiegleyd1c2bd82011-07-11 22:39:46 +0000406 std::vector<Type*> Doubles(Args.size(),
407 Type::getDoubleTy(getGlobalContext()));
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +0000408 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
409 Doubles, false);
410
411 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
412
413 // If F conflicted, there was already something named 'Name'. If it has a
414 // body, don't allow redefinition or reextern.
415 if (F->getName() != Name) {
416 // Delete the one we just made and get the existing one.
417 F->eraseFromParent();
418 F = TheModule->getFunction(Name);
419
420 // If F already has a body, reject this.
421 if (!F->empty()) {
422 ErrorF("redefinition of function");
423 return 0;
424 }
425
426 // If F took a different number of args, reject.
427 if (F->arg_size() != Args.size()) {
428 ErrorF("redefinition of function with different # args");
429 return 0;
430 }
431 }
432
433 // Set names for all arguments.
434 unsigned Idx = 0;
435 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
436 ++AI, ++Idx) {
437 AI->setName(Args[Idx]);
438
439 // Add arguments to variable symbol table.
440 NamedValues[Args[Idx]] = AI;
441 }
442
443 return F;
444}
445
446Function *FunctionAST::Codegen() {
447 NamedValues.clear();
448
449 Function *TheFunction = Proto->Codegen();
450 if (TheFunction == 0)
451 return 0;
452
453 // Create a new basic block to start insertion into.
454 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
455 Builder.SetInsertPoint(BB);
456
457 if (Value *RetVal = Body->Codegen()) {
458 // Finish off the function.
459 Builder.CreateRet(RetVal);
460
461 // Validate the generated code, checking for consistency.
462 verifyFunction(*TheFunction);
463
464 return TheFunction;
465 }
466
467 // Error reading body, remove function.
468 TheFunction->eraseFromParent();
469 return 0;
470}
471
472//===----------------------------------------------------------------------===//
473// Top-Level parsing and JIT Driver
474//===----------------------------------------------------------------------===//
475
476static void HandleDefinition() {
477 if (FunctionAST *F = ParseDefinition()) {
478 if (Function *LF = F->Codegen()) {
479 fprintf(stderr, "Read function definition:");
480 LF->dump();
481 }
482 } else {
483 // Skip token for error recovery.
484 getNextToken();
485 }
486}
487
488static void HandleExtern() {
489 if (PrototypeAST *P = ParseExtern()) {
490 if (Function *F = P->Codegen()) {
491 fprintf(stderr, "Read extern: ");
492 F->dump();
493 }
494 } else {
495 // Skip token for error recovery.
496 getNextToken();
497 }
498}
499
500static void HandleTopLevelExpression() {
501 // Evaluate a top-level expression into an anonymous function.
502 if (FunctionAST *F = ParseTopLevelExpr()) {
503 if (Function *LF = F->Codegen()) {
504 fprintf(stderr, "Read top-level expression:");
505 LF->dump();
506 }
507 } else {
508 // Skip token for error recovery.
509 getNextToken();
510 }
511}
512
513/// top ::= definition | external | expression | ';'
514static void MainLoop() {
515 while (1) {
516 fprintf(stderr, "ready> ");
517 switch (CurTok) {
518 case tok_eof: return;
519 case ';': getNextToken(); break; // ignore top-level semicolons.
520 case tok_def: HandleDefinition(); break;
521 case tok_extern: HandleExtern(); break;
522 default: HandleTopLevelExpression(); break;
523 }
524 }
525}
526
527//===----------------------------------------------------------------------===//
528// "Library" functions that can be "extern'd" from user code.
529//===----------------------------------------------------------------------===//
530
531/// putchard - putchar that takes a double and returns 0.
532extern "C"
533double putchard(double X) {
534 putchar((char)X);
535 return 0;
536}
537
538//===----------------------------------------------------------------------===//
539// Main driver code.
540//===----------------------------------------------------------------------===//
541
542int main() {
543 LLVMContext &Context = getGlobalContext();
544
545 // Install standard binary operators.
546 // 1 is lowest precedence.
547 BinopPrecedence['<'] = 10;
548 BinopPrecedence['+'] = 20;
549 BinopPrecedence['-'] = 20;
550 BinopPrecedence['*'] = 40; // highest.
551
552 // Prime the first token.
553 fprintf(stderr, "ready> ");
554 getNextToken();
555
556 // Make the module, which holds all the code.
557 TheModule = new Module("my cool jit", Context);
558
559 // Run the main "interpreter loop" now.
560 MainLoop();
561
562 // Print out all of the generated code.
563 TheModule->dump();
564
565 return 0;
566}