1 //===- CloneFunction.cpp - Clone a function into another function ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the CloneFunctionInto interface, which is used as the 10 // low-level function cloner. This is used by the CloneFunction and function 11 // inliner to do the dirty work of copying the body of a function around. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ADT/SetVector.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/Analysis/DomTreeUpdater.h" 18 #include "llvm/Analysis/InstructionSimplify.h" 19 #include "llvm/Analysis/LoopInfo.h" 20 #include "llvm/IR/CFG.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DebugInfo.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/Instructions.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/LLVMContext.h" 28 #include "llvm/IR/MDBuilder.h" 29 #include "llvm/IR/Metadata.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 32 #include "llvm/Transforms/Utils/Cloning.h" 33 #include "llvm/Transforms/Utils/Local.h" 34 #include "llvm/Transforms/Utils/ValueMapper.h" 35 #include <map> 36 using namespace llvm; 37 38 #define DEBUG_TYPE "clone-function" 39 40 /// See comments in Cloning.h. 41 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, 42 const Twine &NameSuffix, Function *F, 43 ClonedCodeInfo *CodeInfo, 44 DebugInfoFinder *DIFinder) { 45 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F); 46 if (BB->hasName()) 47 NewBB->setName(BB->getName() + NameSuffix); 48 49 bool hasCalls = false, hasDynamicAllocas = false; 50 Module *TheModule = F ? F->getParent() : nullptr; 51 52 // Loop over all instructions, and copy them over. 53 for (const Instruction &I : *BB) { 54 if (DIFinder && TheModule) 55 DIFinder->processInstruction(*TheModule, I); 56 57 Instruction *NewInst = I.clone(); 58 if (I.hasName()) 59 NewInst->setName(I.getName() + NameSuffix); 60 NewBB->getInstList().push_back(NewInst); 61 VMap[&I] = NewInst; // Add instruction map to value. 62 63 hasCalls |= (isa<CallInst>(I) && !I.isDebugOrPseudoInst()); 64 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 65 if (!AI->isStaticAlloca()) { 66 hasDynamicAllocas = true; 67 } 68 } 69 } 70 71 if (CodeInfo) { 72 CodeInfo->ContainsCalls |= hasCalls; 73 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 74 } 75 return NewBB; 76 } 77 78 // Clone OldFunc into NewFunc, transforming the old arguments into references to 79 // VMap values. 80 // 81 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc, 82 ValueToValueMapTy &VMap, 83 CloneFunctionChangeType Changes, 84 SmallVectorImpl<ReturnInst *> &Returns, 85 const char *NameSuffix, ClonedCodeInfo *CodeInfo, 86 ValueMapTypeRemapper *TypeMapper, 87 ValueMaterializer *Materializer) { 88 assert(NameSuffix && "NameSuffix cannot be null!"); 89 90 #ifndef NDEBUG 91 for (const Argument &I : OldFunc->args()) 92 assert(VMap.count(&I) && "No mapping from source argument specified!"); 93 #endif 94 95 bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly; 96 97 // Copy all attributes other than those stored in the AttributeList. We need 98 // to remap the parameter indices of the AttributeList. 99 AttributeList NewAttrs = NewFunc->getAttributes(); 100 NewFunc->copyAttributesFrom(OldFunc); 101 NewFunc->setAttributes(NewAttrs); 102 103 // Fix up the personality function that got copied over. 104 if (OldFunc->hasPersonalityFn()) 105 NewFunc->setPersonalityFn( 106 MapValue(OldFunc->getPersonalityFn(), VMap, 107 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 108 TypeMapper, Materializer)); 109 110 SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size()); 111 AttributeList OldAttrs = OldFunc->getAttributes(); 112 113 // Clone any argument attributes that are present in the VMap. 114 for (const Argument &OldArg : OldFunc->args()) { 115 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) { 116 NewArgAttrs[NewArg->getArgNo()] = 117 OldAttrs.getParamAttrs(OldArg.getArgNo()); 118 } 119 } 120 121 NewFunc->setAttributes( 122 AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(), 123 OldAttrs.getRetAttrs(), NewArgAttrs)); 124 125 // Everything else beyond this point deals with function instructions, 126 // so if we are dealing with a function declaration, we're done. 127 if (OldFunc->isDeclaration()) 128 return; 129 130 // When we remap instructions within the same module, we want to avoid 131 // duplicating inlined DISubprograms, so record all subprograms we find as we 132 // duplicate instructions and then freeze them in the MD map. We also record 133 // information about dbg.value and dbg.declare to avoid duplicating the 134 // types. 135 Optional<DebugInfoFinder> DIFinder; 136 137 // Track the subprogram attachment that needs to be cloned to fine-tune the 138 // mapping within the same module. 139 DISubprogram *SPClonedWithinModule = nullptr; 140 if (Changes < CloneFunctionChangeType::DifferentModule) { 141 assert((NewFunc->getParent() == nullptr || 142 NewFunc->getParent() == OldFunc->getParent()) && 143 "Expected NewFunc to have the same parent, or no parent"); 144 145 // Need to find subprograms, types, and compile units. 146 DIFinder.emplace(); 147 148 SPClonedWithinModule = OldFunc->getSubprogram(); 149 if (SPClonedWithinModule) 150 DIFinder->processSubprogram(SPClonedWithinModule); 151 } else { 152 assert((NewFunc->getParent() == nullptr || 153 NewFunc->getParent() != OldFunc->getParent()) && 154 "Expected NewFunc to have different parents, or no parent"); 155 156 if (Changes == CloneFunctionChangeType::DifferentModule) { 157 assert(NewFunc->getParent() && 158 "Need parent of new function to maintain debug info invariants"); 159 160 // Need to find all the compile units. 161 DIFinder.emplace(); 162 } 163 } 164 165 // Loop over all of the basic blocks in the function, cloning them as 166 // appropriate. Note that we save BE this way in order to handle cloning of 167 // recursive functions into themselves. 168 for (const BasicBlock &BB : *OldFunc) { 169 170 // Create a new basic block and copy instructions into it! 171 BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo, 172 DIFinder ? &*DIFinder : nullptr); 173 174 // Add basic block mapping. 175 VMap[&BB] = CBB; 176 177 // It is only legal to clone a function if a block address within that 178 // function is never referenced outside of the function. Given that, we 179 // want to map block addresses from the old function to block addresses in 180 // the clone. (This is different from the generic ValueMapper 181 // implementation, which generates an invalid blockaddress when 182 // cloning a function.) 183 if (BB.hasAddressTaken()) { 184 Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc), 185 const_cast<BasicBlock *>(&BB)); 186 VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB); 187 } 188 189 // Note return instructions for the caller. 190 if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator())) 191 Returns.push_back(RI); 192 } 193 194 if (Changes < CloneFunctionChangeType::DifferentModule && 195 DIFinder->subprogram_count() > 0) { 196 // Turn on module-level changes, since we need to clone (some of) the 197 // debug info metadata. 198 // 199 // FIXME: Metadata effectively owned by a function should be made 200 // local, and only that local metadata should be cloned. 201 ModuleLevelChanges = true; 202 203 auto mapToSelfIfNew = [&VMap](MDNode *N) { 204 // Avoid clobbering an existing mapping. 205 (void)VMap.MD().try_emplace(N, N); 206 }; 207 208 // Avoid cloning types, compile units, and (other) subprograms. 209 SmallPtrSet<const DISubprogram *, 16> MappedToSelfSPs; 210 for (DISubprogram *ISP : DIFinder->subprograms()) { 211 if (ISP != SPClonedWithinModule) { 212 mapToSelfIfNew(ISP); 213 MappedToSelfSPs.insert(ISP); 214 } 215 } 216 217 // If a subprogram isn't going to be cloned skip its lexical blocks as well. 218 for (DIScope *S : DIFinder->scopes()) { 219 auto *LScope = dyn_cast<DILocalScope>(S); 220 if (LScope && MappedToSelfSPs.count(LScope->getSubprogram())) 221 mapToSelfIfNew(S); 222 } 223 224 for (DICompileUnit *CU : DIFinder->compile_units()) 225 mapToSelfIfNew(CU); 226 227 for (DIType *Type : DIFinder->types()) 228 mapToSelfIfNew(Type); 229 } else { 230 assert(!SPClonedWithinModule && 231 "Subprogram should be in DIFinder->subprogram_count()..."); 232 } 233 234 const auto RemapFlag = ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges; 235 // Duplicate the metadata that is attached to the cloned function. 236 // Subprograms/CUs/types that were already mapped to themselves won't be 237 // duplicated. 238 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 239 OldFunc->getAllMetadata(MDs); 240 for (auto MD : MDs) { 241 NewFunc->addMetadata(MD.first, *MapMetadata(MD.second, VMap, RemapFlag, 242 TypeMapper, Materializer)); 243 } 244 245 // Loop over all of the instructions in the new function, fixing up operand 246 // references as we go. This uses VMap to do all the hard work. 247 for (Function::iterator 248 BB = cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(), 249 BE = NewFunc->end(); 250 BB != BE; ++BB) 251 // Loop over all instructions, fixing each one as we find it... 252 for (Instruction &II : *BB) 253 RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer); 254 255 // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the 256 // same module, the compile unit will already be listed (or not). When 257 // cloning a module, CloneModule() will handle creating the named metadata. 258 if (Changes != CloneFunctionChangeType::DifferentModule) 259 return; 260 261 // Update !llvm.dbg.cu with compile units added to the new module if this 262 // function is being cloned in isolation. 263 // 264 // FIXME: This is making global / module-level changes, which doesn't seem 265 // like the right encapsulation Consider dropping the requirement to update 266 // !llvm.dbg.cu (either obsoleting the node, or restricting it to 267 // non-discardable compile units) instead of discovering compile units by 268 // visiting the metadata attached to global values, which would allow this 269 // code to be deleted. Alternatively, perhaps give responsibility for this 270 // update to CloneFunctionInto's callers. 271 auto *NewModule = NewFunc->getParent(); 272 auto *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu"); 273 // Avoid multiple insertions of the same DICompileUnit to NMD. 274 SmallPtrSet<const void *, 8> Visited; 275 for (auto *Operand : NMD->operands()) 276 Visited.insert(Operand); 277 for (auto *Unit : DIFinder->compile_units()) { 278 MDNode *MappedUnit = 279 MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer); 280 if (Visited.insert(MappedUnit).second) 281 NMD->addOperand(MappedUnit); 282 } 283 } 284 285 /// Return a copy of the specified function and add it to that function's 286 /// module. Also, any references specified in the VMap are changed to refer to 287 /// their mapped value instead of the original one. If any of the arguments to 288 /// the function are in the VMap, the arguments are deleted from the resultant 289 /// function. The VMap is updated to include mappings from all of the 290 /// instructions and basicblocks in the function from their old to new values. 291 /// 292 Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap, 293 ClonedCodeInfo *CodeInfo) { 294 std::vector<Type *> ArgTypes; 295 296 // The user might be deleting arguments to the function by specifying them in 297 // the VMap. If so, we need to not add the arguments to the arg ty vector 298 // 299 for (const Argument &I : F->args()) 300 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet? 301 ArgTypes.push_back(I.getType()); 302 303 // Create a new function type... 304 FunctionType *FTy = 305 FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes, 306 F->getFunctionType()->isVarArg()); 307 308 // Create the new function... 309 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(), 310 F->getName(), F->getParent()); 311 312 // Loop over the arguments, copying the names of the mapped arguments over... 313 Function::arg_iterator DestI = NewF->arg_begin(); 314 for (const Argument &I : F->args()) 315 if (VMap.count(&I) == 0) { // Is this argument preserved? 316 DestI->setName(I.getName()); // Copy the name over... 317 VMap[&I] = &*DestI++; // Add mapping to VMap 318 } 319 320 SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned. 321 CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly, 322 Returns, "", CodeInfo); 323 324 return NewF; 325 } 326 327 namespace { 328 /// This is a private class used to implement CloneAndPruneFunctionInto. 329 struct PruningFunctionCloner { 330 Function *NewFunc; 331 const Function *OldFunc; 332 ValueToValueMapTy &VMap; 333 bool ModuleLevelChanges; 334 const char *NameSuffix; 335 ClonedCodeInfo *CodeInfo; 336 bool HostFuncIsStrictFP; 337 338 Instruction *cloneInstruction(BasicBlock::const_iterator II); 339 340 public: 341 PruningFunctionCloner(Function *newFunc, const Function *oldFunc, 342 ValueToValueMapTy &valueMap, bool moduleLevelChanges, 343 const char *nameSuffix, ClonedCodeInfo *codeInfo) 344 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap), 345 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix), 346 CodeInfo(codeInfo) { 347 HostFuncIsStrictFP = 348 newFunc->getAttributes().hasFnAttr(Attribute::StrictFP); 349 } 350 351 /// The specified block is found to be reachable, clone it and 352 /// anything that it can reach. 353 void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst, 354 std::vector<const BasicBlock *> &ToClone); 355 }; 356 } // namespace 357 358 static bool hasRoundingModeOperand(Intrinsic::ID CIID) { 359 switch (CIID) { 360 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 361 case Intrinsic::INTRINSIC: \ 362 return ROUND_MODE == 1; 363 #define FUNCTION INSTRUCTION 364 #include "llvm/IR/ConstrainedOps.def" 365 default: 366 llvm_unreachable("Unexpected constrained intrinsic id"); 367 } 368 } 369 370 Instruction * 371 PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) { 372 const Instruction &OldInst = *II; 373 Instruction *NewInst = nullptr; 374 if (HostFuncIsStrictFP) { 375 Intrinsic::ID CIID = getConstrainedIntrinsicID(OldInst); 376 if (CIID != Intrinsic::not_intrinsic) { 377 // Instead of cloning the instruction, a call to constrained intrinsic 378 // should be created. 379 // Assume the first arguments of constrained intrinsics are the same as 380 // the operands of original instruction. 381 382 // Determine overloaded types of the intrinsic. 383 SmallVector<Type *, 2> TParams; 384 SmallVector<Intrinsic::IITDescriptor, 8> Descriptor; 385 getIntrinsicInfoTableEntries(CIID, Descriptor); 386 for (unsigned I = 0, E = Descriptor.size(); I != E; ++I) { 387 Intrinsic::IITDescriptor Operand = Descriptor[I]; 388 switch (Operand.Kind) { 389 case Intrinsic::IITDescriptor::Argument: 390 if (Operand.getArgumentKind() != 391 Intrinsic::IITDescriptor::AK_MatchType) { 392 if (I == 0) 393 TParams.push_back(OldInst.getType()); 394 else 395 TParams.push_back(OldInst.getOperand(I - 1)->getType()); 396 } 397 break; 398 case Intrinsic::IITDescriptor::SameVecWidthArgument: 399 ++I; 400 break; 401 default: 402 break; 403 } 404 } 405 406 // Create intrinsic call. 407 LLVMContext &Ctx = NewFunc->getContext(); 408 Function *IFn = 409 Intrinsic::getDeclaration(NewFunc->getParent(), CIID, TParams); 410 SmallVector<Value *, 4> Args; 411 unsigned NumOperands = OldInst.getNumOperands(); 412 if (isa<CallInst>(OldInst)) 413 --NumOperands; 414 for (unsigned I = 0; I < NumOperands; ++I) { 415 Value *Op = OldInst.getOperand(I); 416 Args.push_back(Op); 417 } 418 if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) { 419 FCmpInst::Predicate Pred = CmpI->getPredicate(); 420 StringRef PredName = FCmpInst::getPredicateName(Pred); 421 Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName))); 422 } 423 424 // The last arguments of a constrained intrinsic are metadata that 425 // represent rounding mode (absents in some intrinsics) and exception 426 // behavior. The inlined function uses default settings. 427 if (hasRoundingModeOperand(CIID)) 428 Args.push_back( 429 MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest"))); 430 Args.push_back( 431 MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore"))); 432 433 NewInst = CallInst::Create(IFn, Args, OldInst.getName() + ".strict"); 434 } 435 } 436 if (!NewInst) 437 NewInst = II->clone(); 438 return NewInst; 439 } 440 441 /// The specified block is found to be reachable, clone it and 442 /// anything that it can reach. 443 void PruningFunctionCloner::CloneBlock( 444 const BasicBlock *BB, BasicBlock::const_iterator StartingInst, 445 std::vector<const BasicBlock *> &ToClone) { 446 WeakTrackingVH &BBEntry = VMap[BB]; 447 448 // Have we already cloned this block? 449 if (BBEntry) 450 return; 451 452 // Nope, clone it now. 453 BasicBlock *NewBB; 454 BBEntry = NewBB = BasicBlock::Create(BB->getContext()); 455 if (BB->hasName()) 456 NewBB->setName(BB->getName() + NameSuffix); 457 458 // It is only legal to clone a function if a block address within that 459 // function is never referenced outside of the function. Given that, we 460 // want to map block addresses from the old function to block addresses in 461 // the clone. (This is different from the generic ValueMapper 462 // implementation, which generates an invalid blockaddress when 463 // cloning a function.) 464 // 465 // Note that we don't need to fix the mapping for unreachable blocks; 466 // the default mapping there is safe. 467 if (BB->hasAddressTaken()) { 468 Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc), 469 const_cast<BasicBlock *>(BB)); 470 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB); 471 } 472 473 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false; 474 475 // Loop over all instructions, and copy them over, DCE'ing as we go. This 476 // loop doesn't include the terminator. 477 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE; 478 ++II) { 479 480 Instruction *NewInst = cloneInstruction(II); 481 482 if (HostFuncIsStrictFP) { 483 // All function calls in the inlined function must get 'strictfp' 484 // attribute to prevent undesirable optimizations. 485 if (auto *Call = dyn_cast<CallInst>(NewInst)) 486 Call->addFnAttr(Attribute::StrictFP); 487 } 488 489 // Eagerly remap operands to the newly cloned instruction, except for PHI 490 // nodes for which we defer processing until we update the CFG. 491 if (!isa<PHINode>(NewInst)) { 492 RemapInstruction(NewInst, VMap, 493 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 494 495 // If we can simplify this instruction to some other value, simply add 496 // a mapping to that value rather than inserting a new instruction into 497 // the basic block. 498 if (Value *V = 499 simplifyInstruction(NewInst, BB->getModule()->getDataLayout())) { 500 // On the off-chance that this simplifies to an instruction in the old 501 // function, map it back into the new function. 502 if (NewFunc != OldFunc) 503 if (Value *MappedV = VMap.lookup(V)) 504 V = MappedV; 505 506 if (!NewInst->mayHaveSideEffects()) { 507 VMap[&*II] = V; 508 NewInst->deleteValue(); 509 continue; 510 } 511 } 512 } 513 514 if (II->hasName()) 515 NewInst->setName(II->getName() + NameSuffix); 516 VMap[&*II] = NewInst; // Add instruction map to value. 517 NewBB->getInstList().push_back(NewInst); 518 hasCalls |= (isa<CallInst>(II) && !II->isDebugOrPseudoInst()); 519 520 if (CodeInfo) { 521 CodeInfo->OrigVMap[&*II] = NewInst; 522 if (auto *CB = dyn_cast<CallBase>(&*II)) 523 if (CB->hasOperandBundles()) 524 CodeInfo->OperandBundleCallSites.push_back(NewInst); 525 } 526 527 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 528 if (isa<ConstantInt>(AI->getArraySize())) 529 hasStaticAllocas = true; 530 else 531 hasDynamicAllocas = true; 532 } 533 } 534 535 // Finally, clone over the terminator. 536 const Instruction *OldTI = BB->getTerminator(); 537 bool TerminatorDone = false; 538 if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) { 539 if (BI->isConditional()) { 540 // If the condition was a known constant in the callee... 541 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 542 // Or is a known constant in the caller... 543 if (!Cond) { 544 Value *V = VMap.lookup(BI->getCondition()); 545 Cond = dyn_cast_or_null<ConstantInt>(V); 546 } 547 548 // Constant fold to uncond branch! 549 if (Cond) { 550 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue()); 551 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 552 ToClone.push_back(Dest); 553 TerminatorDone = true; 554 } 555 } 556 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) { 557 // If switching on a value known constant in the caller. 558 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition()); 559 if (!Cond) { // Or known constant after constant prop in the callee... 560 Value *V = VMap.lookup(SI->getCondition()); 561 Cond = dyn_cast_or_null<ConstantInt>(V); 562 } 563 if (Cond) { // Constant fold to uncond branch! 564 SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond); 565 BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor()); 566 VMap[OldTI] = BranchInst::Create(Dest, NewBB); 567 ToClone.push_back(Dest); 568 TerminatorDone = true; 569 } 570 } 571 572 if (!TerminatorDone) { 573 Instruction *NewInst = OldTI->clone(); 574 if (OldTI->hasName()) 575 NewInst->setName(OldTI->getName() + NameSuffix); 576 NewBB->getInstList().push_back(NewInst); 577 VMap[OldTI] = NewInst; // Add instruction map to value. 578 579 if (CodeInfo) { 580 CodeInfo->OrigVMap[OldTI] = NewInst; 581 if (auto *CB = dyn_cast<CallBase>(OldTI)) 582 if (CB->hasOperandBundles()) 583 CodeInfo->OperandBundleCallSites.push_back(NewInst); 584 } 585 586 // Recursively clone any reachable successor blocks. 587 append_range(ToClone, successors(BB->getTerminator())); 588 } 589 590 if (CodeInfo) { 591 CodeInfo->ContainsCalls |= hasCalls; 592 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas; 593 CodeInfo->ContainsDynamicAllocas |= 594 hasStaticAllocas && BB != &BB->getParent()->front(); 595 } 596 } 597 598 /// This works like CloneAndPruneFunctionInto, except that it does not clone the 599 /// entire function. Instead it starts at an instruction provided by the caller 600 /// and copies (and prunes) only the code reachable from that instruction. 601 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, 602 const Instruction *StartingInst, 603 ValueToValueMapTy &VMap, 604 bool ModuleLevelChanges, 605 SmallVectorImpl<ReturnInst *> &Returns, 606 const char *NameSuffix, 607 ClonedCodeInfo *CodeInfo) { 608 assert(NameSuffix && "NameSuffix cannot be null!"); 609 610 ValueMapTypeRemapper *TypeMapper = nullptr; 611 ValueMaterializer *Materializer = nullptr; 612 613 #ifndef NDEBUG 614 // If the cloning starts at the beginning of the function, verify that 615 // the function arguments are mapped. 616 if (!StartingInst) 617 for (const Argument &II : OldFunc->args()) 618 assert(VMap.count(&II) && "No mapping from source argument specified!"); 619 #endif 620 621 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges, 622 NameSuffix, CodeInfo); 623 const BasicBlock *StartingBB; 624 if (StartingInst) 625 StartingBB = StartingInst->getParent(); 626 else { 627 StartingBB = &OldFunc->getEntryBlock(); 628 StartingInst = &StartingBB->front(); 629 } 630 631 // Clone the entry block, and anything recursively reachable from it. 632 std::vector<const BasicBlock *> CloneWorklist; 633 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist); 634 while (!CloneWorklist.empty()) { 635 const BasicBlock *BB = CloneWorklist.back(); 636 CloneWorklist.pop_back(); 637 PFC.CloneBlock(BB, BB->begin(), CloneWorklist); 638 } 639 640 // Loop over all of the basic blocks in the old function. If the block was 641 // reachable, we have cloned it and the old block is now in the value map: 642 // insert it into the new function in the right order. If not, ignore it. 643 // 644 // Defer PHI resolution until rest of function is resolved. 645 SmallVector<const PHINode *, 16> PHIToResolve; 646 for (const BasicBlock &BI : *OldFunc) { 647 Value *V = VMap.lookup(&BI); 648 BasicBlock *NewBB = cast_or_null<BasicBlock>(V); 649 if (!NewBB) 650 continue; // Dead block. 651 652 // Add the new block to the new function. 653 NewFunc->getBasicBlockList().push_back(NewBB); 654 655 // Handle PHI nodes specially, as we have to remove references to dead 656 // blocks. 657 for (const PHINode &PN : BI.phis()) { 658 // PHI nodes may have been remapped to non-PHI nodes by the caller or 659 // during the cloning process. 660 if (isa<PHINode>(VMap[&PN])) 661 PHIToResolve.push_back(&PN); 662 else 663 break; 664 } 665 666 // Finally, remap the terminator instructions, as those can't be remapped 667 // until all BBs are mapped. 668 RemapInstruction(NewBB->getTerminator(), VMap, 669 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, 670 TypeMapper, Materializer); 671 } 672 673 // Defer PHI resolution until rest of function is resolved, PHI resolution 674 // requires the CFG to be up-to-date. 675 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) { 676 const PHINode *OPN = PHIToResolve[phino]; 677 unsigned NumPreds = OPN->getNumIncomingValues(); 678 const BasicBlock *OldBB = OPN->getParent(); 679 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]); 680 681 // Map operands for blocks that are live and remove operands for blocks 682 // that are dead. 683 for (; phino != PHIToResolve.size() && 684 PHIToResolve[phino]->getParent() == OldBB; 685 ++phino) { 686 OPN = PHIToResolve[phino]; 687 PHINode *PN = cast<PHINode>(VMap[OPN]); 688 for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) { 689 Value *V = VMap.lookup(PN->getIncomingBlock(pred)); 690 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) { 691 Value *InVal = 692 MapValue(PN->getIncomingValue(pred), VMap, 693 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges); 694 assert(InVal && "Unknown input value?"); 695 PN->setIncomingValue(pred, InVal); 696 PN->setIncomingBlock(pred, MappedBlock); 697 } else { 698 PN->removeIncomingValue(pred, false); 699 --pred; // Revisit the next entry. 700 --e; 701 } 702 } 703 } 704 705 // The loop above has removed PHI entries for those blocks that are dead 706 // and has updated others. However, if a block is live (i.e. copied over) 707 // but its terminator has been changed to not go to this block, then our 708 // phi nodes will have invalid entries. Update the PHI nodes in this 709 // case. 710 PHINode *PN = cast<PHINode>(NewBB->begin()); 711 NumPreds = pred_size(NewBB); 712 if (NumPreds != PN->getNumIncomingValues()) { 713 assert(NumPreds < PN->getNumIncomingValues()); 714 // Count how many times each predecessor comes to this block. 715 std::map<BasicBlock *, unsigned> PredCount; 716 for (BasicBlock *Pred : predecessors(NewBB)) 717 --PredCount[Pred]; 718 719 // Figure out how many entries to remove from each PHI. 720 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 721 ++PredCount[PN->getIncomingBlock(i)]; 722 723 // At this point, the excess predecessor entries are positive in the 724 // map. Loop over all of the PHIs and remove excess predecessor 725 // entries. 726 BasicBlock::iterator I = NewBB->begin(); 727 for (; (PN = dyn_cast<PHINode>(I)); ++I) { 728 for (const auto &PCI : PredCount) { 729 BasicBlock *Pred = PCI.first; 730 for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove) 731 PN->removeIncomingValue(Pred, false); 732 } 733 } 734 } 735 736 // If the loops above have made these phi nodes have 0 or 1 operand, 737 // replace them with poison or the input value. We must do this for 738 // correctness, because 0-operand phis are not valid. 739 PN = cast<PHINode>(NewBB->begin()); 740 if (PN->getNumIncomingValues() == 0) { 741 BasicBlock::iterator I = NewBB->begin(); 742 BasicBlock::const_iterator OldI = OldBB->begin(); 743 while ((PN = dyn_cast<PHINode>(I++))) { 744 Value *NV = PoisonValue::get(PN->getType()); 745 PN->replaceAllUsesWith(NV); 746 assert(VMap[&*OldI] == PN && "VMap mismatch"); 747 VMap[&*OldI] = NV; 748 PN->eraseFromParent(); 749 ++OldI; 750 } 751 } 752 } 753 754 // Make a second pass over the PHINodes now that all of them have been 755 // remapped into the new function, simplifying the PHINode and performing any 756 // recursive simplifications exposed. This will transparently update the 757 // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce 758 // two PHINodes, the iteration over the old PHIs remains valid, and the 759 // mapping will just map us to the new node (which may not even be a PHI 760 // node). 761 const DataLayout &DL = NewFunc->getParent()->getDataLayout(); 762 SmallSetVector<const Value *, 8> Worklist; 763 for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx) 764 if (isa<PHINode>(VMap[PHIToResolve[Idx]])) 765 Worklist.insert(PHIToResolve[Idx]); 766 767 // Note that we must test the size on each iteration, the worklist can grow. 768 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 769 const Value *OrigV = Worklist[Idx]; 770 auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV)); 771 if (!I) 772 continue; 773 774 // Skip over non-intrinsic callsites, we don't want to remove any nodes from 775 // the CGSCC. 776 CallBase *CB = dyn_cast<CallBase>(I); 777 if (CB && CB->getCalledFunction() && 778 !CB->getCalledFunction()->isIntrinsic()) 779 continue; 780 781 // See if this instruction simplifies. 782 Value *SimpleV = simplifyInstruction(I, DL); 783 if (!SimpleV) 784 continue; 785 786 // Stash away all the uses of the old instruction so we can check them for 787 // recursive simplifications after a RAUW. This is cheaper than checking all 788 // uses of To on the recursive step in most cases. 789 for (const User *U : OrigV->users()) 790 Worklist.insert(cast<Instruction>(U)); 791 792 // Replace the instruction with its simplified value. 793 I->replaceAllUsesWith(SimpleV); 794 795 // If the original instruction had no side effects, remove it. 796 if (isInstructionTriviallyDead(I)) 797 I->eraseFromParent(); 798 else 799 VMap[OrigV] = I; 800 } 801 802 // Simplify conditional branches and switches with a constant operand. We try 803 // to prune these out when cloning, but if the simplification required 804 // looking through PHI nodes, those are only available after forming the full 805 // basic block. That may leave some here, and we still want to prune the dead 806 // code as early as possible. 807 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator(); 808 for (BasicBlock &BB : make_range(Begin, NewFunc->end())) 809 ConstantFoldTerminator(&BB); 810 811 // Some blocks may have become unreachable as a result. Find and delete them. 812 { 813 SmallPtrSet<BasicBlock *, 16> ReachableBlocks; 814 SmallVector<BasicBlock *, 16> Worklist; 815 Worklist.push_back(&*Begin); 816 while (!Worklist.empty()) { 817 BasicBlock *BB = Worklist.pop_back_val(); 818 if (ReachableBlocks.insert(BB).second) 819 append_range(Worklist, successors(BB)); 820 } 821 822 SmallVector<BasicBlock *, 16> UnreachableBlocks; 823 for (BasicBlock &BB : make_range(Begin, NewFunc->end())) 824 if (!ReachableBlocks.contains(&BB)) 825 UnreachableBlocks.push_back(&BB); 826 DeleteDeadBlocks(UnreachableBlocks); 827 } 828 829 // Now that the inlined function body has been fully constructed, go through 830 // and zap unconditional fall-through branches. This happens all the time when 831 // specializing code: code specialization turns conditional branches into 832 // uncond branches, and this code folds them. 833 Function::iterator I = Begin; 834 while (I != NewFunc->end()) { 835 BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator()); 836 if (!BI || BI->isConditional()) { 837 ++I; 838 continue; 839 } 840 841 BasicBlock *Dest = BI->getSuccessor(0); 842 if (!Dest->getSinglePredecessor()) { 843 ++I; 844 continue; 845 } 846 847 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify 848 // above should have zapped all of them.. 849 assert(!isa<PHINode>(Dest->begin())); 850 851 // We know all single-entry PHI nodes in the inlined function have been 852 // removed, so we just need to splice the blocks. 853 BI->eraseFromParent(); 854 855 // Make all PHI nodes that referred to Dest now refer to I as their source. 856 Dest->replaceAllUsesWith(&*I); 857 858 // Move all the instructions in the succ to the pred. 859 I->getInstList().splice(I->end(), Dest->getInstList()); 860 861 // Remove the dest block. 862 Dest->eraseFromParent(); 863 864 // Do not increment I, iteratively merge all things this block branches to. 865 } 866 867 // Make a final pass over the basic blocks from the old function to gather 868 // any return instructions which survived folding. We have to do this here 869 // because we can iteratively remove and merge returns above. 870 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(), 871 E = NewFunc->end(); 872 I != E; ++I) 873 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) 874 Returns.push_back(RI); 875 } 876 877 /// This works exactly like CloneFunctionInto, 878 /// except that it does some simple constant prop and DCE on the fly. The 879 /// effect of this is to copy significantly less code in cases where (for 880 /// example) a function call with constant arguments is inlined, and those 881 /// constant arguments cause a significant amount of code in the callee to be 882 /// dead. Since this doesn't produce an exact copy of the input, it can't be 883 /// used for things like CloneFunction or CloneModule. 884 void llvm::CloneAndPruneFunctionInto( 885 Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, 886 bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns, 887 const char *NameSuffix, ClonedCodeInfo *CodeInfo) { 888 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap, 889 ModuleLevelChanges, Returns, NameSuffix, CodeInfo); 890 } 891 892 /// Remaps instructions in \p Blocks using the mapping in \p VMap. 893 void llvm::remapInstructionsInBlocks( 894 const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) { 895 // Rewrite the code to refer to itself. 896 for (auto *BB : Blocks) 897 for (auto &Inst : *BB) 898 RemapInstruction(&Inst, VMap, 899 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 900 } 901 902 /// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p 903 /// Blocks. 904 /// 905 /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block 906 /// \p LoopDomBB. Insert the new blocks before block specified in \p Before. 907 Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, 908 Loop *OrigLoop, ValueToValueMapTy &VMap, 909 const Twine &NameSuffix, LoopInfo *LI, 910 DominatorTree *DT, 911 SmallVectorImpl<BasicBlock *> &Blocks) { 912 Function *F = OrigLoop->getHeader()->getParent(); 913 Loop *ParentLoop = OrigLoop->getParentLoop(); 914 DenseMap<Loop *, Loop *> LMap; 915 916 Loop *NewLoop = LI->AllocateLoop(); 917 LMap[OrigLoop] = NewLoop; 918 if (ParentLoop) 919 ParentLoop->addChildLoop(NewLoop); 920 else 921 LI->addTopLevelLoop(NewLoop); 922 923 BasicBlock *OrigPH = OrigLoop->getLoopPreheader(); 924 assert(OrigPH && "No preheader"); 925 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F); 926 // To rename the loop PHIs. 927 VMap[OrigPH] = NewPH; 928 Blocks.push_back(NewPH); 929 930 // Update LoopInfo. 931 if (ParentLoop) 932 ParentLoop->addBasicBlockToLoop(NewPH, *LI); 933 934 // Update DominatorTree. 935 DT->addNewBlock(NewPH, LoopDomBB); 936 937 for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) { 938 Loop *&NewLoop = LMap[CurLoop]; 939 if (!NewLoop) { 940 NewLoop = LI->AllocateLoop(); 941 942 // Establish the parent/child relationship. 943 Loop *OrigParent = CurLoop->getParentLoop(); 944 assert(OrigParent && "Could not find the original parent loop"); 945 Loop *NewParentLoop = LMap[OrigParent]; 946 assert(NewParentLoop && "Could not find the new parent loop"); 947 948 NewParentLoop->addChildLoop(NewLoop); 949 } 950 } 951 952 for (BasicBlock *BB : OrigLoop->getBlocks()) { 953 Loop *CurLoop = LI->getLoopFor(BB); 954 Loop *&NewLoop = LMap[CurLoop]; 955 assert(NewLoop && "Expecting new loop to be allocated"); 956 957 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F); 958 VMap[BB] = NewBB; 959 960 // Update LoopInfo. 961 NewLoop->addBasicBlockToLoop(NewBB, *LI); 962 963 // Add DominatorTree node. After seeing all blocks, update to correct 964 // IDom. 965 DT->addNewBlock(NewBB, NewPH); 966 967 Blocks.push_back(NewBB); 968 } 969 970 for (BasicBlock *BB : OrigLoop->getBlocks()) { 971 // Update loop headers. 972 Loop *CurLoop = LI->getLoopFor(BB); 973 if (BB == CurLoop->getHeader()) 974 LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB])); 975 976 // Update DominatorTree. 977 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock(); 978 DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]), 979 cast<BasicBlock>(VMap[IDomBB])); 980 } 981 982 // Move them physically from the end of the block list. 983 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(), 984 NewPH); 985 F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(), 986 NewLoop->getHeader()->getIterator(), F->end()); 987 988 return NewLoop; 989 } 990 991 /// Duplicate non-Phi instructions from the beginning of block up to 992 /// StopAt instruction into a split block between BB and its predecessor. 993 BasicBlock *llvm::DuplicateInstructionsInSplitBetween( 994 BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, 995 ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) { 996 997 assert(count(successors(PredBB), BB) == 1 && 998 "There must be a single edge between PredBB and BB!"); 999 // We are going to have to map operands from the original BB block to the new 1000 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to 1001 // account for entry from PredBB. 1002 BasicBlock::iterator BI = BB->begin(); 1003 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1004 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1005 1006 BasicBlock *NewBB = SplitEdge(PredBB, BB); 1007 NewBB->setName(PredBB->getName() + ".split"); 1008 Instruction *NewTerm = NewBB->getTerminator(); 1009 1010 // FIXME: SplitEdge does not yet take a DTU, so we include the split edge 1011 // in the update set here. 1012 DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB}, 1013 {DominatorTree::Insert, PredBB, NewBB}, 1014 {DominatorTree::Insert, NewBB, BB}}); 1015 1016 // Clone the non-phi instructions of BB into NewBB, keeping track of the 1017 // mapping and using it to remap operands in the cloned instructions. 1018 // Stop once we see the terminator too. This covers the case where BB's 1019 // terminator gets replaced and StopAt == BB's terminator. 1020 for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) { 1021 Instruction *New = BI->clone(); 1022 New->setName(BI->getName()); 1023 New->insertBefore(NewTerm); 1024 ValueMapping[&*BI] = New; 1025 1026 // Remap operands to patch up intra-block references. 1027 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1028 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1029 auto I = ValueMapping.find(Inst); 1030 if (I != ValueMapping.end()) 1031 New->setOperand(i, I->second); 1032 } 1033 } 1034 1035 return NewBB; 1036 } 1037 1038 void llvm::cloneNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes, 1039 DenseMap<MDNode *, MDNode *> &ClonedScopes, 1040 StringRef Ext, LLVMContext &Context) { 1041 MDBuilder MDB(Context); 1042 1043 for (auto *ScopeList : NoAliasDeclScopes) { 1044 for (auto &MDOperand : ScopeList->operands()) { 1045 if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) { 1046 AliasScopeNode SNANode(MD); 1047 1048 std::string Name; 1049 auto ScopeName = SNANode.getName(); 1050 if (!ScopeName.empty()) 1051 Name = (Twine(ScopeName) + ":" + Ext).str(); 1052 else 1053 Name = std::string(Ext); 1054 1055 MDNode *NewScope = MDB.createAnonymousAliasScope( 1056 const_cast<MDNode *>(SNANode.getDomain()), Name); 1057 ClonedScopes.insert(std::make_pair(MD, NewScope)); 1058 } 1059 } 1060 } 1061 } 1062 1063 void llvm::adaptNoAliasScopes(Instruction *I, 1064 const DenseMap<MDNode *, MDNode *> &ClonedScopes, 1065 LLVMContext &Context) { 1066 auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * { 1067 bool NeedsReplacement = false; 1068 SmallVector<Metadata *, 8> NewScopeList; 1069 for (auto &MDOp : ScopeList->operands()) { 1070 if (MDNode *MD = dyn_cast<MDNode>(MDOp)) { 1071 if (auto *NewMD = ClonedScopes.lookup(MD)) { 1072 NewScopeList.push_back(NewMD); 1073 NeedsReplacement = true; 1074 continue; 1075 } 1076 NewScopeList.push_back(MD); 1077 } 1078 } 1079 if (NeedsReplacement) 1080 return MDNode::get(Context, NewScopeList); 1081 return nullptr; 1082 }; 1083 1084 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I)) 1085 if (auto *NewScopeList = CloneScopeList(Decl->getScopeList())) 1086 Decl->setScopeList(NewScopeList); 1087 1088 auto replaceWhenNeeded = [&](unsigned MD_ID) { 1089 if (const MDNode *CSNoAlias = I->getMetadata(MD_ID)) 1090 if (auto *NewScopeList = CloneScopeList(CSNoAlias)) 1091 I->setMetadata(MD_ID, NewScopeList); 1092 }; 1093 replaceWhenNeeded(LLVMContext::MD_noalias); 1094 replaceWhenNeeded(LLVMContext::MD_alias_scope); 1095 } 1096 1097 void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes, 1098 ArrayRef<BasicBlock *> NewBlocks, 1099 LLVMContext &Context, StringRef Ext) { 1100 if (NoAliasDeclScopes.empty()) 1101 return; 1102 1103 DenseMap<MDNode *, MDNode *> ClonedScopes; 1104 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning " 1105 << NoAliasDeclScopes.size() << " node(s)\n"); 1106 1107 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context); 1108 // Identify instructions using metadata that needs adaptation 1109 for (BasicBlock *NewBlock : NewBlocks) 1110 for (Instruction &I : *NewBlock) 1111 adaptNoAliasScopes(&I, ClonedScopes, Context); 1112 } 1113 1114 void llvm::cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes, 1115 Instruction *IStart, Instruction *IEnd, 1116 LLVMContext &Context, StringRef Ext) { 1117 if (NoAliasDeclScopes.empty()) 1118 return; 1119 1120 DenseMap<MDNode *, MDNode *> ClonedScopes; 1121 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning " 1122 << NoAliasDeclScopes.size() << " node(s)\n"); 1123 1124 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context); 1125 // Identify instructions using metadata that needs adaptation 1126 assert(IStart->getParent() == IEnd->getParent() && "different basic block ?"); 1127 auto ItStart = IStart->getIterator(); 1128 auto ItEnd = IEnd->getIterator(); 1129 ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range 1130 for (auto &I : llvm::make_range(ItStart, ItEnd)) 1131 adaptNoAliasScopes(&I, ClonedScopes, Context); 1132 } 1133 1134 void llvm::identifyNoAliasScopesToClone( 1135 ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) { 1136 for (BasicBlock *BB : BBs) 1137 for (Instruction &I : *BB) 1138 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 1139 NoAliasDeclScopes.push_back(Decl->getScopeList()); 1140 } 1141 1142 void llvm::identifyNoAliasScopesToClone( 1143 BasicBlock::iterator Start, BasicBlock::iterator End, 1144 SmallVectorImpl<MDNode *> &NoAliasDeclScopes) { 1145 for (Instruction &I : make_range(Start, End)) 1146 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 1147 NoAliasDeclScopes.push_back(Decl->getScopeList()); 1148 } 1149