Ast.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // LLVM includes
  2. #include "llvm/IR/Verifier.h"
  3. // Local includes
  4. #include "Ast.h"
  5. #include "Parser.h"
  6. #include "JIT.h"
  7. using namespace jit;
  8. namespace ast{
  9. // attributes added from chapter 3 of the tutorial
  10. std::unique_ptr<Module> AstObjects::TheModule =
  11. std::make_unique<Module>("my cool jit", getGlobalContext());
  12. IRBuilder<> AstObjects::Builder(getGlobalContext());
  13. std::map<std::string, Value *> AstObjects::NamedValues;
  14. Value *ErrorV(const char *Str) {
  15. parser::Error(Str);
  16. return nullptr;
  17. }
  18. Value *NumberExprAST::codegen() {
  19. return ConstantFP::get(getGlobalContext(), APFloat(Val));
  20. }
  21. Value *VariableExprAST::codegen() {
  22. // Look this variable up in the function.
  23. Value *V = AstObjects::NamedValues[Name];
  24. if (!V)
  25. ErrorV("Unknown variable name");
  26. return V;
  27. }
  28. Value *UnaryExprAST::codegen() {
  29. Value *OperandV = Operand->codegen();
  30. if (!OperandV)
  31. return nullptr;
  32. Function *F = getFunction(std::string("unary") + Opcode);
  33. if (!F)
  34. return ErrorV("Unknown unary operator");
  35. return AstObjects::Builder.CreateCall(F, OperandV, "unop");
  36. }
  37. Value *BinaryExprAST::codegen() {
  38. Value *L = LHS->codegen();
  39. Value *R = RHS->codegen();
  40. if (!L || !R)
  41. return nullptr;
  42. switch (Op) {
  43. case '+':
  44. return AstObjects::Builder.CreateFAdd(L, R, "addtmp");
  45. case '-':
  46. return AstObjects::Builder.CreateFSub(L, R, "subtmp");
  47. case '*':
  48. return AstObjects::Builder.CreateFMul(L, R, "multmp");
  49. case '<':
  50. L = AstObjects::Builder.CreateFCmpULT(L, R, "cmptmp");
  51. // Convert bool 0/1 to double 0.0 or 1.0
  52. return AstObjects::Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
  53. "booltmp");
  54. default:
  55. break;
  56. }
  57. // If it wasn't a builtin binary operator, it must be a user defined one. Emit
  58. // a call to it.
  59. Function *F = AstObjects::TheModule->getFunction(std::string("binary") + Op);
  60. assert(F && "binary operator not found!");
  61. Value *Ops[2] = { L, R };
  62. return AstObjects::Builder.CreateCall(F, Ops, "binop");
  63. }
  64. Value *CallExprAST::codegen() {
  65. // Look up the name in the global module table.
  66. Function *CalleeF = getFunction(Callee);
  67. if (!CalleeF)
  68. return ErrorV("Unknown function referenced");
  69. // If argument mismatch error.
  70. if (CalleeF->arg_size() != Args.size())
  71. return ErrorV("Incorrect # arguments passed");
  72. std::vector<Value *> ArgsV;
  73. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  74. ArgsV.push_back(Args[i]->codegen());
  75. if (!ArgsV.back())
  76. return nullptr;
  77. }
  78. return AstObjects::Builder.CreateCall(CalleeF, ArgsV, "calltmp");
  79. }
  80. Value *IfExprAST::codegen() {
  81. Value *CondV = Cond->codegen();
  82. if (!CondV)
  83. return nullptr;
  84. // Convert condition to a bool by comparing equal to 0.0.
  85. CondV = AstObjects::Builder.CreateFCmpONE(
  86. CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
  87. Function *TheFunction = AstObjects::Builder.GetInsertBlock()->getParent();
  88. // Create blocks for the then and else cases. Insert the 'then' block at the
  89. // end of the function.
  90. BasicBlock *ThenBB =
  91. BasicBlock::Create(getGlobalContext(), "then", TheFunction);
  92. BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
  93. BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
  94. AstObjects::Builder.CreateCondBr(CondV, ThenBB, ElseBB);
  95. // Emit then value.
  96. AstObjects::Builder.SetInsertPoint(ThenBB);
  97. Value *ThenV = Then->codegen();
  98. if (!ThenV)
  99. return nullptr;
  100. AstObjects::Builder.CreateBr(MergeBB);
  101. // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
  102. ThenBB = AstObjects::Builder.GetInsertBlock();
  103. // Emit else block.
  104. TheFunction->getBasicBlockList().push_back(ElseBB);
  105. AstObjects::Builder.SetInsertPoint(ElseBB);
  106. Value *ElseV = Else->codegen();
  107. if (!ElseV)
  108. return nullptr;
  109. AstObjects::Builder.CreateBr(MergeBB);
  110. // codegen of 'Else' can change the current block, update ElseBB for the PHI.
  111. ElseBB = AstObjects::Builder.GetInsertBlock();
  112. // Emit merge block.
  113. TheFunction->getBasicBlockList().push_back(MergeBB);
  114. AstObjects::Builder.SetInsertPoint(MergeBB);
  115. PHINode *PN =
  116. AstObjects::Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
  117. PN->addIncoming(ThenV, ThenBB);
  118. PN->addIncoming(ElseV, ElseBB);
  119. return PN;
  120. }
  121. Value *ForExprAST::codegen() {
  122. // Emit the start code first, without 'variable' in scope.
  123. Value *StartVal = Start->codegen();
  124. if (StartVal == 0) return 0;
  125. // Make the new basic block for the loop header, inserting after current
  126. // block.
  127. Function *TheFunction = AstObjects::Builder.GetInsertBlock()->getParent();
  128. BasicBlock *PreheaderBB = AstObjects::Builder.GetInsertBlock();
  129. BasicBlock *LoopBB =
  130. BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
  131. // Insert an explicit fall through from the current block to the LoopBB.
  132. AstObjects::Builder.CreateBr(LoopBB);
  133. // Start insertion in LoopBB.
  134. AstObjects::Builder.SetInsertPoint(LoopBB);
  135. // Start the PHI node with an entry for Start.
  136. PHINode *Variable = AstObjects::Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
  137. 2, VarName.c_str());
  138. Variable->addIncoming(StartVal, PreheaderBB);
  139. // Within the loop, the variable is defined equal to the PHI node. If it
  140. // shadows an existing variable, we have to restore it, so save it now.
  141. Value *OldVal = AstObjects::NamedValues[VarName];
  142. AstObjects::NamedValues[VarName] = Variable;
  143. // Emit the body of the loop. This, like any other expr, can change the
  144. // current BB. Note that we ignore the value computed by the body, but don't
  145. // allow an error.
  146. if (!Body->codegen())
  147. return nullptr;
  148. // Emit the step value.
  149. Value *StepVal = nullptr;
  150. if (Step) {
  151. StepVal = Step->codegen();
  152. if (!StepVal)
  153. return nullptr;
  154. } else {
  155. // If not specified, use 1.0.
  156. StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
  157. }
  158. Value *NextVar = AstObjects::Builder.CreateFAdd(Variable, StepVal, "nextvar");
  159. // Compute the end condition.
  160. Value *EndCond = End->codegen();
  161. if (!EndCond)
  162. return nullptr;
  163. // Convert condition to a bool by comparing equal to 0.0.
  164. EndCond = AstObjects::Builder.CreateFCmpONE(
  165. EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
  166. // Create the "after loop" block and insert it.
  167. BasicBlock *LoopEndBB = AstObjects::Builder.GetInsertBlock();
  168. BasicBlock *AfterBB =
  169. BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
  170. // Insert the conditional branch into the end of LoopEndBB.
  171. AstObjects::Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
  172. // Any new code will be inserted in AfterBB.
  173. AstObjects::Builder.SetInsertPoint(AfterBB);
  174. // Add a new entry to the PHI node for the backedge.
  175. Variable->addIncoming(NextVar, LoopEndBB);
  176. // Restore the unshadowed variable.
  177. if (OldVal)
  178. AstObjects::NamedValues[VarName] = OldVal;
  179. else
  180. AstObjects::NamedValues.erase(VarName);
  181. // for expr always returns 0.0.
  182. return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
  183. }
  184. Function *PrototypeAST::codegen() {
  185. // Make the function type: double(double,double) etc.
  186. std::vector<Type *> Doubles(Args.size(),
  187. Type::getDoubleTy(getGlobalContext()));
  188. FunctionType *FT = FunctionType::get(Type::getDoubleTy(
  189. getGlobalContext()), Doubles, false);
  190. Function *F = Function::Create(FT, Function::ExternalLinkage, Name,
  191. AstObjects::TheModule.get());
  192. // Set names for all arguments.
  193. unsigned Idx = 0;
  194. for (auto &Arg : F->args())
  195. Arg.setName(Args[Idx++]);
  196. return F;
  197. }
  198. Function *FunctionAST::codegen() {
  199. // Transfer ownership of the prototype to the FunctionProtos map, but keep a
  200. // reference to it for use below.
  201. auto &P = *Proto;
  202. JITObjects::FunctionProtos[Proto->getName()] = std::move(Proto);
  203. Function *TheFunction = getFunction(P.getName());
  204. if (!TheFunction)
  205. return nullptr;
  206. // If this is an operator, install it.
  207. if (P.isBinaryOp())
  208. parser::BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
  209. // Create a new basic block to start insertion into.
  210. BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
  211. AstObjects::Builder.SetInsertPoint(BB);
  212. // Record the function arguments in the NamedValues map.
  213. AstObjects::NamedValues.clear();
  214. for (auto &Arg : TheFunction->args())
  215. AstObjects::NamedValues[Arg.getName()] = &Arg;
  216. if (Value *RetVal = Body->codegen()) {
  217. // Finish off the function.
  218. AstObjects::Builder.CreateRet(RetVal);
  219. // Validate the generated code, checking for consistency.
  220. verifyFunction(*TheFunction);
  221. // Run the optimizer on the function.
  222. JITObjects::TheFPM->run(*TheFunction);
  223. return TheFunction;
  224. }
  225. // Error reading body, remove function.
  226. TheFunction->eraseFromParent();
  227. if (P.isBinaryOp())
  228. parser::BinopPrecedence.erase(Proto->getOperatorName());
  229. return nullptr;
  230. }
  231. }