1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/Passes.h"
3 #include "llvm/IR/IRBuilder.h"
4 #include "llvm/IR/LLVMContext.h"
5 #include "llvm/IR/LegacyPassManager.h"
6 #include "llvm/IR/Module.h"
7 #include "llvm/IR/Verifier.h"
8 #include "llvm/Support/TargetSelect.h"
9 #include "llvm/Transforms/Scalar.h"
15 #include "../include/KaleidoscopeJIT.h"
18 using namespace llvm::orc;
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
38 static std::string IdentifierStr; // Filled in if tok_identifier
39 static double NumVal; // Filled in if tok_number
41 /// gettok - Return the next token from standard input.
43 static int LastChar = ' ';
45 // Skip any whitespace.
46 while (isspace(LastChar))
49 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
50 IdentifierStr = LastChar;
51 while (isalnum((LastChar = getchar())))
52 IdentifierStr += LastChar;
54 if (IdentifierStr == "def")
56 if (IdentifierStr == "extern")
58 return tok_identifier;
61 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
66 } while (isdigit(LastChar) || LastChar == '.');
68 NumVal = strtod(NumStr.c_str(), 0);
72 if (LastChar == '#') {
73 // Comment until end of line.
76 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
82 // Check for end of file. Don't eat the EOF.
86 // Otherwise, just return the character as its ascii value.
87 int ThisChar = LastChar;
92 //===----------------------------------------------------------------------===//
93 // Abstract Syntax Tree (aka Parse Tree)
94 //===----------------------------------------------------------------------===//
96 /// ExprAST - Base class for all expression nodes.
100 virtual Value *codegen() = 0;
103 /// NumberExprAST - Expression class for numeric literals like "1.0".
104 class NumberExprAST : public ExprAST {
108 NumberExprAST(double Val) : Val(Val) {}
109 Value *codegen() override;
112 /// VariableExprAST - Expression class for referencing a variable, like "a".
113 class VariableExprAST : public ExprAST {
117 VariableExprAST(const std::string &Name) : Name(Name) {}
118 Value *codegen() override;
121 /// BinaryExprAST - Expression class for a binary operator.
122 class BinaryExprAST : public ExprAST {
124 std::unique_ptr<ExprAST> LHS, RHS;
127 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
128 std::unique_ptr<ExprAST> RHS)
129 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
130 Value *codegen() override;
133 /// CallExprAST - Expression class for function calls.
134 class CallExprAST : public ExprAST {
136 std::vector<std::unique_ptr<ExprAST>> Args;
139 CallExprAST(const std::string &Callee,
140 std::vector<std::unique_ptr<ExprAST>> Args)
141 : Callee(Callee), Args(std::move(Args)) {}
142 Value *codegen() override;
145 /// PrototypeAST - This class represents the "prototype" for a function,
146 /// which captures its name, and its argument names (thus implicitly the number
147 /// of arguments the function takes).
150 std::vector<std::string> Args;
153 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
154 : Name(Name), Args(std::move(Args)) {}
156 const std::string &getName() const { return Name; }
159 /// FunctionAST - This class represents a function definition itself.
161 std::unique_ptr<PrototypeAST> Proto;
162 std::unique_ptr<ExprAST> Body;
165 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
166 std::unique_ptr<ExprAST> Body)
167 : Proto(std::move(Proto)), Body(std::move(Body)) {}
170 } // end anonymous namespace
172 //===----------------------------------------------------------------------===//
174 //===----------------------------------------------------------------------===//
176 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
177 /// token the parser is looking at. getNextToken reads another token from the
178 /// lexer and updates CurTok with its results.
180 static int getNextToken() { return CurTok = gettok(); }
182 /// BinopPrecedence - This holds the precedence for each binary operator that is
184 static std::map<char, int> BinopPrecedence;
186 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
187 static int GetTokPrecedence() {
188 if (!isascii(CurTok))
191 // Make sure it's a declared binop.
192 int TokPrec = BinopPrecedence[CurTok];
198 /// Error* - These are little helper functions for error handling.
199 std::unique_ptr<ExprAST> Error(const char *Str) {
200 fprintf(stderr, "Error: %s\n", Str);
203 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
208 static std::unique_ptr<ExprAST> ParseExpression();
210 /// numberexpr ::= number
211 static std::unique_ptr<ExprAST> ParseNumberExpr() {
212 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
213 getNextToken(); // consume the number
214 return std::move(Result);
217 /// parenexpr ::= '(' expression ')'
218 static std::unique_ptr<ExprAST> ParseParenExpr() {
219 getNextToken(); // eat (.
220 auto V = ParseExpression();
225 return Error("expected ')'");
226 getNextToken(); // eat ).
232 /// ::= identifier '(' expression* ')'
233 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
234 std::string IdName = IdentifierStr;
236 getNextToken(); // eat identifier.
238 if (CurTok != '(') // Simple variable ref.
239 return llvm::make_unique<VariableExprAST>(IdName);
242 getNextToken(); // eat (
243 std::vector<std::unique_ptr<ExprAST>> Args;
246 if (auto Arg = ParseExpression())
247 Args.push_back(std::move(Arg));
255 return Error("Expected ')' or ',' in argument list");
263 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
267 /// ::= identifierexpr
270 static std::unique_ptr<ExprAST> ParsePrimary() {
273 return Error("unknown token when expecting an expression");
275 return ParseIdentifierExpr();
277 return ParseNumberExpr();
279 return ParseParenExpr();
284 /// ::= ('+' primary)*
285 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
286 std::unique_ptr<ExprAST> LHS) {
287 // If this is a binop, find its precedence.
289 int TokPrec = GetTokPrecedence();
291 // If this is a binop that binds at least as tightly as the current binop,
292 // consume it, otherwise we are done.
293 if (TokPrec < ExprPrec)
296 // Okay, we know this is a binop.
298 getNextToken(); // eat binop
300 // Parse the primary expression after the binary operator.
301 auto RHS = ParsePrimary();
305 // If BinOp binds less tightly with RHS than the operator after RHS, let
306 // the pending operator take RHS as its LHS.
307 int NextPrec = GetTokPrecedence();
308 if (TokPrec < NextPrec) {
309 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
316 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
321 /// ::= primary binoprhs
323 static std::unique_ptr<ExprAST> ParseExpression() {
324 auto LHS = ParsePrimary();
328 return ParseBinOpRHS(0, std::move(LHS));
332 /// ::= id '(' id* ')'
333 static std::unique_ptr<PrototypeAST> ParsePrototype() {
334 if (CurTok != tok_identifier)
335 return ErrorP("Expected function name in prototype");
337 std::string FnName = IdentifierStr;
341 return ErrorP("Expected '(' in prototype");
343 std::vector<std::string> ArgNames;
344 while (getNextToken() == tok_identifier)
345 ArgNames.push_back(IdentifierStr);
347 return ErrorP("Expected ')' in prototype");
350 getNextToken(); // eat ')'.
352 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
355 /// definition ::= 'def' prototype expression
356 static std::unique_ptr<FunctionAST> ParseDefinition() {
357 getNextToken(); // eat def.
358 auto Proto = ParsePrototype();
362 if (auto E = ParseExpression())
363 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
367 /// toplevelexpr ::= expression
368 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
369 if (auto E = ParseExpression()) {
370 // Make an anonymous proto.
371 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
372 std::vector<std::string>());
373 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
378 /// external ::= 'extern' prototype
379 static std::unique_ptr<PrototypeAST> ParseExtern() {
380 getNextToken(); // eat extern.
381 return ParsePrototype();
384 //===----------------------------------------------------------------------===//
386 //===----------------------------------------------------------------------===//
388 static std::unique_ptr<Module> TheModule;
389 static IRBuilder<> Builder(getGlobalContext());
390 static std::map<std::string, Value *> NamedValues;
391 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
392 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
393 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
395 Value *ErrorV(const char *Str) {
400 Function *getFunction(std::string Name) {
401 // First, see if the function has already been added to the current module.
402 if (auto *F = TheModule->getFunction(Name))
405 // If not, check whether we can codegen the declaration from some existing
407 auto FI = FunctionProtos.find(Name);
408 if (FI != FunctionProtos.end())
409 return FI->second->codegen();
411 // If no existing prototype exists, return null.
415 Value *NumberExprAST::codegen() {
416 return ConstantFP::get(getGlobalContext(), APFloat(Val));
419 Value *VariableExprAST::codegen() {
420 // Look this variable up in the function.
421 Value *V = NamedValues[Name];
423 return ErrorV("Unknown variable name");
427 Value *BinaryExprAST::codegen() {
428 Value *L = LHS->codegen();
429 Value *R = RHS->codegen();
435 return Builder.CreateFAdd(L, R, "addtmp");
437 return Builder.CreateFSub(L, R, "subtmp");
439 return Builder.CreateFMul(L, R, "multmp");
441 L = Builder.CreateFCmpULT(L, R, "cmptmp");
442 // Convert bool 0/1 to double 0.0 or 1.0
443 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
446 return ErrorV("invalid binary operator");
450 Value *CallExprAST::codegen() {
451 // Look up the name in the global module table.
452 Function *CalleeF = getFunction(Callee);
454 return ErrorV("Unknown function referenced");
456 // If argument mismatch error.
457 if (CalleeF->arg_size() != Args.size())
458 return ErrorV("Incorrect # arguments passed");
460 std::vector<Value *> ArgsV;
461 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
462 ArgsV.push_back(Args[i]->codegen());
467 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
470 Function *PrototypeAST::codegen() {
471 // Make the function type: double(double,double) etc.
472 std::vector<Type *> Doubles(Args.size(),
473 Type::getDoubleTy(getGlobalContext()));
475 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
478 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
480 // Set names for all arguments.
482 for (auto &Arg : F->args())
483 Arg.setName(Args[Idx++]);
488 Function *FunctionAST::codegen() {
489 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
490 // reference to it for use below.
492 FunctionProtos[Proto->getName()] = std::move(Proto);
493 Function *TheFunction = getFunction(P.getName());
497 // Create a new basic block to start insertion into.
498 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
499 Builder.SetInsertPoint(BB);
501 // Record the function arguments in the NamedValues map.
503 for (auto &Arg : TheFunction->args())
504 NamedValues[Arg.getName()] = &Arg;
506 if (Value *RetVal = Body->codegen()) {
507 // Finish off the function.
508 Builder.CreateRet(RetVal);
510 // Validate the generated code, checking for consistency.
511 verifyFunction(*TheFunction);
513 // Run the optimizer on the function.
514 TheFPM->run(*TheFunction);
519 // Error reading body, remove function.
520 TheFunction->eraseFromParent();
524 //===----------------------------------------------------------------------===//
525 // Top-Level parsing and JIT Driver
526 //===----------------------------------------------------------------------===//
528 static void InitializeModuleAndPassManager() {
529 // Open a new module.
530 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
531 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
533 // Create a new pass manager attached to it.
534 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
536 // Do simple "peephole" optimizations and bit-twiddling optzns.
537 TheFPM->add(createInstructionCombiningPass());
538 // Reassociate expressions.
539 TheFPM->add(createReassociatePass());
540 // Eliminate Common SubExpressions.
541 TheFPM->add(createGVNPass());
542 // Simplify the control flow graph (deleting unreachable blocks, etc).
543 TheFPM->add(createCFGSimplificationPass());
545 TheFPM->doInitialization();
548 static void HandleDefinition() {
549 if (auto FnAST = ParseDefinition()) {
550 if (auto *FnIR = FnAST->codegen()) {
551 fprintf(stderr, "Read function definition:");
553 TheJIT->addModule(std::move(TheModule));
554 InitializeModuleAndPassManager();
557 // Skip token for error recovery.
562 static void HandleExtern() {
563 if (auto ProtoAST = ParseExtern()) {
564 if (auto *FnIR = ProtoAST->codegen()) {
565 fprintf(stderr, "Read extern: ");
567 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
570 // Skip token for error recovery.
575 static void HandleTopLevelExpression() {
576 // Evaluate a top-level expression into an anonymous function.
577 if (auto FnAST = ParseTopLevelExpr()) {
578 if (FnAST->codegen()) {
580 // JIT the module containing the anonymous expression, keeping a handle so
581 // we can free it later.
582 auto H = TheJIT->addModule(std::move(TheModule));
583 InitializeModuleAndPassManager();
585 // Search the JIT for the __anon_expr symbol.
586 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
587 assert(ExprSymbol && "Function not found");
589 // Get the symbol's address and cast it to the right type (takes no
590 // arguments, returns a double) so we can call it as a native function.
591 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
592 fprintf(stderr, "Evaluated to %f\n", FP());
594 // Delete the anonymous expression module from the JIT.
595 TheJIT->removeModule(H);
598 // Skip token for error recovery.
603 /// top ::= definition | external | expression | ';'
604 static void MainLoop() {
606 fprintf(stderr, "ready> ");
610 case ';': // ignore top-level semicolons.
620 HandleTopLevelExpression();
626 //===----------------------------------------------------------------------===//
627 // "Library" functions that can be "extern'd" from user code.
628 //===----------------------------------------------------------------------===//
630 /// putchard - putchar that takes a double and returns 0.
631 extern "C" double putchard(double X) {
632 fputc((char)X, stderr);
636 /// printd - printf that takes a double prints it as "%f\n", returning 0.
637 extern "C" double printd(double X) {
638 fprintf(stderr, "%f\n", X);
642 //===----------------------------------------------------------------------===//
644 //===----------------------------------------------------------------------===//
647 InitializeNativeTarget();
648 InitializeNativeTargetAsmPrinter();
649 InitializeNativeTargetAsmParser();
651 // Install standard binary operators.
652 // 1 is lowest precedence.
653 BinopPrecedence['<'] = 10;
654 BinopPrecedence['+'] = 20;
655 BinopPrecedence['-'] = 20;
656 BinopPrecedence['*'] = 40; // highest.
658 // Prime the first token.
659 fprintf(stderr, "ready> ");
662 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
664 InitializeModuleAndPassManager();
666 // Run the main "interpreter loop" now.