CallPromotionUtils.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. //===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements utilities useful for promoting indirect call sites to
  11. // direct call sites.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/CallPromotionUtils.h"
  15. #include "llvm/IR/IRBuilder.h"
  16. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  17. using namespace llvm;
  18. #define DEBUG_TYPE "call-promotion-utils"
  19. /// Fix-up phi nodes in an invoke instruction's normal destination.
  20. ///
  21. /// After versioning an invoke instruction, values coming from the original
  22. /// block will now be coming from the "merge" block. For example, in the code
  23. /// below:
  24. ///
  25. /// then_bb:
  26. /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
  27. ///
  28. /// else_bb:
  29. /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
  30. ///
  31. /// merge_bb:
  32. /// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
  33. /// br %normal_dst
  34. ///
  35. /// normal_dst:
  36. /// %t3 = phi i32 [ %x, %orig_bb ], ...
  37. ///
  38. /// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
  39. /// "normal_dst" must be fixed to refer to "merge_bb":
  40. ///
  41. /// normal_dst:
  42. /// %t3 = phi i32 [ %x, %merge_bb ], ...
  43. ///
  44. static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
  45. BasicBlock *MergeBlock) {
  46. for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
  47. int Idx = Phi.getBasicBlockIndex(OrigBlock);
  48. if (Idx == -1)
  49. continue;
  50. Phi.setIncomingBlock(Idx, MergeBlock);
  51. }
  52. }
  53. /// Fix-up phi nodes in an invoke instruction's unwind destination.
  54. ///
  55. /// After versioning an invoke instruction, values coming from the original
  56. /// block will now be coming from either the "then" block or the "else" block.
  57. /// For example, in the code below:
  58. ///
  59. /// then_bb:
  60. /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
  61. ///
  62. /// else_bb:
  63. /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
  64. ///
  65. /// unwind_dst:
  66. /// %t3 = phi i32 [ %x, %orig_bb ], ...
  67. ///
  68. /// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
  69. /// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
  70. ///
  71. /// unwind_dst:
  72. /// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
  73. ///
  74. static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
  75. BasicBlock *ThenBlock,
  76. BasicBlock *ElseBlock) {
  77. for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
  78. int Idx = Phi.getBasicBlockIndex(OrigBlock);
  79. if (Idx == -1)
  80. continue;
  81. auto *V = Phi.getIncomingValue(Idx);
  82. Phi.setIncomingBlock(Idx, ThenBlock);
  83. Phi.addIncoming(V, ElseBlock);
  84. }
  85. }
  86. /// Create a phi node for the returned value of a call or invoke instruction.
  87. ///
  88. /// After versioning a call or invoke instruction that returns a value, we have
  89. /// to merge the value of the original and new instructions. We do this by
  90. /// creating a phi node and replacing uses of the original instruction with this
  91. /// phi node.
  92. ///
  93. /// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
  94. /// defined in "then_bb", we create the following phi node:
  95. ///
  96. /// ; Uses of the original instruction are replaced by uses of the phi node.
  97. /// %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
  98. ///
  99. static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
  100. BasicBlock *MergeBlock, IRBuilder<> &Builder) {
  101. if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
  102. return;
  103. Builder.SetInsertPoint(&MergeBlock->front());
  104. PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0);
  105. SmallVector<User *, 16> UsersToUpdate;
  106. for (User *U : OrigInst->users())
  107. UsersToUpdate.push_back(U);
  108. for (User *U : UsersToUpdate)
  109. U->replaceUsesOfWith(OrigInst, Phi);
  110. Phi->addIncoming(OrigInst, OrigInst->getParent());
  111. Phi->addIncoming(NewInst, NewInst->getParent());
  112. }
  113. /// Cast a call or invoke instruction to the given type.
  114. ///
  115. /// When promoting a call site, the return type of the call site might not match
  116. /// that of the callee. If this is the case, we have to cast the returned value
  117. /// to the correct type. The location of the cast depends on if we have a call
  118. /// or invoke instruction.
  119. ///
  120. /// For example, if the call instruction below requires a bitcast after
  121. /// promotion:
  122. ///
  123. /// orig_bb:
  124. /// %t0 = call i32 @func()
  125. /// ...
  126. ///
  127. /// The bitcast is placed after the call instruction:
  128. ///
  129. /// orig_bb:
  130. /// ; Uses of the original return value are replaced by uses of the bitcast.
  131. /// %t0 = call i32 @func()
  132. /// %t1 = bitcast i32 %t0 to ...
  133. /// ...
  134. ///
  135. /// A similar transformation is performed for invoke instructions. However,
  136. /// since invokes are terminating, a new block is created for the bitcast. For
  137. /// example, if the invoke instruction below requires a bitcast after promotion:
  138. ///
  139. /// orig_bb:
  140. /// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
  141. ///
  142. /// The edge between the original block and the invoke's normal destination is
  143. /// split, and the bitcast is placed there:
  144. ///
  145. /// orig_bb:
  146. /// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
  147. ///
  148. /// split_bb:
  149. /// ; Uses of the original return value are replaced by uses of the bitcast.
  150. /// %t1 = bitcast i32 %t0 to ...
  151. /// br label %normal_dst
  152. ///
  153. static void createRetBitCast(CallSite CS, Type *RetTy, CastInst **RetBitCast) {
  154. // Save the users of the calling instruction. These uses will be changed to
  155. // use the bitcast after we create it.
  156. SmallVector<User *, 16> UsersToUpdate;
  157. for (User *U : CS.getInstruction()->users())
  158. UsersToUpdate.push_back(U);
  159. // Determine an appropriate location to create the bitcast for the return
  160. // value. The location depends on if we have a call or invoke instruction.
  161. Instruction *InsertBefore = nullptr;
  162. if (auto *Invoke = dyn_cast<InvokeInst>(CS.getInstruction()))
  163. InsertBefore =
  164. &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
  165. else
  166. InsertBefore = &*std::next(CS.getInstruction()->getIterator());
  167. // Bitcast the return value to the correct type.
  168. auto *Cast = CastInst::Create(Instruction::BitCast, CS.getInstruction(),
  169. RetTy, "", InsertBefore);
  170. if (RetBitCast)
  171. *RetBitCast = Cast;
  172. // Replace all the original uses of the calling instruction with the bitcast.
  173. for (User *U : UsersToUpdate)
  174. U->replaceUsesOfWith(CS.getInstruction(), Cast);
  175. }
  176. /// Predicate and clone the given call site.
  177. ///
  178. /// This function creates an if-then-else structure at the location of the call
  179. /// site. The "if" condition compares the call site's called value to the given
  180. /// callee. The original call site is moved into the "else" block, and a clone
  181. /// of the call site is placed in the "then" block. The cloned instruction is
  182. /// returned.
  183. ///
  184. /// For example, the call instruction below:
  185. ///
  186. /// orig_bb:
  187. /// %t0 = call i32 %ptr()
  188. /// ...
  189. ///
  190. /// Is replace by the following:
  191. ///
  192. /// orig_bb:
  193. /// %cond = icmp eq i32 ()* %ptr, @func
  194. /// br i1 %cond, %then_bb, %else_bb
  195. ///
  196. /// then_bb:
  197. /// ; The clone of the original call instruction is placed in the "then"
  198. /// ; block. It is not yet promoted.
  199. /// %t1 = call i32 %ptr()
  200. /// br merge_bb
  201. ///
  202. /// else_bb:
  203. /// ; The original call instruction is moved to the "else" block.
  204. /// %t0 = call i32 %ptr()
  205. /// br merge_bb
  206. ///
  207. /// merge_bb:
  208. /// ; Uses of the original call instruction are replaced by uses of the phi
  209. /// ; node.
  210. /// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
  211. /// ...
  212. ///
  213. /// A similar transformation is performed for invoke instructions. However,
  214. /// since invokes are terminating, more work is required. For example, the
  215. /// invoke instruction below:
  216. ///
  217. /// orig_bb:
  218. /// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
  219. ///
  220. /// Is replace by the following:
  221. ///
  222. /// orig_bb:
  223. /// %cond = icmp eq i32 ()* %ptr, @func
  224. /// br i1 %cond, %then_bb, %else_bb
  225. ///
  226. /// then_bb:
  227. /// ; The clone of the original invoke instruction is placed in the "then"
  228. /// ; block, and its normal destination is set to the "merge" block. It is
  229. /// ; not yet promoted.
  230. /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
  231. ///
  232. /// else_bb:
  233. /// ; The original invoke instruction is moved into the "else" block, and
  234. /// ; its normal destination is set to the "merge" block.
  235. /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
  236. ///
  237. /// merge_bb:
  238. /// ; Uses of the original invoke instruction are replaced by uses of the
  239. /// ; phi node, and the merge block branches to the normal destination.
  240. /// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
  241. /// br %normal_dst
  242. ///
  243. static Instruction *versionCallSite(CallSite CS, Value *Callee,
  244. MDNode *BranchWeights) {
  245. IRBuilder<> Builder(CS.getInstruction());
  246. Instruction *OrigInst = CS.getInstruction();
  247. BasicBlock *OrigBlock = OrigInst->getParent();
  248. // Create the compare. The called value and callee must have the same type to
  249. // be compared.
  250. if (CS.getCalledValue()->getType() != Callee->getType())
  251. Callee = Builder.CreateBitCast(Callee, CS.getCalledValue()->getType());
  252. auto *Cond = Builder.CreateICmpEQ(CS.getCalledValue(), Callee);
  253. // Create an if-then-else structure. The original instruction is moved into
  254. // the "else" block, and a clone of the original instruction is placed in the
  255. // "then" block.
  256. TerminatorInst *ThenTerm = nullptr;
  257. TerminatorInst *ElseTerm = nullptr;
  258. SplitBlockAndInsertIfThenElse(Cond, CS.getInstruction(), &ThenTerm, &ElseTerm,
  259. BranchWeights);
  260. BasicBlock *ThenBlock = ThenTerm->getParent();
  261. BasicBlock *ElseBlock = ElseTerm->getParent();
  262. BasicBlock *MergeBlock = OrigInst->getParent();
  263. ThenBlock->setName("if.true.direct_targ");
  264. ElseBlock->setName("if.false.orig_indirect");
  265. MergeBlock->setName("if.end.icp");
  266. Instruction *NewInst = OrigInst->clone();
  267. OrigInst->moveBefore(ElseTerm);
  268. NewInst->insertBefore(ThenTerm);
  269. // If the original call site is an invoke instruction, we have extra work to
  270. // do since invoke instructions are terminating. We have to fix-up phi nodes
  271. // in the invoke's normal and unwind destinations.
  272. if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
  273. auto *NewInvoke = cast<InvokeInst>(NewInst);
  274. // Invoke instructions are terminating, so we don't need the terminator
  275. // instructions that were just created.
  276. ThenTerm->eraseFromParent();
  277. ElseTerm->eraseFromParent();
  278. // Branch from the "merge" block to the original normal destination.
  279. Builder.SetInsertPoint(MergeBlock);
  280. Builder.CreateBr(OrigInvoke->getNormalDest());
  281. // Fix-up phi nodes in the original invoke's normal and unwind destinations.
  282. fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
  283. fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
  284. // Now set the normal destinations of the invoke instructions to be the
  285. // "merge" block.
  286. OrigInvoke->setNormalDest(MergeBlock);
  287. NewInvoke->setNormalDest(MergeBlock);
  288. }
  289. // Create a phi node for the returned value of the call site.
  290. createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
  291. return NewInst;
  292. }
  293. bool llvm::isLegalToPromote(CallSite CS, Function *Callee,
  294. const char **FailureReason) {
  295. assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
  296. // Check the return type. The callee's return value type must be bitcast
  297. // compatible with the call site's type.
  298. Type *CallRetTy = CS.getInstruction()->getType();
  299. Type *FuncRetTy = Callee->getReturnType();
  300. if (CallRetTy != FuncRetTy)
  301. if (!CastInst::isBitCastable(FuncRetTy, CallRetTy)) {
  302. if (FailureReason)
  303. *FailureReason = "Return type mismatch";
  304. return false;
  305. }
  306. // The number of formal arguments of the callee.
  307. unsigned NumParams = Callee->getFunctionType()->getNumParams();
  308. // Check the number of arguments. The callee and call site must agree on the
  309. // number of arguments.
  310. if (CS.arg_size() != NumParams && !Callee->isVarArg()) {
  311. if (FailureReason)
  312. *FailureReason = "The number of arguments mismatch";
  313. return false;
  314. }
  315. // Check the argument types. The callee's formal argument types must be
  316. // bitcast compatible with the corresponding actual argument types of the call
  317. // site.
  318. for (unsigned I = 0; I < NumParams; ++I) {
  319. Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
  320. Type *ActualTy = CS.getArgument(I)->getType();
  321. if (FormalTy == ActualTy)
  322. continue;
  323. if (!CastInst::isBitCastable(ActualTy, FormalTy)) {
  324. if (FailureReason)
  325. *FailureReason = "Argument type mismatch";
  326. return false;
  327. }
  328. }
  329. return true;
  330. }
  331. Instruction *llvm::promoteCall(CallSite CS, Function *Callee,
  332. CastInst **RetBitCast) {
  333. assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
  334. // Set the called function of the call site to be the given callee.
  335. CS.setCalledFunction(Callee);
  336. // Since the call site will no longer be direct, we must clear metadata that
  337. // is only appropriate for indirect calls. This includes !prof and !callees
  338. // metadata.
  339. CS.getInstruction()->setMetadata(LLVMContext::MD_prof, nullptr);
  340. CS.getInstruction()->setMetadata(LLVMContext::MD_callees, nullptr);
  341. // If the function type of the call site matches that of the callee, no
  342. // additional work is required.
  343. if (CS.getFunctionType() == Callee->getFunctionType())
  344. return CS.getInstruction();
  345. // Save the return types of the call site and callee.
  346. Type *CallSiteRetTy = CS.getInstruction()->getType();
  347. Type *CalleeRetTy = Callee->getReturnType();
  348. // Change the function type of the call site the match that of the callee.
  349. CS.mutateFunctionType(Callee->getFunctionType());
  350. // Inspect the arguments of the call site. If an argument's type doesn't
  351. // match the corresponding formal argument's type in the callee, bitcast it
  352. // to the correct type.
  353. for (Use &U : CS.args()) {
  354. unsigned ArgNo = CS.getArgumentNo(&U);
  355. Type *FormalTy = Callee->getFunctionType()->getParamType(ArgNo);
  356. Type *ActualTy = U.get()->getType();
  357. if (FormalTy != ActualTy) {
  358. auto *Cast = CastInst::Create(Instruction::BitCast, U.get(), FormalTy, "",
  359. CS.getInstruction());
  360. CS.setArgument(ArgNo, Cast);
  361. }
  362. }
  363. // If the return type of the call site doesn't match that of the callee, cast
  364. // the returned value to the appropriate type.
  365. if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy)
  366. createRetBitCast(CS, CallSiteRetTy, RetBitCast);
  367. return CS.getInstruction();
  368. }
  369. Instruction *llvm::promoteCallWithIfThenElse(CallSite CS, Function *Callee,
  370. MDNode *BranchWeights) {
  371. // Version the indirect call site. If the called value is equal to the given
  372. // callee, 'NewInst' will be executed, otherwise the original call site will
  373. // be executed.
  374. Instruction *NewInst = versionCallSite(CS, Callee, BranchWeights);
  375. // Promote 'NewInst' so that it directly calls the desired function.
  376. return promoteCall(CallSite(NewInst), Callee);
  377. }
  378. #undef DEBUG_TYPE