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