CloneFunction.cpp 41 KB

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