1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/BasicAliasAnalysis.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.h"
5 #include "llvm/ExecutionEngine/MCJIT.h"
6 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
7 #include "llvm/IR/DataLayout.h"
8 #include "llvm/IR/DerivedTypes.h"
9 #include "llvm/IR/IRBuilder.h"
10 #include "llvm/IR/LLVMContext.h"
11 #include "llvm/IR/LegacyPassManager.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Transforms/Scalar.h"
23 //===----------------------------------------------------------------------===//
25 //===----------------------------------------------------------------------===//
27 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
28 // of these for known things.
41 static std::string IdentifierStr; // Filled in if tok_identifier
42 static double NumVal; // Filled in if tok_number
44 /// gettok - Return the next token from standard input.
46 static int LastChar = ' ';
48 // Skip any whitespace.
49 while (isspace(LastChar))
52 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
53 IdentifierStr = LastChar;
54 while (isalnum((LastChar = getchar())))
55 IdentifierStr += LastChar;
57 if (IdentifierStr == "def")
59 if (IdentifierStr == "extern")
61 return tok_identifier;
64 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
69 } while (isdigit(LastChar) || LastChar == '.');
71 NumVal = strtod(NumStr.c_str(), 0);
75 if (LastChar == '#') {
76 // Comment until end of line.
79 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
85 // Check for end of file. Don't eat the EOF.
89 // Otherwise, just return the character as its ascii value.
90 int ThisChar = LastChar;
95 //===----------------------------------------------------------------------===//
96 // Abstract Syntax Tree (aka Parse Tree)
97 //===----------------------------------------------------------------------===//
99 /// ExprAST - Base class for all expression nodes.
102 virtual ~ExprAST() {}
103 virtual Value *Codegen() = 0;
106 /// NumberExprAST - Expression class for numeric literals like "1.0".
107 class NumberExprAST : public ExprAST {
110 NumberExprAST(double Val) : Val(Val) {}
111 Value *Codegen() override;
114 /// VariableExprAST - Expression class for referencing a variable, like "a".
115 class VariableExprAST : public ExprAST {
118 VariableExprAST(const std::string &Name) : Name(Name) {}
119 Value *Codegen() override;
122 /// BinaryExprAST - Expression class for a binary operator.
123 class BinaryExprAST : public ExprAST {
125 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;
138 CallExprAST(const std::string &Callee,
139 std::vector<std::unique_ptr<ExprAST>> Args)
140 : Callee(Callee), Args(std::move(Args)) {}
141 Value *Codegen() override;
144 /// PrototypeAST - This class represents the "prototype" for a function,
145 /// which captures its name, and its argument names (thus implicitly the number
146 /// of arguments the function takes).
149 std::vector<std::string> Args;
151 PrototypeAST(const std::string &name, std::vector<std::string> Args)
152 : Name(name), Args(std::move(Args)) {}
156 /// FunctionAST - This class represents a function definition itself.
158 std::unique_ptr<PrototypeAST> Proto;
159 std::unique_ptr<ExprAST> Body;
161 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
162 std::unique_ptr<ExprAST> Body)
163 : Proto(std::move(Proto)), Body(std::move(Body)) {}
166 } // end anonymous namespace
168 //===----------------------------------------------------------------------===//
170 //===----------------------------------------------------------------------===//
172 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
173 /// token the parser is looking at. getNextToken reads another token from the
174 /// lexer and updates CurTok with its results.
176 static int getNextToken() { return CurTok = gettok(); }
178 /// BinopPrecedence - This holds the precedence for each binary operator that is
180 static std::map<char, int> BinopPrecedence;
182 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
183 static int GetTokPrecedence() {
184 if (!isascii(CurTok))
187 // Make sure it's a declared binop.
188 int TokPrec = BinopPrecedence[CurTok];
194 /// Error* - These are little helper functions for error handling.
195 std::unique_ptr<ExprAST> Error(const char *Str) {
196 fprintf(stderr, "Error: %s\n", Str);
199 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
203 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
208 static std::unique_ptr<ExprAST> ParseExpression();
212 /// ::= identifier '(' expression* ')'
213 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
214 std::string IdName = IdentifierStr;
216 getNextToken(); // eat identifier.
218 if (CurTok != '(') // Simple variable ref.
219 return llvm::make_unique<VariableExprAST>(IdName);
222 getNextToken(); // eat (
223 std::vector<std::unique_ptr<ExprAST>> Args;
226 if (auto Arg = ParseExpression())
227 Args.push_back(std::move(Arg));
235 return Error("Expected ')' or ',' in argument list");
243 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
246 /// numberexpr ::= number
247 static std::unique_ptr<ExprAST> ParseNumberExpr() {
248 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
249 getNextToken(); // consume the number
250 return std::move(Result);
253 /// parenexpr ::= '(' expression ')'
254 static std::unique_ptr<ExprAST> ParseParenExpr() {
255 getNextToken(); // eat (.
256 auto V = ParseExpression();
261 return Error("expected ')'");
262 getNextToken(); // eat ).
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));
315 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
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>("",
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 //===----------------------------------------------------------------------===//
385 // Quick and dirty hack
386 //===----------------------------------------------------------------------===//
388 // FIXME: Obviously we can do better than this
389 std::string GenerateUniqueName(const char *root) {
392 sprintf(s, "%s%d", root, i++);
397 std::string MakeLegalFunctionName(std::string Name) {
400 return GenerateUniqueName("anon_func_");
402 // Start with what we have
405 // Look for a numberic first character
406 if (NewName.find_first_of("0123456789") == 0) {
407 NewName.insert(0, 1, 'n');
410 // Replace illegal characters with their ASCII equivalent
411 std::string legal_elements =
412 "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
414 while ((pos = NewName.find_first_not_of(legal_elements)) !=
416 char old_c = NewName.at(pos);
418 sprintf(new_str, "%d", (int)old_c);
419 NewName = NewName.replace(pos, 1, new_str);
425 //===----------------------------------------------------------------------===//
426 // MCJIT helper class
427 //===----------------------------------------------------------------------===//
431 MCJITHelper(LLVMContext &C) : Context(C), OpenModule(NULL) {}
434 Function *getFunction(const std::string FnName);
435 Module *getModuleForNewFunction();
436 void *getPointerToFunction(Function *F);
437 void *getSymbolAddress(const std::string &Name);
441 typedef std::vector<Module *> ModuleVector;
442 typedef std::vector<ExecutionEngine *> EngineVector;
444 LLVMContext &Context;
446 ModuleVector Modules;
447 EngineVector Engines;
450 class HelpingMemoryManager : public SectionMemoryManager {
451 HelpingMemoryManager(const HelpingMemoryManager &) = delete;
452 void operator=(const HelpingMemoryManager &) = delete;
455 HelpingMemoryManager(MCJITHelper *Helper) : MasterHelper(Helper) {}
456 ~HelpingMemoryManager() override {}
458 /// This method returns the address of the specified symbol.
459 /// Our implementation will attempt to find symbols in other
460 /// modules associated with the MCJITHelper to cross link symbols
461 /// from one generated module to another.
462 uint64_t getSymbolAddress(const std::string &Name) override;
465 MCJITHelper *MasterHelper;
468 uint64_t HelpingMemoryManager::getSymbolAddress(const std::string &Name) {
469 uint64_t FnAddr = SectionMemoryManager::getSymbolAddress(Name);
473 uint64_t HelperFun = (uint64_t)MasterHelper->getSymbolAddress(Name);
475 report_fatal_error("Program used extern function '" + Name +
476 "' which could not be resolved!");
481 MCJITHelper::~MCJITHelper() {
484 EngineVector::iterator begin = Engines.begin();
485 EngineVector::iterator end = Engines.end();
486 EngineVector::iterator it;
487 for (it = begin; it != end; ++it)
491 Function *MCJITHelper::getFunction(const std::string FnName) {
492 ModuleVector::iterator begin = Modules.begin();
493 ModuleVector::iterator end = Modules.end();
494 ModuleVector::iterator it;
495 for (it = begin; it != end; ++it) {
496 Function *F = (*it)->getFunction(FnName);
498 if (*it == OpenModule)
501 assert(OpenModule != NULL);
503 // This function is in a module that has already been JITed.
504 // We need to generate a new prototype for external linkage.
505 Function *PF = OpenModule->getFunction(FnName);
506 if (PF && !PF->empty()) {
507 ErrorF("redefinition of function across modules");
511 // If we don't have a prototype yet, create one.
513 PF = Function::Create(F->getFunctionType(), Function::ExternalLinkage,
521 Module *MCJITHelper::getModuleForNewFunction() {
522 // If we have a Module that hasn't been JITed, use that.
526 // Otherwise create a new Module.
527 std::string ModName = GenerateUniqueName("mcjit_module_");
528 Module *M = new Module(ModName, Context);
529 Modules.push_back(M);
534 void *MCJITHelper::getPointerToFunction(Function *F) {
535 // See if an existing instance of MCJIT has this function.
536 EngineVector::iterator begin = Engines.begin();
537 EngineVector::iterator end = Engines.end();
538 EngineVector::iterator it;
539 for (it = begin; it != end; ++it) {
540 void *P = (*it)->getPointerToFunction(F);
545 // If we didn't find the function, see if we can generate it.
548 ExecutionEngine *NewEngine =
549 EngineBuilder(std::unique_ptr<Module>(OpenModule))
550 .setErrorStr(&ErrStr)
551 .setMCJITMemoryManager(std::unique_ptr<HelpingMemoryManager>(
552 new HelpingMemoryManager(this)))
555 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
559 // Create a function pass manager for this engine
560 auto *FPM = new legacy::FunctionPassManager(OpenModule);
562 // Set up the optimizer pipeline. Start with registering info about how the
563 // target lays out data structures.
564 OpenModule->setDataLayout(NewEngine->getDataLayout());
565 // Provide basic AliasAnalysis support for GVN.
566 FPM->add(createBasicAliasAnalysisPass());
567 // Promote allocas to registers.
568 FPM->add(createPromoteMemoryToRegisterPass());
569 // Do simple "peephole" optimizations and bit-twiddling optzns.
570 FPM->add(createInstructionCombiningPass());
571 // Reassociate expressions.
572 FPM->add(createReassociatePass());
573 // Eliminate Common SubExpressions.
574 FPM->add(createGVNPass());
575 // Simplify the control flow graph (deleting unreachable blocks, etc).
576 FPM->add(createCFGSimplificationPass());
577 FPM->doInitialization();
579 // For each function in the module
581 Module::iterator end = OpenModule->end();
582 for (it = OpenModule->begin(); it != end; ++it) {
583 // Run the FPM on this function
587 // We don't need this anymore
591 Engines.push_back(NewEngine);
592 NewEngine->finalizeObject();
593 return NewEngine->getPointerToFunction(F);
598 void *MCJITHelper::getSymbolAddress(const std::string &Name) {
599 // Look for the symbol in each of our execution engines.
600 EngineVector::iterator begin = Engines.begin();
601 EngineVector::iterator end = Engines.end();
602 EngineVector::iterator it;
603 for (it = begin; it != end; ++it) {
604 uint64_t FAddr = (*it)->getFunctionAddress(Name);
606 return (void *)FAddr;
612 void MCJITHelper::dump() {
613 ModuleVector::iterator begin = Modules.begin();
614 ModuleVector::iterator end = Modules.end();
615 ModuleVector::iterator it;
616 for (it = begin; it != end; ++it)
619 //===----------------------------------------------------------------------===//
621 //===----------------------------------------------------------------------===//
623 static MCJITHelper *JITHelper;
624 static IRBuilder<> Builder(getGlobalContext());
625 static std::map<std::string, Value *> NamedValues;
627 Value *ErrorV(const char *Str) {
632 Value *NumberExprAST::Codegen() {
633 return ConstantFP::get(getGlobalContext(), APFloat(Val));
636 Value *VariableExprAST::Codegen() {
637 // Look this variable up in the function.
638 Value *V = NamedValues[Name];
639 return V ? V : ErrorV("Unknown variable name");
642 Value *BinaryExprAST::Codegen() {
643 Value *L = LHS->Codegen();
644 Value *R = RHS->Codegen();
650 return Builder.CreateFAdd(L, R, "addtmp");
652 return Builder.CreateFSub(L, R, "subtmp");
654 return Builder.CreateFMul(L, R, "multmp");
656 L = Builder.CreateFCmpULT(L, R, "cmptmp");
657 // Convert bool 0/1 to double 0.0 or 1.0
658 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
661 return ErrorV("invalid binary operator");
665 Value *CallExprAST::Codegen() {
666 // Look up the name in the global module table.
667 Function *CalleeF = JITHelper->getFunction(Callee);
669 return ErrorV("Unknown function referenced");
671 // If argument mismatch error.
672 if (CalleeF->arg_size() != Args.size())
673 return ErrorV("Incorrect # arguments passed");
675 std::vector<Value *> ArgsV;
676 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
677 ArgsV.push_back(Args[i]->Codegen());
682 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
685 Function *PrototypeAST::Codegen() {
686 // Make the function type: double(double,double) etc.
687 std::vector<Type *> Doubles(Args.size(),
688 Type::getDoubleTy(getGlobalContext()));
690 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
692 std::string FnName = MakeLegalFunctionName(Name);
694 Module *M = JITHelper->getModuleForNewFunction();
696 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName, M);
698 // If F conflicted, there was already something named 'Name'. If it has a
699 // body, don't allow redefinition or reextern.
700 if (F->getName() != FnName) {
701 // Delete the one we just made and get the existing one.
702 F->eraseFromParent();
703 F = JITHelper->getFunction(Name);
704 // If F already has a body, reject this.
706 ErrorF("redefinition of function");
710 // If F took a different number of args, reject.
711 if (F->arg_size() != Args.size()) {
712 ErrorF("redefinition of function with different # args");
717 // Set names for all arguments.
719 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
721 AI->setName(Args[Idx]);
723 // Add arguments to variable symbol table.
724 NamedValues[Args[Idx]] = AI;
730 Function *FunctionAST::Codegen() {
733 Function *TheFunction = Proto->Codegen();
737 // Create a new basic block to start insertion into.
738 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
739 Builder.SetInsertPoint(BB);
741 if (Value *RetVal = Body->Codegen()) {
742 // Finish off the function.
743 Builder.CreateRet(RetVal);
745 // Validate the generated code, checking for consistency.
746 verifyFunction(*TheFunction);
751 // Error reading body, remove function.
752 TheFunction->eraseFromParent();
756 //===----------------------------------------------------------------------===//
757 // Top-Level parsing and JIT Driver
758 //===----------------------------------------------------------------------===//
760 static void HandleDefinition() {
761 if (auto FnAST = ParseDefinition()) {
762 if (auto *FnIR = FnAST->Codegen()) {
763 fprintf(stderr, "Read function definition:");
767 // Skip token for error recovery.
772 static void HandleExtern() {
773 if (auto ProtoAST = ParseExtern()) {
774 if (auto *FnIR = ProtoAST->Codegen()) {
775 fprintf(stderr, "Read extern: ");
779 // Skip token for error recovery.
784 static void HandleTopLevelExpression() {
785 // Evaluate a top-level expression into an anonymous function.
786 if (auto FnAST = ParseTopLevelExpr()) {
787 if (auto *FnIR = FnAST->Codegen()) {
788 // JIT the function, returning a function pointer.
789 void *FPtr = JITHelper->getPointerToFunction(FnIR);
791 // Cast it to the right type (takes no arguments, returns a double) so we
792 // can call it as a native function.
793 double (*FP)() = (double (*)())(intptr_t)FPtr;
794 fprintf(stderr, "Evaluated to %f\n", FP());
797 // Skip token for error recovery.
802 /// top ::= definition | external | expression | ';'
803 static void MainLoop() {
805 fprintf(stderr, "ready> ");
811 break; // ignore top-level semicolons.
819 HandleTopLevelExpression();
825 //===----------------------------------------------------------------------===//
826 // "Library" functions that can be "extern'd" from user code.
827 //===----------------------------------------------------------------------===//
829 /// putchard - putchar that takes a double and returns 0.
830 extern "C" double putchard(double X) {
835 //===----------------------------------------------------------------------===//
837 //===----------------------------------------------------------------------===//
840 InitializeNativeTarget();
841 InitializeNativeTargetAsmPrinter();
842 InitializeNativeTargetAsmParser();
843 LLVMContext &Context = getGlobalContext();
844 JITHelper = new MCJITHelper(Context);
846 // Install standard binary operators.
847 // 1 is lowest precedence.
848 BinopPrecedence['<'] = 10;
849 BinopPrecedence['+'] = 20;
850 BinopPrecedence['-'] = 20;
851 BinopPrecedence['*'] = 40; // highest.
853 // Prime the first token.
854 fprintf(stderr, "ready> ");
857 // Run the main "interpreter loop" now.
860 // Print out all of the generated code.