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.
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(), 0);
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)) {}
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) {
200 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
205 static std::unique_ptr<ExprAST> ParseExpression();
207 /// numberexpr ::= number
208 static std::unique_ptr<ExprAST> ParseNumberExpr() {
209 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
210 getNextToken(); // consume the number
211 return std::move(Result);
214 /// parenexpr ::= '(' expression ')'
215 static std::unique_ptr<ExprAST> ParseParenExpr() {
216 getNextToken(); // eat (.
217 auto V = ParseExpression();
222 return Error("expected ')'");
223 getNextToken(); // eat ).
229 /// ::= identifier '(' expression* ')'
230 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
231 std::string IdName = IdentifierStr;
233 getNextToken(); // eat identifier.
235 if (CurTok != '(') // Simple variable ref.
236 return llvm::make_unique<VariableExprAST>(IdName);
239 getNextToken(); // eat (
240 std::vector<std::unique_ptr<ExprAST>> Args;
243 if (auto Arg = ParseExpression())
244 Args.push_back(std::move(Arg));
252 return Error("Expected ')' or ',' in argument list");
260 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
264 /// ::= identifierexpr
267 static std::unique_ptr<ExprAST> ParsePrimary() {
270 return Error("unknown token when expecting an expression");
272 return ParseIdentifierExpr();
274 return ParseNumberExpr();
276 return ParseParenExpr();
281 /// ::= ('+' primary)*
282 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
283 std::unique_ptr<ExprAST> LHS) {
284 // If this is a binop, find its precedence.
286 int TokPrec = GetTokPrecedence();
288 // If this is a binop that binds at least as tightly as the current binop,
289 // consume it, otherwise we are done.
290 if (TokPrec < ExprPrec)
293 // Okay, we know this is a binop.
295 getNextToken(); // eat binop
297 // Parse the primary expression after the binary operator.
298 auto RHS = ParsePrimary();
302 // If BinOp binds less tightly with RHS than the operator after RHS, let
303 // the pending operator take RHS as its LHS.
304 int NextPrec = GetTokPrecedence();
305 if (TokPrec < NextPrec) {
306 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
313 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
318 /// ::= primary binoprhs
320 static std::unique_ptr<ExprAST> ParseExpression() {
321 auto LHS = ParsePrimary();
325 return ParseBinOpRHS(0, std::move(LHS));
329 /// ::= id '(' id* ')'
330 static std::unique_ptr<PrototypeAST> ParsePrototype() {
331 if (CurTok != tok_identifier)
332 return ErrorP("Expected function name in prototype");
334 std::string FnName = IdentifierStr;
338 return ErrorP("Expected '(' in prototype");
340 std::vector<std::string> ArgNames;
341 while (getNextToken() == tok_identifier)
342 ArgNames.push_back(IdentifierStr);
344 return ErrorP("Expected ')' in prototype");
347 getNextToken(); // eat ')'.
349 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
352 /// definition ::= 'def' prototype expression
353 static std::unique_ptr<FunctionAST> ParseDefinition() {
354 getNextToken(); // eat def.
355 auto Proto = ParsePrototype();
359 if (auto E = ParseExpression())
360 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
364 /// toplevelexpr ::= expression
365 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
366 if (auto E = ParseExpression()) {
367 // Make an anonymous proto.
369 llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
370 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
375 /// external ::= 'extern' prototype
376 static std::unique_ptr<PrototypeAST> ParseExtern() {
377 getNextToken(); // eat extern.
378 return ParsePrototype();
381 //===----------------------------------------------------------------------===//
383 //===----------------------------------------------------------------------===//
385 Value *ErrorV(const char *Str) {
390 static Module *TheModule;
391 static IRBuilder<> Builder(getGlobalContext());
392 static std::map<std::string, Value *> NamedValues;
394 Value *NumberExprAST::Codegen() {
395 return ConstantFP::get(getGlobalContext(), APFloat(Val));
398 Value *VariableExprAST::Codegen() {
399 // Look this variable up in the function.
400 Value *V = NamedValues[Name];
401 return V ? V : 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);
457 // If F conflicted, there was already something named 'Name'. If it has a
458 // body, don't allow redefinition or reextern.
459 if (F->getName() != Name) {
460 // Delete the one we just made and get the existing one.
461 F->eraseFromParent();
462 F = TheModule->getFunction(Name);
464 // If F already has a body, reject this.
466 ErrorF("redefinition of function");
470 // If F took a different number of args, reject.
471 if (F->arg_size() != Args.size()) {
472 ErrorF("redefinition of function with different # args");
477 // Set names for all arguments.
479 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
481 AI->setName(Args[Idx]);
483 // Add arguments to variable symbol table.
484 NamedValues[Args[Idx]] = AI;
490 Function *FunctionAST::Codegen() {
493 Function *TheFunction = Proto->Codegen();
497 // Create a new basic block to start insertion into.
498 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
499 Builder.SetInsertPoint(BB);
501 if (Value *RetVal = Body->Codegen()) {
502 // Finish off the function.
503 Builder.CreateRet(RetVal);
505 // Validate the generated code, checking for consistency.
506 verifyFunction(*TheFunction);
511 // Error reading body, remove function.
512 TheFunction->eraseFromParent();
516 //===----------------------------------------------------------------------===//
517 // Top-Level parsing and JIT Driver
518 //===----------------------------------------------------------------------===//
520 static void HandleDefinition() {
521 if (auto FnAST = ParseDefinition()) {
522 if (auto *FnIR = FnAST->Codegen()) {
523 fprintf(stderr, "Read function definition:");
527 // Skip token for error recovery.
532 static void HandleExtern() {
533 if (auto ProtoAST = ParseExtern()) {
534 if (auto *FnIR = ProtoAST->Codegen()) {
535 fprintf(stderr, "Read extern: ");
539 // Skip token for error recovery.
544 static void HandleTopLevelExpression() {
545 // Evaluate a top-level expression into an anonymous function.
546 if (auto FnAST = ParseTopLevelExpr()) {
547 if (auto *FnIR = FnAST->Codegen()) {
548 fprintf(stderr, "Read top-level expression:");
552 // Skip token for error recovery.
557 /// top ::= definition | external | expression | ';'
558 static void MainLoop() {
560 fprintf(stderr, "ready> ");
564 case ';': // ignore top-level semicolons.
574 HandleTopLevelExpression();
580 //===----------------------------------------------------------------------===//
582 //===----------------------------------------------------------------------===//
585 LLVMContext &Context = getGlobalContext();
587 // Install standard binary operators.
588 // 1 is lowest precedence.
589 BinopPrecedence['<'] = 10;
590 BinopPrecedence['+'] = 20;
591 BinopPrecedence['-'] = 20;
592 BinopPrecedence['*'] = 40; // highest.
594 // Prime the first token.
595 fprintf(stderr, "ready> ");
598 // Make the module, which holds all the code.
599 std::unique_ptr<Module> Owner =
600 llvm::make_unique<Module>("my cool jit", Context);
601 TheModule = Owner.get();
603 // Run the main "interpreter loop" now.
606 // Print out all of the generated code.