1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/IR/IRBuilder.h"
3 #include "llvm/IR/LLVMContext.h"
4 #include "llvm/IR/Module.h"
5 #include "llvm/IR/Verifier.h"
13 //===----------------------------------------------------------------------===//
15 //===----------------------------------------------------------------------===//
17 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
18 // of these for known things.
31 static std::string IdentifierStr; // Filled in if tok_identifier
32 static double NumVal; // Filled in if tok_number
34 /// gettok - Return the next token from standard input.
36 static int LastChar = ' ';
38 // Skip any whitespace.
39 while (isspace(LastChar))
42 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
43 IdentifierStr = LastChar;
44 while (isalnum((LastChar = getchar())))
45 IdentifierStr += LastChar;
47 if (IdentifierStr == "def")
49 if (IdentifierStr == "extern")
51 return tok_identifier;
54 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
59 } while (isdigit(LastChar) || LastChar == '.');
61 NumVal = strtod(NumStr.c_str(), 0);
65 if (LastChar == '#') {
66 // Comment until end of line.
69 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
75 // Check for end of file. Don't eat the EOF.
79 // Otherwise, just return the character as its ascii value.
80 int ThisChar = LastChar;
85 //===----------------------------------------------------------------------===//
86 // Abstract Syntax Tree (aka Parse Tree)
87 //===----------------------------------------------------------------------===//
89 /// ExprAST - Base class for all expression nodes.
93 virtual Value *codegen() = 0;
96 /// NumberExprAST - Expression class for numeric literals like "1.0".
97 class NumberExprAST : public ExprAST {
101 NumberExprAST(double Val) : Val(Val) {}
102 Value *codegen() override;
105 /// VariableExprAST - Expression class for referencing a variable, like "a".
106 class VariableExprAST : public ExprAST {
110 VariableExprAST(const std::string &Name) : Name(Name) {}
111 Value *codegen() override;
114 /// BinaryExprAST - Expression class for a binary operator.
115 class BinaryExprAST : public ExprAST {
117 std::unique_ptr<ExprAST> LHS, RHS;
120 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
121 std::unique_ptr<ExprAST> RHS)
122 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
123 Value *codegen() override;
126 /// CallExprAST - Expression class for function calls.
127 class CallExprAST : public ExprAST {
129 std::vector<std::unique_ptr<ExprAST>> Args;
132 CallExprAST(const std::string &Callee,
133 std::vector<std::unique_ptr<ExprAST>> Args)
134 : Callee(Callee), Args(std::move(Args)) {}
135 Value *codegen() override;
138 /// PrototypeAST - This class represents the "prototype" for a function,
139 /// which captures its name, and its argument names (thus implicitly the number
140 /// of arguments the function takes).
143 std::vector<std::string> Args;
146 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
147 : Name(Name), Args(std::move(Args)) {}
149 const std::string &getName() const { return Name; }
152 /// FunctionAST - This class represents a function definition itself.
154 std::unique_ptr<PrototypeAST> Proto;
155 std::unique_ptr<ExprAST> Body;
158 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
159 std::unique_ptr<ExprAST> Body)
160 : Proto(std::move(Proto)), Body(std::move(Body)) {}
163 } // end anonymous namespace
165 //===----------------------------------------------------------------------===//
167 //===----------------------------------------------------------------------===//
169 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
170 /// token the parser is looking at. getNextToken reads another token from the
171 /// lexer and updates CurTok with its results.
173 static int getNextToken() { return CurTok = gettok(); }
175 /// BinopPrecedence - This holds the precedence for each binary operator that is
177 static std::map<char, int> BinopPrecedence;
179 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
180 static int GetTokPrecedence() {
181 if (!isascii(CurTok))
184 // Make sure it's a declared binop.
185 int TokPrec = BinopPrecedence[CurTok];
191 /// Error* - These are little helper functions for error handling.
192 std::unique_ptr<ExprAST> Error(const char *Str) {
193 fprintf(stderr, "Error: %s\n", Str);
196 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
201 static std::unique_ptr<ExprAST> ParseExpression();
203 /// numberexpr ::= number
204 static std::unique_ptr<ExprAST> ParseNumberExpr() {
205 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
206 getNextToken(); // consume the number
207 return std::move(Result);
210 /// parenexpr ::= '(' expression ')'
211 static std::unique_ptr<ExprAST> ParseParenExpr() {
212 getNextToken(); // eat (.
213 auto V = ParseExpression();
218 return Error("expected ')'");
219 getNextToken(); // eat ).
225 /// ::= identifier '(' expression* ')'
226 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
227 std::string IdName = IdentifierStr;
229 getNextToken(); // eat identifier.
231 if (CurTok != '(') // Simple variable ref.
232 return llvm::make_unique<VariableExprAST>(IdName);
235 getNextToken(); // eat (
236 std::vector<std::unique_ptr<ExprAST>> Args;
239 if (auto Arg = ParseExpression())
240 Args.push_back(std::move(Arg));
248 return Error("Expected ')' or ',' in argument list");
256 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
260 /// ::= identifierexpr
263 static std::unique_ptr<ExprAST> ParsePrimary() {
266 return Error("unknown token when expecting an expression");
268 return ParseIdentifierExpr();
270 return ParseNumberExpr();
272 return ParseParenExpr();
277 /// ::= ('+' primary)*
278 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
279 std::unique_ptr<ExprAST> LHS) {
280 // If this is a binop, find its precedence.
282 int TokPrec = GetTokPrecedence();
284 // If this is a binop that binds at least as tightly as the current binop,
285 // consume it, otherwise we are done.
286 if (TokPrec < ExprPrec)
289 // Okay, we know this is a binop.
291 getNextToken(); // eat binop
293 // Parse the primary expression after the binary operator.
294 auto RHS = ParsePrimary();
298 // If BinOp binds less tightly with RHS than the operator after RHS, let
299 // the pending operator take RHS as its LHS.
300 int NextPrec = GetTokPrecedence();
301 if (TokPrec < NextPrec) {
302 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
309 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
314 /// ::= primary binoprhs
316 static std::unique_ptr<ExprAST> ParseExpression() {
317 auto LHS = ParsePrimary();
321 return ParseBinOpRHS(0, std::move(LHS));
325 /// ::= id '(' id* ')'
326 static std::unique_ptr<PrototypeAST> ParsePrototype() {
327 if (CurTok != tok_identifier)
328 return ErrorP("Expected function name in prototype");
330 std::string FnName = IdentifierStr;
334 return ErrorP("Expected '(' in prototype");
336 std::vector<std::string> ArgNames;
337 while (getNextToken() == tok_identifier)
338 ArgNames.push_back(IdentifierStr);
340 return ErrorP("Expected ')' in prototype");
343 getNextToken(); // eat ')'.
345 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
348 /// definition ::= 'def' prototype expression
349 static std::unique_ptr<FunctionAST> ParseDefinition() {
350 getNextToken(); // eat def.
351 auto Proto = ParsePrototype();
355 if (auto E = ParseExpression())
356 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
360 /// toplevelexpr ::= expression
361 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
362 if (auto E = ParseExpression()) {
363 // Make an anonymous proto.
364 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
365 std::vector<std::string>());
366 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
371 /// external ::= 'extern' prototype
372 static std::unique_ptr<PrototypeAST> ParseExtern() {
373 getNextToken(); // eat extern.
374 return ParsePrototype();
377 //===----------------------------------------------------------------------===//
379 //===----------------------------------------------------------------------===//
381 static std::unique_ptr<Module> TheModule;
382 static IRBuilder<> Builder(getGlobalContext());
383 static std::map<std::string, Value *> NamedValues;
385 Value *ErrorV(const char *Str) {
390 Value *NumberExprAST::codegen() {
391 return ConstantFP::get(getGlobalContext(), APFloat(Val));
394 Value *VariableExprAST::codegen() {
395 // Look this variable up in the function.
396 Value *V = NamedValues[Name];
398 return ErrorV("Unknown variable name");
402 Value *BinaryExprAST::codegen() {
403 Value *L = LHS->codegen();
404 Value *R = RHS->codegen();
410 return Builder.CreateFAdd(L, R, "addtmp");
412 return Builder.CreateFSub(L, R, "subtmp");
414 return Builder.CreateFMul(L, R, "multmp");
416 L = Builder.CreateFCmpULT(L, R, "cmptmp");
417 // Convert bool 0/1 to double 0.0 or 1.0
418 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
421 return ErrorV("invalid binary operator");
425 Value *CallExprAST::codegen() {
426 // Look up the name in the global module table.
427 Function *CalleeF = TheModule->getFunction(Callee);
429 return ErrorV("Unknown function referenced");
431 // If argument mismatch error.
432 if (CalleeF->arg_size() != Args.size())
433 return ErrorV("Incorrect # arguments passed");
435 std::vector<Value *> ArgsV;
436 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
437 ArgsV.push_back(Args[i]->codegen());
442 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
445 Function *PrototypeAST::codegen() {
446 // Make the function type: double(double,double) etc.
447 std::vector<Type *> Doubles(Args.size(),
448 Type::getDoubleTy(getGlobalContext()));
450 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
453 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
455 // Set names for all arguments.
457 for (auto &Arg : F->args())
458 Arg.setName(Args[Idx++]);
463 Function *FunctionAST::codegen() {
464 // First, check for an existing function from a previous 'extern' declaration.
465 Function *TheFunction = TheModule->getFunction(Proto->getName());
468 TheFunction = Proto->codegen();
473 // Create a new basic block to start insertion into.
474 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
475 Builder.SetInsertPoint(BB);
477 // Record the function arguments in the NamedValues map.
479 for (auto &Arg : TheFunction->args())
480 NamedValues[Arg.getName()] = &Arg;
482 if (Value *RetVal = Body->codegen()) {
483 // Finish off the function.
484 Builder.CreateRet(RetVal);
486 // Validate the generated code, checking for consistency.
487 verifyFunction(*TheFunction);
492 // Error reading body, remove function.
493 TheFunction->eraseFromParent();
497 //===----------------------------------------------------------------------===//
498 // Top-Level parsing and JIT Driver
499 //===----------------------------------------------------------------------===//
501 static void HandleDefinition() {
502 if (auto FnAST = ParseDefinition()) {
503 if (auto *FnIR = FnAST->codegen()) {
504 fprintf(stderr, "Read function definition:");
508 // Skip token for error recovery.
513 static void HandleExtern() {
514 if (auto ProtoAST = ParseExtern()) {
515 if (auto *FnIR = ProtoAST->codegen()) {
516 fprintf(stderr, "Read extern: ");
520 // Skip token for error recovery.
525 static void HandleTopLevelExpression() {
526 // Evaluate a top-level expression into an anonymous function.
527 if (auto FnAST = ParseTopLevelExpr()) {
528 if (auto *FnIR = FnAST->codegen()) {
529 fprintf(stderr, "Read top-level expression:");
533 // Skip token for error recovery.
538 /// top ::= definition | external | expression | ';'
539 static void MainLoop() {
541 fprintf(stderr, "ready> ");
545 case ';': // ignore top-level semicolons.
555 HandleTopLevelExpression();
561 //===----------------------------------------------------------------------===//
563 //===----------------------------------------------------------------------===//
566 // Install standard binary operators.
567 // 1 is lowest precedence.
568 BinopPrecedence['<'] = 10;
569 BinopPrecedence['+'] = 20;
570 BinopPrecedence['-'] = 20;
571 BinopPrecedence['*'] = 40; // highest.
573 // Prime the first token.
574 fprintf(stderr, "ready> ");
577 // Make the module, which holds all the code.
578 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
580 // Run the main "interpreter loop" now.
583 // Print out all of the generated code.