1 #include "llvm/Analysis/BasicAliasAnalysis.h"
2 #include "llvm/Analysis/Passes.h"
3 #include "llvm/ExecutionEngine/ExecutionEngine.h"
4 #include "llvm/ExecutionEngine/MCJIT.h"
5 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
6 #include "llvm/IR/DataLayout.h"
7 #include "llvm/IR/DerivedTypes.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/Verifier.h"
13 #include "llvm/Support/TargetSelect.h"
14 #include "llvm/Transforms/Scalar.h"
22 //===----------------------------------------------------------------------===//
24 //===----------------------------------------------------------------------===//
26 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
27 // of these for known things.
40 static std::string IdentifierStr; // Filled in if tok_identifier
41 static double NumVal; // Filled in if tok_number
43 /// gettok - Return the next token from standard input.
45 static int LastChar = ' ';
47 // Skip any whitespace.
48 while (isspace(LastChar))
51 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
52 IdentifierStr = LastChar;
53 while (isalnum((LastChar = getchar())))
54 IdentifierStr += LastChar;
56 if (IdentifierStr == "def")
58 if (IdentifierStr == "extern")
60 return tok_identifier;
63 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
68 } while (isdigit(LastChar) || LastChar == '.');
70 NumVal = strtod(NumStr.c_str(), 0);
74 if (LastChar == '#') {
75 // Comment until end of line.
78 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
84 // Check for end of file. Don't eat the EOF.
88 // Otherwise, just return the character as its ascii value.
89 int ThisChar = LastChar;
94 //===----------------------------------------------------------------------===//
95 // Abstract Syntax Tree (aka Parse Tree)
96 //===----------------------------------------------------------------------===//
98 /// ExprAST - Base class for all expression nodes.
101 virtual ~ExprAST() {}
102 virtual Value *Codegen() = 0;
105 /// NumberExprAST - Expression class for numeric literals like "1.0".
106 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 {
119 VariableExprAST(const std::string &name) : Name(name) {}
120 Value *Codegen() override;
123 /// BinaryExprAST - Expression class for a binary operator.
124 class BinaryExprAST : public ExprAST {
129 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
130 : Op(op), LHS(lhs), RHS(rhs) {}
131 Value *Codegen() override;
134 /// CallExprAST - Expression class for function calls.
135 class CallExprAST : public ExprAST {
137 std::vector<ExprAST *> Args;
140 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
141 : Callee(callee), Args(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, const std::vector<std::string> &args)
154 : Name(name), Args(args) {}
159 /// FunctionAST - This class represents a function definition itself.
165 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
169 } // end anonymous namespace
171 //===----------------------------------------------------------------------===//
173 //===----------------------------------------------------------------------===//
175 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
176 /// token the parser is looking at. getNextToken reads another token from the
177 /// lexer and updates CurTok with its results.
179 static int getNextToken() { return CurTok = gettok(); }
181 /// BinopPrecedence - This holds the precedence for each binary operator that is
183 static std::map<char, int> BinopPrecedence;
185 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
186 static int GetTokPrecedence() {
187 if (!isascii(CurTok))
190 // Make sure it's a declared binop.
191 int TokPrec = BinopPrecedence[CurTok];
197 /// Error* - These are little helper functions for error handling.
198 ExprAST *Error(const char *Str) {
199 fprintf(stderr, "Error: %s\n", Str);
202 PrototypeAST *ErrorP(const char *Str) {
206 FunctionAST *ErrorF(const char *Str) {
211 static ExprAST *ParseExpression();
215 /// ::= identifier '(' expression* ')'
216 static ExprAST *ParseIdentifierExpr() {
217 std::string IdName = IdentifierStr;
219 getNextToken(); // eat identifier.
221 if (CurTok != '(') // Simple variable ref.
222 return new VariableExprAST(IdName);
225 getNextToken(); // eat (
226 std::vector<ExprAST *> Args;
229 ExprAST *Arg = ParseExpression();
238 return Error("Expected ')' or ',' in argument list");
246 return new CallExprAST(IdName, Args);
249 /// numberexpr ::= number
250 static ExprAST *ParseNumberExpr() {
251 ExprAST *Result = new NumberExprAST(NumVal);
252 getNextToken(); // consume the number
256 /// parenexpr ::= '(' expression ')'
257 static ExprAST *ParseParenExpr() {
258 getNextToken(); // eat (.
259 ExprAST *V = ParseExpression();
264 return Error("expected ')'");
265 getNextToken(); // eat ).
270 /// ::= identifierexpr
273 static ExprAST *ParsePrimary() {
276 return Error("unknown token when expecting an expression");
278 return ParseIdentifierExpr();
280 return ParseNumberExpr();
282 return ParseParenExpr();
287 /// ::= ('+' primary)*
288 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
289 // If this is a binop, find its precedence.
291 int TokPrec = GetTokPrecedence();
293 // If this is a binop that binds at least as tightly as the current binop,
294 // consume it, otherwise we are done.
295 if (TokPrec < ExprPrec)
298 // Okay, we know this is a binop.
300 getNextToken(); // eat binop
302 // Parse the primary expression after the binary operator.
303 ExprAST *RHS = ParsePrimary();
307 // If BinOp binds less tightly with RHS than the operator after RHS, let
308 // the pending operator take RHS as its LHS.
309 int NextPrec = GetTokPrecedence();
310 if (TokPrec < NextPrec) {
311 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
317 LHS = new BinaryExprAST(BinOp, LHS, RHS);
322 /// ::= primary binoprhs
324 static ExprAST *ParseExpression() {
325 ExprAST *LHS = ParsePrimary();
329 return ParseBinOpRHS(0, LHS);
333 /// ::= id '(' id* ')'
334 static PrototypeAST *ParsePrototype() {
335 if (CurTok != tok_identifier)
336 return ErrorP("Expected function name in prototype");
338 std::string FnName = IdentifierStr;
342 return ErrorP("Expected '(' in prototype");
344 std::vector<std::string> ArgNames;
345 while (getNextToken() == tok_identifier)
346 ArgNames.push_back(IdentifierStr);
348 return ErrorP("Expected ')' in prototype");
351 getNextToken(); // eat ')'.
353 return new PrototypeAST(FnName, ArgNames);
356 /// definition ::= 'def' prototype expression
357 static FunctionAST *ParseDefinition() {
358 getNextToken(); // eat def.
359 PrototypeAST *Proto = ParsePrototype();
363 if (ExprAST *E = ParseExpression())
364 return new FunctionAST(Proto, E);
368 /// toplevelexpr ::= expression
369 static FunctionAST *ParseTopLevelExpr() {
370 if (ExprAST *E = ParseExpression()) {
371 // Make an anonymous proto.
372 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
373 return new FunctionAST(Proto, E);
378 /// external ::= 'extern' prototype
379 static 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();
645 if (L == 0 || R == 0)
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());
678 if (ArgsV.back() == 0)
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();
734 if (TheFunction == 0)
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 (FunctionAST *F = ParseDefinition()) {
762 if (Function *LF = F->Codegen()) {
763 fprintf(stderr, "Read function definition:");
767 // Skip token for error recovery.
772 static void HandleExtern() {
773 if (PrototypeAST *P = ParseExtern()) {
774 if (Function *F = P->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 (FunctionAST *F = ParseTopLevelExpr()) {
787 if (Function *LF = F->Codegen()) {
788 // JIT the function, returning a function pointer.
789 void *FPtr = JITHelper->getPointerToFunction(LF);
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.