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 {
111 NumberExprAST(double Val) : Val(Val) {}
112 Value *Codegen() override;
115 /// VariableExprAST - Expression class for referencing a variable, like "a".
116 class VariableExprAST : public ExprAST {
120 VariableExprAST(const std::string &Name) : Name(Name) {}
121 Value *Codegen() override;
124 /// BinaryExprAST - Expression class for a binary operator.
125 class BinaryExprAST : public ExprAST {
127 std::unique_ptr<ExprAST> LHS, RHS;
130 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
131 std::unique_ptr<ExprAST> RHS)
132 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
133 Value *Codegen() override;
136 /// CallExprAST - Expression class for function calls.
137 class CallExprAST : public ExprAST {
139 std::vector<std::unique_ptr<ExprAST>> Args;
142 CallExprAST(const std::string &Callee,
143 std::vector<std::unique_ptr<ExprAST>> Args)
144 : Callee(Callee), Args(std::move(Args)) {}
145 Value *Codegen() override;
148 /// PrototypeAST - This class represents the "prototype" for a function,
149 /// which captures its name, and its argument names (thus implicitly the number
150 /// of arguments the function takes).
153 std::vector<std::string> Args;
156 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
157 : Name(Name), Args(std::move(Args)) {}
161 /// FunctionAST - This class represents a function definition itself.
163 std::unique_ptr<PrototypeAST> Proto;
164 std::unique_ptr<ExprAST> Body;
167 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
168 std::unique_ptr<ExprAST> Body)
169 : Proto(std::move(Proto)), Body(std::move(Body)) {}
172 } // end anonymous namespace
174 //===----------------------------------------------------------------------===//
176 //===----------------------------------------------------------------------===//
178 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
179 /// token the parser is looking at. getNextToken reads another token from the
180 /// lexer and updates CurTok with its results.
182 static int getNextToken() { return CurTok = gettok(); }
184 /// BinopPrecedence - This holds the precedence for each binary operator that is
186 static std::map<char, int> BinopPrecedence;
188 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
189 static int GetTokPrecedence() {
190 if (!isascii(CurTok))
193 // Make sure it's a declared binop.
194 int TokPrec = BinopPrecedence[CurTok];
200 /// Error* - These are little helper functions for error handling.
201 std::unique_ptr<ExprAST> Error(const char *Str) {
202 fprintf(stderr, "Error: %s\n", Str);
205 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
209 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
214 static std::unique_ptr<ExprAST> ParseExpression();
216 /// numberexpr ::= number
217 static std::unique_ptr<ExprAST> ParseNumberExpr() {
218 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
219 getNextToken(); // consume the number
220 return std::move(Result);
223 /// parenexpr ::= '(' expression ')'
224 static std::unique_ptr<ExprAST> ParseParenExpr() {
225 getNextToken(); // eat (.
226 auto V = ParseExpression();
231 return Error("expected ')'");
232 getNextToken(); // eat ).
238 /// ::= identifier '(' expression* ')'
239 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
240 std::string IdName = IdentifierStr;
242 getNextToken(); // eat identifier.
244 if (CurTok != '(') // Simple variable ref.
245 return llvm::make_unique<VariableExprAST>(IdName);
248 getNextToken(); // eat (
249 std::vector<std::unique_ptr<ExprAST>> Args;
252 if (auto Arg = ParseExpression())
253 Args.push_back(std::move(Arg));
261 return Error("Expected ')' or ',' in argument list");
269 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
273 /// ::= identifierexpr
276 static std::unique_ptr<ExprAST> ParsePrimary() {
279 return Error("unknown token when expecting an expression");
281 return ParseIdentifierExpr();
283 return ParseNumberExpr();
285 return ParseParenExpr();
290 /// ::= ('+' primary)*
291 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
292 std::unique_ptr<ExprAST> LHS) {
293 // If this is a binop, find its precedence.
295 int TokPrec = GetTokPrecedence();
297 // If this is a binop that binds at least as tightly as the current binop,
298 // consume it, otherwise we are done.
299 if (TokPrec < ExprPrec)
302 // Okay, we know this is a binop.
304 getNextToken(); // eat binop
306 // Parse the primary expression after the binary operator.
307 auto RHS = ParsePrimary();
311 // If BinOp binds less tightly with RHS than the operator after RHS, let
312 // the pending operator take RHS as its LHS.
313 int NextPrec = GetTokPrecedence();
314 if (TokPrec < NextPrec) {
315 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
322 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
327 /// ::= primary binoprhs
329 static std::unique_ptr<ExprAST> ParseExpression() {
330 auto LHS = ParsePrimary();
334 return ParseBinOpRHS(0, std::move(LHS));
338 /// ::= id '(' id* ')'
339 static std::unique_ptr<PrototypeAST> ParsePrototype() {
340 if (CurTok != tok_identifier)
341 return ErrorP("Expected function name in prototype");
343 std::string FnName = IdentifierStr;
347 return ErrorP("Expected '(' in prototype");
349 std::vector<std::string> ArgNames;
350 while (getNextToken() == tok_identifier)
351 ArgNames.push_back(IdentifierStr);
353 return ErrorP("Expected ')' in prototype");
356 getNextToken(); // eat ')'.
358 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
361 /// definition ::= 'def' prototype expression
362 static std::unique_ptr<FunctionAST> ParseDefinition() {
363 getNextToken(); // eat def.
364 auto Proto = ParsePrototype();
368 if (auto E = ParseExpression())
369 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
373 /// toplevelexpr ::= expression
374 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
375 if (auto E = ParseExpression()) {
376 // Make an anonymous proto.
378 llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
379 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
384 /// external ::= 'extern' prototype
385 static std::unique_ptr<PrototypeAST> ParseExtern() {
386 getNextToken(); // eat extern.
387 return ParsePrototype();
390 //===----------------------------------------------------------------------===//
391 // Quick and dirty hack
392 //===----------------------------------------------------------------------===//
394 // FIXME: Obviously we can do better than this
395 std::string GenerateUniqueName(const char *root) {
398 sprintf(s, "%s%d", root, i++);
403 std::string MakeLegalFunctionName(std::string Name) {
406 return GenerateUniqueName("anon_func_");
408 // Start with what we have
411 // Look for a numberic first character
412 if (NewName.find_first_of("0123456789") == 0) {
413 NewName.insert(0, 1, 'n');
416 // Replace illegal characters with their ASCII equivalent
417 std::string legal_elements =
418 "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
420 while ((pos = NewName.find_first_not_of(legal_elements)) !=
422 char old_c = NewName.at(pos);
424 sprintf(new_str, "%d", (int)old_c);
425 NewName = NewName.replace(pos, 1, new_str);
431 //===----------------------------------------------------------------------===//
432 // MCJIT helper class
433 //===----------------------------------------------------------------------===//
437 MCJITHelper(LLVMContext &C) : Context(C), OpenModule(NULL) {}
440 Function *getFunction(const std::string FnName);
441 Module *getModuleForNewFunction();
442 void *getPointerToFunction(Function *F);
443 void *getSymbolAddress(const std::string &Name);
447 typedef std::vector<Module *> ModuleVector;
448 typedef std::vector<ExecutionEngine *> EngineVector;
450 LLVMContext &Context;
452 ModuleVector Modules;
453 EngineVector Engines;
456 class HelpingMemoryManager : public SectionMemoryManager {
457 HelpingMemoryManager(const HelpingMemoryManager &) = delete;
458 void operator=(const HelpingMemoryManager &) = delete;
461 HelpingMemoryManager(MCJITHelper *Helper) : MasterHelper(Helper) {}
462 ~HelpingMemoryManager() override {}
464 /// This method returns the address of the specified symbol.
465 /// Our implementation will attempt to find symbols in other
466 /// modules associated with the MCJITHelper to cross link symbols
467 /// from one generated module to another.
468 uint64_t getSymbolAddress(const std::string &Name) override;
471 MCJITHelper *MasterHelper;
474 uint64_t HelpingMemoryManager::getSymbolAddress(const std::string &Name) {
475 uint64_t FnAddr = SectionMemoryManager::getSymbolAddress(Name);
479 uint64_t HelperFun = (uint64_t)MasterHelper->getSymbolAddress(Name);
481 report_fatal_error("Program used extern function '" + Name +
482 "' which could not be resolved!");
487 MCJITHelper::~MCJITHelper() {
490 EngineVector::iterator begin = Engines.begin();
491 EngineVector::iterator end = Engines.end();
492 EngineVector::iterator it;
493 for (it = begin; it != end; ++it)
497 Function *MCJITHelper::getFunction(const std::string FnName) {
498 ModuleVector::iterator begin = Modules.begin();
499 ModuleVector::iterator end = Modules.end();
500 ModuleVector::iterator it;
501 for (it = begin; it != end; ++it) {
502 Function *F = (*it)->getFunction(FnName);
504 if (*it == OpenModule)
507 assert(OpenModule != NULL);
509 // This function is in a module that has already been JITed.
510 // We need to generate a new prototype for external linkage.
511 Function *PF = OpenModule->getFunction(FnName);
512 if (PF && !PF->empty()) {
513 ErrorF("redefinition of function across modules");
517 // If we don't have a prototype yet, create one.
519 PF = Function::Create(F->getFunctionType(), Function::ExternalLinkage,
527 Module *MCJITHelper::getModuleForNewFunction() {
528 // If we have a Module that hasn't been JITed, use that.
532 // Otherwise create a new Module.
533 std::string ModName = GenerateUniqueName("mcjit_module_");
534 Module *M = new Module(ModName, Context);
535 Modules.push_back(M);
540 void *MCJITHelper::getPointerToFunction(Function *F) {
541 // See if an existing instance of MCJIT has this function.
542 EngineVector::iterator begin = Engines.begin();
543 EngineVector::iterator end = Engines.end();
544 EngineVector::iterator it;
545 for (it = begin; it != end; ++it) {
546 void *P = (*it)->getPointerToFunction(F);
551 // If we didn't find the function, see if we can generate it.
554 ExecutionEngine *NewEngine =
555 EngineBuilder(std::unique_ptr<Module>(OpenModule))
556 .setErrorStr(&ErrStr)
557 .setMCJITMemoryManager(std::unique_ptr<HelpingMemoryManager>(
558 new HelpingMemoryManager(this)))
561 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
565 // Create a function pass manager for this engine
566 auto *FPM = new legacy::FunctionPassManager(OpenModule);
568 // Set up the optimizer pipeline. Start with registering info about how the
569 // target lays out data structures.
570 OpenModule->setDataLayout(NewEngine->getDataLayout());
571 // Provide basic AliasAnalysis support for GVN.
572 FPM->add(createBasicAliasAnalysisPass());
573 // Promote allocas to registers.
574 FPM->add(createPromoteMemoryToRegisterPass());
575 // Do simple "peephole" optimizations and bit-twiddling optzns.
576 FPM->add(createInstructionCombiningPass());
577 // Reassociate expressions.
578 FPM->add(createReassociatePass());
579 // Eliminate Common SubExpressions.
580 FPM->add(createGVNPass());
581 // Simplify the control flow graph (deleting unreachable blocks, etc).
582 FPM->add(createCFGSimplificationPass());
583 FPM->doInitialization();
585 // For each function in the module
587 Module::iterator end = OpenModule->end();
588 for (it = OpenModule->begin(); it != end; ++it) {
589 // Run the FPM on this function
593 // We don't need this anymore
597 Engines.push_back(NewEngine);
598 NewEngine->finalizeObject();
599 return NewEngine->getPointerToFunction(F);
604 void *MCJITHelper::getSymbolAddress(const std::string &Name) {
605 // Look for the symbol in each of our execution engines.
606 EngineVector::iterator begin = Engines.begin();
607 EngineVector::iterator end = Engines.end();
608 EngineVector::iterator it;
609 for (it = begin; it != end; ++it) {
610 uint64_t FAddr = (*it)->getFunctionAddress(Name);
612 return (void *)FAddr;
618 void MCJITHelper::dump() {
619 ModuleVector::iterator begin = Modules.begin();
620 ModuleVector::iterator end = Modules.end();
621 ModuleVector::iterator it;
622 for (it = begin; it != end; ++it)
625 //===----------------------------------------------------------------------===//
627 //===----------------------------------------------------------------------===//
629 static MCJITHelper *JITHelper;
630 static IRBuilder<> Builder(getGlobalContext());
631 static std::map<std::string, Value *> NamedValues;
633 Value *ErrorV(const char *Str) {
638 Value *NumberExprAST::Codegen() {
639 return ConstantFP::get(getGlobalContext(), APFloat(Val));
642 Value *VariableExprAST::Codegen() {
643 // Look this variable up in the function.
644 Value *V = NamedValues[Name];
645 return V ? V : ErrorV("Unknown variable name");
648 Value *BinaryExprAST::Codegen() {
649 Value *L = LHS->Codegen();
650 Value *R = RHS->Codegen();
656 return Builder.CreateFAdd(L, R, "addtmp");
658 return Builder.CreateFSub(L, R, "subtmp");
660 return Builder.CreateFMul(L, R, "multmp");
662 L = Builder.CreateFCmpULT(L, R, "cmptmp");
663 // Convert bool 0/1 to double 0.0 or 1.0
664 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
667 return ErrorV("invalid binary operator");
671 Value *CallExprAST::Codegen() {
672 // Look up the name in the global module table.
673 Function *CalleeF = JITHelper->getFunction(Callee);
675 return ErrorV("Unknown function referenced");
677 // If argument mismatch error.
678 if (CalleeF->arg_size() != Args.size())
679 return ErrorV("Incorrect # arguments passed");
681 std::vector<Value *> ArgsV;
682 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
683 ArgsV.push_back(Args[i]->Codegen());
688 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
691 Function *PrototypeAST::Codegen() {
692 // Make the function type: double(double,double) etc.
693 std::vector<Type *> Doubles(Args.size(),
694 Type::getDoubleTy(getGlobalContext()));
696 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
698 std::string FnName = MakeLegalFunctionName(Name);
700 Module *M = JITHelper->getModuleForNewFunction();
702 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName, M);
704 // If F conflicted, there was already something named 'Name'. If it has a
705 // body, don't allow redefinition or reextern.
706 if (F->getName() != FnName) {
707 // Delete the one we just made and get the existing one.
708 F->eraseFromParent();
709 F = JITHelper->getFunction(Name);
710 // If F already has a body, reject this.
712 ErrorF("redefinition of function");
716 // If F took a different number of args, reject.
717 if (F->arg_size() != Args.size()) {
718 ErrorF("redefinition of function with different # args");
723 // Set names for all arguments.
725 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
727 AI->setName(Args[Idx]);
729 // Add arguments to variable symbol table.
730 NamedValues[Args[Idx]] = AI;
736 Function *FunctionAST::Codegen() {
739 Function *TheFunction = Proto->Codegen();
743 // Create a new basic block to start insertion into.
744 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
745 Builder.SetInsertPoint(BB);
747 if (Value *RetVal = Body->Codegen()) {
748 // Finish off the function.
749 Builder.CreateRet(RetVal);
751 // Validate the generated code, checking for consistency.
752 verifyFunction(*TheFunction);
757 // Error reading body, remove function.
758 TheFunction->eraseFromParent();
762 //===----------------------------------------------------------------------===//
763 // Top-Level parsing and JIT Driver
764 //===----------------------------------------------------------------------===//
766 static void HandleDefinition() {
767 if (auto FnAST = ParseDefinition()) {
768 if (auto *FnIR = FnAST->Codegen()) {
769 fprintf(stderr, "Read function definition:");
773 // Skip token for error recovery.
778 static void HandleExtern() {
779 if (auto ProtoAST = ParseExtern()) {
780 if (auto *FnIR = ProtoAST->Codegen()) {
781 fprintf(stderr, "Read extern: ");
785 // Skip token for error recovery.
790 static void HandleTopLevelExpression() {
791 // Evaluate a top-level expression into an anonymous function.
792 if (auto FnAST = ParseTopLevelExpr()) {
793 if (auto *FnIR = FnAST->Codegen()) {
794 // JIT the function, returning a function pointer.
795 void *FPtr = JITHelper->getPointerToFunction(FnIR);
797 // Cast it to the right type (takes no arguments, returns a double) so we
798 // can call it as a native function.
799 double (*FP)() = (double (*)())(intptr_t)FPtr;
800 fprintf(stderr, "Evaluated to %f\n", FP());
803 // Skip token for error recovery.
808 /// top ::= definition | external | expression | ';'
809 static void MainLoop() {
811 fprintf(stderr, "ready> ");
815 case ';': // ignore top-level semicolons.
825 HandleTopLevelExpression();
831 //===----------------------------------------------------------------------===//
832 // "Library" functions that can be "extern'd" from user code.
833 //===----------------------------------------------------------------------===//
835 /// putchard - putchar that takes a double and returns 0.
836 extern "C" double putchard(double X) {
841 /// printd - printf that takes a double prints it as "%f\n", returning 0.
842 extern "C" double printd(double X) {
847 //===----------------------------------------------------------------------===//
849 //===----------------------------------------------------------------------===//
852 InitializeNativeTarget();
853 InitializeNativeTargetAsmPrinter();
854 InitializeNativeTargetAsmParser();
855 LLVMContext &Context = getGlobalContext();
856 JITHelper = new MCJITHelper(Context);
858 // Install standard binary operators.
859 // 1 is lowest precedence.
860 BinopPrecedence['<'] = 10;
861 BinopPrecedence['+'] = 20;
862 BinopPrecedence['-'] = 20;
863 BinopPrecedence['*'] = 40; // highest.
865 // Prime the first token.
866 fprintf(stderr, "ready> ");
869 // Run the main "interpreter loop" now.
872 // Print out all of the generated code.