1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/IR/Verifier.h"
3 #include "llvm/IR/DerivedTypes.h"
4 #include "llvm/IR/IRBuilder.h"
5 #include "llvm/IR/LLVMContext.h"
6 #include "llvm/IR/Module.h"
14 //===----------------------------------------------------------------------===//
16 //===----------------------------------------------------------------------===//
18 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
19 // of these for known things.
24 tok_def = -2, tok_extern = -3,
27 tok_identifier = -4, tok_number = -5
30 static std::string IdentifierStr; // Filled in if tok_identifier
31 static double NumVal; // Filled in if tok_number
33 /// gettok - Return the next token from standard input.
35 static int LastChar = ' ';
37 // Skip any whitespace.
38 while (isspace(LastChar))
41 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
42 IdentifierStr = LastChar;
43 while (isalnum((LastChar = getchar())))
44 IdentifierStr += LastChar;
46 if (IdentifierStr == "def") return tok_def;
47 if (IdentifierStr == "extern") return tok_extern;
48 return tok_identifier;
51 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
56 } while (isdigit(LastChar) || LastChar == '.');
58 NumVal = strtod(NumStr.c_str(), 0);
62 if (LastChar == '#') {
63 // Comment until end of line.
64 do LastChar = getchar();
65 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
71 // Check for end of file. Don't eat the EOF.
75 // Otherwise, just return the character as its ascii value.
76 int ThisChar = LastChar;
81 //===----------------------------------------------------------------------===//
82 // Abstract Syntax Tree (aka Parse Tree)
83 //===----------------------------------------------------------------------===//
85 /// ExprAST - Base class for all expression nodes.
89 virtual Value *Codegen() = 0;
92 /// NumberExprAST - Expression class for numeric literals like "1.0".
93 class NumberExprAST : public ExprAST {
96 NumberExprAST(double Val) : Val(Val) {}
97 Value *Codegen() override;
100 /// VariableExprAST - Expression class for referencing a variable, like "a".
101 class VariableExprAST : public ExprAST {
104 VariableExprAST(const std::string &Name) : Name(Name) {}
105 Value *Codegen() override;
108 /// BinaryExprAST - Expression class for a binary operator.
109 class BinaryExprAST : public ExprAST {
111 std::unique_ptr<ExprAST> LHS, RHS;
113 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
114 std::unique_ptr<ExprAST> RHS)
115 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
116 Value *Codegen() override;
119 /// CallExprAST - Expression class for function calls.
120 class CallExprAST : public ExprAST {
122 std::vector<std::unique_ptr<ExprAST>> Args;
124 CallExprAST(const std::string &Callee,
125 std::vector<std::unique_ptr<ExprAST>> Args)
126 : Callee(Callee), Args(std::move(Args)) {}
127 Value *Codegen() override;
130 /// PrototypeAST - This class represents the "prototype" for a function,
131 /// which captures its name, and its argument names (thus implicitly the number
132 /// of arguments the function takes).
135 std::vector<std::string> Args;
137 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
138 : Name(Name), Args(std::move(Args)) {}
143 /// FunctionAST - This class represents a function definition itself.
145 std::unique_ptr<PrototypeAST> Proto;
146 std::unique_ptr<ExprAST> Body;
148 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
149 std::unique_ptr<ExprAST> Body)
150 : Proto(std::move(Proto)), Body(std::move(Body)) {}
154 } // end anonymous namespace
156 //===----------------------------------------------------------------------===//
158 //===----------------------------------------------------------------------===//
160 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
161 /// token the parser is looking at. getNextToken reads another token from the
162 /// lexer and updates CurTok with its results.
164 static int getNextToken() {
165 return CurTok = gettok();
168 /// BinopPrecedence - This holds the precedence for each binary operator that is
170 static std::map<char, int> BinopPrecedence;
172 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
173 static int GetTokPrecedence() {
174 if (!isascii(CurTok))
177 // Make sure it's a declared binop.
178 int TokPrec = BinopPrecedence[CurTok];
179 if (TokPrec <= 0) return -1;
183 /// Error* - These are little helper functions for error handling.
184 std::unique_ptr<ExprAST> Error(const char *Str) {
185 fprintf(stderr, "Error: %s\n", Str);
188 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
192 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
197 static std::unique_ptr<ExprAST> ParseExpression();
201 /// ::= identifier '(' expression* ')'
202 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
203 std::string IdName = IdentifierStr;
205 getNextToken(); // eat identifier.
207 if (CurTok != '(') // Simple variable ref.
208 return llvm::make_unique<VariableExprAST>(IdName);
211 getNextToken(); // eat (
212 std::vector<std::unique_ptr<ExprAST>> Args;
215 if (auto Arg = ParseExpression())
216 Args.push_back(std::move(Arg));
220 if (CurTok == ')') break;
223 return Error("Expected ')' or ',' in argument list");
231 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
234 /// numberexpr ::= number
235 static std::unique_ptr<ExprAST> ParseNumberExpr() {
236 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
237 getNextToken(); // consume the number
238 return std::move(Result);
241 /// parenexpr ::= '(' expression ')'
242 static std::unique_ptr<ExprAST> ParseParenExpr() {
243 getNextToken(); // eat (.
244 auto V = ParseExpression();
249 return Error("expected ')'");
250 getNextToken(); // eat ).
255 /// ::= identifierexpr
258 static std::unique_ptr<ExprAST> ParsePrimary() {
260 default: return Error("unknown token when expecting an expression");
261 case tok_identifier: return ParseIdentifierExpr();
262 case tok_number: return ParseNumberExpr();
263 case '(': return ParseParenExpr();
268 /// ::= ('+' primary)*
269 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
270 std::unique_ptr<ExprAST> LHS) {
271 // If this is a binop, find its precedence.
273 int TokPrec = GetTokPrecedence();
275 // If this is a binop that binds at least as tightly as the current binop,
276 // consume it, otherwise we are done.
277 if (TokPrec < ExprPrec)
280 // Okay, we know this is a binop.
282 getNextToken(); // eat binop
284 // Parse the primary expression after the binary operator.
285 auto RHS = ParsePrimary();
286 if (!RHS) return nullptr;
288 // If BinOp binds less tightly with RHS than the operator after RHS, let
289 // the pending operator take RHS as its LHS.
290 int NextPrec = GetTokPrecedence();
291 if (TokPrec < NextPrec) {
292 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
293 if (!RHS) return nullptr;
297 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
303 /// ::= primary binoprhs
305 static std::unique_ptr<ExprAST> ParseExpression() {
306 auto LHS = ParsePrimary();
307 if (!LHS) return nullptr;
309 return ParseBinOpRHS(0, std::move(LHS));
313 /// ::= id '(' id* ')'
314 static std::unique_ptr<PrototypeAST> ParsePrototype() {
315 if (CurTok != tok_identifier)
316 return ErrorP("Expected function name in prototype");
318 std::string FnName = IdentifierStr;
322 return ErrorP("Expected '(' in prototype");
324 std::vector<std::string> ArgNames;
325 while (getNextToken() == tok_identifier)
326 ArgNames.push_back(IdentifierStr);
328 return ErrorP("Expected ')' in prototype");
331 getNextToken(); // eat ')'.
333 return llvm::make_unique<PrototypeAST>(std::move(FnName),
334 std::move(ArgNames));
337 /// definition ::= 'def' prototype expression
338 static std::unique_ptr<FunctionAST> ParseDefinition() {
339 getNextToken(); // eat def.
340 auto Proto = ParsePrototype();
341 if (!Proto) return nullptr;
343 if (auto E = ParseExpression())
344 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
348 /// toplevelexpr ::= expression
349 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
350 if (auto E = ParseExpression()) {
351 // Make an anonymous proto.
352 auto Proto = llvm::make_unique<PrototypeAST>("",
353 std::vector<std::string>());
354 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
359 /// external ::= 'extern' prototype
360 static std::unique_ptr<PrototypeAST> ParseExtern() {
361 getNextToken(); // eat extern.
362 return ParsePrototype();
365 //===----------------------------------------------------------------------===//
367 //===----------------------------------------------------------------------===//
369 static Module *TheModule;
370 static IRBuilder<> Builder(getGlobalContext());
371 static std::map<std::string, Value*> NamedValues;
373 Value *ErrorV(const char *Str) { Error(Str); return nullptr; }
375 Value *NumberExprAST::Codegen() {
376 return ConstantFP::get(getGlobalContext(), APFloat(Val));
379 Value *VariableExprAST::Codegen() {
380 // Look this variable up in the function.
381 Value *V = NamedValues[Name];
382 return V ? V : ErrorV("Unknown variable name");
385 Value *BinaryExprAST::Codegen() {
386 Value *L = LHS->Codegen();
387 Value *R = RHS->Codegen();
388 if (!L || !R) return nullptr;
391 case '+': return Builder.CreateFAdd(L, R, "addtmp");
392 case '-': return Builder.CreateFSub(L, R, "subtmp");
393 case '*': return Builder.CreateFMul(L, R, "multmp");
395 L = Builder.CreateFCmpULT(L, R, "cmptmp");
396 // Convert bool 0/1 to double 0.0 or 1.0
397 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
399 default: return ErrorV("invalid binary operator");
403 Value *CallExprAST::Codegen() {
404 // Look up the name in the global module table.
405 Function *CalleeF = TheModule->getFunction(Callee);
407 return ErrorV("Unknown function referenced");
409 // If argument mismatch error.
410 if (CalleeF->arg_size() != Args.size())
411 return ErrorV("Incorrect # arguments passed");
413 std::vector<Value*> ArgsV;
414 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
415 ArgsV.push_back(Args[i]->Codegen());
416 if (!ArgsV.back()) return nullptr;
419 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
422 Function *PrototypeAST::Codegen() {
423 // Make the function type: double(double,double) etc.
424 std::vector<Type*> Doubles(Args.size(),
425 Type::getDoubleTy(getGlobalContext()));
426 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
429 Function *F = Function::Create(FT, Function::ExternalLinkage, Name,
432 // If F conflicted, there was already something named 'Name'. If it has a
433 // body, don't allow redefinition or reextern.
434 if (F->getName() != Name) {
435 // Delete the one we just made and get the existing one.
436 F->eraseFromParent();
437 F = TheModule->getFunction(Name);
439 // If F already has a body, reject this.
441 ErrorF("redefinition of function");
445 // If F took a different number of args, reject.
446 if (F->arg_size() != Args.size()) {
447 ErrorF("redefinition of function with different # args");
452 // Set names for all arguments.
454 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
456 AI->setName(Args[Idx]);
458 // Add arguments to variable symbol table.
459 NamedValues[Args[Idx]] = AI;
465 Function *FunctionAST::Codegen() {
468 Function *TheFunction = Proto->Codegen();
472 // Create a new basic block to start insertion into.
473 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
474 Builder.SetInsertPoint(BB);
476 if (Value *RetVal = Body->Codegen()) {
477 // Finish off the function.
478 Builder.CreateRet(RetVal);
480 // Validate the generated code, checking for consistency.
481 verifyFunction(*TheFunction);
486 // Error reading body, remove function.
487 TheFunction->eraseFromParent();
491 //===----------------------------------------------------------------------===//
492 // Top-Level parsing and JIT Driver
493 //===----------------------------------------------------------------------===//
495 static void HandleDefinition() {
496 if (auto FnAST = ParseDefinition()) {
497 if (auto *FnIR = FnAST->Codegen()) {
498 fprintf(stderr, "Read function definition:");
502 // Skip token for error recovery.
507 static void HandleExtern() {
508 if (auto ProtoAST = ParseExtern()) {
509 if (auto *FnIR = ProtoAST->Codegen()) {
510 fprintf(stderr, "Read extern: ");
514 // Skip token for error recovery.
519 static void HandleTopLevelExpression() {
520 // Evaluate a top-level expression into an anonymous function.
521 if (auto FnAST = ParseTopLevelExpr()) {
522 if (auto *FnIR = FnAST->Codegen()) {
523 fprintf(stderr, "Read top-level expression:");
527 // Skip token for error recovery.
532 /// top ::= definition | external | expression | ';'
533 static void MainLoop() {
535 fprintf(stderr, "ready> ");
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;
546 //===----------------------------------------------------------------------===//
547 // "Library" functions that can be "extern'd" from user code.
548 //===----------------------------------------------------------------------===//
550 /// putchard - putchar that takes a double and returns 0.
552 double putchard(double X) {
557 //===----------------------------------------------------------------------===//
559 //===----------------------------------------------------------------------===//
562 LLVMContext &Context = getGlobalContext();
564 // Install standard binary operators.
565 // 1 is lowest precedence.
566 BinopPrecedence['<'] = 10;
567 BinopPrecedence['+'] = 20;
568 BinopPrecedence['-'] = 20;
569 BinopPrecedence['*'] = 40; // highest.
571 // Prime the first token.
572 fprintf(stderr, "ready> ");
575 // Make the module, which holds all the code.
576 std::unique_ptr<Module> Owner = llvm::make_unique<Module>("my cool jit", Context);
577 TheModule = Owner.get();
579 // Run the main "interpreter loop" now.
582 // Print out all of the generated code.