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];
402 return ErrorV("Unknown variable name");
406 Value *BinaryExprAST::Codegen() {
407 Value *L = LHS->Codegen();
408 Value *R = RHS->Codegen();
414 return Builder.CreateFAdd(L, R, "addtmp");
416 return Builder.CreateFSub(L, R, "subtmp");
418 return Builder.CreateFMul(L, R, "multmp");
420 L = Builder.CreateFCmpULT(L, R, "cmptmp");
421 // Convert bool 0/1 to double 0.0 or 1.0
422 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
425 return ErrorV("invalid binary operator");
429 Value *CallExprAST::Codegen() {
430 // Look up the name in the global module table.
431 Function *CalleeF = TheModule->getFunction(Callee);
433 return ErrorV("Unknown function referenced");
435 // If argument mismatch error.
436 if (CalleeF->arg_size() != Args.size())
437 return ErrorV("Incorrect # arguments passed");
439 std::vector<Value *> ArgsV;
440 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
441 ArgsV.push_back(Args[i]->Codegen());
446 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
449 Function *PrototypeAST::Codegen() {
450 // Make the function type: double(double,double) etc.
451 std::vector<Type *> Doubles(Args.size(),
452 Type::getDoubleTy(getGlobalContext()));
454 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
457 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
459 // If F conflicted, there was already something named 'Name'. If it has a
460 // body, don't allow redefinition or reextern.
461 if (F->getName() != Name) {
462 // Delete the one we just made and get the existing one.
463 F->eraseFromParent();
464 F = TheModule->getFunction(Name);
466 // If F already has a body, reject this.
468 ErrorF("redefinition of function");
472 // If F took a different number of args, reject.
473 if (F->arg_size() != Args.size()) {
474 ErrorF("redefinition of function with different # args");
479 // Set names for all arguments.
481 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
483 AI->setName(Args[Idx]);
485 // Add arguments to variable symbol table.
486 NamedValues[Args[Idx]] = AI;
492 Function *FunctionAST::Codegen() {
495 Function *TheFunction = Proto->Codegen();
499 // Create a new basic block to start insertion into.
500 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
501 Builder.SetInsertPoint(BB);
503 if (Value *RetVal = Body->Codegen()) {
504 // Finish off the function.
505 Builder.CreateRet(RetVal);
507 // Validate the generated code, checking for consistency.
508 verifyFunction(*TheFunction);
513 // Error reading body, remove function.
514 TheFunction->eraseFromParent();
518 //===----------------------------------------------------------------------===//
519 // Top-Level parsing and JIT Driver
520 //===----------------------------------------------------------------------===//
522 static void HandleDefinition() {
523 if (auto FnAST = ParseDefinition()) {
524 if (auto *FnIR = FnAST->Codegen()) {
525 fprintf(stderr, "Read function definition:");
529 // Skip token for error recovery.
534 static void HandleExtern() {
535 if (auto ProtoAST = ParseExtern()) {
536 if (auto *FnIR = ProtoAST->Codegen()) {
537 fprintf(stderr, "Read extern: ");
541 // Skip token for error recovery.
546 static void HandleTopLevelExpression() {
547 // Evaluate a top-level expression into an anonymous function.
548 if (auto FnAST = ParseTopLevelExpr()) {
549 if (auto *FnIR = FnAST->Codegen()) {
550 fprintf(stderr, "Read top-level expression:");
554 // Skip token for error recovery.
559 /// top ::= definition | external | expression | ';'
560 static void MainLoop() {
562 fprintf(stderr, "ready> ");
566 case ';': // ignore top-level semicolons.
576 HandleTopLevelExpression();
582 //===----------------------------------------------------------------------===//
584 //===----------------------------------------------------------------------===//
587 LLVMContext &Context = getGlobalContext();
589 // Install standard binary operators.
590 // 1 is lowest precedence.
591 BinopPrecedence['<'] = 10;
592 BinopPrecedence['+'] = 20;
593 BinopPrecedence['-'] = 20;
594 BinopPrecedence['*'] = 40; // highest.
596 // Prime the first token.
597 fprintf(stderr, "ready> ");
600 // Make the module, which holds all the code.
601 std::unique_ptr<Module> Owner =
602 llvm::make_unique<Module>("my cool jit", Context);
603 TheModule = Owner.get();
605 // Run the main "interpreter loop" now.
608 // Print out all of the generated code.