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"
14 //===----------------------------------------------------------------------===//
16 //===----------------------------------------------------------------------===//
18 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
19 // of these for known things.
32 static std::string IdentifierStr; // Filled in if tok_identifier
33 static double NumVal; // Filled in if tok_number
35 /// gettok - Return the next token from standard input.
37 static int LastChar = ' ';
39 // Skip any whitespace.
40 while (isspace(LastChar))
43 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
44 IdentifierStr = LastChar;
45 while (isalnum((LastChar = getchar())))
46 IdentifierStr += LastChar;
48 if (IdentifierStr == "def")
50 if (IdentifierStr == "extern")
52 return tok_identifier;
55 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
60 } while (isdigit(LastChar) || LastChar == '.');
62 NumVal = strtod(NumStr.c_str(), nullptr);
66 if (LastChar == '#') {
67 // Comment until end of line.
70 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
76 // Check for end of file. Don't eat the EOF.
80 // Otherwise, just return the character as its ascii value.
81 int ThisChar = LastChar;
86 //===----------------------------------------------------------------------===//
87 // Abstract Syntax Tree (aka Parse Tree)
88 //===----------------------------------------------------------------------===//
90 /// ExprAST - Base class for all expression nodes.
94 virtual Value *codegen() = 0;
97 /// NumberExprAST - Expression class for numeric literals like "1.0".
98 class NumberExprAST : public ExprAST {
102 NumberExprAST(double Val) : Val(Val) {}
103 Value *codegen() override;
106 /// VariableExprAST - Expression class for referencing a variable, like "a".
107 class VariableExprAST : public ExprAST {
111 VariableExprAST(const std::string &Name) : Name(Name) {}
112 Value *codegen() override;
115 /// BinaryExprAST - Expression class for a binary operator.
116 class BinaryExprAST : public ExprAST {
118 std::unique_ptr<ExprAST> LHS, RHS;
121 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
122 std::unique_ptr<ExprAST> RHS)
123 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
124 Value *codegen() override;
127 /// CallExprAST - Expression class for function calls.
128 class CallExprAST : public ExprAST {
130 std::vector<std::unique_ptr<ExprAST>> Args;
133 CallExprAST(const std::string &Callee,
134 std::vector<std::unique_ptr<ExprAST>> Args)
135 : Callee(Callee), Args(std::move(Args)) {}
136 Value *codegen() override;
139 /// PrototypeAST - This class represents the "prototype" for a function,
140 /// which captures its name, and its argument names (thus implicitly the number
141 /// of arguments the function takes).
144 std::vector<std::string> Args;
147 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
148 : Name(Name), Args(std::move(Args)) {}
150 const std::string &getName() const { return Name; }
153 /// FunctionAST - This class represents a function definition itself.
155 std::unique_ptr<PrototypeAST> Proto;
156 std::unique_ptr<ExprAST> Body;
159 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
160 std::unique_ptr<ExprAST> Body)
161 : Proto(std::move(Proto)), Body(std::move(Body)) {}
164 } // end anonymous namespace
166 //===----------------------------------------------------------------------===//
168 //===----------------------------------------------------------------------===//
170 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
171 /// token the parser is looking at. getNextToken reads another token from the
172 /// lexer and updates CurTok with its results.
174 static int getNextToken() { return CurTok = gettok(); }
176 /// BinopPrecedence - This holds the precedence for each binary operator that is
178 static std::map<char, int> BinopPrecedence;
180 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
181 static int GetTokPrecedence() {
182 if (!isascii(CurTok))
185 // Make sure it's a declared binop.
186 int TokPrec = BinopPrecedence[CurTok];
192 /// Error* - These are little helper functions for error handling.
193 std::unique_ptr<ExprAST> Error(const char *Str) {
194 fprintf(stderr, "Error: %s\n", Str);
198 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
203 static std::unique_ptr<ExprAST> ParseExpression();
205 /// numberexpr ::= number
206 static std::unique_ptr<ExprAST> ParseNumberExpr() {
207 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
208 getNextToken(); // consume the number
209 return std::move(Result);
212 /// parenexpr ::= '(' expression ')'
213 static std::unique_ptr<ExprAST> ParseParenExpr() {
214 getNextToken(); // eat (.
215 auto V = ParseExpression();
220 return Error("expected ')'");
221 getNextToken(); // eat ).
227 /// ::= identifier '(' expression* ')'
228 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
229 std::string IdName = IdentifierStr;
231 getNextToken(); // eat identifier.
233 if (CurTok != '(') // Simple variable ref.
234 return llvm::make_unique<VariableExprAST>(IdName);
237 getNextToken(); // eat (
238 std::vector<std::unique_ptr<ExprAST>> Args;
241 if (auto Arg = ParseExpression())
242 Args.push_back(std::move(Arg));
250 return Error("Expected ')' or ',' in argument list");
258 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
262 /// ::= identifierexpr
265 static std::unique_ptr<ExprAST> ParsePrimary() {
268 return Error("unknown token when expecting an expression");
270 return ParseIdentifierExpr();
272 return ParseNumberExpr();
274 return ParseParenExpr();
279 /// ::= ('+' primary)*
280 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
281 std::unique_ptr<ExprAST> LHS) {
282 // If this is a binop, find its precedence.
284 int TokPrec = GetTokPrecedence();
286 // If this is a binop that binds at least as tightly as the current binop,
287 // consume it, otherwise we are done.
288 if (TokPrec < ExprPrec)
291 // Okay, we know this is a binop.
293 getNextToken(); // eat binop
295 // Parse the primary expression after the binary operator.
296 auto RHS = ParsePrimary();
300 // If BinOp binds less tightly with RHS than the operator after RHS, let
301 // the pending operator take RHS as its LHS.
302 int NextPrec = GetTokPrecedence();
303 if (TokPrec < NextPrec) {
304 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
311 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
316 /// ::= primary binoprhs
318 static std::unique_ptr<ExprAST> ParseExpression() {
319 auto LHS = ParsePrimary();
323 return ParseBinOpRHS(0, std::move(LHS));
327 /// ::= id '(' id* ')'
328 static std::unique_ptr<PrototypeAST> ParsePrototype() {
329 if (CurTok != tok_identifier)
330 return ErrorP("Expected function name in prototype");
332 std::string FnName = IdentifierStr;
336 return ErrorP("Expected '(' in prototype");
338 std::vector<std::string> ArgNames;
339 while (getNextToken() == tok_identifier)
340 ArgNames.push_back(IdentifierStr);
342 return ErrorP("Expected ')' in prototype");
345 getNextToken(); // eat ')'.
347 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
350 /// definition ::= 'def' prototype expression
351 static std::unique_ptr<FunctionAST> ParseDefinition() {
352 getNextToken(); // eat def.
353 auto Proto = ParsePrototype();
357 if (auto E = ParseExpression())
358 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
362 /// toplevelexpr ::= expression
363 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
364 if (auto E = ParseExpression()) {
365 // Make an anonymous proto.
366 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
367 std::vector<std::string>());
368 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
373 /// external ::= 'extern' prototype
374 static std::unique_ptr<PrototypeAST> ParseExtern() {
375 getNextToken(); // eat extern.
376 return ParsePrototype();
379 //===----------------------------------------------------------------------===//
381 //===----------------------------------------------------------------------===//
383 static std::unique_ptr<Module> TheModule;
384 static IRBuilder<> Builder(getGlobalContext());
385 static std::map<std::string, Value *> NamedValues;
387 Value *ErrorV(const char *Str) {
392 Value *NumberExprAST::codegen() {
393 return ConstantFP::get(getGlobalContext(), APFloat(Val));
396 Value *VariableExprAST::codegen() {
397 // Look this variable up in the function.
398 Value *V = NamedValues[Name];
400 return ErrorV("Unknown variable name");
404 Value *BinaryExprAST::codegen() {
405 Value *L = LHS->codegen();
406 Value *R = RHS->codegen();
412 return Builder.CreateFAdd(L, R, "addtmp");
414 return Builder.CreateFSub(L, R, "subtmp");
416 return Builder.CreateFMul(L, R, "multmp");
418 L = Builder.CreateFCmpULT(L, R, "cmptmp");
419 // Convert bool 0/1 to double 0.0 or 1.0
420 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
423 return ErrorV("invalid binary operator");
427 Value *CallExprAST::codegen() {
428 // Look up the name in the global module table.
429 Function *CalleeF = TheModule->getFunction(Callee);
431 return ErrorV("Unknown function referenced");
433 // If argument mismatch error.
434 if (CalleeF->arg_size() != Args.size())
435 return ErrorV("Incorrect # arguments passed");
437 std::vector<Value *> ArgsV;
438 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
439 ArgsV.push_back(Args[i]->codegen());
444 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
447 Function *PrototypeAST::codegen() {
448 // Make the function type: double(double,double) etc.
449 std::vector<Type *> Doubles(Args.size(),
450 Type::getDoubleTy(getGlobalContext()));
452 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
455 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
457 // Set names for all arguments.
459 for (auto &Arg : F->args())
460 Arg.setName(Args[Idx++]);
465 Function *FunctionAST::codegen() {
466 // First, check for an existing function from a previous 'extern' declaration.
467 Function *TheFunction = TheModule->getFunction(Proto->getName());
470 TheFunction = Proto->codegen();
475 // Create a new basic block to start insertion into.
476 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
477 Builder.SetInsertPoint(BB);
479 // Record the function arguments in the NamedValues map.
481 for (auto &Arg : TheFunction->args())
482 NamedValues[Arg.getName()] = &Arg;
484 if (Value *RetVal = Body->codegen()) {
485 // Finish off the function.
486 Builder.CreateRet(RetVal);
488 // Validate the generated code, checking for consistency.
489 verifyFunction(*TheFunction);
494 // Error reading body, remove function.
495 TheFunction->eraseFromParent();
499 //===----------------------------------------------------------------------===//
500 // Top-Level parsing and JIT Driver
501 //===----------------------------------------------------------------------===//
503 static void HandleDefinition() {
504 if (auto FnAST = ParseDefinition()) {
505 if (auto *FnIR = FnAST->codegen()) {
506 fprintf(stderr, "Read function definition:");
510 // Skip token for error recovery.
515 static void HandleExtern() {
516 if (auto ProtoAST = ParseExtern()) {
517 if (auto *FnIR = ProtoAST->codegen()) {
518 fprintf(stderr, "Read extern: ");
522 // Skip token for error recovery.
527 static void HandleTopLevelExpression() {
528 // Evaluate a top-level expression into an anonymous function.
529 if (auto FnAST = ParseTopLevelExpr()) {
530 if (auto *FnIR = FnAST->codegen()) {
531 fprintf(stderr, "Read top-level expression:");
535 // Skip token for error recovery.
540 /// top ::= definition | external | expression | ';'
541 static void MainLoop() {
543 fprintf(stderr, "ready> ");
547 case ';': // ignore top-level semicolons.
557 HandleTopLevelExpression();
563 //===----------------------------------------------------------------------===//
565 //===----------------------------------------------------------------------===//
568 // Install standard binary operators.
569 // 1 is lowest precedence.
570 BinopPrecedence['<'] = 10;
571 BinopPrecedence['+'] = 20;
572 BinopPrecedence['-'] = 20;
573 BinopPrecedence['*'] = 40; // highest.
575 // Prime the first token.
576 fprintf(stderr, "ready> ");
579 // Make the module, which holds all the code.
580 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
582 // Run the main "interpreter loop" now.
585 // Print out all of the generated code.