1 #include "../include/KaleidoscopeJIT.h"
2 #include "llvm/ADT/APFloat.h"
3 #include "llvm/ADT/STLExtras.h"
4 #include "llvm/IR/BasicBlock.h"
5 #include "llvm/IR/Constants.h"
6 #include "llvm/IR/DerivedTypes.h"
7 #include "llvm/IR/Function.h"
8 #include "llvm/IR/IRBuilder.h"
9 #include "llvm/IR/LLVMContext.h"
10 #include "llvm/IR/LegacyPassManager.h"
11 #include "llvm/IR/Module.h"
12 #include "llvm/IR/Type.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Transforms/InstCombine/InstCombine.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Transforms/Scalar/GVN.h"
19 #include <algorithm>
20 #include <cassert>
21 #include <cctype>
22 #include <cstdint>
23 #include <cstdio>
24 #include <cstdlib>
25 #include <map>
26 #include <memory>
27 #include <string>
28 #include <vector>
29 
30 using namespace llvm;
31 using namespace llvm::orc;
32 
33 //===----------------------------------------------------------------------===//
34 // Lexer
35 //===----------------------------------------------------------------------===//
36 
37 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
38 // of these for known things.
39 enum Token {
40   tok_eof = -1,
41 
42   // commands
43   tok_def = -2,
44   tok_extern = -3,
45 
46   // primary
47   tok_identifier = -4,
48   tok_number = -5
49 };
50 
51 static std::string IdentifierStr; // Filled in if tok_identifier
52 static double NumVal;             // Filled in if tok_number
53 
54 /// gettok - Return the next token from standard input.
gettok()55 static int gettok() {
56   static int LastChar = ' ';
57 
58   // Skip any whitespace.
59   while (isspace(LastChar))
60     LastChar = getchar();
61 
62   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
63     IdentifierStr = LastChar;
64     while (isalnum((LastChar = getchar())))
65       IdentifierStr += LastChar;
66 
67     if (IdentifierStr == "def")
68       return tok_def;
69     if (IdentifierStr == "extern")
70       return tok_extern;
71     return tok_identifier;
72   }
73 
74   if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
75     std::string NumStr;
76     do {
77       NumStr += LastChar;
78       LastChar = getchar();
79     } while (isdigit(LastChar) || LastChar == '.');
80 
81     NumVal = strtod(NumStr.c_str(), nullptr);
82     return tok_number;
83   }
84 
85   if (LastChar == '#') {
86     // Comment until end of line.
87     do
88       LastChar = getchar();
89     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
90 
91     if (LastChar != EOF)
92       return gettok();
93   }
94 
95   // Check for end of file.  Don't eat the EOF.
96   if (LastChar == EOF)
97     return tok_eof;
98 
99   // Otherwise, just return the character as its ascii value.
100   int ThisChar = LastChar;
101   LastChar = getchar();
102   return ThisChar;
103 }
104 
105 //===----------------------------------------------------------------------===//
106 // Abstract Syntax Tree (aka Parse Tree)
107 //===----------------------------------------------------------------------===//
108 
109 namespace {
110 
111 /// ExprAST - Base class for all expression nodes.
112 class ExprAST {
113 public:
114   virtual ~ExprAST() = default;
115 
116   virtual Value *codegen() = 0;
117 };
118 
119 /// NumberExprAST - Expression class for numeric literals like "1.0".
120 class NumberExprAST : public ExprAST {
121   double Val;
122 
123 public:
NumberExprAST(double Val)124   NumberExprAST(double Val) : Val(Val) {}
125 
126   Value *codegen() override;
127 };
128 
129 /// VariableExprAST - Expression class for referencing a variable, like "a".
130 class VariableExprAST : public ExprAST {
131   std::string Name;
132 
133 public:
VariableExprAST(const std::string & Name)134   VariableExprAST(const std::string &Name) : Name(Name) {}
135 
136   Value *codegen() override;
137 };
138 
139 /// BinaryExprAST - Expression class for a binary operator.
140 class BinaryExprAST : public ExprAST {
141   char Op;
142   std::unique_ptr<ExprAST> LHS, RHS;
143 
144 public:
BinaryExprAST(char Op,std::unique_ptr<ExprAST> LHS,std::unique_ptr<ExprAST> RHS)145   BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
146                 std::unique_ptr<ExprAST> RHS)
147       : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
148 
149   Value *codegen() override;
150 };
151 
152 /// CallExprAST - Expression class for function calls.
153 class CallExprAST : public ExprAST {
154   std::string Callee;
155   std::vector<std::unique_ptr<ExprAST>> Args;
156 
157 public:
CallExprAST(const std::string & Callee,std::vector<std::unique_ptr<ExprAST>> Args)158   CallExprAST(const std::string &Callee,
159               std::vector<std::unique_ptr<ExprAST>> Args)
160       : Callee(Callee), Args(std::move(Args)) {}
161 
162   Value *codegen() override;
163 };
164 
165 /// PrototypeAST - This class represents the "prototype" for a function,
166 /// which captures its name, and its argument names (thus implicitly the number
167 /// of arguments the function takes).
168 class PrototypeAST {
169   std::string Name;
170   std::vector<std::string> Args;
171 
172 public:
PrototypeAST(const std::string & Name,std::vector<std::string> Args)173   PrototypeAST(const std::string &Name, std::vector<std::string> Args)
174       : Name(Name), Args(std::move(Args)) {}
175 
176   Function *codegen();
getName() const177   const std::string &getName() const { return Name; }
178 };
179 
180 /// FunctionAST - This class represents a function definition itself.
181 class FunctionAST {
182   std::unique_ptr<PrototypeAST> Proto;
183   std::unique_ptr<ExprAST> Body;
184 
185 public:
FunctionAST(std::unique_ptr<PrototypeAST> Proto,std::unique_ptr<ExprAST> Body)186   FunctionAST(std::unique_ptr<PrototypeAST> Proto,
187               std::unique_ptr<ExprAST> Body)
188       : Proto(std::move(Proto)), Body(std::move(Body)) {}
189 
190   Function *codegen();
191 };
192 
193 } // end anonymous namespace
194 
195 //===----------------------------------------------------------------------===//
196 // Parser
197 //===----------------------------------------------------------------------===//
198 
199 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
200 /// token the parser is looking at.  getNextToken reads another token from the
201 /// lexer and updates CurTok with its results.
202 static int CurTok;
getNextToken()203 static int getNextToken() { return CurTok = gettok(); }
204 
205 /// BinopPrecedence - This holds the precedence for each binary operator that is
206 /// defined.
207 static std::map<char, int> BinopPrecedence;
208 
209 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
GetTokPrecedence()210 static int GetTokPrecedence() {
211   if (!isascii(CurTok))
212     return -1;
213 
214   // Make sure it's a declared binop.
215   int TokPrec = BinopPrecedence[CurTok];
216   if (TokPrec <= 0)
217     return -1;
218   return TokPrec;
219 }
220 
221 /// LogError* - These are little helper functions for error handling.
LogError(const char * Str)222 std::unique_ptr<ExprAST> LogError(const char *Str) {
223   fprintf(stderr, "Error: %s\n", Str);
224   return nullptr;
225 }
226 
LogErrorP(const char * Str)227 std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
228   LogError(Str);
229   return nullptr;
230 }
231 
232 static std::unique_ptr<ExprAST> ParseExpression();
233 
234 /// numberexpr ::= number
ParseNumberExpr()235 static std::unique_ptr<ExprAST> ParseNumberExpr() {
236   auto Result = std::make_unique<NumberExprAST>(NumVal);
237   getNextToken(); // consume the number
238   return std::move(Result);
239 }
240 
241 /// parenexpr ::= '(' expression ')'
ParseParenExpr()242 static std::unique_ptr<ExprAST> ParseParenExpr() {
243   getNextToken(); // eat (.
244   auto V = ParseExpression();
245   if (!V)
246     return nullptr;
247 
248   if (CurTok != ')')
249     return LogError("expected ')'");
250   getNextToken(); // eat ).
251   return V;
252 }
253 
254 /// identifierexpr
255 ///   ::= identifier
256 ///   ::= identifier '(' expression* ')'
ParseIdentifierExpr()257 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
258   std::string IdName = IdentifierStr;
259 
260   getNextToken(); // eat identifier.
261 
262   if (CurTok != '(') // Simple variable ref.
263     return std::make_unique<VariableExprAST>(IdName);
264 
265   // Call.
266   getNextToken(); // eat (
267   std::vector<std::unique_ptr<ExprAST>> Args;
268   if (CurTok != ')') {
269     while (true) {
270       if (auto Arg = ParseExpression())
271         Args.push_back(std::move(Arg));
272       else
273         return nullptr;
274 
275       if (CurTok == ')')
276         break;
277 
278       if (CurTok != ',')
279         return LogError("Expected ')' or ',' in argument list");
280       getNextToken();
281     }
282   }
283 
284   // Eat the ')'.
285   getNextToken();
286 
287   return std::make_unique<CallExprAST>(IdName, std::move(Args));
288 }
289 
290 /// primary
291 ///   ::= identifierexpr
292 ///   ::= numberexpr
293 ///   ::= parenexpr
ParsePrimary()294 static std::unique_ptr<ExprAST> ParsePrimary() {
295   switch (CurTok) {
296   default:
297     return LogError("unknown token when expecting an expression");
298   case tok_identifier:
299     return ParseIdentifierExpr();
300   case tok_number:
301     return ParseNumberExpr();
302   case '(':
303     return ParseParenExpr();
304   }
305 }
306 
307 /// binoprhs
308 ///   ::= ('+' primary)*
ParseBinOpRHS(int ExprPrec,std::unique_ptr<ExprAST> LHS)309 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
310                                               std::unique_ptr<ExprAST> LHS) {
311   // If this is a binop, find its precedence.
312   while (true) {
313     int TokPrec = GetTokPrecedence();
314 
315     // If this is a binop that binds at least as tightly as the current binop,
316     // consume it, otherwise we are done.
317     if (TokPrec < ExprPrec)
318       return LHS;
319 
320     // Okay, we know this is a binop.
321     int BinOp = CurTok;
322     getNextToken(); // eat binop
323 
324     // Parse the primary expression after the binary operator.
325     auto RHS = ParsePrimary();
326     if (!RHS)
327       return nullptr;
328 
329     // If BinOp binds less tightly with RHS than the operator after RHS, let
330     // the pending operator take RHS as its LHS.
331     int NextPrec = GetTokPrecedence();
332     if (TokPrec < NextPrec) {
333       RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
334       if (!RHS)
335         return nullptr;
336     }
337 
338     // Merge LHS/RHS.
339     LHS =
340         std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
341   }
342 }
343 
344 /// expression
345 ///   ::= primary binoprhs
346 ///
ParseExpression()347 static std::unique_ptr<ExprAST> ParseExpression() {
348   auto LHS = ParsePrimary();
349   if (!LHS)
350     return nullptr;
351 
352   return ParseBinOpRHS(0, std::move(LHS));
353 }
354 
355 /// prototype
356 ///   ::= id '(' id* ')'
ParsePrototype()357 static std::unique_ptr<PrototypeAST> ParsePrototype() {
358   if (CurTok != tok_identifier)
359     return LogErrorP("Expected function name in prototype");
360 
361   std::string FnName = IdentifierStr;
362   getNextToken();
363 
364   if (CurTok != '(')
365     return LogErrorP("Expected '(' in prototype");
366 
367   std::vector<std::string> ArgNames;
368   while (getNextToken() == tok_identifier)
369     ArgNames.push_back(IdentifierStr);
370   if (CurTok != ')')
371     return LogErrorP("Expected ')' in prototype");
372 
373   // success.
374   getNextToken(); // eat ')'.
375 
376   return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
377 }
378 
379 /// definition ::= 'def' prototype expression
ParseDefinition()380 static std::unique_ptr<FunctionAST> ParseDefinition() {
381   getNextToken(); // eat def.
382   auto Proto = ParsePrototype();
383   if (!Proto)
384     return nullptr;
385 
386   if (auto E = ParseExpression())
387     return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
388   return nullptr;
389 }
390 
391 /// toplevelexpr ::= expression
ParseTopLevelExpr()392 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
393   if (auto E = ParseExpression()) {
394     // Make an anonymous proto.
395     auto Proto = std::make_unique<PrototypeAST>("__anon_expr",
396                                                  std::vector<std::string>());
397     return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
398   }
399   return nullptr;
400 }
401 
402 /// external ::= 'extern' prototype
ParseExtern()403 static std::unique_ptr<PrototypeAST> ParseExtern() {
404   getNextToken(); // eat extern.
405   return ParsePrototype();
406 }
407 
408 //===----------------------------------------------------------------------===//
409 // Code Generation
410 //===----------------------------------------------------------------------===//
411 
412 static std::unique_ptr<LLVMContext> TheContext;
413 static std::unique_ptr<Module> TheModule;
414 static std::unique_ptr<IRBuilder<>> Builder;
415 static std::map<std::string, Value *> NamedValues;
416 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
417 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
418 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
419 static ExitOnError ExitOnErr;
420 
LogErrorV(const char * Str)421 Value *LogErrorV(const char *Str) {
422   LogError(Str);
423   return nullptr;
424 }
425 
getFunction(std::string Name)426 Function *getFunction(std::string Name) {
427   // First, see if the function has already been added to the current module.
428   if (auto *F = TheModule->getFunction(Name))
429     return F;
430 
431   // If not, check whether we can codegen the declaration from some existing
432   // prototype.
433   auto FI = FunctionProtos.find(Name);
434   if (FI != FunctionProtos.end())
435     return FI->second->codegen();
436 
437   // If no existing prototype exists, return null.
438   return nullptr;
439 }
440 
codegen()441 Value *NumberExprAST::codegen() {
442   return ConstantFP::get(*TheContext, APFloat(Val));
443 }
444 
codegen()445 Value *VariableExprAST::codegen() {
446   // Look this variable up in the function.
447   Value *V = NamedValues[Name];
448   if (!V)
449     return LogErrorV("Unknown variable name");
450   return V;
451 }
452 
codegen()453 Value *BinaryExprAST::codegen() {
454   Value *L = LHS->codegen();
455   Value *R = RHS->codegen();
456   if (!L || !R)
457     return nullptr;
458 
459   switch (Op) {
460   case '+':
461     return Builder->CreateFAdd(L, R, "addtmp");
462   case '-':
463     return Builder->CreateFSub(L, R, "subtmp");
464   case '*':
465     return Builder->CreateFMul(L, R, "multmp");
466   case '<':
467     L = Builder->CreateFCmpULT(L, R, "cmptmp");
468     // Convert bool 0/1 to double 0.0 or 1.0
469     return Builder->CreateUIToFP(L, Type::getDoubleTy(*TheContext), "booltmp");
470   default:
471     return LogErrorV("invalid binary operator");
472   }
473 }
474 
codegen()475 Value *CallExprAST::codegen() {
476   // Look up the name in the global module table.
477   Function *CalleeF = getFunction(Callee);
478   if (!CalleeF)
479     return LogErrorV("Unknown function referenced");
480 
481   // If argument mismatch error.
482   if (CalleeF->arg_size() != Args.size())
483     return LogErrorV("Incorrect # arguments passed");
484 
485   std::vector<Value *> ArgsV;
486   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
487     ArgsV.push_back(Args[i]->codegen());
488     if (!ArgsV.back())
489       return nullptr;
490   }
491 
492   return Builder->CreateCall(CalleeF, ArgsV, "calltmp");
493 }
494 
codegen()495 Function *PrototypeAST::codegen() {
496   // Make the function type:  double(double,double) etc.
497   std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(*TheContext));
498   FunctionType *FT =
499       FunctionType::get(Type::getDoubleTy(*TheContext), Doubles, false);
500 
501   Function *F =
502       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
503 
504   // Set names for all arguments.
505   unsigned Idx = 0;
506   for (auto &Arg : F->args())
507     Arg.setName(Args[Idx++]);
508 
509   return F;
510 }
511 
codegen()512 Function *FunctionAST::codegen() {
513   // Transfer ownership of the prototype to the FunctionProtos map, but keep a
514   // reference to it for use below.
515   auto &P = *Proto;
516   FunctionProtos[Proto->getName()] = std::move(Proto);
517   Function *TheFunction = getFunction(P.getName());
518   if (!TheFunction)
519     return nullptr;
520 
521   // Create a new basic block to start insertion into.
522   BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", TheFunction);
523   Builder->SetInsertPoint(BB);
524 
525   // Record the function arguments in the NamedValues map.
526   NamedValues.clear();
527   for (auto &Arg : TheFunction->args())
528     NamedValues[std::string(Arg.getName())] = &Arg;
529 
530   if (Value *RetVal = Body->codegen()) {
531     // Finish off the function.
532     Builder->CreateRet(RetVal);
533 
534     // Validate the generated code, checking for consistency.
535     verifyFunction(*TheFunction);
536 
537     // Run the optimizer on the function.
538     TheFPM->run(*TheFunction);
539 
540     return TheFunction;
541   }
542 
543   // Error reading body, remove function.
544   TheFunction->eraseFromParent();
545   return nullptr;
546 }
547 
548 //===----------------------------------------------------------------------===//
549 // Top-Level parsing and JIT Driver
550 //===----------------------------------------------------------------------===//
551 
InitializeModuleAndPassManager()552 static void InitializeModuleAndPassManager() {
553   // Open a new context and module.
554   TheContext = std::make_unique<LLVMContext>();
555   TheModule = std::make_unique<Module>("my cool jit", *TheContext);
556   TheModule->setDataLayout(TheJIT->getDataLayout());
557 
558   // Create a new builder for the module.
559   Builder = std::make_unique<IRBuilder<>>(*TheContext);
560 
561   // Create a new pass manager attached to it.
562   TheFPM = std::make_unique<legacy::FunctionPassManager>(TheModule.get());
563 
564   // Do simple "peephole" optimizations and bit-twiddling optzns.
565   TheFPM->add(createInstructionCombiningPass());
566   // Reassociate expressions.
567   TheFPM->add(createReassociatePass());
568   // Eliminate Common SubExpressions.
569   TheFPM->add(createGVNPass());
570   // Simplify the control flow graph (deleting unreachable blocks, etc).
571   TheFPM->add(createCFGSimplificationPass());
572 
573   TheFPM->doInitialization();
574 }
575 
HandleDefinition()576 static void HandleDefinition() {
577   if (auto FnAST = ParseDefinition()) {
578     if (auto *FnIR = FnAST->codegen()) {
579       fprintf(stderr, "Read function definition:");
580       FnIR->print(errs());
581       fprintf(stderr, "\n");
582       ExitOnErr(TheJIT->addModule(
583           ThreadSafeModule(std::move(TheModule), std::move(TheContext))));
584       InitializeModuleAndPassManager();
585     }
586   } else {
587     // Skip token for error recovery.
588     getNextToken();
589   }
590 }
591 
HandleExtern()592 static void HandleExtern() {
593   if (auto ProtoAST = ParseExtern()) {
594     if (auto *FnIR = ProtoAST->codegen()) {
595       fprintf(stderr, "Read extern: ");
596       FnIR->print(errs());
597       fprintf(stderr, "\n");
598       FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
599     }
600   } else {
601     // Skip token for error recovery.
602     getNextToken();
603   }
604 }
605 
HandleTopLevelExpression()606 static void HandleTopLevelExpression() {
607   // Evaluate a top-level expression into an anonymous function.
608   if (auto FnAST = ParseTopLevelExpr()) {
609     if (FnAST->codegen()) {
610       // Create a ResourceTracker to track JIT'd memory allocated to our
611       // anonymous expression -- that way we can free it after executing.
612       auto RT = TheJIT->getMainJITDylib().createResourceTracker();
613 
614       auto TSM = ThreadSafeModule(std::move(TheModule), std::move(TheContext));
615       ExitOnErr(TheJIT->addModule(std::move(TSM), RT));
616       InitializeModuleAndPassManager();
617 
618       // Search the JIT for the __anon_expr symbol.
619       auto ExprSymbol = ExitOnErr(TheJIT->lookup("__anon_expr"));
620 
621       // Get the symbol's address and cast it to the right type (takes no
622       // arguments, returns a double) so we can call it as a native function.
623       double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
624       fprintf(stderr, "Evaluated to %f\n", FP());
625 
626       // Delete the anonymous expression module from the JIT.
627       ExitOnErr(RT->remove());
628     }
629   } else {
630     // Skip token for error recovery.
631     getNextToken();
632   }
633 }
634 
635 /// top ::= definition | external | expression | ';'
MainLoop()636 static void MainLoop() {
637   while (true) {
638     fprintf(stderr, "ready> ");
639     switch (CurTok) {
640     case tok_eof:
641       return;
642     case ';': // ignore top-level semicolons.
643       getNextToken();
644       break;
645     case tok_def:
646       HandleDefinition();
647       break;
648     case tok_extern:
649       HandleExtern();
650       break;
651     default:
652       HandleTopLevelExpression();
653       break;
654     }
655   }
656 }
657 
658 //===----------------------------------------------------------------------===//
659 // "Library" functions that can be "extern'd" from user code.
660 //===----------------------------------------------------------------------===//
661 
662 #ifdef _WIN32
663 #define DLLEXPORT __declspec(dllexport)
664 #else
665 #define DLLEXPORT
666 #endif
667 
668 /// putchard - putchar that takes a double and returns 0.
putchard(double X)669 extern "C" DLLEXPORT double putchard(double X) {
670   fputc((char)X, stderr);
671   return 0;
672 }
673 
674 /// printd - printf that takes a double prints it as "%f\n", returning 0.
printd(double X)675 extern "C" DLLEXPORT double printd(double X) {
676   fprintf(stderr, "%f\n", X);
677   return 0;
678 }
679 
680 //===----------------------------------------------------------------------===//
681 // Main driver code.
682 //===----------------------------------------------------------------------===//
683 
main()684 int main() {
685   InitializeNativeTarget();
686   InitializeNativeTargetAsmPrinter();
687   InitializeNativeTargetAsmParser();
688 
689   // Install standard binary operators.
690   // 1 is lowest precedence.
691   BinopPrecedence['<'] = 10;
692   BinopPrecedence['+'] = 20;
693   BinopPrecedence['-'] = 20;
694   BinopPrecedence['*'] = 40; // highest.
695 
696   // Prime the first token.
697   fprintf(stderr, "ready> ");
698   getNextToken();
699 
700   TheJIT = ExitOnErr(KaleidoscopeJIT::Create());
701 
702   InitializeModuleAndPassManager();
703 
704   // Run the main "interpreter loop" now.
705   MainLoop();
706 
707   return 0;
708 }
709