LLVM  16.0.0git
CloneFunction.cpp
Go to the documentation of this file.
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"
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"
35 #include <map>
36 #include <optional>
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "clone-function"
40 
41 /// See comments in Cloning.h.
43  const Twine &NameSuffix, Function *F,
44  ClonedCodeInfo *CodeInfo,
45  DebugInfoFinder *DIFinder) {
46  BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
47  if (BB->hasName())
48  NewBB->setName(BB->getName() + NameSuffix);
49 
50  bool hasCalls = false, hasDynamicAllocas = false, hasMemProfMetadata = false;
51  Module *TheModule = F ? F->getParent() : nullptr;
52 
53  // Loop over all instructions, and copy them over.
54  for (const Instruction &I : *BB) {
55  if (DIFinder && TheModule)
56  DIFinder->processInstruction(*TheModule, I);
57 
58  Instruction *NewInst = I.clone();
59  if (I.hasName())
60  NewInst->setName(I.getName() + NameSuffix);
61  NewBB->getInstList().push_back(NewInst);
62  VMap[&I] = NewInst; // Add instruction map to value.
63 
64  if (isa<CallInst>(I) && !I.isDebugOrPseudoInst()) {
65  hasCalls = true;
66  hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_memprof);
67  }
68  if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
69  if (!AI->isStaticAlloca()) {
70  hasDynamicAllocas = true;
71  }
72  }
73  }
74 
75  if (CodeInfo) {
76  CodeInfo->ContainsCalls |= hasCalls;
77  CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
78  CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
79  }
80  return NewBB;
81 }
82 
83 // Clone OldFunc into NewFunc, transforming the old arguments into references to
84 // VMap values.
85 //
86 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
87  ValueToValueMapTy &VMap,
90  const char *NameSuffix, ClonedCodeInfo *CodeInfo,
91  ValueMapTypeRemapper *TypeMapper,
92  ValueMaterializer *Materializer) {
93  assert(NameSuffix && "NameSuffix cannot be null!");
94 
95 #ifndef NDEBUG
96  for (const Argument &I : OldFunc->args())
97  assert(VMap.count(&I) && "No mapping from source argument specified!");
98 #endif
99 
100  bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
101 
102  // Copy all attributes other than those stored in the AttributeList. We need
103  // to remap the parameter indices of the AttributeList.
104  AttributeList NewAttrs = NewFunc->getAttributes();
105  NewFunc->copyAttributesFrom(OldFunc);
106  NewFunc->setAttributes(NewAttrs);
107 
108  // Fix up the personality function that got copied over.
109  if (OldFunc->hasPersonalityFn())
110  NewFunc->setPersonalityFn(
111  MapValue(OldFunc->getPersonalityFn(), VMap,
112  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
113  TypeMapper, Materializer));
114 
115  SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
116  AttributeList OldAttrs = OldFunc->getAttributes();
117 
118  // Clone any argument attributes that are present in the VMap.
119  for (const Argument &OldArg : OldFunc->args()) {
120  if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
121  NewArgAttrs[NewArg->getArgNo()] =
122  OldAttrs.getParamAttrs(OldArg.getArgNo());
123  }
124  }
125 
126  NewFunc->setAttributes(
127  AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(),
128  OldAttrs.getRetAttrs(), NewArgAttrs));
129 
130  // Everything else beyond this point deals with function instructions,
131  // so if we are dealing with a function declaration, we're done.
132  if (OldFunc->isDeclaration())
133  return;
134 
135  // When we remap instructions within the same module, we want to avoid
136  // duplicating inlined DISubprograms, so record all subprograms we find as we
137  // duplicate instructions and then freeze them in the MD map. We also record
138  // information about dbg.value and dbg.declare to avoid duplicating the
139  // types.
140  std::optional<DebugInfoFinder> DIFinder;
141 
142  // Track the subprogram attachment that needs to be cloned to fine-tune the
143  // mapping within the same module.
144  DISubprogram *SPClonedWithinModule = nullptr;
146  assert((NewFunc->getParent() == nullptr ||
147  NewFunc->getParent() == OldFunc->getParent()) &&
148  "Expected NewFunc to have the same parent, or no parent");
149 
150  // Need to find subprograms, types, and compile units.
151  DIFinder.emplace();
152 
153  SPClonedWithinModule = OldFunc->getSubprogram();
154  if (SPClonedWithinModule)
155  DIFinder->processSubprogram(SPClonedWithinModule);
156  } else {
157  assert((NewFunc->getParent() == nullptr ||
158  NewFunc->getParent() != OldFunc->getParent()) &&
159  "Expected NewFunc to have different parents, or no parent");
160 
162  assert(NewFunc->getParent() &&
163  "Need parent of new function to maintain debug info invariants");
164 
165  // Need to find all the compile units.
166  DIFinder.emplace();
167  }
168  }
169 
170  // Loop over all of the basic blocks in the function, cloning them as
171  // appropriate. Note that we save BE this way in order to handle cloning of
172  // recursive functions into themselves.
173  for (const BasicBlock &BB : *OldFunc) {
174 
175  // Create a new basic block and copy instructions into it!
176  BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,
177  DIFinder ? &*DIFinder : nullptr);
178 
179  // Add basic block mapping.
180  VMap[&BB] = CBB;
181 
182  // It is only legal to clone a function if a block address within that
183  // function is never referenced outside of the function. Given that, we
184  // want to map block addresses from the old function to block addresses in
185  // the clone. (This is different from the generic ValueMapper
186  // implementation, which generates an invalid blockaddress when
187  // cloning a function.)
188  if (BB.hasAddressTaken()) {
189  Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
190  const_cast<BasicBlock *>(&BB));
191  VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
192  }
193 
194  // Note return instructions for the caller.
195  if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
196  Returns.push_back(RI);
197  }
198 
200  DIFinder->subprogram_count() > 0) {
201  // Turn on module-level changes, since we need to clone (some of) the
202  // debug info metadata.
203  //
204  // FIXME: Metadata effectively owned by a function should be made
205  // local, and only that local metadata should be cloned.
206  ModuleLevelChanges = true;
207 
208  auto mapToSelfIfNew = [&VMap](MDNode *N) {
209  // Avoid clobbering an existing mapping.
210  (void)VMap.MD().try_emplace(N, N);
211  };
212 
213  // Avoid cloning types, compile units, and (other) subprograms.
215  for (DISubprogram *ISP : DIFinder->subprograms()) {
216  if (ISP != SPClonedWithinModule) {
217  mapToSelfIfNew(ISP);
218  MappedToSelfSPs.insert(ISP);
219  }
220  }
221 
222  // If a subprogram isn't going to be cloned skip its lexical blocks as well.
223  for (DIScope *S : DIFinder->scopes()) {
224  auto *LScope = dyn_cast<DILocalScope>(S);
225  if (LScope && MappedToSelfSPs.count(LScope->getSubprogram()))
226  mapToSelfIfNew(S);
227  }
228 
229  for (DICompileUnit *CU : DIFinder->compile_units())
230  mapToSelfIfNew(CU);
231 
232  for (DIType *Type : DIFinder->types())
233  mapToSelfIfNew(Type);
234  } else {
235  assert(!SPClonedWithinModule &&
236  "Subprogram should be in DIFinder->subprogram_count()...");
237  }
238 
239  const auto RemapFlag = ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
240  // Duplicate the metadata that is attached to the cloned function.
241  // Subprograms/CUs/types that were already mapped to themselves won't be
242  // duplicated.
244  OldFunc->getAllMetadata(MDs);
245  for (auto MD : MDs) {
246  NewFunc->addMetadata(MD.first, *MapMetadata(MD.second, VMap, RemapFlag,
247  TypeMapper, Materializer));
248  }
249 
250  // Loop over all of the instructions in the new function, fixing up operand
251  // references as we go. This uses VMap to do all the hard work.
252  for (Function::iterator
253  BB = cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
254  BE = NewFunc->end();
255  BB != BE; ++BB)
256  // Loop over all instructions, fixing each one as we find it...
257  for (Instruction &II : *BB)
258  RemapInstruction(&II, VMap, RemapFlag, TypeMapper, Materializer);
259 
260  // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the
261  // same module, the compile unit will already be listed (or not). When
262  // cloning a module, CloneModule() will handle creating the named metadata.
264  return;
265 
266  // Update !llvm.dbg.cu with compile units added to the new module if this
267  // function is being cloned in isolation.
268  //
269  // FIXME: This is making global / module-level changes, which doesn't seem
270  // like the right encapsulation Consider dropping the requirement to update
271  // !llvm.dbg.cu (either obsoleting the node, or restricting it to
272  // non-discardable compile units) instead of discovering compile units by
273  // visiting the metadata attached to global values, which would allow this
274  // code to be deleted. Alternatively, perhaps give responsibility for this
275  // update to CloneFunctionInto's callers.
276  auto *NewModule = NewFunc->getParent();
277  auto *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
278  // Avoid multiple insertions of the same DICompileUnit to NMD.
280  for (auto *Operand : NMD->operands())
281  Visited.insert(Operand);
282  for (auto *Unit : DIFinder->compile_units()) {
283  MDNode *MappedUnit =
284  MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);
285  if (Visited.insert(MappedUnit).second)
286  NMD->addOperand(MappedUnit);
287  }
288 }
289 
290 /// Return a copy of the specified function and add it to that function's
291 /// module. Also, any references specified in the VMap are changed to refer to
292 /// their mapped value instead of the original one. If any of the arguments to
293 /// the function are in the VMap, the arguments are deleted from the resultant
294 /// function. The VMap is updated to include mappings from all of the
295 /// instructions and basicblocks in the function from their old to new values.
296 ///
298  ClonedCodeInfo *CodeInfo) {
299  std::vector<Type *> ArgTypes;
300 
301  // The user might be deleting arguments to the function by specifying them in
302  // the VMap. If so, we need to not add the arguments to the arg ty vector
303  //
304  for (const Argument &I : F->args())
305  if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
306  ArgTypes.push_back(I.getType());
307 
308  // Create a new function type...
309  FunctionType *FTy =
310  FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,
311  F->getFunctionType()->isVarArg());
312 
313  // Create the new function...
314  Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
315  F->getName(), F->getParent());
316 
317  // Loop over the arguments, copying the names of the mapped arguments over...
318  Function::arg_iterator DestI = NewF->arg_begin();
319  for (const Argument &I : F->args())
320  if (VMap.count(&I) == 0) { // Is this argument preserved?
321  DestI->setName(I.getName()); // Copy the name over...
322  VMap[&I] = &*DestI++; // Add mapping to VMap
323  }
324 
325  SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
327  Returns, "", CodeInfo);
328 
329  return NewF;
330 }
331 
332 namespace {
333 /// This is a private class used to implement CloneAndPruneFunctionInto.
334 struct PruningFunctionCloner {
335  Function *NewFunc;
336  const Function *OldFunc;
337  ValueToValueMapTy &VMap;
338  bool ModuleLevelChanges;
339  const char *NameSuffix;
340  ClonedCodeInfo *CodeInfo;
341  bool HostFuncIsStrictFP;
342 
343  Instruction *cloneInstruction(BasicBlock::const_iterator II);
344 
345 public:
346  PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
347  ValueToValueMapTy &valueMap, bool moduleLevelChanges,
348  const char *nameSuffix, ClonedCodeInfo *codeInfo)
349  : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
350  ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
351  CodeInfo(codeInfo) {
352  HostFuncIsStrictFP =
353  newFunc->getAttributes().hasFnAttr(Attribute::StrictFP);
354  }
355 
356  /// The specified block is found to be reachable, clone it and
357  /// anything that it can reach.
358  void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
359  std::vector<const BasicBlock *> &ToClone);
360 };
361 } // namespace
362 
364  switch (CIID) {
365 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
366  case Intrinsic::INTRINSIC: \
367  return ROUND_MODE == 1;
368 #define FUNCTION INSTRUCTION
369 #include "llvm/IR/ConstrainedOps.def"
370  default:
371  llvm_unreachable("Unexpected constrained intrinsic id");
372  }
373 }
374 
375 Instruction *
376 PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) {
377  const Instruction &OldInst = *II;
378  Instruction *NewInst = nullptr;
379  if (HostFuncIsStrictFP) {
381  if (CIID != Intrinsic::not_intrinsic) {
382  // Instead of cloning the instruction, a call to constrained intrinsic
383  // should be created.
384  // Assume the first arguments of constrained intrinsics are the same as
385  // the operands of original instruction.
386 
387  // Determine overloaded types of the intrinsic.
388  SmallVector<Type *, 2> TParams;
390  getIntrinsicInfoTableEntries(CIID, Descriptor);
391  for (unsigned I = 0, E = Descriptor.size(); I != E; ++I) {
392  Intrinsic::IITDescriptor Operand = Descriptor[I];
393  switch (Operand.Kind) {
395  if (Operand.getArgumentKind() !=
397  if (I == 0)
398  TParams.push_back(OldInst.getType());
399  else
400  TParams.push_back(OldInst.getOperand(I - 1)->getType());
401  }
402  break;
404  ++I;
405  break;
406  default:
407  break;
408  }
409  }
410 
411  // Create intrinsic call.
412  LLVMContext &Ctx = NewFunc->getContext();
413  Function *IFn =
414  Intrinsic::getDeclaration(NewFunc->getParent(), CIID, TParams);
416  unsigned NumOperands = OldInst.getNumOperands();
417  if (isa<CallInst>(OldInst))
418  --NumOperands;
419  for (unsigned I = 0; I < NumOperands; ++I) {
420  Value *Op = OldInst.getOperand(I);
421  Args.push_back(Op);
422  }
423  if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {
424  FCmpInst::Predicate Pred = CmpI->getPredicate();
425  StringRef PredName = FCmpInst::getPredicateName(Pred);
426  Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName)));
427  }
428 
429  // The last arguments of a constrained intrinsic are metadata that
430  // represent rounding mode (absents in some intrinsics) and exception
431  // behavior. The inlined function uses default settings.
432  if (hasRoundingModeOperand(CIID))
433  Args.push_back(
434  MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest")));
435  Args.push_back(
436  MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore")));
437 
438  NewInst = CallInst::Create(IFn, Args, OldInst.getName() + ".strict");
439  }
440  }
441  if (!NewInst)
442  NewInst = II->clone();
443  return NewInst;
444 }
445 
446 /// The specified block is found to be reachable, clone it and
447 /// anything that it can reach.
448 void PruningFunctionCloner::CloneBlock(
449  const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
450  std::vector<const BasicBlock *> &ToClone) {
451  WeakTrackingVH &BBEntry = VMap[BB];
452 
453  // Have we already cloned this block?
454  if (BBEntry)
455  return;
456 
457  // Nope, clone it now.
458  BasicBlock *NewBB;
459  BBEntry = NewBB = BasicBlock::Create(BB->getContext());
460  if (BB->hasName())
461  NewBB->setName(BB->getName() + NameSuffix);
462 
463  // It is only legal to clone a function if a block address within that
464  // function is never referenced outside of the function. Given that, we
465  // want to map block addresses from the old function to block addresses in
466  // the clone. (This is different from the generic ValueMapper
467  // implementation, which generates an invalid blockaddress when
468  // cloning a function.)
469  //
470  // Note that we don't need to fix the mapping for unreachable blocks;
471  // the default mapping there is safe.
472  if (BB->hasAddressTaken()) {
473  Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
474  const_cast<BasicBlock *>(BB));
475  VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
476  }
477 
478  bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
479  bool hasMemProfMetadata = false;
480 
481  // Loop over all instructions, and copy them over, DCE'ing as we go. This
482  // loop doesn't include the terminator.
483  for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;
484  ++II) {
485 
486  Instruction *NewInst = cloneInstruction(II);
487 
488  if (HostFuncIsStrictFP) {
489  // All function calls in the inlined function must get 'strictfp'
490  // attribute to prevent undesirable optimizations.
491  if (auto *Call = dyn_cast<CallInst>(NewInst))
492  Call->addFnAttr(Attribute::StrictFP);
493  }
494 
495  // Eagerly remap operands to the newly cloned instruction, except for PHI
496  // nodes for which we defer processing until we update the CFG. Also defer
497  // debug intrinsic processing because they may contain use-before-defs.
498  if (!isa<PHINode>(NewInst) && !isa<DbgVariableIntrinsic>(NewInst)) {
499  RemapInstruction(NewInst, VMap,
500  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
501 
502  // If we can simplify this instruction to some other value, simply add
503  // a mapping to that value rather than inserting a new instruction into
504  // the basic block.
505  if (Value *V =
506  simplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
507  // On the off-chance that this simplifies to an instruction in the old
508  // function, map it back into the new function.
509  if (NewFunc != OldFunc)
510  if (Value *MappedV = VMap.lookup(V))
511  V = MappedV;
512 
513  if (!NewInst->mayHaveSideEffects()) {
514  VMap[&*II] = V;
515  NewInst->deleteValue();
516  continue;
517  }
518  }
519  }
520 
521  if (II->hasName())
522  NewInst->setName(II->getName() + NameSuffix);
523  VMap[&*II] = NewInst; // Add instruction map to value.
524  NewBB->getInstList().push_back(NewInst);
525  if (isa<CallInst>(II) && !II->isDebugOrPseudoInst()) {
526  hasCalls = true;
527  hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_memprof);
528  }
529 
530  if (CodeInfo) {
531  CodeInfo->OrigVMap[&*II] = NewInst;
532  if (auto *CB = dyn_cast<CallBase>(&*II))
533  if (CB->hasOperandBundles())
534  CodeInfo->OperandBundleCallSites.push_back(NewInst);
535  }
536 
537  if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
538  if (isa<ConstantInt>(AI->getArraySize()))
539  hasStaticAllocas = true;
540  else
541  hasDynamicAllocas = true;
542  }
543  }
544 
545  // Finally, clone over the terminator.
546  const Instruction *OldTI = BB->getTerminator();
547  bool TerminatorDone = false;
548  if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
549  if (BI->isConditional()) {
550  // If the condition was a known constant in the callee...
551  ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
552  // Or is a known constant in the caller...
553  if (!Cond) {
554  Value *V = VMap.lookup(BI->getCondition());
555  Cond = dyn_cast_or_null<ConstantInt>(V);
556  }
557 
558  // Constant fold to uncond branch!
559  if (Cond) {
560  BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
561  VMap[OldTI] = BranchInst::Create(Dest, NewBB);
562  ToClone.push_back(Dest);
563  TerminatorDone = true;
564  }
565  }
566  } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
567  // If switching on a value known constant in the caller.
568  ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
569  if (!Cond) { // Or known constant after constant prop in the callee...
570  Value *V = VMap.lookup(SI->getCondition());
571  Cond = dyn_cast_or_null<ConstantInt>(V);
572  }
573  if (Cond) { // Constant fold to uncond branch!
574  SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
575  BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
576  VMap[OldTI] = BranchInst::Create(Dest, NewBB);
577  ToClone.push_back(Dest);
578  TerminatorDone = true;
579  }
580  }
581 
582  if (!TerminatorDone) {
583  Instruction *NewInst = OldTI->clone();
584  if (OldTI->hasName())
585  NewInst->setName(OldTI->getName() + NameSuffix);
586  NewBB->getInstList().push_back(NewInst);
587  VMap[OldTI] = NewInst; // Add instruction map to value.
588 
589  if (CodeInfo) {
590  CodeInfo->OrigVMap[OldTI] = NewInst;
591  if (auto *CB = dyn_cast<CallBase>(OldTI))
592  if (CB->hasOperandBundles())
593  CodeInfo->OperandBundleCallSites.push_back(NewInst);
594  }
595 
596  // Recursively clone any reachable successor blocks.
597  append_range(ToClone, successors(BB->getTerminator()));
598  }
599 
600  if (CodeInfo) {
601  CodeInfo->ContainsCalls |= hasCalls;
602  CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
603  CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
604  CodeInfo->ContainsDynamicAllocas |=
605  hasStaticAllocas && BB != &BB->getParent()->front();
606  }
607 }
608 
609 /// This works like CloneAndPruneFunctionInto, except that it does not clone the
610 /// entire function. Instead it starts at an instruction provided by the caller
611 /// and copies (and prunes) only the code reachable from that instruction.
612 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
613  const Instruction *StartingInst,
614  ValueToValueMapTy &VMap,
615  bool ModuleLevelChanges,
617  const char *NameSuffix,
618  ClonedCodeInfo *CodeInfo) {
619  assert(NameSuffix && "NameSuffix cannot be null!");
620 
621  ValueMapTypeRemapper *TypeMapper = nullptr;
622  ValueMaterializer *Materializer = nullptr;
623 
624 #ifndef NDEBUG
625  // If the cloning starts at the beginning of the function, verify that
626  // the function arguments are mapped.
627  if (!StartingInst)
628  for (const Argument &II : OldFunc->args())
629  assert(VMap.count(&II) && "No mapping from source argument specified!");
630 #endif
631 
632  PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
633  NameSuffix, CodeInfo);
634  const BasicBlock *StartingBB;
635  if (StartingInst)
636  StartingBB = StartingInst->getParent();
637  else {
638  StartingBB = &OldFunc->getEntryBlock();
639  StartingInst = &StartingBB->front();
640  }
641 
642  // Collect debug intrinsics for remapping later.
644  for (const auto &BB : *OldFunc) {
645  for (const auto &I : BB) {
646  if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
647  DbgIntrinsics.push_back(DVI);
648  }
649  }
650 
651  // Clone the entry block, and anything recursively reachable from it.
652  std::vector<const BasicBlock *> CloneWorklist;
653  PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
654  while (!CloneWorklist.empty()) {
655  const BasicBlock *BB = CloneWorklist.back();
656  CloneWorklist.pop_back();
657  PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
658  }
659 
660  // Loop over all of the basic blocks in the old function. If the block was
661  // reachable, we have cloned it and the old block is now in the value map:
662  // insert it into the new function in the right order. If not, ignore it.
663  //
664  // Defer PHI resolution until rest of function is resolved.
666  for (const BasicBlock &BI : *OldFunc) {
667  Value *V = VMap.lookup(&BI);
668  BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
669  if (!NewBB)
670  continue; // Dead block.
671 
672  // Add the new block to the new function.
673  NewFunc->getBasicBlockList().push_back(NewBB);
674 
675  // Handle PHI nodes specially, as we have to remove references to dead
676  // blocks.
677  for (const PHINode &PN : BI.phis()) {
678  // PHI nodes may have been remapped to non-PHI nodes by the caller or
679  // during the cloning process.
680  if (isa<PHINode>(VMap[&PN]))
681  PHIToResolve.push_back(&PN);
682  else
683  break;
684  }
685 
686  // Finally, remap the terminator instructions, as those can't be remapped
687  // until all BBs are mapped.
688  RemapInstruction(NewBB->getTerminator(), VMap,
689  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
690  TypeMapper, Materializer);
691  }
692 
693  // Defer PHI resolution until rest of function is resolved, PHI resolution
694  // requires the CFG to be up-to-date.
695  for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {
696  const PHINode *OPN = PHIToResolve[phino];
697  unsigned NumPreds = OPN->getNumIncomingValues();
698  const BasicBlock *OldBB = OPN->getParent();
699  BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
700 
701  // Map operands for blocks that are live and remove operands for blocks
702  // that are dead.
703  for (; phino != PHIToResolve.size() &&
704  PHIToResolve[phino]->getParent() == OldBB;
705  ++phino) {
706  OPN = PHIToResolve[phino];
707  PHINode *PN = cast<PHINode>(VMap[OPN]);
708  for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
709  Value *V = VMap.lookup(PN->getIncomingBlock(pred));
710  if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
711  Value *InVal =
712  MapValue(PN->getIncomingValue(pred), VMap,
713  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
714  assert(InVal && "Unknown input value?");
715  PN->setIncomingValue(pred, InVal);
716  PN->setIncomingBlock(pred, MappedBlock);
717  } else {
718  PN->removeIncomingValue(pred, false);
719  --pred; // Revisit the next entry.
720  --e;
721  }
722  }
723  }
724 
725  // The loop above has removed PHI entries for those blocks that are dead
726  // and has updated others. However, if a block is live (i.e. copied over)
727  // but its terminator has been changed to not go to this block, then our
728  // phi nodes will have invalid entries. Update the PHI nodes in this
729  // case.
730  PHINode *PN = cast<PHINode>(NewBB->begin());
731  NumPreds = pred_size(NewBB);
732  if (NumPreds != PN->getNumIncomingValues()) {
733  assert(NumPreds < PN->getNumIncomingValues());
734  // Count how many times each predecessor comes to this block.
735  std::map<BasicBlock *, unsigned> PredCount;
736  for (BasicBlock *Pred : predecessors(NewBB))
737  --PredCount[Pred];
738 
739  // Figure out how many entries to remove from each PHI.
740  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
741  ++PredCount[PN->getIncomingBlock(i)];
742 
743  // At this point, the excess predecessor entries are positive in the
744  // map. Loop over all of the PHIs and remove excess predecessor
745  // entries.
746  BasicBlock::iterator I = NewBB->begin();
747  for (; (PN = dyn_cast<PHINode>(I)); ++I) {
748  for (const auto &PCI : PredCount) {
749  BasicBlock *Pred = PCI.first;
750  for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
751  PN->removeIncomingValue(Pred, false);
752  }
753  }
754  }
755 
756  // If the loops above have made these phi nodes have 0 or 1 operand,
757  // replace them with poison or the input value. We must do this for
758  // correctness, because 0-operand phis are not valid.
759  PN = cast<PHINode>(NewBB->begin());
760  if (PN->getNumIncomingValues() == 0) {
761  BasicBlock::iterator I = NewBB->begin();
762  BasicBlock::const_iterator OldI = OldBB->begin();
763  while ((PN = dyn_cast<PHINode>(I++))) {
764  Value *NV = PoisonValue::get(PN->getType());
765  PN->replaceAllUsesWith(NV);
766  assert(VMap[&*OldI] == PN && "VMap mismatch");
767  VMap[&*OldI] = NV;
768  PN->eraseFromParent();
769  ++OldI;
770  }
771  }
772  }
773 
774  // Make a second pass over the PHINodes now that all of them have been
775  // remapped into the new function, simplifying the PHINode and performing any
776  // recursive simplifications exposed. This will transparently update the
777  // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce
778  // two PHINodes, the iteration over the old PHIs remains valid, and the
779  // mapping will just map us to the new node (which may not even be a PHI
780  // node).
781  const DataLayout &DL = NewFunc->getParent()->getDataLayout();
783  for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
784  if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
785  Worklist.insert(PHIToResolve[Idx]);
786 
787  // Note that we must test the size on each iteration, the worklist can grow.
788  for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
789  const Value *OrigV = Worklist[Idx];
790  auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
791  if (!I)
792  continue;
793 
794  // Skip over non-intrinsic callsites, we don't want to remove any nodes from
795  // the CGSCC.
796  CallBase *CB = dyn_cast<CallBase>(I);
797  if (CB && CB->getCalledFunction() &&
798  !CB->getCalledFunction()->isIntrinsic())
799  continue;
800 
801  // See if this instruction simplifies.
802  Value *SimpleV = simplifyInstruction(I, DL);
803  if (!SimpleV)
804  continue;
805 
806  // Stash away all the uses of the old instruction so we can check them for
807  // recursive simplifications after a RAUW. This is cheaper than checking all
808  // uses of To on the recursive step in most cases.
809  for (const User *U : OrigV->users())
810  Worklist.insert(cast<Instruction>(U));
811 
812  // Replace the instruction with its simplified value.
813  I->replaceAllUsesWith(SimpleV);
814 
815  // If the original instruction had no side effects, remove it.
817  I->eraseFromParent();
818  else
819  VMap[OrigV] = I;
820  }
821 
822  // Remap debug intrinsic operands now that all values have been mapped.
823  // Doing this now (late) preserves use-before-defs in debug intrinsics. If
824  // we didn't do this, ValueAsMetadata(use-before-def) operands would be
825  // replaced by empty metadata. This would signal later cleanup passes to
826  // remove the debug intrinsics, potentially causing incorrect locations.
827  for (const auto *DVI : DbgIntrinsics) {
828  if (DbgVariableIntrinsic *NewDVI =
829  cast_or_null<DbgVariableIntrinsic>(VMap.lookup(DVI)))
830  RemapInstruction(NewDVI, VMap,
831  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
832  TypeMapper, Materializer);
833  }
834 
835  // Simplify conditional branches and switches with a constant operand. We try
836  // to prune these out when cloning, but if the simplification required
837  // looking through PHI nodes, those are only available after forming the full
838  // basic block. That may leave some here, and we still want to prune the dead
839  // code as early as possible.
840  Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
841  for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
843 
844  // Some blocks may have become unreachable as a result. Find and delete them.
845  {
846  SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
848  Worklist.push_back(&*Begin);
849  while (!Worklist.empty()) {
850  BasicBlock *BB = Worklist.pop_back_val();
851  if (ReachableBlocks.insert(BB).second)
852  append_range(Worklist, successors(BB));
853  }
854 
855  SmallVector<BasicBlock *, 16> UnreachableBlocks;
856  for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
857  if (!ReachableBlocks.contains(&BB))
858  UnreachableBlocks.push_back(&BB);
859  DeleteDeadBlocks(UnreachableBlocks);
860  }
861 
862  // Now that the inlined function body has been fully constructed, go through
863  // and zap unconditional fall-through branches. This happens all the time when
864  // specializing code: code specialization turns conditional branches into
865  // uncond branches, and this code folds them.
866  Function::iterator I = Begin;
867  while (I != NewFunc->end()) {
868  BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
869  if (!BI || BI->isConditional()) {
870  ++I;
871  continue;
872  }
873 
874  BasicBlock *Dest = BI->getSuccessor(0);
875  if (!Dest->getSinglePredecessor()) {
876  ++I;
877  continue;
878  }
879 
880  // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
881  // above should have zapped all of them..
882  assert(!isa<PHINode>(Dest->begin()));
883 
884  // We know all single-entry PHI nodes in the inlined function have been
885  // removed, so we just need to splice the blocks.
886  BI->eraseFromParent();
887 
888  // Make all PHI nodes that referred to Dest now refer to I as their source.
889  Dest->replaceAllUsesWith(&*I);
890 
891  // Move all the instructions in the succ to the pred.
892  I->splice(I->end(), Dest);
893 
894  // Remove the dest block.
895  Dest->eraseFromParent();
896 
897  // Do not increment I, iteratively merge all things this block branches to.
898  }
899 
900  // Make a final pass over the basic blocks from the old function to gather
901  // any return instructions which survived folding. We have to do this here
902  // because we can iteratively remove and merge returns above.
903  for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
904  E = NewFunc->end();
905  I != E; ++I)
906  if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
907  Returns.push_back(RI);
908 }
909 
910 /// This works exactly like CloneFunctionInto,
911 /// except that it does some simple constant prop and DCE on the fly. The
912 /// effect of this is to copy significantly less code in cases where (for
913 /// example) a function call with constant arguments is inlined, and those
914 /// constant arguments cause a significant amount of code in the callee to be
915 /// dead. Since this doesn't produce an exact copy of the input, it can't be
916 /// used for things like CloneFunction or CloneModule.
918  Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap,
919  bool ModuleLevelChanges, SmallVectorImpl<ReturnInst *> &Returns,
920  const char *NameSuffix, ClonedCodeInfo *CodeInfo) {
921  CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
922  ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
923 }
924 
925 /// Remaps instructions in \p Blocks using the mapping in \p VMap.
927  const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
928  // Rewrite the code to refer to itself.
929  for (auto *BB : Blocks)
930  for (auto &Inst : *BB)
931  RemapInstruction(&Inst, VMap,
933 }
934 
935 /// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
936 /// Blocks.
937 ///
938 /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
939 /// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
941  Loop *OrigLoop, ValueToValueMapTy &VMap,
942  const Twine &NameSuffix, LoopInfo *LI,
943  DominatorTree *DT,
945  Function *F = OrigLoop->getHeader()->getParent();
946  Loop *ParentLoop = OrigLoop->getParentLoop();
948 
949  Loop *NewLoop = LI->AllocateLoop();
950  LMap[OrigLoop] = NewLoop;
951  if (ParentLoop)
952  ParentLoop->addChildLoop(NewLoop);
953  else
954  LI->addTopLevelLoop(NewLoop);
955 
956  BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
957  assert(OrigPH && "No preheader");
958  BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
959  // To rename the loop PHIs.
960  VMap[OrigPH] = NewPH;
961  Blocks.push_back(NewPH);
962 
963  // Update LoopInfo.
964  if (ParentLoop)
965  ParentLoop->addBasicBlockToLoop(NewPH, *LI);
966 
967  // Update DominatorTree.
968  DT->addNewBlock(NewPH, LoopDomBB);
969 
970  for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
971  Loop *&NewLoop = LMap[CurLoop];
972  if (!NewLoop) {
973  NewLoop = LI->AllocateLoop();
974 
975  // Establish the parent/child relationship.
976  Loop *OrigParent = CurLoop->getParentLoop();
977  assert(OrigParent && "Could not find the original parent loop");
978  Loop *NewParentLoop = LMap[OrigParent];
979  assert(NewParentLoop && "Could not find the new parent loop");
980 
981  NewParentLoop->addChildLoop(NewLoop);
982  }
983  }
984 
985  for (BasicBlock *BB : OrigLoop->getBlocks()) {
986  Loop *CurLoop = LI->getLoopFor(BB);
987  Loop *&NewLoop = LMap[CurLoop];
988  assert(NewLoop && "Expecting new loop to be allocated");
989 
990  BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
991  VMap[BB] = NewBB;
992 
993  // Update LoopInfo.
994  NewLoop->addBasicBlockToLoop(NewBB, *LI);
995 
996  // Add DominatorTree node. After seeing all blocks, update to correct
997  // IDom.
998  DT->addNewBlock(NewBB, NewPH);
999 
1000  Blocks.push_back(NewBB);
1001  }
1002 
1003  for (BasicBlock *BB : OrigLoop->getBlocks()) {
1004  // Update loop headers.
1005  Loop *CurLoop = LI->getLoopFor(BB);
1006  if (BB == CurLoop->getHeader())
1007  LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
1008 
1009  // Update DominatorTree.
1010  BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
1011  DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
1012  cast<BasicBlock>(VMap[IDomBB]));
1013  }
1014 
1015  // Move them physically from the end of the block list.
1016  F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
1017  NewPH);
1018  F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
1019  NewLoop->getHeader()->getIterator(), F->end());
1020 
1021  return NewLoop;
1022 }
1023 
1024 /// Duplicate non-Phi instructions from the beginning of block up to
1025 /// StopAt instruction into a split block between BB and its predecessor.
1027  BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
1028  ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
1029 
1030  assert(count(successors(PredBB), BB) == 1 &&
1031  "There must be a single edge between PredBB and BB!");
1032  // We are going to have to map operands from the original BB block to the new
1033  // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1034  // account for entry from PredBB.
1035  BasicBlock::iterator BI = BB->begin();
1036  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1037  ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1038 
1039  BasicBlock *NewBB = SplitEdge(PredBB, BB);
1040  NewBB->setName(PredBB->getName() + ".split");
1041  Instruction *NewTerm = NewBB->getTerminator();
1042 
1043  // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
1044  // in the update set here.
1045  DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
1046  {DominatorTree::Insert, PredBB, NewBB},
1047  {DominatorTree::Insert, NewBB, BB}});
1048 
1049  // Clone the non-phi instructions of BB into NewBB, keeping track of the
1050  // mapping and using it to remap operands in the cloned instructions.
1051  // Stop once we see the terminator too. This covers the case where BB's
1052  // terminator gets replaced and StopAt == BB's terminator.
1053  for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
1054  Instruction *New = BI->clone();
1055  New->setName(BI->getName());
1056  New->insertBefore(NewTerm);
1057  ValueMapping[&*BI] = New;
1058 
1059  // Remap operands to patch up intra-block references.
1060  for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1061  if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1062  auto I = ValueMapping.find(Inst);
1063  if (I != ValueMapping.end())
1064  New->setOperand(i, I->second);
1065  }
1066  }
1067 
1068  return NewBB;
1069 }
1070 
1072  DenseMap<MDNode *, MDNode *> &ClonedScopes,
1074  MDBuilder MDB(Context);
1075 
1076  for (auto *ScopeList : NoAliasDeclScopes) {
1077  for (const auto &MDOperand : ScopeList->operands()) {
1078  if (MDNode *MD = dyn_cast<MDNode>(MDOperand)) {
1079  AliasScopeNode SNANode(MD);
1080 
1081  std::string Name;
1082  auto ScopeName = SNANode.getName();
1083  if (!ScopeName.empty())
1084  Name = (Twine(ScopeName) + ":" + Ext).str();
1085  else
1086  Name = std::string(Ext);
1087 
1088  MDNode *NewScope = MDB.createAnonymousAliasScope(
1089  const_cast<MDNode *>(SNANode.getDomain()), Name);
1090  ClonedScopes.insert(std::make_pair(MD, NewScope));
1091  }
1092  }
1093  }
1094 }
1095 
1097  const DenseMap<MDNode *, MDNode *> &ClonedScopes,
1098  LLVMContext &Context) {
1099  auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
1100  bool NeedsReplacement = false;
1101  SmallVector<Metadata *, 8> NewScopeList;
1102  for (const auto &MDOp : ScopeList->operands()) {
1103  if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1104  if (auto *NewMD = ClonedScopes.lookup(MD)) {
1105  NewScopeList.push_back(NewMD);
1106  NeedsReplacement = true;
1107  continue;
1108  }
1109  NewScopeList.push_back(MD);
1110  }
1111  }
1112  if (NeedsReplacement)
1113  return MDNode::get(Context, NewScopeList);
1114  return nullptr;
1115  };
1116 
1117  if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
1118  if (auto *NewScopeList = CloneScopeList(Decl->getScopeList()))
1119  Decl->setScopeList(NewScopeList);
1120 
1121  auto replaceWhenNeeded = [&](unsigned MD_ID) {
1122  if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
1123  if (auto *NewScopeList = CloneScopeList(CSNoAlias))
1124  I->setMetadata(MD_ID, NewScopeList);
1125  };
1126  replaceWhenNeeded(LLVMContext::MD_noalias);
1127  replaceWhenNeeded(LLVMContext::MD_alias_scope);
1128 }
1129 
1131  ArrayRef<BasicBlock *> NewBlocks,
1133  if (NoAliasDeclScopes.empty())
1134  return;
1135 
1136  DenseMap<MDNode *, MDNode *> ClonedScopes;
1137  LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1138  << NoAliasDeclScopes.size() << " node(s)\n");
1139 
1140  cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1141  // Identify instructions using metadata that needs adaptation
1142  for (BasicBlock *NewBlock : NewBlocks)
1143  for (Instruction &I : *NewBlock)
1144  adaptNoAliasScopes(&I, ClonedScopes, Context);
1145 }
1146 
1148  Instruction *IStart, Instruction *IEnd,
1150  if (NoAliasDeclScopes.empty())
1151  return;
1152 
1153  DenseMap<MDNode *, MDNode *> ClonedScopes;
1154  LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1155  << NoAliasDeclScopes.size() << " node(s)\n");
1156 
1157  cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, Ext, Context);
1158  // Identify instructions using metadata that needs adaptation
1159  assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
1160  auto ItStart = IStart->getIterator();
1161  auto ItEnd = IEnd->getIterator();
1162  ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
1163  for (auto &I : llvm::make_range(ItStart, ItEnd))
1164  adaptNoAliasScopes(&I, ClonedScopes, Context);
1165 }
1166 
1168  ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1169  for (BasicBlock *BB : BBs)
1170  for (Instruction &I : *BB)
1171  if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1172  NoAliasDeclScopes.push_back(Decl->getScopeList());
1173 }
1174 
1177  SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1178  for (Instruction &I : make_range(Start, End))
1179  if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1180  NoAliasDeclScopes.push_back(Decl->getScopeList());
1181 }
i
i
Definition: README.txt:29
llvm::Argument
This class represents an incoming formal argument to a Function.
Definition: Argument.h:28
llvm::RF_None
@ RF_None
Definition: ValueMapper.h:66
llvm::Function::isIntrinsic
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition: Function.h:210
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::DIType
Base class for types.
Definition: DebugInfoMetadata.h:698
llvm::Function::args
iterator_range< arg_iterator > args()
Definition: Function.h:746
llvm::make_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Definition: iterator_range.h:53
llvm::ReturnInst
Return a value (possibly void), from a function.
Definition: Instructions.h:3050
llvm::ClonedCodeInfo
This struct can be used to capture information about code being cloned, while it is being cloned.
Definition: Cloning.h:62
llvm::WeakTrackingVH
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:204
ValueMapper.h
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:113
llvm::Intrinsic::IITDescriptor::Kind
enum llvm::Intrinsic::IITDescriptor::IITDescriptorKind Kind
Metadata.h
llvm::MapMetadata
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Lookup or compute a mapping for a piece of metadata.
Definition: ValueMapper.h:231
llvm::Function::end
iterator end()
Definition: Function.h:709
llvm::CmpInst::Predicate
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:719
llvm::BasicBlock::iterator
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
llvm::cloneLoopWithPreheader
Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
Definition: CloneFunction.cpp:940
llvm::BasicBlock::getParent
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:104
IntrinsicInst.h
llvm::ClonedCodeInfo::ContainsMemProfMetadata
bool ContainsMemProfMetadata
This is set to true if there is memprof related metadata (memprof or callsite metadata) in the cloned...
Definition: Cloning.h:68
llvm::ValueMap::end
iterator end()
Definition: ValueMap.h:136
llvm::Function::getBasicBlockList
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
Definition: Function.h:684
llvm::DomTreeUpdater::applyUpdates
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
Definition: DomTreeUpdater.cpp:230
llvm::Function
Definition: Function.h:60
llvm::Loop
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:547
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::lookup
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:197
llvm::SetVector< T, SmallVector< T, N >, SmallDenseSet< T, N > >::size
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:77
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1199
llvm::pred_size
unsigned pred_size(MachineBasicBlock *BB)
Definition: MachineSSAContext.h:32
llvm::SwitchInst::CaseHandleImpl
A handle to a particular switch case.
Definition: Instructions.h:3325
llvm::Function::getSubprogram
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1625
llvm::Value::hasName
bool hasName() const
Definition: Value.h:261
llvm::Function::getEntryBlock
const BasicBlock & getEntryBlock() const
Definition: Function.h:691
DomTreeUpdater.h
llvm::PHINode::removeIncomingValue
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Definition: Instructions.cpp:116
llvm::DeleteDeadBlocks
void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
Definition: BasicBlockUtils.cpp:100
llvm::FunctionType::get
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:360
Local.h
llvm::AttributeList::get
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
Definition: Attributes.cpp:1132
llvm::DominatorTree
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
llvm::MapValue
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Look up or compute a value in the value map.
Definition: ValueMapper.h:209
llvm::Function::getContext
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:321
llvm::Function::arg_size
size_t arg_size() const
Definition: Function.h:755
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
llvm::CloneFunctionChangeType::DifferentModule
@ DifferentModule
Module.h
llvm::BasicBlock::eraseFromParent
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition: BasicBlock.cpp:132
llvm::AttributeList
Definition: Attributes.h:432
llvm::DominatorTreeBase< BasicBlock, false >::Insert
static constexpr UpdateKind Insert
Definition: GenericDomTree.h:242
llvm::DominatorTreeBase::getNode
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Definition: GenericDomTree.h:351
llvm::AttributeList::getFnAttrs
AttributeSet getFnAttrs() const
The function attributes are returned.
Definition: Attributes.cpp:1469
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
llvm::CloneFunctionChangeType::LocalChangesOnly
@ LocalChangesOnly
llvm::ore::NV
DiagnosticInfoOptimizationBase::Argument NV
Definition: OptimizationRemarkEmitter.h:136
llvm::successors
auto successors(MachineBasicBlock *BB)
Definition: MachineSSAContext.h:29
llvm::ValueMapTypeRemapper
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition: ValueMapper.h:36
llvm::Intrinsic::not_intrinsic
@ not_intrinsic
Definition: Intrinsics.h:45
llvm::BasicBlock::getSinglePredecessor
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:285
llvm::CmpInst::getPredicateName
static StringRef getPredicateName(Predicate P)
Definition: Instructions.cpp:4097
llvm::DomTreeNodeBase::getIDom
DomTreeNodeBase * getIDom() const
Definition: GenericDomTree.h:89
llvm::DebugInfoFinder
Utility to find all debug info in a module.
Definition: DebugInfo.h:98
llvm::PHINode::setIncomingValue
void setIncomingValue(unsigned i, Value *V)
Definition: Instructions.h:2796
llvm::MDBuilder::createAnonymousAliasScope
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition: MDBuilder.h:159
llvm::Intrinsic::IITDescriptor::AK_MatchType
@ AK_MatchType
Definition: Intrinsics.h:164
llvm::ArrayRef::empty
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:159
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::MDNode::get
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1400
F
#define F(x, y, z)
Definition: MD5.cpp:55
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:55
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::SwitchInst::CaseHandleImpl::getCaseSuccessor
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
Definition: Instructions.h:3349
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
llvm::LoopBase::getParentLoop
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Definition: LoopInfo.h:114
llvm::RemapInstruction
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
Definition: ValueMapper.h:254
llvm::getConstrainedIntrinsicID
Intrinsic::ID getConstrainedIntrinsicID(const Instruction &Instr)
Returns constrained intrinsic id to represent the given instruction in strictfp function.
Definition: FPEnv.cpp:90
llvm::GlobalValue::isDeclaration
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:266
Constants.h
llvm::PHINode::getIncomingValue
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Definition: Instructions.h:2793
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::User
Definition: User.h:44
llvm::Intrinsic::IITDescriptor::SameVecWidthArgument
@ SameVecWidthArgument
Definition: Intrinsics.h:136
llvm::CallBase::getCalledFunction
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1396
llvm::LoopBase::addChildLoop
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Definition: LoopInfo.h:412
llvm::BasicBlock::begin
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:306
llvm::remapInstructionsInBlocks
void remapInstructionsInBlocks(const SmallVectorImpl< BasicBlock * > &Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
Definition: CloneFunction.cpp:926
llvm::CallInst::Create
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:1517
SI
@ SI
Definition: SIInstrInfo.cpp:7985
llvm::LoopInfoBase::addTopLevelLoop
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
Definition: LoopInfo.h:1049
llvm::ClonedCodeInfo::OperandBundleCallSites
std::vector< WeakTrackingVH > OperandBundleCallSites
All cloned call sites that have operand bundles attached are appended to this vector.
Definition: Cloning.h:78
llvm::PHINode::getIncomingValueForBlock
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Definition: Instructions.h:2882
llvm::LoopBase::getBlocks
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:188
llvm::Instruction
Definition: Instruction.h:42
llvm::AttributeList::hasFnAttr
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if the attribute exists for the function.
Definition: Attributes.cpp:1486
MDBuilder.h
llvm::predecessors
auto predecessors(MachineBasicBlock *BB)
Definition: MachineSSAContext.h:30
llvm::Function::copyAttributesFrom
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:715
llvm::GlobalObject::addMetadata
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1359
llvm::Value::setName
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:375
llvm::Function::hasPersonalityFn
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:759
llvm::DomTreeUpdater
Definition: DomTreeUpdater.h:28
llvm::LoopBase::getLoopsInPreorder
SmallVector< const LoopT *, 4 > getLoopsInPreorder() const
Return all loops in the loop nest rooted by the loop in preorder, with siblings in forward program or...
Definition: LoopInfo.h:378
llvm::DominatorTreeBase::changeImmediateDominator
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
Definition: GenericDomTree.h:655
llvm::MCID::Call
@ Call
Definition: MCInstrDesc.h:155
llvm::ValueMap::count
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: ValueMap.h:152
llvm::PHINode::getNumIncomingValues
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Definition: Instructions.h:2789
llvm::RF_NoModuleLevelChanges
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:71
CFG.h
LoopInfo.h
llvm::LoopInfoBase::AllocateLoop
LoopT * AllocateLoop(ArgsTy &&... Args)
Definition: LoopInfo.h:956
llvm::Function::getAttributes
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:314
llvm::ARM_PROC::IE
@ IE
Definition: ARMBaseInfo.h:27
llvm::ValueMap::MD
MDMapT & MD()
Definition: ValueMap.h:115
llvm::cloneAndAdaptNoAliasScopes
void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
Definition: CloneFunction.cpp:1130
llvm::CloneBasicBlock
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
Definition: CloneFunction.cpp:42
llvm::DbgVariableIntrinsic
This is the common base class for debug info intrinsics for variables.
Definition: IntrinsicInst.h:181
llvm::DuplicateInstructionsInSplitBetween
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
Definition: CloneFunction.cpp:1026
llvm::MipsISD::Ext
@ Ext
Definition: MipsISelLowering.h:159
llvm::AttributeList::getRetAttrs
AttributeSet getRetAttrs() const
The attributes for the ret value are returned.
Definition: Attributes.cpp:1465
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
llvm::Instruction::eraseFromParent
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:81
llvm::count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1895
llvm::DomTreeNodeBase::getBlock
NodeT * getBlock() const
Definition: GenericDomTree.h:88
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
llvm::PHINode::setIncomingBlock
void setIncomingBlock(unsigned i, BasicBlock *BB)
Definition: Instructions.h:2832
llvm::Intrinsic::getIntrinsicInfoTableEntries
void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Return the IIT table descriptor for the specified intrinsic into an array of IITDescriptors.
Definition: Function.cpp:1299
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:53
llvm::BranchInst::Create
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
Definition: Instructions.h:3188
llvm::DenseMap
Definition: DenseMap.h:714
DebugInfo.h
llvm::LoopInfoBase::getLoopFor
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:992
I
#define I(x, y, z)
Definition: MD5.cpp:58
Cloning.h
llvm::DICompileUnit
Compile unit.
Definition: DebugInfoMetadata.h:1364
llvm::LoopBase::getLoopPreheader
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:183
llvm::adaptNoAliasScopes
void adaptNoAliasScopes(llvm::Instruction *I, const DenseMap< MDNode *, MDNode * > &ClonedScopes, LLVMContext &Context)
Adapt the metadata for the specified instruction according to the provided mapping.
Definition: CloneFunction.cpp:1096
llvm::simplifyInstruction
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Definition: InstructionSimplify.cpp:6601
llvm::MDString::get
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:497
llvm::Function::Create
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:137
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::cloneNoAliasScopes
void cloneNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, DenseMap< MDNode *, MDNode * > &ClonedScopes, StringRef Ext, LLVMContext &Context)
Duplicate the specified list of noalias decl scopes.
Definition: CloneFunction.cpp:1071
llvm::Function::setPersonalityFn
void setPersonalityFn(Constant *Fn)
Definition: Function.cpp:1982
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
llvm::MDNode
Metadata node.
Definition: Metadata.h:944
hasRoundingModeOperand
static bool hasRoundingModeOperand(Intrinsic::ID CIID)
Definition: CloneFunction.cpp:363
llvm::SmallPtrSetImpl::count
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
llvm::Intrinsic::IITDescriptor::Argument
@ Argument
Definition: Intrinsics.h:132
llvm::SetVector< T, SmallVector< T, N >, SmallDenseSet< T, N > >::insert
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:141
llvm::Instruction::clone
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
Definition: Instruction.cpp:895
llvm::CloneAndPruneFunctionInto
void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr)
This works exactly like CloneFunctionInto, except that it does some simple constant prop and DCE on t...
Definition: CloneFunction.cpp:917
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: APInt.h:33
llvm::isInstructionTriviallyDead
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition: Local.cpp:396
llvm::LoopInfo
Definition: LoopInfo.h:1108
Cond
SmallVector< MachineOperand, 4 > Cond
Definition: BasicBlockSections.cpp:137
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
llvm::ClonedCodeInfo::OrigVMap
DenseMap< const Value *, const Value * > OrigVMap
Like VMap, but maps only unsimplified instructions.
Definition: Cloning.h:83
llvm::identifyNoAliasScopesToClone
void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
Definition: CloneFunction.cpp:1167
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
llvm::CloneAndPruneIntoFromInst
void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, const Instruction *StartingInst, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr)
This works like CloneAndPruneFunctionInto, except that it does not clone the entire function.
Definition: CloneFunction.cpp:612
llvm::Value::replaceAllUsesWith
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:532
llvm::BasicBlock::Create
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:97
getParent
static const Function * getParent(const Value *V)
Definition: BasicAliasAnalysis.cpp:805
llvm::append_range
void append_range(Container &C, Range &&R)
Wrapper function to append a range to a container.
Definition: STLExtras.h:2013
llvm::ilist_node_impl::getIterator
self_iterator getIterator()
Definition: ilist_node.h:82
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::CloneFunction
Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
Definition: CloneFunction.cpp:297
llvm::Value::getName
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:308
llvm::ValueMap< const Value *, WeakTrackingVH >
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::insert
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:207
llvm::DominatorTreeBase::addNewBlock
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
Definition: GenericDomTree.h:619
llvm::Intrinsic::getDeclaration
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1481
llvm::ClonedCodeInfo::ContainsCalls
bool ContainsCalls
This is set to true if the cloned code contains a normal call instruction.
Definition: Cloning.h:64
llvm::BasicBlock::front
const Instruction & front() const
Definition: BasicBlock.h:318
llvm::RF_IgnoreMissingLocals
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition: ValueMapper.h:89
llvm::Instruction::mayHaveSideEffects
bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
Definition: Instruction.cpp:732
llvm::CloneFunctionChangeType
CloneFunctionChangeType
Definition: Cloning.h:138
llvm::SplitEdge
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
Definition: BasicBlockUtils.cpp:597
llvm::AliasScopeNode::getName
StringRef getName() const
Definition: Metadata.h:1440
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
llvm::ConstantFoldTerminator
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition: Local.cpp:126
llvm::DIScope
Base class for scope-like contexts.
Definition: DebugInfoMetadata.h:509
llvm::MetadataAsValue::get
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:102
llvm::AMDGPU::SendMsg::Op
Op
Definition: SIDefines.h:351
llvm::AliasScopeNode::getDomain
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition: Metadata.h:1435
Function.h
llvm::LoopBase::getHeader
BlockT * getHeader() const
Definition: LoopInfo.h:105
llvm::Module::getOrInsertNamedMetadata
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition: Module.cpp:260
llvm::ValueMap::find
iterator find(const KeyT &Val)
Definition: ValueMap.h:156
llvm::Function::getPersonalityFn
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1977
llvm::Function::arg_begin
arg_iterator arg_begin()
Definition: Function.h:722
llvm::MDBuilder
Definition: MDBuilder.h:36
llvm::Function::front
const BasicBlock & front() const
Definition: Function.h:714
llvm::BasicBlock::getInstList
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:373
Instructions.h
llvm::User::getNumOperands
unsigned getNumOperands() const
Definition: User.h:191
SmallVector.h
llvm::LoopBase::addBasicBlockToLoop
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
Definition: LoopInfoImpl.h:258
llvm::AliasScopeNode
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Definition: Metadata.h:1424
N
#define N
llvm::DenseMapBase::try_emplace
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:222
llvm::Instruction::getParent
const BasicBlock * getParent() const
Definition: Instruction.h:91
InstructionSimplify.h
llvm::SmallVectorImpl::pop_back_val
T pop_back_val()
Definition: SmallVector.h:677
llvm::Value::deleteValue
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:109
llvm::BlockAddress::get
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1751
llvm::PHINode::getIncomingBlock
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Definition: Instructions.h:2813
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:164
llvm::PHINode
Definition: Instructions.h:2697
llvm::BasicBlock::getTerminator
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:119
llvm::DISubprogram
Subprogram description.
Definition: DebugInfoMetadata.h:1845
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
llvm::CallBase
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1174
llvm::Module::getDataLayout
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:398
DerivedTypes.h
llvm::SmallSetVector
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:307
pred
hexagon gen pred
Definition: HexagonGenPredicate.cpp:134
llvm::CloneFunctionInto
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, CloneFunctionChangeType Changes, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values.
Definition: CloneFunction.cpp:86
BB
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM BB
Definition: README.txt:39
llvm::ValueMap::lookup
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:165
LLVMContext.h
llvm::SwitchInst
Multiway switch.
Definition: Instructions.h:3276
llvm::AMDGPU::HSAMD::Kernel::Key::Args
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Definition: AMDGPUMetadata.h:394
llvm::AllocaInst
an instruction to allocate memory on the stack
Definition: Instructions.h:59
llvm::User::getOperand
Value * getOperand(unsigned i) const
Definition: User.h:169
llvm::Intrinsic::IITDescriptor
This is a type descriptor which explains the type requirements of an intrinsic.
Definition: Intrinsics.h:116
llvm::BranchInst
Conditional or Unconditional Branch instruction.
Definition: Instructions.h:3132
llvm::ClonedCodeInfo::ContainsDynamicAllocas
bool ContainsDynamicAllocas
This is set to true if the cloned code contains a 'dynamic' alloca.
Definition: Cloning.h:73
llvm::DebugInfoFinder::processInstruction
void processInstruction(const Module &M, const Instruction &I)
Process a single instruction and collect debug info anchors.
Definition: DebugInfo.cpp:214
llvm::SmallPtrSetImpl::contains
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:389
llvm::AttributeList::getParamAttrs
AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
Definition: Attributes.cpp:1461
BasicBlockUtils.h
llvm::ValueMaterializer
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:49
llvm::Function::setAttributes
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition: Function.h:317
CU
Definition: AArch64AsmBackend.cpp:505
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::Value::users
iterator_range< user_iterator > users()
Definition: Value.h:421
llvm::Intrinsic::IITDescriptor::getArgumentKind
ArgKind getArgumentKind() const
Definition: Intrinsics.h:176
llvm::BranchInst::isConditional
bool isConditional() const
Definition: Instructions.h:3211
llvm::MDOperand
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:773
llvm::BranchInst::getSuccessor
BasicBlock * getSuccessor(unsigned i) const
Definition: Instructions.h:3225
SetVector.h
llvm::DominatorTreeBase< BasicBlock, false >::Delete
static constexpr UpdateKind Delete
Definition: GenericDomTree.h:243
llvm::BasicBlock::const_iterator
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:88
llvm::FunctionType
Class to represent function types.
Definition: DerivedTypes.h:103
llvm::Function::iterator
BasicBlockListType::iterator iterator
Definition: Function.h:66
llvm::SmallPtrSetImpl::insert
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:365
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:39
llvm::PoisonValue::get
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1732