1 #include "llvm/IR/Verifier.h"
2 #include "llvm/IR/DerivedTypes.h"
3 #include "llvm/IR/IRBuilder.h"
4 #include "llvm/IR/LLVMContext.h"
5 #include "llvm/IR/Module.h"
13 //===----------------------------------------------------------------------===//
15 //===----------------------------------------------------------------------===//
17 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
18 // of these for known things.
23 tok_def = -2, tok_extern = -3,
26 tok_identifier = -4, tok_number = -5
29 static std::string IdentifierStr; // Filled in if tok_identifier
30 static double NumVal; // Filled in if tok_number
32 /// gettok - Return the next token from standard input.
34 static int LastChar = ' ';
36 // Skip any whitespace.
37 while (isspace(LastChar))
40 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
41 IdentifierStr = LastChar;
42 while (isalnum((LastChar = getchar())))
43 IdentifierStr += LastChar;
45 if (IdentifierStr == "def") return tok_def;
46 if (IdentifierStr == "extern") return tok_extern;
47 return tok_identifier;
50 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
55 } while (isdigit(LastChar) || LastChar == '.');
57 NumVal = strtod(NumStr.c_str(), 0);
61 if (LastChar == '#') {
62 // Comment until end of line.
63 do LastChar = getchar();
64 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
70 // Check for end of file. Don't eat the EOF.
74 // Otherwise, just return the character as its ascii value.
75 int ThisChar = LastChar;
80 //===----------------------------------------------------------------------===//
81 // Abstract Syntax Tree (aka Parse Tree)
82 //===----------------------------------------------------------------------===//
84 /// ExprAST - Base class for all expression nodes.
88 virtual Value *Codegen() = 0;
91 /// NumberExprAST - Expression class for numeric literals like "1.0".
92 class NumberExprAST : public ExprAST {
95 NumberExprAST(double val) : Val(val) {}
96 virtual Value *Codegen();
99 /// VariableExprAST - Expression class for referencing a variable, like "a".
100 class VariableExprAST : public ExprAST {
103 VariableExprAST(const std::string &name) : Name(name) {}
104 virtual Value *Codegen();
107 /// BinaryExprAST - Expression class for a binary operator.
108 class BinaryExprAST : public ExprAST {
112 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
113 : Op(op), LHS(lhs), RHS(rhs) {}
114 virtual Value *Codegen();
117 /// CallExprAST - Expression class for function calls.
118 class CallExprAST : public ExprAST {
120 std::vector<ExprAST*> Args;
122 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
123 : Callee(callee), Args(args) {}
124 virtual Value *Codegen();
127 /// PrototypeAST - This class represents the "prototype" for a function,
128 /// which captures its name, and its argument names (thus implicitly the number
129 /// of arguments the function takes).
132 std::vector<std::string> Args;
134 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
135 : Name(name), Args(args) {}
140 /// FunctionAST - This class represents a function definition itself.
145 FunctionAST(PrototypeAST *proto, ExprAST *body)
146 : Proto(proto), Body(body) {}
150 } // end anonymous namespace
152 //===----------------------------------------------------------------------===//
154 //===----------------------------------------------------------------------===//
156 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
157 /// token the parser is looking at. getNextToken reads another token from the
158 /// lexer and updates CurTok with its results.
160 static int getNextToken() {
161 return CurTok = gettok();
164 /// BinopPrecedence - This holds the precedence for each binary operator that is
166 static std::map<char, int> BinopPrecedence;
168 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
169 static int GetTokPrecedence() {
170 if (!isascii(CurTok))
173 // Make sure it's a declared binop.
174 int TokPrec = BinopPrecedence[CurTok];
175 if (TokPrec <= 0) return -1;
179 /// Error* - These are little helper functions for error handling.
180 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
181 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
182 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
184 static ExprAST *ParseExpression();
188 /// ::= identifier '(' expression* ')'
189 static ExprAST *ParseIdentifierExpr() {
190 std::string IdName = IdentifierStr;
192 getNextToken(); // eat identifier.
194 if (CurTok != '(') // Simple variable ref.
195 return new VariableExprAST(IdName);
198 getNextToken(); // eat (
199 std::vector<ExprAST*> Args;
202 ExprAST *Arg = ParseExpression();
206 if (CurTok == ')') break;
209 return Error("Expected ')' or ',' in argument list");
217 return new CallExprAST(IdName, Args);
220 /// numberexpr ::= number
221 static ExprAST *ParseNumberExpr() {
222 ExprAST *Result = new NumberExprAST(NumVal);
223 getNextToken(); // consume the number
227 /// parenexpr ::= '(' expression ')'
228 static ExprAST *ParseParenExpr() {
229 getNextToken(); // eat (.
230 ExprAST *V = ParseExpression();
234 return Error("expected ')'");
235 getNextToken(); // eat ).
240 /// ::= identifierexpr
243 static ExprAST *ParsePrimary() {
245 default: return Error("unknown token when expecting an expression");
246 case tok_identifier: return ParseIdentifierExpr();
247 case tok_number: return ParseNumberExpr();
248 case '(': return ParseParenExpr();
253 /// ::= ('+' primary)*
254 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
255 // If this is a binop, find its precedence.
257 int TokPrec = GetTokPrecedence();
259 // If this is a binop that binds at least as tightly as the current binop,
260 // consume it, otherwise we are done.
261 if (TokPrec < ExprPrec)
264 // Okay, we know this is a binop.
266 getNextToken(); // eat binop
268 // Parse the primary expression after the binary operator.
269 ExprAST *RHS = ParsePrimary();
272 // If BinOp binds less tightly with RHS than the operator after RHS, let
273 // the pending operator take RHS as its LHS.
274 int NextPrec = GetTokPrecedence();
275 if (TokPrec < NextPrec) {
276 RHS = ParseBinOpRHS(TokPrec+1, RHS);
277 if (RHS == 0) return 0;
281 LHS = new BinaryExprAST(BinOp, LHS, RHS);
286 /// ::= primary binoprhs
288 static ExprAST *ParseExpression() {
289 ExprAST *LHS = ParsePrimary();
292 return ParseBinOpRHS(0, LHS);
296 /// ::= id '(' id* ')'
297 static PrototypeAST *ParsePrototype() {
298 if (CurTok != tok_identifier)
299 return ErrorP("Expected function name in prototype");
301 std::string FnName = IdentifierStr;
305 return ErrorP("Expected '(' in prototype");
307 std::vector<std::string> ArgNames;
308 while (getNextToken() == tok_identifier)
309 ArgNames.push_back(IdentifierStr);
311 return ErrorP("Expected ')' in prototype");
314 getNextToken(); // eat ')'.
316 return new PrototypeAST(FnName, ArgNames);
319 /// definition ::= 'def' prototype expression
320 static FunctionAST *ParseDefinition() {
321 getNextToken(); // eat def.
322 PrototypeAST *Proto = ParsePrototype();
323 if (Proto == 0) return 0;
325 if (ExprAST *E = ParseExpression())
326 return new FunctionAST(Proto, E);
330 /// toplevelexpr ::= expression
331 static FunctionAST *ParseTopLevelExpr() {
332 if (ExprAST *E = ParseExpression()) {
333 // Make an anonymous proto.
334 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
335 return new FunctionAST(Proto, E);
340 /// external ::= 'extern' prototype
341 static PrototypeAST *ParseExtern() {
342 getNextToken(); // eat extern.
343 return ParsePrototype();
346 //===----------------------------------------------------------------------===//
348 //===----------------------------------------------------------------------===//
350 static Module *TheModule;
351 static IRBuilder<> Builder(getGlobalContext());
352 static std::map<std::string, Value*> NamedValues;
354 Value *ErrorV(const char *Str) { Error(Str); return 0; }
356 Value *NumberExprAST::Codegen() {
357 return ConstantFP::get(getGlobalContext(), APFloat(Val));
360 Value *VariableExprAST::Codegen() {
361 // Look this variable up in the function.
362 Value *V = NamedValues[Name];
363 return V ? V : ErrorV("Unknown variable name");
366 Value *BinaryExprAST::Codegen() {
367 Value *L = LHS->Codegen();
368 Value *R = RHS->Codegen();
369 if (L == 0 || R == 0) return 0;
372 case '+': return Builder.CreateFAdd(L, R, "addtmp");
373 case '-': return Builder.CreateFSub(L, R, "subtmp");
374 case '*': return Builder.CreateFMul(L, R, "multmp");
376 L = Builder.CreateFCmpULT(L, R, "cmptmp");
377 // Convert bool 0/1 to double 0.0 or 1.0
378 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
380 default: return ErrorV("invalid binary operator");
384 Value *CallExprAST::Codegen() {
385 // Look up the name in the global module table.
386 Function *CalleeF = TheModule->getFunction(Callee);
388 return ErrorV("Unknown function referenced");
390 // If argument mismatch error.
391 if (CalleeF->arg_size() != Args.size())
392 return ErrorV("Incorrect # arguments passed");
394 std::vector<Value*> ArgsV;
395 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
396 ArgsV.push_back(Args[i]->Codegen());
397 if (ArgsV.back() == 0) return 0;
400 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
403 Function *PrototypeAST::Codegen() {
404 // Make the function type: double(double,double) etc.
405 std::vector<Type*> Doubles(Args.size(),
406 Type::getDoubleTy(getGlobalContext()));
407 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
410 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
412 // If F conflicted, there was already something named 'Name'. If it has a
413 // body, don't allow redefinition or reextern.
414 if (F->getName() != Name) {
415 // Delete the one we just made and get the existing one.
416 F->eraseFromParent();
417 F = TheModule->getFunction(Name);
419 // If F already has a body, reject this.
421 ErrorF("redefinition of function");
425 // If F took a different number of args, reject.
426 if (F->arg_size() != Args.size()) {
427 ErrorF("redefinition of function with different # args");
432 // Set names for all arguments.
434 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
436 AI->setName(Args[Idx]);
438 // Add arguments to variable symbol table.
439 NamedValues[Args[Idx]] = AI;
445 Function *FunctionAST::Codegen() {
448 Function *TheFunction = Proto->Codegen();
449 if (TheFunction == 0)
452 // Create a new basic block to start insertion into.
453 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
454 Builder.SetInsertPoint(BB);
456 if (Value *RetVal = Body->Codegen()) {
457 // Finish off the function.
458 Builder.CreateRet(RetVal);
460 // Validate the generated code, checking for consistency.
461 verifyFunction(*TheFunction);
466 // Error reading body, remove function.
467 TheFunction->eraseFromParent();
471 //===----------------------------------------------------------------------===//
472 // Top-Level parsing and JIT Driver
473 //===----------------------------------------------------------------------===//
475 static void HandleDefinition() {
476 if (FunctionAST *F = ParseDefinition()) {
477 if (Function *LF = F->Codegen()) {
478 fprintf(stderr, "Read function definition:");
482 // Skip token for error recovery.
487 static void HandleExtern() {
488 if (PrototypeAST *P = ParseExtern()) {
489 if (Function *F = P->Codegen()) {
490 fprintf(stderr, "Read extern: ");
494 // Skip token for error recovery.
499 static void HandleTopLevelExpression() {
500 // Evaluate a top-level expression into an anonymous function.
501 if (FunctionAST *F = ParseTopLevelExpr()) {
502 if (Function *LF = F->Codegen()) {
503 fprintf(stderr, "Read top-level expression:");
507 // Skip token for error recovery.
512 /// top ::= definition | external | expression | ';'
513 static void MainLoop() {
515 fprintf(stderr, "ready> ");
517 case tok_eof: return;
518 case ';': getNextToken(); break; // ignore top-level semicolons.
519 case tok_def: HandleDefinition(); break;
520 case tok_extern: HandleExtern(); break;
521 default: HandleTopLevelExpression(); break;
526 //===----------------------------------------------------------------------===//
527 // "Library" functions that can be "extern'd" from user code.
528 //===----------------------------------------------------------------------===//
530 /// putchard - putchar that takes a double and returns 0.
532 double putchard(double X) {
537 //===----------------------------------------------------------------------===//
539 //===----------------------------------------------------------------------===//
542 LLVMContext &Context = getGlobalContext();
544 // Install standard binary operators.
545 // 1 is lowest precedence.
546 BinopPrecedence['<'] = 10;
547 BinopPrecedence['+'] = 20;
548 BinopPrecedence['-'] = 20;
549 BinopPrecedence['*'] = 40; // highest.
551 // Prime the first token.
552 fprintf(stderr, "ready> ");
555 // Make the module, which holds all the code.
556 TheModule = new Module("my cool jit", Context);
558 // Run the main "interpreter loop" now.
561 // Print out all of the generated code.