LLVM 24.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
17#include "llvm/ADT/Statistic.h"
23#include "llvm/IR/CFG.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DebugInfo.h"
27#include "llvm/IR/Function.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/MDBuilder.h"
33#include "llvm/IR/Metadata.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/Operator.h"
40#include <cstdint>
41#include <optional>
42using namespace llvm;
43
44#define DEBUG_TYPE "clone-function"
45
46STATISTIC(RemappedAtomMax, "Highest global NextAtomGroup (after mapping)");
47
49 uint64_t CurGroup = DL->getAtomGroup();
50 if (!CurGroup)
51 return;
52
53 // Try inserting a new entry. If there's already a mapping for this atom
54 // then there's nothing to do.
55 auto [It, Inserted] = VMap.AtomMap.insert({{DL.getInlinedAt(), CurGroup}, 0});
56 if (!Inserted)
57 return;
58
59 // Map entry to a new atom group.
60 uint64_t NewGroup = DL->getContext().incNextDILocationAtomGroup();
61 assert(NewGroup > CurGroup && "Next should always be greater than current");
62 It->second = NewGroup;
63
64 RemappedAtomMax = std::max<uint64_t>(NewGroup, RemappedAtomMax);
65}
66
68 DebugInfoFinder &DIFinder) {
69 const Module *M = F.getParent();
70 if (!M)
71 return;
72 // Inspect instructions to process e.g. DILexicalBlocks of inlined functions
73 for (const Instruction &I : instructions(F))
74 DIFinder.processInstruction(*M, I);
75}
76
77// Create a predicate that matches the metadata that should be identity mapped
78// during function cloning.
82 return [](const Metadata *MD) { return false; };
83
84 DISubprogram *SPClonedWithinModule = F.getSubprogram();
85
86 // Don't clone inlined subprograms.
87 auto ShouldKeep = [SPClonedWithinModule](const DISubprogram *SP) -> bool {
88 return SP != SPClonedWithinModule;
89 };
90
91 return [=](const Metadata *MD) {
92 // Avoid cloning compile units.
93 if (isa<DICompileUnit>(MD))
94 return true;
95
96 if (auto *SP = dyn_cast<DISubprogram>(MD))
97 return ShouldKeep(SP);
98
99 // If a subprogram isn't going to be cloned skip its lexical blocks as well.
100 if (auto *LScope = dyn_cast<DILocalScope>(MD))
101 return ShouldKeep(LScope->getSubprogram());
102
103 // Avoid cloning local variables of subprograms that won't be cloned.
104 if (auto *DV = dyn_cast<DILocalVariable>(MD))
105 if (auto *S = dyn_cast_or_null<DILocalScope>(DV->getScope()))
106 return ShouldKeep(S->getSubprogram());
107
108 // DIGlobalVariableExpression representing static local variable may be
109 // encountered in DISubprogram's retainedNodes list. Do not remap it, and
110 // remove it from retainedNodes after mapping.
112 return true;
113
114 // Clone types that are local to subprograms being cloned.
115 // Avoid cloning other types.
116 auto *Type = dyn_cast<DIType>(MD);
117 if (!Type)
118 return false;
119
120 // No need to clone types if subprograms are not cloned.
121 if (SPClonedWithinModule == nullptr)
122 return true;
123
124 // Scopeless types may be derived from local types (e.g. pointers to local
125 // types). They may need cloning.
127 DTy && !DTy->getScope())
128 return false;
129
130 auto *LScope = dyn_cast_or_null<DILocalScope>(Type->getScope());
131 if (!LScope)
132 return true;
133
134 if (ShouldKeep(LScope->getSubprogram()))
135 return true;
136
137 return false;
138 };
139}
140
141/// See comments in Cloning.h.
143 const Twine &NameSuffix, Function *F,
144 ClonedCodeInfo *CodeInfo, bool MapAtoms) {
145 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
146 if (BB->hasName())
147 NewBB->setName(BB->getName() + NameSuffix);
148
149 bool hasCalls = false, hasDynamicAllocas = false, hasMemProfMetadata = false;
150
151 // Loop over all instructions, and copy them over.
152 for (const Instruction &I : *BB) {
153 Instruction *NewInst = I.clone();
154 if (I.hasName())
155 NewInst->setName(I.getName() + NameSuffix);
156
157 NewInst->insertBefore(*NewBB, NewBB->end());
158 NewInst->cloneDebugInfoFrom(&I);
159
160 VMap[&I] = NewInst; // Add instruction map to value.
161
162 if (MapAtoms) {
163 if (const DebugLoc &DL = NewInst->getDebugLoc())
164 mapAtomInstance(DL.get(), VMap);
165 }
166
167 if (isa<CallInst>(I)) {
168 hasCalls = true;
169 hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_memprof);
170 hasMemProfMetadata |= I.hasMetadata(LLVMContext::MD_callsite);
171 }
172 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
173 if (!AI->isStaticAlloca()) {
174 hasDynamicAllocas = true;
175 }
176 }
177 }
178
179 if (CodeInfo) {
180 CodeInfo->ContainsCalls |= hasCalls;
181 CodeInfo->ContainsMemProfMetadata |= hasMemProfMetadata;
182 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
183 }
184 return NewBB;
185}
186
188 const Function *OldFunc,
189 ValueToValueMapTy &VMap,
190 bool ModuleLevelChanges,
191 ValueMapTypeRemapper *TypeMapper,
192 ValueMaterializer *Materializer) {
193 // Copy all attributes other than those stored in Function's AttributeList
194 // which holds e.g. parameters and return value attributes.
195 AttributeList NewAttrs = NewFunc->getAttributes();
196 NewFunc->copyAttributesFrom(OldFunc);
197 NewFunc->setAttributes(NewAttrs);
198
199 const RemapFlags FuncGlobalRefFlags =
200 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges;
201
202 // Fix up the personality function that got copied over.
203 if (OldFunc->hasPersonalityFn())
204 NewFunc->setPersonalityFn(MapValue(OldFunc->getPersonalityFn(), VMap,
205 FuncGlobalRefFlags, TypeMapper,
206 Materializer));
207
208 if (OldFunc->hasPrefixData()) {
209 NewFunc->setPrefixData(MapValue(OldFunc->getPrefixData(), VMap,
210 FuncGlobalRefFlags, TypeMapper,
211 Materializer));
212 }
213
214 if (OldFunc->hasPrologueData()) {
215 NewFunc->setPrologueData(MapValue(OldFunc->getPrologueData(), VMap,
216 FuncGlobalRefFlags, TypeMapper,
217 Materializer));
218 }
219
220 SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
221 AttributeList OldAttrs = OldFunc->getAttributes();
222
223 // Clone any argument attributes that are present in the VMap.
224 for (const Argument &OldArg : OldFunc->args()) {
225 if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
226 // Remap the parameter indices.
227 NewArgAttrs[NewArg->getArgNo()] =
228 OldAttrs.getParamAttrs(OldArg.getArgNo());
229 }
230 }
231
232 NewFunc->setAttributes(
233 AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttrs(),
234 OldAttrs.getRetAttrs(), NewArgAttrs));
235}
236
238 ValueToValueMapTy &VMap,
239 RemapFlags RemapFlag,
240 ValueMapTypeRemapper *TypeMapper,
241 ValueMaterializer *Materializer,
242 const MetadataPredicate *IdentityMD) {
244 OldFunc.getAllMetadata(MDs);
245 for (const auto &[Kind, MD] : MDs) {
246 NewFunc.addMetadata(Kind, *MapMetadata(MD, VMap, RemapFlag, TypeMapper,
247 Materializer, IdentityMD));
248 }
249}
250
251void llvm::CloneFunctionBodyInto(Function &NewFunc, const Function &OldFunc,
252 ValueToValueMapTy &VMap, RemapFlags RemapFlag,
254 const char *NameSuffix,
255 ClonedCodeInfo *CodeInfo,
256 ValueMapTypeRemapper *TypeMapper,
257 ValueMaterializer *Materializer,
258 const MetadataPredicate *IdentityMD) {
259 if (OldFunc.isDeclaration())
260 return;
261
262 // Loop over all of the basic blocks in the function, cloning them as
263 // appropriate. Note that we save BE this way in order to handle cloning of
264 // recursive functions into themselves.
265 for (const BasicBlock &BB : OldFunc) {
266 // Create a new basic block and copy instructions into it!
267 BasicBlock *CBB =
268 CloneBasicBlock(&BB, VMap, NameSuffix, &NewFunc, CodeInfo);
269
270 // Add basic block mapping.
271 VMap[&BB] = CBB;
272
273 // It is only legal to clone a function if a block address within that
274 // function is never referenced outside of the function. Given that, we
275 // want to map block addresses from the old function to block addresses in
276 // the clone. (This is different from the generic ValueMapper
277 // implementation, which generates an invalid blockaddress when
278 // cloning a function.)
279 if (BB.hasAddressTaken()) {
280 Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(&OldFunc),
281 const_cast<BasicBlock *>(&BB));
282 VMap[OldBBAddr] = BlockAddress::get(&NewFunc, CBB);
283 }
284
285 // Note return instructions for the caller.
287 Returns.push_back(RI);
288 }
289
290 // Loop over all of the instructions in the new function, fixing up operand
291 // references as we go. This uses VMap to do all the hard work.
292 ValueMapper Mapper(VMap, RemapFlag, TypeMapper, Materializer, IdentityMD);
294 BB = cast<BasicBlock>(VMap[&OldFunc.front()])->getIterator(),
295 BE = NewFunc.end();
296 BB != BE; ++BB)
297 // Loop over all instructions, fixing each one as we find it, and any
298 // attached debug-info records.
299 for (Instruction &II : *BB) {
300 Mapper.remapInstruction(II);
301 Mapper.remapDbgRecordRange(II.getModule(), II.getDbgRecordRange());
302 }
303}
304
305// Clone OldFunc into NewFunc, transforming the old arguments into references to
306// VMap values.
307void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
308 ValueToValueMapTy &VMap,
311 const char *NameSuffix, ClonedCodeInfo *CodeInfo,
312 ValueMapTypeRemapper *TypeMapper,
313 ValueMaterializer *Materializer) {
314 assert(NameSuffix && "NameSuffix cannot be null!");
315
316#ifndef NDEBUG
317 for (const Argument &I : OldFunc->args())
318 assert(VMap.count(&I) && "No mapping from source argument specified!");
319#endif
320
321 bool ModuleLevelChanges = Changes > CloneFunctionChangeType::LocalChangesOnly;
322
323 CloneFunctionAttributesInto(NewFunc, OldFunc, VMap, ModuleLevelChanges,
324 TypeMapper, Materializer);
325
326 // Everything else beyond this point deals with function instructions,
327 // so if we are dealing with a function declaration, we're done.
328 if (OldFunc->isDeclaration())
329 return;
330
332 assert((NewFunc->getParent() == nullptr ||
333 NewFunc->getParent() == OldFunc->getParent()) &&
334 "Expected NewFunc to have the same parent, or no parent");
335 } else {
336 assert((NewFunc->getParent() == nullptr ||
337 NewFunc->getParent() != OldFunc->getParent()) &&
338 "Expected NewFunc to have different parents, or no parent");
339
341 assert(NewFunc->getParent() &&
342 "Need parent of new function to maintain debug info invariants");
343 }
344 }
345
346 MetadataPredicate IdentityMD = createIdentityMDPredicate(*OldFunc, Changes);
347
348 // Cloning is always a Module level operation, since Metadata needs to be
349 // cloned.
350 const RemapFlags RemapFlag = RF_None;
351
352 CloneFunctionMetadataInto(*NewFunc, *OldFunc, VMap, RemapFlag, TypeMapper,
353 Materializer, &IdentityMD);
354
355 CloneFunctionBodyInto(*NewFunc, *OldFunc, VMap, RemapFlag, Returns,
356 NameSuffix, CodeInfo, TypeMapper, Materializer,
357 &IdentityMD);
358
359 // DIGlobalVariableExpressions representing static locals stay in the scope of
360 // OldSP after function cloning. Remove them from retainedNodes of NewSP.
361 if (DISubprogram *NewSP = NewFunc->getSubprogram())
362 NewSP->cleanupRetainedNodesIf([NewSP](Metadata *N) {
364 return !GVE ||
366 });
367
368 // Only update !llvm.dbg.cu for DifferentModule (not CloneModule). In the
369 // same module, the compile unit will already be listed (or not). When
370 // cloning a module, CloneModule() will handle creating the named metadata.
372 return;
373
374 // Update !llvm.dbg.cu with compile units added to the new module if this
375 // function is being cloned in isolation.
376 //
377 // FIXME: This is making global / module-level changes, which doesn't seem
378 // like the right encapsulation Consider dropping the requirement to update
379 // !llvm.dbg.cu (either obsoleting the node, or restricting it to
380 // non-discardable compile units) instead of discovering compile units by
381 // visiting the metadata attached to global values, which would allow this
382 // code to be deleted. Alternatively, perhaps give responsibility for this
383 // update to CloneFunctionInto's callers.
384 Module *NewModule = NewFunc->getParent();
385 NamedMDNode *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
386 // Avoid multiple insertions of the same DICompileUnit to NMD.
388
389 // Collect and clone all the compile units referenced from the instructions in
390 // the function (e.g. as instructions' scope).
391 DebugInfoFinder DIFinder;
392 collectDebugInfoFromInstructions(*OldFunc, DIFinder);
393 for (DICompileUnit *Unit : DIFinder.compile_units()) {
394 MDNode *MappedUnit =
395 MapMetadata(Unit, VMap, RF_None, TypeMapper, Materializer);
396 if (Visited.insert(MappedUnit).second)
397 NMD->addOperand(MappedUnit);
398 }
399}
400
401/// Return a copy of the specified function and add it to that function's
402/// module. Also, any references specified in the VMap are changed to refer to
403/// their mapped value instead of the original one. If any of the arguments to
404/// the function are in the VMap, the arguments are deleted from the resultant
405/// function. The VMap is updated to include mappings from all of the
406/// instructions and basicblocks in the function from their old to new values.
407///
409 ClonedCodeInfo *CodeInfo) {
410 std::vector<Type *> ArgTypes;
411
412 // The user might be deleting arguments to the function by specifying them in
413 // the VMap. If so, we need to not add the arguments to the arg ty vector
414 //
415 for (const Argument &I : F->args())
416 if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
417 ArgTypes.push_back(I.getType());
418
419 // Create a new function type...
420 FunctionType *FTy =
421 FunctionType::get(F->getFunctionType()->getReturnType(), ArgTypes,
422 F->getFunctionType()->isVarArg());
423
424 // Create the new function...
425 Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
426 F->getName(), F->getParent());
427
428 // Loop over the arguments, copying the names of the mapped arguments over...
429 Function::arg_iterator DestI = NewF->arg_begin();
430 for (const Argument &I : F->args())
431 if (VMap.count(&I) == 0) { // Is this argument preserved?
432 DestI->setName(I.getName()); // Copy the name over...
433 VMap[&I] = &*DestI++; // Add mapping to VMap
434 }
435
436 SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
438 Returns, "", CodeInfo);
439
440 return NewF;
441}
442
443namespace {
444/// This is a private class used to implement CloneAndPruneFunctionInto.
445struct PruningFunctionCloner {
446 Function *NewFunc;
447 const Function *OldFunc;
448 ValueToValueMapTy &VMap;
449 ValueMapper &Remapper;
450 bool ModuleLevelChanges;
451 const char *NameSuffix;
452 ClonedCodeInfo &CodeInfo;
453 bool HostFuncIsStrictFP;
454
455 Instruction *cloneInstruction(BasicBlock::const_iterator II);
456
457public:
458 PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
459 ValueToValueMapTy &valueMap, ValueMapper &remapper,
460 bool moduleLevelChanges, const char *nameSuffix,
461 ClonedCodeInfo &codeInfo)
462 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap), Remapper(remapper),
463 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
464 CodeInfo(codeInfo) {
465 HostFuncIsStrictFP =
466 newFunc->getAttributes().hasFnAttr(Attribute::StrictFP);
467 }
468
469 /// The specified block is found to be reachable, clone it and
470 /// anything that it can reach.
471 void CloneBlock(const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
472 std::vector<const BasicBlock *> &ToClone);
473};
474} // namespace
475
477PruningFunctionCloner::cloneInstruction(BasicBlock::const_iterator II) {
478 if (!HostFuncIsStrictFP)
479 return II->clone();
480
481 const Instruction &OldInst = *II;
483 if (CIID == Intrinsic::not_intrinsic)
484 return II->clone();
485
486 // Instead of cloning the instruction, a call to constrained intrinsic should
487 // be created. Assume the first arguments of constrained intrinsics are the
488 // same as the operands of original instruction.
489
490 // Create intrinsic call.
491 LLVMContext &Ctx = NewFunc->getContext();
492 SmallVector<Value *, 4> Args;
493 unsigned NumOperands = OldInst.getNumOperands();
494 if (isa<CallInst>(OldInst))
495 --NumOperands;
496 for (unsigned I = 0; I < NumOperands; ++I)
497 Args.push_back(OldInst.getOperand(I));
498
499 if (const auto *CmpI = dyn_cast<FCmpInst>(&OldInst)) {
500 FCmpInst::Predicate Pred = CmpI->getPredicate();
501 StringRef PredName = FCmpInst::getPredicateName(Pred);
502 Args.push_back(MetadataAsValue::get(Ctx, MDString::get(Ctx, PredName)));
503 }
504
505 // The last arguments of a constrained intrinsic are metadata that represent
506 // rounding mode (absent in some intrinsics) and exception behavior. The
507 // inlined function uses default settings.
509 Args.push_back(
510 MetadataAsValue::get(Ctx, MDString::get(Ctx, "round.tonearest")));
511 Args.push_back(
512 MetadataAsValue::get(Ctx, MDString::get(Ctx, "fpexcept.ignore")));
513
514 SmallVector<Type *> ArgTys = llvm::map_to_vector(Args, &Value::getType);
516 OldInst.getType(), ArgTys);
517 CallInst *NewCall =
518 CallInst::Create(IFn, Args, OldInst.getName() + ".strict");
519 if (isa<FPMathOperator>(NewCall))
520 NewCall->copyFastMathFlags(&OldInst);
521 return NewCall;
522}
523
524/// The specified block is found to be reachable, clone it and
525/// anything that it can reach.
526void PruningFunctionCloner::CloneBlock(
527 const BasicBlock *BB, BasicBlock::const_iterator StartingInst,
528 std::vector<const BasicBlock *> &ToClone) {
529 WeakTrackingVH &BBEntry = VMap[BB];
530
531 // Have we already cloned this block?
532 if (BBEntry)
533 return;
534
535 // Nope, clone it now.
536 BasicBlock *NewBB;
537 Twine NewName(BB->hasName() ? Twine(BB->getName()) + NameSuffix : "");
538 BBEntry = NewBB = BasicBlock::Create(BB->getContext(), NewName, NewFunc);
539
540 // It is only legal to clone a function if a block address within that
541 // function is never referenced outside of the function. Given that, we
542 // want to map block addresses from the old function to block addresses in
543 // the clone. (This is different from the generic ValueMapper
544 // implementation, which generates an invalid blockaddress when
545 // cloning a function.)
546 //
547 // Note that we don't need to fix the mapping for unreachable blocks;
548 // the default mapping there is safe.
549 if (BB->hasAddressTaken()) {
550 Constant *OldBBAddr = BlockAddress::get(const_cast<Function *>(OldFunc),
551 const_cast<BasicBlock *>(BB));
552 VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
553 }
554
555 bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
556 bool hasMemProfMetadata = false;
557
558 // Keep a cursor pointing at the last place we cloned debug-info records from.
559 BasicBlock::const_iterator DbgCursor = StartingInst;
560 auto CloneDbgRecordsToHere =
561 [&DbgCursor](Instruction *NewInst, BasicBlock::const_iterator II) {
562 // Clone debug-info records onto this instruction. Iterate through any
563 // source-instructions we've cloned and then subsequently optimised
564 // away, so that their debug-info doesn't go missing.
565 for (; DbgCursor != II; ++DbgCursor)
566 NewInst->cloneDebugInfoFrom(&*DbgCursor, std::nullopt, false);
567 NewInst->cloneDebugInfoFrom(&*II);
568 DbgCursor = std::next(II);
569 };
570
571 // Loop over all instructions, and copy them over, DCE'ing as we go. This
572 // loop doesn't include the terminator.
573 for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end(); II != IE;
574 ++II) {
575
576 // Don't clone fake_use as it may suppress many optimizations
577 // due to inlining, especially SROA.
578 if (auto *IntrInst = dyn_cast<IntrinsicInst>(II))
579 if (IntrInst->getIntrinsicID() == Intrinsic::fake_use)
580 continue;
581
582 Instruction *NewInst = cloneInstruction(II);
583 NewInst->insertInto(NewBB, NewBB->end());
584
585 if (HostFuncIsStrictFP) {
586 // All function calls in the inlined function must get 'strictfp'
587 // attribute to prevent undesirable optimizations.
588 if (auto *Call = dyn_cast<CallInst>(NewInst))
589 Call->addFnAttr(Attribute::StrictFP);
590 }
591
592 // Eagerly remap operands to the newly cloned instruction, except for PHI
593 // nodes for which we defer processing until we update the CFG.
594 if (!isa<PHINode>(NewInst)) {
595 Remapper.remapInstruction(*NewInst);
596
597 // Eagerly constant fold the newly cloned instruction. If successful, add
598 // a mapping to the new value. Non-constant operands may be incomplete at
599 // this stage, thus instruction simplification is performed after
600 // processing phi-nodes.
602 NewInst, BB->getDataLayout())) {
603 if (isInstructionTriviallyDead(NewInst)) {
604 VMap[&*II] = V;
605 NewInst->eraseFromParent();
606 continue;
607 }
608 }
609 }
610
611 if (auto *CB = dyn_cast<CallBase>(II); CB && CB->isIndirectCall())
612 CodeInfo.OriginallyIndirectCalls.insert(NewInst);
613
614 if (II->hasName())
615 NewInst->setName(II->getName() + NameSuffix);
616 VMap[&*II] = NewInst; // Add instruction map to value.
617 if (isa<CallInst>(II)) {
618 hasCalls = true;
619 hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_memprof);
620 hasMemProfMetadata |= II->hasMetadata(LLVMContext::MD_callsite);
621 }
622
623 CloneDbgRecordsToHere(NewInst, II);
624
625 CodeInfo.OrigVMap[&*II] = NewInst;
626 if (auto *CB = dyn_cast<CallBase>(&*II))
627 if (CB->hasOperandBundles())
628 CodeInfo.OperandBundleCallSites.push_back(NewInst);
629
630 if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
631 if (isa<ConstantInt>(AI->getArraySize()))
632 hasStaticAllocas = true;
633 else
634 hasDynamicAllocas = true;
635 }
636 }
637
638 // Finally, clone over the terminator.
639 const Instruction *OldTI = BB->getTerminator();
640 bool TerminatorDone = false;
641 if (const CondBrInst *BI = dyn_cast<CondBrInst>(OldTI)) {
642 // If the condition was a known constant in the callee...
643 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
644 // Or is a known constant in the caller...
645 if (!Cond) {
646 Value *V = VMap.lookup(BI->getCondition());
648 }
649
650 // Constant fold to uncond branch!
651 if (Cond) {
652 BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
653 auto *NewBI = UncondBrInst::Create(Dest, NewBB);
654 NewBI->setDebugLoc(BI->getDebugLoc());
655 VMap[OldTI] = NewBI;
656 ToClone.push_back(Dest);
657 TerminatorDone = true;
658 }
659 } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
660 // If switching on a value known constant in the caller.
661 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
662 if (!Cond) { // Or known constant after constant prop in the callee...
663 Value *V = VMap.lookup(SI->getCondition());
665 }
666 if (Cond) { // Constant fold to uncond branch!
667 SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
668 BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
669 auto *NewBI = UncondBrInst::Create(Dest, NewBB);
670 NewBI->setDebugLoc(SI->getDebugLoc());
671 VMap[OldTI] = NewBI;
672 ToClone.push_back(Dest);
673 TerminatorDone = true;
674 }
675 }
676
677 if (!TerminatorDone) {
678 Instruction *NewInst = OldTI->clone();
679 if (OldTI->hasName())
680 NewInst->setName(OldTI->getName() + NameSuffix);
681 NewInst->insertInto(NewBB, NewBB->end());
682
683 CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
684
685 VMap[OldTI] = NewInst; // Add instruction map to value.
686
687 CodeInfo.OrigVMap[OldTI] = NewInst;
688 if (auto *CB = dyn_cast<CallBase>(OldTI))
689 if (CB->hasOperandBundles())
690 CodeInfo.OperandBundleCallSites.push_back(NewInst);
691
692 // Recursively clone any reachable successor blocks.
693 append_range(ToClone, successors(BB->getTerminator()));
694 } else {
695 // If we didn't create a new terminator, clone DbgVariableRecords from the
696 // old terminator onto the new terminator.
697 Instruction *NewInst = NewBB->getTerminator();
698
699 CloneDbgRecordsToHere(NewInst, OldTI->getIterator());
700 }
701
702 CodeInfo.ContainsCalls |= hasCalls;
703 CodeInfo.ContainsMemProfMetadata |= hasMemProfMetadata;
704 CodeInfo.ContainsDynamicAllocas |= hasDynamicAllocas;
705 CodeInfo.ContainsDynamicAllocas |=
706 hasStaticAllocas && BB != &BB->getParent()->front();
707}
708
710 Function::iterator Begin) {
711 // Simplify conditional branches and switches with a constant operand. We try
712 // to prune these out when cloning, but if the simplification required
713 // looking through PHI nodes, those are only available after forming the full
714 // basic block. That may leave some here, and we still want to prune the dead
715 // code as early as possible.
716 for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
718
719 // Some blocks may have become unreachable as a result. Find and delete them.
720 {
721 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
723 Worklist.push_back(&*Begin);
724 while (!Worklist.empty()) {
725 BasicBlock *BB = Worklist.pop_back_val();
726 if (ReachableBlocks.insert(BB).second)
727 append_range(Worklist, successors(BB));
728 }
729
730 SmallVector<BasicBlock *, 16> UnreachableBlocks;
731 for (BasicBlock &BB : make_range(Begin, NewFunc->end()))
732 if (!ReachableBlocks.contains(&BB))
733 UnreachableBlocks.push_back(&BB);
734 DeleteDeadBlocks(UnreachableBlocks);
735 }
736
737 // Now that the inlined function body has been fully constructed, go through
738 // and zap unconditional fall-through branches. This happens all the time when
739 // specializing code: code specialization turns conditional branches into
740 // uncond branches, and this code folds them.
741 Function::iterator I = Begin;
742 while (I != NewFunc->end()) {
743 UncondBrInst *BI = dyn_cast<UncondBrInst>(I->getTerminator());
744 if (!BI) {
745 ++I;
746 continue;
747 }
748
749 BasicBlock *Dest = BI->getSuccessor();
750 if (!Dest->getSinglePredecessor() || Dest->hasAddressTaken()) {
751 ++I;
752 continue;
753 }
754
755 // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
756 // above should have zapped all of them..
757 assert(!isa<PHINode>(Dest->begin()));
758
759 // We know all single-entry PHI nodes in the inlined function have been
760 // removed, so we just need to splice the blocks.
761 BI->eraseFromParent();
762
763 // Make all PHI nodes that referred to Dest now refer to I as their source.
764 Dest->replaceAllUsesWith(&*I);
765
766 // Move all the instructions in the succ to the pred.
767 I->splice(I->end(), Dest);
768
769 // Remove the dest block.
770 Dest->eraseFromParent();
771
772 // Do not increment I, iteratively merge all things this block branches to.
773 }
774}
775
776/// This works like CloneAndPruneFunctionInto, except that it does not clone the
777/// entire function. Instead it starts at an instruction provided by the caller
778/// and copies (and prunes) only the code reachable from that instruction.
780 const Instruction *StartingInst,
781 ValueToValueMapTy &VMap,
782 bool ModuleLevelChanges,
784 const char *NameSuffix,
785 ClonedCodeInfo &CodeInfo) {
786 assert(NameSuffix && "NameSuffix cannot be null!");
787
788 ValueMapTypeRemapper *TypeMapper = nullptr;
789 ValueMaterializer *Materializer = nullptr;
790
791#ifndef NDEBUG
792 // If the cloning starts at the beginning of the function, verify that
793 // the function arguments are mapped.
794 if (!StartingInst)
795 for (const Argument &II : OldFunc->args())
796 assert(VMap.count(&II) && "No mapping from source argument specified!");
797#endif
798
799 ValueMapper Mapper(VMap,
800 ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
801 TypeMapper, Materializer);
802 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, Mapper, ModuleLevelChanges,
803 NameSuffix, CodeInfo);
804 const BasicBlock *StartingBB;
805 if (StartingInst)
806 StartingBB = StartingInst->getParent();
807 else {
808 StartingBB = &OldFunc->getEntryBlock();
809 StartingInst = &StartingBB->front();
810 }
811
812 // Clone the entry block, and anything recursively reachable from it.
813 std::vector<const BasicBlock *> CloneWorklist;
814 PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
815 while (!CloneWorklist.empty()) {
816 const BasicBlock *BB = CloneWorklist.back();
817 CloneWorklist.pop_back();
818 PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
819 }
820
821 // Loop over all of the basic blocks in the old function. If the block was
822 // reachable, we have cloned it and the old block is now in the value map:
823 // insert it into the new function in the right order. If not, ignore it.
824 //
825 // Defer PHI resolution until rest of function is resolved.
827 for (const BasicBlock &BI : *OldFunc) {
828 Value *V = VMap.lookup(&BI);
830 if (!NewBB)
831 continue; // Dead block.
832
833 // Move the new block to preserve the order in the original function.
834 NewBB->moveBefore(NewFunc->end());
835
836 // Handle PHI nodes specially, as we have to remove references to dead
837 // blocks.
838 for (const PHINode &PN : BI.phis()) {
839 // PHI nodes may have been remapped to non-PHI nodes by the caller or
840 // during the cloning process.
841 if (isa<PHINode>(VMap[&PN]))
842 PHIToResolve.push_back(&PN);
843 else
844 break;
845 }
846
847 // Finally, remap the terminator instructions, as those can't be remapped
848 // until all BBs are mapped.
849 Mapper.remapInstruction(*NewBB->getTerminator());
850 }
851
852 // Defer PHI resolution until rest of function is resolved, PHI resolution
853 // requires the CFG to be up-to-date.
854 for (unsigned phino = 0, e = PHIToResolve.size(); phino != e;) {
855 const PHINode *OPN = PHIToResolve[phino];
856 unsigned NumPreds = OPN->getNumIncomingValues();
857 const BasicBlock *OldBB = OPN->getParent();
858 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
859
860 // Map operands for blocks that are live and remove operands for blocks
861 // that are dead.
862 for (; phino != PHIToResolve.size() &&
863 PHIToResolve[phino]->getParent() == OldBB;
864 ++phino) {
865 OPN = PHIToResolve[phino];
866 PHINode *PN = cast<PHINode>(VMap[OPN]);
867 for (int64_t pred = NumPreds - 1; pred >= 0; --pred) {
868 Value *V = VMap.lookup(PN->getIncomingBlock(pred));
869 if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
870 Value *InVal = Mapper.mapValue(*PN->getIncomingValue(pred));
871 assert(InVal && "Unknown input value?");
872 PN->setIncomingValue(pred, InVal);
873 PN->setIncomingBlock(pred, MappedBlock);
874 continue;
875 }
876 PN->removeIncomingValue(pred, false);
877 }
878 }
879
880 // The loop above has removed PHI entries for those blocks that are dead
881 // and has updated others. However, if a block is live (i.e. copied over)
882 // but its terminator has been changed to not go to this block, then our
883 // phi nodes will have invalid entries. Update the PHI nodes in this
884 // case.
885 PHINode *PN = cast<PHINode>(NewBB->begin());
886 NumPreds = pred_size(NewBB);
887 if (NumPreds != PN->getNumIncomingValues()) {
888 assert(NumPreds < PN->getNumIncomingValues());
889 // Count how many times each predecessor comes to this block.
891 for (BasicBlock *Pred : predecessors(NewBB))
892 ++PredCount[Pred];
893
894 BasicBlock::iterator I = NewBB->begin();
896 SeenPredCount.reserve(PredCount.size());
897 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
898 SeenPredCount.clear();
900 [&](unsigned Idx) {
901 BasicBlock *IncomingBlock = PN->getIncomingBlock(Idx);
902 auto It = PredCount.find(IncomingBlock);
903 if (It == PredCount.end())
904 return true;
905 unsigned &SeenCount = SeenPredCount[IncomingBlock];
906 if (SeenCount < It->second) {
907 SeenCount++;
908 return false;
909 }
910 return true;
911 },
912 false);
913 }
914 }
915
916 // If the loops above have made these phi nodes have 0 or 1 operand,
917 // replace them with poison or the input value. We must do this for
918 // correctness, because 0-operand phis are not valid.
919 PN = cast<PHINode>(NewBB->begin());
920 if (PN->getNumIncomingValues() == 0) {
921 BasicBlock::iterator I = NewBB->begin();
922 BasicBlock::const_iterator OldI = OldBB->begin();
923 while ((PN = dyn_cast<PHINode>(I++))) {
924 Value *NV = PoisonValue::get(PN->getType());
925 PN->replaceAllUsesWith(NV);
926 assert(VMap[&*OldI] == PN && "VMap mismatch");
927 VMap[&*OldI] = NV;
928 PN->eraseFromParent();
929 ++OldI;
930 }
931 }
932 }
933
934 // Drop all incompatible return attributes that cannot be applied to NewFunc
935 // during cloning, so as to allow instruction simplification to reason on the
936 // old state of the function. The original attributes are restored later.
937 AttributeList Attrs = NewFunc->getAttributes();
938 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(
939 OldFunc->getReturnType(), Attrs.getRetAttrs());
940 NewFunc->removeRetAttrs(IncompatibleAttrs);
941
942 // As phi-nodes have been now remapped, allow incremental simplification of
943 // newly-cloned instructions.
944 const DataLayout &DL = NewFunc->getDataLayout();
945 for (const BasicBlock &BB : *OldFunc) {
946 for (const Instruction &I : BB) {
947 auto *NewI = dyn_cast_or_null<Instruction>(VMap.lookup(&I));
948 if (!NewI)
949 continue;
950
951 if (Value *V = simplifyInstruction(NewI, DL)) {
952 NewI->replaceAllUsesWith(V);
953
954 if (isInstructionTriviallyDead(NewI)) {
955 NewI->eraseFromParent();
956 } else {
957 // Did not erase it? Restore the new instruction into VMap previously
958 // dropped by `ValueIsRAUWd`.
959 VMap[&I] = NewI;
960 }
961 }
962 }
963 }
964
965 // Restore attributes.
966 NewFunc->setAttributes(Attrs);
967
968 // Remap debug records operands now that all values have been mapped.
969 // Doing this now (late) preserves use-before-defs in debug records. If
970 // we didn't do this, ValueAsMetadata(use-before-def) operands would be
971 // replaced by empty metadata. This would signal later cleanup passes to
972 // remove the debug records, potentially causing incorrect locations.
973 Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
974 for (BasicBlock &BB : make_range(Begin, NewFunc->end())) {
975 for (Instruction &I : BB) {
976 Mapper.remapDbgRecordRange(I.getModule(), I.getDbgRecordRange());
977 }
978 }
979
981
982 // Make a final pass over the basic blocks from the old function to gather
983 // any return instructions which survived folding. We have to do this here
984 // because we can iteratively remove and merge returns above.
985 for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
986 E = NewFunc->end();
987 I != E; ++I)
988 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
989 Returns.push_back(RI);
990}
991
992/// This works exactly like CloneFunctionInto,
993/// except that it does some simple constant prop and DCE on the fly. The
994/// effect of this is to copy significantly less code in cases where (for
995/// example) a function call with constant arguments is inlined, and those
996/// constant arguments cause a significant amount of code in the callee to be
997/// dead. Since this doesn't produce an exact copy of the input, it can't be
998/// used for things like CloneFunction or CloneModule.
1000 ValueToValueMapTy &VMap,
1001 bool ModuleLevelChanges,
1003 const char *NameSuffix,
1004 ClonedCodeInfo &CodeInfo) {
1005 CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
1006 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
1007}
1008
1009/// Remaps instructions in \p Blocks using the mapping in \p VMap.
1011 ValueToValueMapTy &VMap) {
1012 // Rewrite the code to refer to itself.
1014 for (BasicBlock *BB : Blocks) {
1015 for (Instruction &Inst : *BB) {
1016 Mapper.remapDbgRecordRange(Inst.getModule(), Inst.getDbgRecordRange());
1017 Mapper.remapInstruction(Inst);
1018 }
1019 }
1020}
1021
1022/// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
1023/// Blocks.
1024///
1025/// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
1026/// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
1027/// The client needs to further update the CFG and DominatorTree after calling
1028/// this function, to ensure the IR remains valid.
1030 Loop *OrigLoop, ValueToValueMapTy &VMap,
1031 const Twine &NameSuffix, LoopInfo *LI,
1032 DominatorTree *DT,
1034 Function *F = OrigLoop->getHeader()->getParent();
1035 Loop *ParentLoop = OrigLoop->getParentLoop();
1037
1038 Loop *NewLoop = LI->AllocateLoop();
1039 LMap[OrigLoop] = NewLoop;
1040 if (ParentLoop)
1041 ParentLoop->addChildLoop(NewLoop);
1042 else
1043 LI->addTopLevelLoop(NewLoop);
1044
1045 BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
1046 assert(OrigPH && "No preheader");
1047 BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
1048 // To rename the loop PHIs.
1049 VMap[OrigPH] = NewPH;
1050 Blocks.push_back(NewPH);
1051
1052 // Update LoopInfo.
1053 if (ParentLoop)
1054 ParentLoop->addBasicBlockToLoop(NewPH, *LI);
1055
1056 // Update DominatorTree.
1057 DT->addNewBlock(NewPH, LoopDomBB);
1058
1059 for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
1060 Loop *&NewLoop = LMap[CurLoop];
1061 if (!NewLoop) {
1062 NewLoop = LI->AllocateLoop();
1063
1064 // Establish the parent/child relationship.
1065 Loop *OrigParent = CurLoop->getParentLoop();
1066 assert(OrigParent && "Could not find the original parent loop");
1067 Loop *NewParentLoop = LMap[OrigParent];
1068 assert(NewParentLoop && "Could not find the new parent loop");
1069
1070 NewParentLoop->addChildLoop(NewLoop);
1071 }
1072 }
1073
1074 for (BasicBlock *BB : OrigLoop->getBlocks()) {
1075 Loop *CurLoop = LI->getLoopFor(BB);
1076 Loop *&NewLoop = LMap[CurLoop];
1077 assert(NewLoop && "Expecting new loop to be allocated");
1078
1079 BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
1080 VMap[BB] = NewBB;
1081
1082 // Update LoopInfo.
1083 NewLoop->addBasicBlockToLoop(NewBB, *LI);
1084
1085 // Add DominatorTree node. After seeing all blocks, update to correct
1086 // IDom.
1087 DT->addNewBlock(NewBB, NewPH);
1088
1089 Blocks.push_back(NewBB);
1090 }
1091
1092 for (BasicBlock *BB : OrigLoop->getBlocks()) {
1093 // Update loop headers.
1094 Loop *CurLoop = LI->getLoopFor(BB);
1095 if (BB == CurLoop->getHeader())
1096 LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
1097
1098 // Update DominatorTree.
1099 BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
1101 cast<BasicBlock>(VMap[IDomBB]));
1102 }
1103
1104 // Move them physically from the end of the block list.
1105 F->splice(Before->getIterator(), F, NewPH->getIterator());
1106 F->splice(Before->getIterator(), F, NewLoop->getHeader()->getIterator(),
1107 F->end());
1108
1109 return NewLoop;
1110}
1111
1112/// Duplicate non-Phi instructions from the beginning of block up to
1113/// StopAt instruction into a split block between BB and its predecessor.
1115 BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
1116 ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
1117
1118 assert(count(successors(PredBB), BB) == 1 &&
1119 "There must be a single edge between PredBB and BB!");
1120 // We are going to have to map operands from the original BB block to the new
1121 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1122 // account for entry from PredBB.
1123 BasicBlock::iterator BI = BB->begin();
1124 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1125 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1126
1127 BasicBlock *NewBB = SplitEdge(PredBB, BB);
1128 NewBB->setName(PredBB->getName() + ".split");
1129 Instruction *NewTerm = NewBB->getTerminator();
1130
1131 // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
1132 // in the update set here.
1133 DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
1134 {DominatorTree::Insert, PredBB, NewBB},
1135 {DominatorTree::Insert, NewBB, BB}});
1136
1137 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1138 // mapping and using it to remap operands in the cloned instructions.
1139 // Stop once we see the terminator too. This covers the case where BB's
1140 // terminator gets replaced and StopAt == BB's terminator.
1141 for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
1142 Instruction *New = BI->clone();
1143 New->setName(BI->getName());
1144 New->insertBefore(NewTerm->getIterator());
1145 New->cloneDebugInfoFrom(&*BI);
1146 ValueMapping[&*BI] = New;
1147
1148 // Remap operands to patch up intra-block references.
1149 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1150 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1151 auto I = ValueMapping.find(Inst);
1152 if (I != ValueMapping.end())
1153 New->setOperand(i, I->second);
1154 }
1155
1156 // Remap debug variable operands.
1157 remapDebugVariable(ValueMapping, New);
1158 }
1159
1160 return NewBB;
1161}
1162
1163/// Create a clone of the scope \p SNANode in \p Domain, whose name is that of
1164/// the original scope extended with \p Ext.
1166 StringRef Ext, MDBuilder &MDB) {
1167 std::string Name;
1168 auto ScopeName = SNANode.getName();
1169 if (!ScopeName.empty())
1170 Name = (Twine(ScopeName) + ":" + Ext).str();
1171 else
1172 Name = std::string(Ext);
1173 return MDB.createAnonymousAliasScope(Domain, Name);
1174}
1175
1177 DenseMap<MDNode *, MDNode *> &ClonedScopes,
1179 StringRef Ext, LLVMContext &Context) {
1180 MDBuilder MDB(Context);
1181
1182 for (MDNode *ScopeList : NoAliasDeclScopes) {
1183 for (const MDOperand &MDOp : ScopeList->operands()) {
1184 if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1185 AliasScopeNode SNANode(MD);
1186
1187 // A cloned scope has to go into a clone of its domain if that domain
1188 // has disjoint scopes, otherwise the duplicated operations would become
1189 // implicitly noalias with the original accesses (that are still using
1190 // the original scope). We take care to duplicate all scopes of the
1191 // domain in cloned code, see adaptNoAliasScope.
1192 const MDNode *Domain = SNANode.getDomain();
1193 MDNode *NewDomain = const_cast<MDNode *>(Domain);
1194 if (AliasScopeDomainNode(Domain).hasDisjointScopes()) {
1195 MDNode *&ClonedDomain = ClonedDomains[Domain];
1196 if (!ClonedDomain)
1197 ClonedDomain = MDB.createAnonymousAliasScopeDomain(
1199 /*DisjointScopes=*/true);
1200 NewDomain = ClonedDomain;
1201 }
1202
1203 ClonedScopes.insert(std::make_pair(
1204 MD, createClonedScope(SNANode, NewDomain, Ext, MDB)));
1205 }
1206 }
1207 }
1208}
1209
1212 const DenseMap<const MDNode *, MDNode *> &ClonedDomains, StringRef Ext,
1213 LLVMContext &Context) {
1214 MDBuilder MDB(Context);
1215
1216 auto CloneScopeList = [&](const MDNode *ScopeList) -> MDNode * {
1217 bool NeedsReplacement = false;
1218 SmallVector<Metadata *, 8> NewScopeList;
1219 for (const MDOperand &MDOp : ScopeList->operands()) {
1220 if (MDNode *MD = dyn_cast<MDNode>(MDOp)) {
1221 MDNode *NewMD = ClonedScopes.lookup(MD);
1222 // Scopes must follow their domain if that domain is cloned, even if
1223 // there isn't an llvm.experimental.noalias.scope.decl for them.
1224 if (!NewMD && !ClonedDomains.empty()) {
1225 AliasScopeNode SNANode(MD);
1226 if (MDNode *NewDomain = ClonedDomains.lookup(SNANode.getDomain())) {
1227 NewMD = createClonedScope(SNANode, NewDomain, Ext, MDB);
1228 ClonedScopes[MD] = NewMD;
1229 }
1230 }
1231 if (NewMD) {
1232 NewScopeList.push_back(NewMD);
1233 NeedsReplacement = true;
1234 continue;
1235 }
1236 NewScopeList.push_back(MD);
1237 }
1238 }
1239 if (NeedsReplacement)
1240 return MDNode::get(Context, NewScopeList);
1241 return nullptr;
1242 };
1243
1244 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(I))
1245 if (MDNode *NewScopeList = CloneScopeList(Decl->getScopeList()))
1246 Decl->setScopeList(NewScopeList);
1247
1248 auto replaceWhenNeeded = [&](unsigned MD_ID) {
1249 if (const MDNode *CSNoAlias = I->getMetadata(MD_ID))
1250 if (MDNode *NewScopeList = CloneScopeList(CSNoAlias))
1251 I->setMetadata(MD_ID, NewScopeList);
1252 };
1253 replaceWhenNeeded(LLVMContext::MD_noalias);
1254 replaceWhenNeeded(LLVMContext::MD_alias_scope);
1255}
1256
1258 ArrayRef<BasicBlock *> NewBlocks,
1259 LLVMContext &Context, StringRef Ext) {
1260 if (NoAliasDeclScopes.empty())
1261 return;
1262
1263 DenseMap<MDNode *, MDNode *> ClonedScopes;
1265 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1266 << NoAliasDeclScopes.size() << " node(s)\n");
1267
1268 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, ClonedDomains, Ext,
1269 Context);
1270 // Identify instructions using metadata that needs adaptation
1271 for (BasicBlock *NewBlock : NewBlocks)
1272 for (Instruction &I : *NewBlock)
1273 adaptNoAliasScopes(&I, ClonedScopes, ClonedDomains, Ext, Context);
1274}
1275
1277 Instruction *IStart, Instruction *IEnd,
1278 LLVMContext &Context, StringRef Ext) {
1279 if (NoAliasDeclScopes.empty())
1280 return;
1281
1282 DenseMap<MDNode *, MDNode *> ClonedScopes;
1284 LLVM_DEBUG(dbgs() << "cloneAndAdaptNoAliasScopes: cloning "
1285 << NoAliasDeclScopes.size() << " node(s)\n");
1286
1287 cloneNoAliasScopes(NoAliasDeclScopes, ClonedScopes, ClonedDomains, Ext,
1288 Context);
1289 // Identify instructions using metadata that needs adaptation
1290 assert(IStart->getParent() == IEnd->getParent() && "different basic block ?");
1291 auto ItStart = IStart->getIterator();
1292 auto ItEnd = IEnd->getIterator();
1293 ++ItEnd; // IEnd is included, increment ItEnd to get the end of the range
1294 for (auto &I : llvm::make_range(ItStart, ItEnd))
1295 adaptNoAliasScopes(&I, ClonedScopes, ClonedDomains, Ext, Context);
1296}
1297
1299 ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1300 for (BasicBlock *BB : BBs)
1301 for (Instruction &I : *BB)
1302 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1303 NoAliasDeclScopes.push_back(Decl->getScopeList());
1304}
1305
1308 SmallVectorImpl<MDNode *> &NoAliasDeclScopes) {
1309 for (Instruction &I : make_range(Start, End))
1310 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1311 NoAliasDeclScopes.push_back(Decl->getScopeList());
1312}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static const Function * getParent(const Value *V)
static MDNode * createClonedScope(AliasScopeNode SNANode, MDNode *Domain, StringRef Ext, MDBuilder &MDB)
Create a clone of the scope SNANode in Domain, whose name is that of the original scope extended with...
static void foldPrunedTerminatorsAndMergeBlocks(Function *NewFunc, Function::iterator Begin)
static MetadataPredicate createIdentityMDPredicate(const Function &F, CloneFunctionChangeType Changes)
static void collectDebugInfoFromInstructions(const Function &F, DebugInfoFinder &DIFinder)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
static std::string getDescription(const Loop &L)
Definition LoopPass.cpp:378
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
SmallVector< MachineOperand, 4 > Cond
This file defines less commonly used SmallVector utilities.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Wrapper around alias scope domain metedata to allow accessing their fields, including surfacing the o...
Definition Metadata.h:1612
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Definition Metadata.h:1642
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition Metadata.h:1653
StringRef getName() const
Definition Metadata.h:1658
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:463
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition BasicBlock.h:367
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
Subprogram description. Uses SubclassData1.
static LLVM_ABI DILocalScope * getRetainedNodeScope(MDNode *N)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Utility to find all debug info in a module.
Definition DebugInfo.h:102
LLVM_ABI void processInstruction(const Module &M, const Instruction &I)
Process a single instruction and collect debug info anchors.
iterator_range< compile_unit_iterator > compile_units() const
Definition DebugInfo.h:148
A debug info location.
Definition DebugLoc.h:127
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Class to represent function types.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
const BasicBlock & getEntryBlock() const
Definition Function.h:803
BasicBlockListType::iterator iterator
Definition Function.h:70
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:356
const BasicBlock & front() const
Definition Function.h:854
iterator_range< arg_iterator > args()
Definition Function.h:886
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPrefixData() const
Check whether this function has prefix data.
Definition Function.h:908
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:899
Constant * getPrologueData() const
Get the prologue data associated with this function.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setPersonalityFn(Constant *Fn)
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
arg_iterator arg_begin()
Definition Function.h:862
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:332
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
size_t arg_size() const
Definition Function.h:895
void setPrologueData(Constant *PrologueData)
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
Definition Function.cpp:709
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
Constant * getPrefixData() const
Get the prefix data associated with this function.
iterator end()
Definition Function.h:849
bool hasPrologueData() const
Check whether this function has prologue data.
Definition Function.h:917
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:846
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
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...
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition MDBuilder.h:195
LLVM_ABI MDNode * createAnonymousAliasScopeDomain(StringRef Description=StringRef(), bool DisjointScopes=false)
Return metadata appropriate for an alias scope domain node, described by Description,...
Metadata node.
Definition Metadata.h:1087
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:327
A tuple of MDNodes.
Definition Metadata.h:1806
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
LLVM_ABI void addOperand(MDNode *M)
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
void setIncomingBlock(unsigned i, BasicBlock *BB)
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Return a value (possibly void), from a function.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
CaseHandleImpl< const SwitchInst, const ConstantInt, const BasicBlock > ConstCaseHandle
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition ValueMapper.h:45
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:167
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition ValueMap.h:156
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator end()
Definition ValueMap.h:139
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
Definition ValueMap.h:123
Context for (re-)mapping values (and metadata).
LLVM_ABI void remapInstruction(Instruction &I)
This is a class that can be implemented by clients to materialize Values on demand.
Definition ValueMapper.h:58
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void CloneFunctionAttributesInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc's attributes into NewFunc, transforming values based on the mappings in VMap.
std::function< bool(const Metadata *)> MetadataPredicate
Definition ValueMapper.h:41
LLVM_ABI 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:133
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
constexpr from_range_t from_range
LLVM_ABI void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix, ClonedCodeInfo &CodeInfo)
This works exactly like CloneFunctionInto, except that it does some simple constant prop and DCE on t...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
Definition Local.cpp:3555
auto cast_or_null(const Y &Val)
Definition Casting.h:714
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI 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...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void CloneFunctionMetadataInto(Function &NewFunc, const Function &OldFunc, ValueToValueMapTy &VMap, RemapFlags RemapFlag, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Clone OldFunc's metadata into NewFunc.
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI 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:408
LLVM_ABI Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
RemapFlags
These are flags that the value mapping APIs allow.
Definition ValueMapper.h:74
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_None
Definition ValueMapper.h:75
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Intrinsic::ID getConstrainedIntrinsicID(const Instruction &Instr)
Returns constrained intrinsic id to represent the given instruction in strictfp function.
Definition FPEnv.cpp:80
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void cloneNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, DenseMap< MDNode *, MDNode * > &ClonedScopes, DenseMap< const MDNode *, MDNode * > &ClonedDomains, StringRef Ext, LLVMContext &Context)
Duplicate the specified list of noalias decl scopes.
LLVM_ABI void CloneFunctionBodyInto(Function &NewFunc, const Function &OldFunc, ValueToValueMapTy &VMap, RemapFlags RemapFlag, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Clone OldFunc's body into NewFunc.
LLVM_ABI void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, const Instruction *StartingInst, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix, ClonedCodeInfo &CodeInfo)
This works like CloneAndPruneFunctionInto, except that it does not clone the entire function.
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:2028
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
CloneFunctionChangeType
Definition Cloning.h:161
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI 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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Look up or compute a value in the value map.
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI void adaptNoAliasScopes(llvm::Instruction *I, DenseMap< MDNode *, MDNode * > &ClonedScopes, const DenseMap< const MDNode *, MDNode * > &ClonedDomains, StringRef Ext, LLVMContext &Context)
Adapt the metadata for the specified instruction according to the provided mapping.
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
LLVM_ABI 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...
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Lookup or compute a mapping for a piece of metadata.
#define N
This struct can be used to capture information about code being cloned, while it is being cloned.
Definition Cloning.h:69
bool ContainsDynamicAllocas
This is set to true if the cloned code contains a 'dynamic' alloca.
Definition Cloning.h:80
bool ContainsCalls
This is set to true if the cloned code contains a normal call instruction.
Definition Cloning.h:71
bool ContainsMemProfMetadata
This is set to true if there is memprof related metadata (memprof or callsite metadata) in the cloned...
Definition Cloning.h:75
SmallSetVector< const Value *, 4 > OriginallyIndirectCalls
Definition Cloning.h:94
DenseMap< const Value *, const Value * > OrigVMap
Like VMap, but maps only unsimplified instructions.
Definition Cloning.h:90
std::vector< WeakTrackingVH > OperandBundleCallSites
All cloned call sites that have operand bundles attached are appended to this vector.
Definition Cloning.h:85