1 //===- Local.cpp - Functions to perform local transformations -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This family of functions perform various local transformations to the
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/TinyPtrVector.h"
28 #include "llvm/Analysis/AssumeBundleQueries.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/DomTreeUpdater.h"
31 #include "llvm/Analysis/EHPersonalities.h"
32 #include "llvm/Analysis/InstructionSimplify.h"
33 #include "llvm/Analysis/LazyValueInfo.h"
34 #include "llvm/Analysis/MemoryBuiltins.h"
35 #include "llvm/Analysis/MemorySSAUpdater.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Analysis/VectorUtils.h"
39 #include "llvm/BinaryFormat/Dwarf.h"
40 #include "llvm/IR/Argument.h"
41 #include "llvm/IR/Attributes.h"
42 #include "llvm/IR/BasicBlock.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Constant.h"
45 #include "llvm/IR/ConstantRange.h"
46 #include "llvm/IR/Constants.h"
47 #include "llvm/IR/DIBuilder.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Dominators.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalObject.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/InstrTypes.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/Intrinsics.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/MDBuilder.h"
64 #include "llvm/IR/Metadata.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #include "llvm/Support/Casting.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/KnownBits.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
79 #include "llvm/Transforms/Utils/ValueMapper.h"
89 using namespace llvm::PatternMatch;
91 #define DEBUG_TYPE "local"
93 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
95 // Max recursion depth for collectBitParts used when detecting bswap and
97 static const unsigned BitPartRecursionMaxDepth = 64;
99 //===----------------------------------------------------------------------===//
100 // Local constant propagation.
103 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
104 /// constant value, convert it into an unconditional branch to the constant
105 /// destination. This is a nontrivial operation because the successors of this
106 /// basic block must have their PHI nodes updated.
107 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
108 /// conditions and indirectbr addresses this might make dead if
109 /// DeleteDeadConditions is true.
110 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
111 const TargetLibraryInfo *TLI,
112 DomTreeUpdater *DTU) {
113 Instruction *T = BB->getTerminator();
114 IRBuilder<> Builder(T);
116 // Branch - See if we are conditional jumping on constant
117 if (auto *BI = dyn_cast<BranchInst>(T)) {
118 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
119 BasicBlock *Dest1 = BI->getSuccessor(0);
120 BasicBlock *Dest2 = BI->getSuccessor(1);
122 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
123 // Are we branching on constant?
124 // YES. Change to unconditional branch...
125 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
126 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
128 // Let the basic block know that we are letting go of it. Based on this,
129 // it will adjust it's PHI nodes.
130 OldDest->removePredecessor(BB);
132 // Replace the conditional branch with an unconditional one.
133 Builder.CreateBr(Destination);
134 BI->eraseFromParent();
136 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, OldDest}});
140 if (Dest2 == Dest1) { // Conditional branch to same location?
141 // This branch matches something like this:
142 // br bool %cond, label %Dest, label %Dest
143 // and changes it into: br label %Dest
145 // Let the basic block know that we are letting go of one copy of it.
146 assert(BI->getParent() && "Terminator not inserted in block!");
147 Dest1->removePredecessor(BI->getParent());
149 // Replace the conditional branch with an unconditional one.
150 Builder.CreateBr(Dest1);
151 Value *Cond = BI->getCondition();
152 BI->eraseFromParent();
153 if (DeleteDeadConditions)
154 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
160 if (auto *SI = dyn_cast<SwitchInst>(T)) {
161 // If we are switching on a constant, we can convert the switch to an
162 // unconditional branch.
163 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
164 BasicBlock *DefaultDest = SI->getDefaultDest();
165 BasicBlock *TheOnlyDest = DefaultDest;
167 // If the default is unreachable, ignore it when searching for TheOnlyDest.
168 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
169 SI->getNumCases() > 0) {
170 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
173 // Figure out which case it goes to.
174 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
175 // Found case matching a constant operand?
176 if (i->getCaseValue() == CI) {
177 TheOnlyDest = i->getCaseSuccessor();
181 // Check to see if this branch is going to the same place as the default
182 // dest. If so, eliminate it as an explicit compare.
183 if (i->getCaseSuccessor() == DefaultDest) {
184 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
185 unsigned NCases = SI->getNumCases();
186 // Fold the case metadata into the default if there will be any branches
187 // left, unless the metadata doesn't match the switch.
188 if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
189 // Collect branch weights into a vector.
190 SmallVector<uint32_t, 8> Weights;
191 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
193 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
194 Weights.push_back(CI->getValue().getZExtValue());
196 // Merge weight of this case to the default weight.
197 unsigned idx = i->getCaseIndex();
198 Weights[0] += Weights[idx+1];
199 // Remove weight for this case.
200 std::swap(Weights[idx+1], Weights.back());
202 SI->setMetadata(LLVMContext::MD_prof,
203 MDBuilder(BB->getContext()).
204 createBranchWeights(Weights));
206 // Remove this entry.
207 BasicBlock *ParentBB = SI->getParent();
208 DefaultDest->removePredecessor(ParentBB);
209 i = SI->removeCase(i);
212 DTU->applyUpdatesPermissive(
213 {{DominatorTree::Delete, ParentBB, DefaultDest}});
217 // Otherwise, check to see if the switch only branches to one destination.
218 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
220 if (i->getCaseSuccessor() != TheOnlyDest)
221 TheOnlyDest = nullptr;
223 // Increment this iterator as we haven't removed the case.
227 if (CI && !TheOnlyDest) {
228 // Branching on a constant, but not any of the cases, go to the default
230 TheOnlyDest = SI->getDefaultDest();
233 // If we found a single destination that we can fold the switch into, do so
236 // Insert the new branch.
237 Builder.CreateBr(TheOnlyDest);
238 BasicBlock *BB = SI->getParent();
239 std::vector <DominatorTree::UpdateType> Updates;
241 Updates.reserve(SI->getNumSuccessors() - 1);
243 // Remove entries from PHI nodes which we no longer branch to...
244 for (BasicBlock *Succ : successors(SI)) {
245 // Found case matching a constant operand?
246 if (Succ == TheOnlyDest) {
247 TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
249 Succ->removePredecessor(BB);
251 Updates.push_back({DominatorTree::Delete, BB, Succ});
255 // Delete the old switch.
256 Value *Cond = SI->getCondition();
257 SI->eraseFromParent();
258 if (DeleteDeadConditions)
259 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
261 DTU->applyUpdatesPermissive(Updates);
265 if (SI->getNumCases() == 1) {
266 // Otherwise, we can fold this switch into a conditional branch
267 // instruction if it has only one non-default destination.
268 auto FirstCase = *SI->case_begin();
269 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
270 FirstCase.getCaseValue(), "cond");
272 // Insert the new branch.
273 BranchInst *NewBr = Builder.CreateCondBr(Cond,
274 FirstCase.getCaseSuccessor(),
275 SI->getDefaultDest());
276 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
277 if (MD && MD->getNumOperands() == 3) {
278 ConstantInt *SICase =
279 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
281 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
282 assert(SICase && SIDef);
283 // The TrueWeight should be the weight for the single case of SI.
284 NewBr->setMetadata(LLVMContext::MD_prof,
285 MDBuilder(BB->getContext()).
286 createBranchWeights(SICase->getValue().getZExtValue(),
287 SIDef->getValue().getZExtValue()));
290 // Update make.implicit metadata to the newly-created conditional branch.
291 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
293 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
295 // Delete the old switch.
296 SI->eraseFromParent();
302 if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
303 // indirectbr blockaddress(@F, @BB) -> br label @BB
305 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
306 BasicBlock *TheOnlyDest = BA->getBasicBlock();
307 std::vector <DominatorTree::UpdateType> Updates;
309 Updates.reserve(IBI->getNumDestinations() - 1);
311 // Insert the new branch.
312 Builder.CreateBr(TheOnlyDest);
314 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
315 if (IBI->getDestination(i) == TheOnlyDest) {
316 TheOnlyDest = nullptr;
318 BasicBlock *ParentBB = IBI->getParent();
319 BasicBlock *DestBB = IBI->getDestination(i);
320 DestBB->removePredecessor(ParentBB);
322 Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
325 Value *Address = IBI->getAddress();
326 IBI->eraseFromParent();
327 if (DeleteDeadConditions)
328 // Delete pointer cast instructions.
329 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
331 // Also zap the blockaddress constant if there are no users remaining,
332 // otherwise the destination is still marked as having its address taken.
334 BA->destroyConstant();
336 // If we didn't find our destination in the IBI successor list, then we
337 // have undefined behavior. Replace the unconditional branch with an
338 // 'unreachable' instruction.
340 BB->getTerminator()->eraseFromParent();
341 new UnreachableInst(BB->getContext(), BB);
345 DTU->applyUpdatesPermissive(Updates);
353 //===----------------------------------------------------------------------===//
354 // Local dead code elimination.
357 /// isInstructionTriviallyDead - Return true if the result produced by the
358 /// instruction is not used, and the instruction has no side effects.
360 bool llvm::isInstructionTriviallyDead(Instruction *I,
361 const TargetLibraryInfo *TLI) {
364 return wouldInstructionBeTriviallyDead(I, TLI);
367 bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
368 const TargetLibraryInfo *TLI) {
369 if (I->isTerminator())
372 // We don't want the landingpad-like instructions removed by anything this
377 // We don't want debug info removed by anything this general, unless
378 // debug info is empty.
379 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
380 if (DDI->getAddress())
384 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
389 if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
395 if (!I->mayHaveSideEffects())
398 // Special case intrinsics that "may have side effects" but can be deleted
400 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
401 // Safe to delete llvm.stacksave and launder.invariant.group if dead.
402 if (II->getIntrinsicID() == Intrinsic::stacksave ||
403 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
406 if (II->isLifetimeStartOrEnd()) {
407 auto *Arg = II->getArgOperand(1);
408 // Lifetime intrinsics are dead when their right-hand is undef.
409 if (isa<UndefValue>(Arg))
411 // If the right-hand is an alloc, global, or argument and the only uses
412 // are lifetime intrinsics then the intrinsics are dead.
413 if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))
414 return llvm::all_of(Arg->uses(), [](Use &Use) {
415 if (IntrinsicInst *IntrinsicUse =
416 dyn_cast<IntrinsicInst>(Use.getUser()))
417 return IntrinsicUse->isLifetimeStartOrEnd();
423 // Assumptions are dead if their condition is trivially true. Guards on
424 // true are operationally no-ops. In the future we can consider more
425 // sophisticated tradeoffs for guards considering potential for check
426 // widening, but for now we keep things simple.
427 if ((II->getIntrinsicID() == Intrinsic::assume &&
428 isAssumeWithEmptyBundle(*II)) ||
429 II->getIntrinsicID() == Intrinsic::experimental_guard) {
430 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
431 return !Cond->isZero();
437 if (isAllocLikeFn(I, TLI))
440 if (CallInst *CI = isFreeCall(I, TLI))
441 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
442 return C->isNullValue() || isa<UndefValue>(C);
444 if (auto *Call = dyn_cast<CallBase>(I))
445 if (isMathLibCallNoop(Call, TLI))
451 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
452 /// trivially dead instruction, delete it. If that makes any of its operands
453 /// trivially dead, delete them too, recursively. Return true if any
454 /// instructions were deleted.
455 bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
456 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
457 Instruction *I = dyn_cast<Instruction>(V);
458 if (!I || !isInstructionTriviallyDead(I, TLI))
461 SmallVector<WeakTrackingVH, 16> DeadInsts;
462 DeadInsts.push_back(I);
463 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
468 bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
469 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
470 MemorySSAUpdater *MSSAU) {
471 unsigned S = 0, E = DeadInsts.size(), Alive = 0;
472 for (; S != E; ++S) {
473 auto *I = cast<Instruction>(DeadInsts[S]);
474 if (!isInstructionTriviallyDead(I)) {
475 DeadInsts[S] = nullptr;
481 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
485 void llvm::RecursivelyDeleteTriviallyDeadInstructions(
486 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
487 MemorySSAUpdater *MSSAU) {
488 // Process the dead instruction list until empty.
489 while (!DeadInsts.empty()) {
490 Value *V = DeadInsts.pop_back_val();
491 Instruction *I = cast_or_null<Instruction>(V);
494 assert(isInstructionTriviallyDead(I, TLI) &&
495 "Live instruction found in dead worklist!");
496 assert(I->use_empty() && "Instructions with uses are not dead.");
498 // Don't lose the debug info while deleting the instructions.
499 salvageDebugInfo(*I);
501 // Null out all of the instruction's operands to see if any operand becomes
503 for (Use &OpU : I->operands()) {
504 Value *OpV = OpU.get();
507 if (!OpV->use_empty())
510 // If the operand is an instruction that became dead as we nulled out the
511 // operand, and if it is 'trivially' dead, delete it in a future loop
513 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
514 if (isInstructionTriviallyDead(OpI, TLI))
515 DeadInsts.push_back(OpI);
518 MSSAU->removeMemoryAccess(I);
520 I->eraseFromParent();
524 bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
525 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
526 findDbgUsers(DbgUsers, I);
527 for (auto *DII : DbgUsers) {
528 Value *Undef = UndefValue::get(I->getType());
529 DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
530 ValueAsMetadata::get(Undef)));
532 return !DbgUsers.empty();
535 /// areAllUsesEqual - Check whether the uses of a value are all the same.
536 /// This is similar to Instruction::hasOneUse() except this will also return
537 /// true when there are no uses or multiple uses that all refer to the same
539 static bool areAllUsesEqual(Instruction *I) {
540 Value::user_iterator UI = I->user_begin();
541 Value::user_iterator UE = I->user_end();
546 for (++UI; UI != UE; ++UI) {
553 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
554 /// dead PHI node, due to being a def-use chain of single-use nodes that
555 /// either forms a cycle or is terminated by a trivially dead instruction,
556 /// delete it. If that makes any of its operands trivially dead, delete them
557 /// too, recursively. Return true if a change was made.
558 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
559 const TargetLibraryInfo *TLI,
560 llvm::MemorySSAUpdater *MSSAU) {
561 SmallPtrSet<Instruction*, 4> Visited;
562 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
563 I = cast<Instruction>(*I->user_begin())) {
565 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
567 // If we find an instruction more than once, we're on a cycle that
568 // won't prove fruitful.
569 if (!Visited.insert(I).second) {
570 // Break the cycle and delete the instruction and its operands.
571 I->replaceAllUsesWith(UndefValue::get(I->getType()));
572 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
580 simplifyAndDCEInstruction(Instruction *I,
581 SmallSetVector<Instruction *, 16> &WorkList,
582 const DataLayout &DL,
583 const TargetLibraryInfo *TLI) {
584 if (isInstructionTriviallyDead(I, TLI)) {
585 salvageDebugInfo(*I);
587 // Null out all of the instruction's operands to see if any operand becomes
589 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
590 Value *OpV = I->getOperand(i);
591 I->setOperand(i, nullptr);
593 if (!OpV->use_empty() || I == OpV)
596 // If the operand is an instruction that became dead as we nulled out the
597 // operand, and if it is 'trivially' dead, delete it in a future loop
599 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
600 if (isInstructionTriviallyDead(OpI, TLI))
601 WorkList.insert(OpI);
604 I->eraseFromParent();
609 if (Value *SimpleV = SimplifyInstruction(I, DL)) {
610 // Add the users to the worklist. CAREFUL: an instruction can use itself,
611 // in the case of a phi node.
612 for (User *U : I->users()) {
614 WorkList.insert(cast<Instruction>(U));
618 // Replace the instruction with its simplified value.
619 bool Changed = false;
620 if (!I->use_empty()) {
621 I->replaceAllUsesWith(SimpleV);
624 if (isInstructionTriviallyDead(I, TLI)) {
625 I->eraseFromParent();
633 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
634 /// simplify any instructions in it and recursively delete dead instructions.
636 /// This returns true if it changed the code, note that it can delete
637 /// instructions in other blocks as well in this block.
638 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
639 const TargetLibraryInfo *TLI) {
640 bool MadeChange = false;
641 const DataLayout &DL = BB->getModule()->getDataLayout();
644 // In debug builds, ensure that the terminator of the block is never replaced
645 // or deleted by these simplifications. The idea of simplification is that it
646 // cannot introduce new instructions, and there is no way to replace the
647 // terminator of a block without introducing a new instruction.
648 AssertingVH<Instruction> TerminatorVH(&BB->back());
651 SmallSetVector<Instruction *, 16> WorkList;
652 // Iterate over the original function, only adding insts to the worklist
653 // if they actually need to be revisited. This avoids having to pre-init
654 // the worklist with the entire function's worth of instructions.
655 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
657 assert(!BI->isTerminator());
658 Instruction *I = &*BI;
661 // We're visiting this instruction now, so make sure it's not in the
662 // worklist from an earlier visit.
663 if (!WorkList.count(I))
664 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
667 while (!WorkList.empty()) {
668 Instruction *I = WorkList.pop_back_val();
669 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
674 //===----------------------------------------------------------------------===//
675 // Control Flow Graph Restructuring.
678 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
679 DomTreeUpdater *DTU) {
680 // This only adjusts blocks with PHI nodes.
681 if (!isa<PHINode>(BB->begin()))
684 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
685 // them down. This will leave us with single entry phi nodes and other phis
686 // that can be removed.
687 BB->removePredecessor(Pred, true);
689 WeakTrackingVH PhiIt = &BB->front();
690 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
691 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
692 Value *OldPhiIt = PhiIt;
694 if (!recursivelySimplifyInstruction(PN))
697 // If recursive simplification ended up deleting the next PHI node we would
698 // iterate to, then our iterator is invalid, restart scanning from the top
700 if (PhiIt != OldPhiIt) PhiIt = &BB->front();
703 DTU->applyUpdatesPermissive({{DominatorTree::Delete, Pred, BB}});
706 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
707 DomTreeUpdater *DTU) {
709 // If BB has single-entry PHI nodes, fold them.
710 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
711 Value *NewVal = PN->getIncomingValue(0);
712 // Replace self referencing PHI with undef, it must be dead.
713 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
714 PN->replaceAllUsesWith(NewVal);
715 PN->eraseFromParent();
718 BasicBlock *PredBB = DestBB->getSinglePredecessor();
719 assert(PredBB && "Block doesn't have a single predecessor!");
721 bool ReplaceEntryBB = false;
722 if (PredBB == &DestBB->getParent()->getEntryBlock())
723 ReplaceEntryBB = true;
725 // DTU updates: Collect all the edges that enter
726 // PredBB. These dominator edges will be redirected to DestBB.
727 SmallVector<DominatorTree::UpdateType, 32> Updates;
730 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
731 for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
732 Updates.push_back({DominatorTree::Delete, *I, PredBB});
733 // This predecessor of PredBB may already have DestBB as a successor.
734 if (llvm::find(successors(*I), DestBB) == succ_end(*I))
735 Updates.push_back({DominatorTree::Insert, *I, DestBB});
739 // Zap anything that took the address of DestBB. Not doing this will give the
740 // address an invalid value.
741 if (DestBB->hasAddressTaken()) {
742 BlockAddress *BA = BlockAddress::get(DestBB);
743 Constant *Replacement =
744 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
745 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
747 BA->destroyConstant();
750 // Anything that branched to PredBB now branches to DestBB.
751 PredBB->replaceAllUsesWith(DestBB);
753 // Splice all the instructions from PredBB to DestBB.
754 PredBB->getTerminator()->eraseFromParent();
755 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
756 new UnreachableInst(PredBB->getContext(), PredBB);
758 // If the PredBB is the entry block of the function, move DestBB up to
759 // become the entry block after we erase PredBB.
761 DestBB->moveAfter(PredBB);
764 assert(PredBB->getInstList().size() == 1 &&
765 isa<UnreachableInst>(PredBB->getTerminator()) &&
766 "The successor list of PredBB isn't empty before "
767 "applying corresponding DTU updates.");
768 DTU->applyUpdatesPermissive(Updates);
769 DTU->deleteBB(PredBB);
770 // Recalculation of DomTree is needed when updating a forward DomTree and
771 // the Entry BB is replaced.
772 if (ReplaceEntryBB && DTU->hasDomTree()) {
773 // The entry block was removed and there is no external interface for
774 // the dominator tree to be notified of this change. In this corner-case
775 // we recalculate the entire tree.
776 DTU->recalculate(*(DestBB->getParent()));
781 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
785 /// Return true if we can choose one of these values to use in place of the
786 /// other. Note that we will always choose the non-undef value to keep.
787 static bool CanMergeValues(Value *First, Value *Second) {
788 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
791 /// Return true if we can fold BB, an almost-empty BB ending in an unconditional
792 /// branch to Succ, into Succ.
794 /// Assumption: Succ is the single successor for BB.
795 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
796 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
798 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
799 << Succ->getName() << "\n");
800 // Shortcut, if there is only a single predecessor it must be BB and merging
802 if (Succ->getSinglePredecessor()) return true;
804 // Make a list of the predecessors of BB
805 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
807 // Look at all the phi nodes in Succ, to see if they present a conflict when
808 // merging these blocks
809 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
810 PHINode *PN = cast<PHINode>(I);
812 // If the incoming value from BB is again a PHINode in
813 // BB which has the same incoming value for *PI as PN does, we can
814 // merge the phi nodes and then the blocks can still be merged
815 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
816 if (BBPN && BBPN->getParent() == BB) {
817 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
818 BasicBlock *IBB = PN->getIncomingBlock(PI);
819 if (BBPreds.count(IBB) &&
820 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
821 PN->getIncomingValue(PI))) {
823 << "Can't fold, phi node " << PN->getName() << " in "
824 << Succ->getName() << " is conflicting with "
825 << BBPN->getName() << " with regard to common predecessor "
826 << IBB->getName() << "\n");
831 Value* Val = PN->getIncomingValueForBlock(BB);
832 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
833 // See if the incoming value for the common predecessor is equal to the
834 // one for BB, in which case this phi node will not prevent the merging
836 BasicBlock *IBB = PN->getIncomingBlock(PI);
837 if (BBPreds.count(IBB) &&
838 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
839 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
840 << " in " << Succ->getName()
841 << " is conflicting with regard to common "
842 << "predecessor " << IBB->getName() << "\n");
852 using PredBlockVector = SmallVector<BasicBlock *, 16>;
853 using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
855 /// Determines the value to use as the phi node input for a block.
857 /// Select between \p OldVal any value that we know flows from \p BB
858 /// to a particular phi on the basis of which one (if either) is not
859 /// undef. Update IncomingValues based on the selected value.
861 /// \param OldVal The value we are considering selecting.
862 /// \param BB The block that the value flows in from.
863 /// \param IncomingValues A map from block-to-value for other phi inputs
864 /// that we have examined.
866 /// \returns the selected value.
867 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
868 IncomingValueMap &IncomingValues) {
869 if (!isa<UndefValue>(OldVal)) {
870 assert((!IncomingValues.count(BB) ||
871 IncomingValues.find(BB)->second == OldVal) &&
872 "Expected OldVal to match incoming value from BB!");
874 IncomingValues.insert(std::make_pair(BB, OldVal));
878 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
879 if (It != IncomingValues.end()) return It->second;
884 /// Create a map from block to value for the operands of a
887 /// Create a map from block to value for each non-undef value flowing
890 /// \param PN The phi we are collecting the map for.
891 /// \param IncomingValues [out] The map from block to value for this phi.
892 static void gatherIncomingValuesToPhi(PHINode *PN,
893 IncomingValueMap &IncomingValues) {
894 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
895 BasicBlock *BB = PN->getIncomingBlock(i);
896 Value *V = PN->getIncomingValue(i);
898 if (!isa<UndefValue>(V))
899 IncomingValues.insert(std::make_pair(BB, V));
903 /// Replace the incoming undef values to a phi with the values
904 /// from a block-to-value map.
906 /// \param PN The phi we are replacing the undefs in.
907 /// \param IncomingValues A map from block to value.
908 static void replaceUndefValuesInPhi(PHINode *PN,
909 const IncomingValueMap &IncomingValues) {
910 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
911 Value *V = PN->getIncomingValue(i);
913 if (!isa<UndefValue>(V)) continue;
915 BasicBlock *BB = PN->getIncomingBlock(i);
916 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
917 if (It == IncomingValues.end()) continue;
919 PN->setIncomingValue(i, It->second);
923 /// Replace a value flowing from a block to a phi with
924 /// potentially multiple instances of that value flowing from the
925 /// block's predecessors to the phi.
927 /// \param BB The block with the value flowing into the phi.
928 /// \param BBPreds The predecessors of BB.
929 /// \param PN The phi that we are updating.
930 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
931 const PredBlockVector &BBPreds,
933 Value *OldVal = PN->removeIncomingValue(BB, false);
934 assert(OldVal && "No entry in PHI for Pred BB!");
936 IncomingValueMap IncomingValues;
938 // We are merging two blocks - BB, and the block containing PN - and
939 // as a result we need to redirect edges from the predecessors of BB
940 // to go to the block containing PN, and update PN
941 // accordingly. Since we allow merging blocks in the case where the
942 // predecessor and successor blocks both share some predecessors,
943 // and where some of those common predecessors might have undef
944 // values flowing into PN, we want to rewrite those values to be
945 // consistent with the non-undef values.
947 gatherIncomingValuesToPhi(PN, IncomingValues);
949 // If this incoming value is one of the PHI nodes in BB, the new entries
950 // in the PHI node are the entries from the old PHI.
951 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
952 PHINode *OldValPN = cast<PHINode>(OldVal);
953 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
954 // Note that, since we are merging phi nodes and BB and Succ might
955 // have common predecessors, we could end up with a phi node with
956 // identical incoming branches. This will be cleaned up later (and
957 // will trigger asserts if we try to clean it up now, without also
958 // simplifying the corresponding conditional branch).
959 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
960 Value *PredVal = OldValPN->getIncomingValue(i);
961 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
964 // And add a new incoming value for this predecessor for the
965 // newly retargeted branch.
966 PN->addIncoming(Selected, PredBB);
969 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
970 // Update existing incoming values in PN for this
971 // predecessor of BB.
972 BasicBlock *PredBB = BBPreds[i];
973 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
976 // And add a new incoming value for this predecessor for the
977 // newly retargeted branch.
978 PN->addIncoming(Selected, PredBB);
982 replaceUndefValuesInPhi(PN, IncomingValues);
985 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
986 DomTreeUpdater *DTU) {
987 assert(BB != &BB->getParent()->getEntryBlock() &&
988 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
990 // We can't eliminate infinite loops.
991 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
992 if (BB == Succ) return false;
994 // Check to see if merging these blocks would cause conflicts for any of the
995 // phi nodes in BB or Succ. If not, we can safely merge.
996 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
998 // Check for cases where Succ has multiple predecessors and a PHI node in BB
999 // has uses which will not disappear when the PHI nodes are merged. It is
1000 // possible to handle such cases, but difficult: it requires checking whether
1001 // BB dominates Succ, which is non-trivial to calculate in the case where
1002 // Succ has multiple predecessors. Also, it requires checking whether
1003 // constructing the necessary self-referential PHI node doesn't introduce any
1004 // conflicts; this isn't too difficult, but the previous code for doing this
1007 // Note that if this check finds a live use, BB dominates Succ, so BB is
1008 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
1009 // folding the branch isn't profitable in that case anyway.
1010 if (!Succ->getSinglePredecessor()) {
1011 BasicBlock::iterator BBI = BB->begin();
1012 while (isa<PHINode>(*BBI)) {
1013 for (Use &U : BBI->uses()) {
1014 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
1015 if (PN->getIncomingBlock(U) != BB)
1025 // We cannot fold the block if it's a branch to an already present callbr
1026 // successor because that creates duplicate successors.
1027 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1028 if (auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) {
1029 if (Succ == CBI->getDefaultDest())
1031 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
1032 if (Succ == CBI->getIndirectDest(i))
1037 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
1039 SmallVector<DominatorTree::UpdateType, 32> Updates;
1041 Updates.push_back({DominatorTree::Delete, BB, Succ});
1042 // All predecessors of BB will be moved to Succ.
1043 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1044 Updates.push_back({DominatorTree::Delete, *I, BB});
1045 // This predecessor of BB may already have Succ as a successor.
1046 if (llvm::find(successors(*I), Succ) == succ_end(*I))
1047 Updates.push_back({DominatorTree::Insert, *I, Succ});
1051 if (isa<PHINode>(Succ->begin())) {
1052 // If there is more than one pred of succ, and there are PHI nodes in
1053 // the successor, then we need to add incoming edges for the PHI nodes
1055 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
1057 // Loop over all of the PHI nodes in the successor of BB.
1058 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1059 PHINode *PN = cast<PHINode>(I);
1061 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
1065 if (Succ->getSinglePredecessor()) {
1066 // BB is the only predecessor of Succ, so Succ will end up with exactly
1067 // the same predecessors BB had.
1069 // Copy over any phi, debug or lifetime instruction.
1070 BB->getTerminator()->eraseFromParent();
1071 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
1074 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1075 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
1076 assert(PN->use_empty() && "There shouldn't be any uses here!");
1077 PN->eraseFromParent();
1081 // If the unconditional branch we replaced contains llvm.loop metadata, we
1082 // add the metadata to the branch instructions in the predecessors.
1083 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
1084 Instruction *TI = BB->getTerminator();
1086 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
1087 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1088 BasicBlock *Pred = *PI;
1089 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
1092 // Everything that jumped to BB now goes to Succ.
1093 BB->replaceAllUsesWith(Succ);
1094 if (!Succ->hasName()) Succ->takeName(BB);
1096 // Clear the successor list of BB to match updates applying to DTU later.
1097 if (BB->getTerminator())
1098 BB->getInstList().pop_back();
1099 new UnreachableInst(BB->getContext(), BB);
1100 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1101 "applying corresponding DTU updates.");
1104 DTU->applyUpdatesPermissive(Updates);
1107 BB->eraseFromParent(); // Delete the old basic block.
1112 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1113 // This implementation doesn't currently consider undef operands
1114 // specially. Theoretically, two phis which are identical except for
1115 // one having an undef where the other doesn't could be collapsed.
1117 struct PHIDenseMapInfo {
1118 static PHINode *getEmptyKey() {
1119 return DenseMapInfo<PHINode *>::getEmptyKey();
1122 static PHINode *getTombstoneKey() {
1123 return DenseMapInfo<PHINode *>::getTombstoneKey();
1126 static unsigned getHashValue(PHINode *PN) {
1127 // Compute a hash value on the operands. Instcombine will likely have
1128 // sorted them, which helps expose duplicates, but we have to check all
1129 // the operands to be safe in case instcombine hasn't run.
1130 return static_cast<unsigned>(hash_combine(
1131 hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1132 hash_combine_range(PN->block_begin(), PN->block_end())));
1135 static bool isEqual(PHINode *LHS, PHINode *RHS) {
1136 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1137 RHS == getEmptyKey() || RHS == getTombstoneKey())
1139 return LHS->isIdenticalTo(RHS);
1143 // Set of unique PHINodes.
1144 DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1146 // Examine each PHI.
1147 bool Changed = false;
1148 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1149 auto Inserted = PHISet.insert(PN);
1150 if (!Inserted.second) {
1151 // A duplicate. Replace this PHI with its duplicate.
1152 PN->replaceAllUsesWith(*Inserted.first);
1153 PN->eraseFromParent();
1156 // The RAUW can change PHIs that we already visited. Start over from the
1166 /// enforceKnownAlignment - If the specified pointer points to an object that
1167 /// we control, modify the object's alignment to PrefAlign. This isn't
1168 /// often possible though. If alignment is important, a more reliable approach
1169 /// is to simply align all global variables and allocation instructions to
1170 /// their preferred alignment from the beginning.
1171 static Align enforceKnownAlignment(Value *V, Align Alignment, Align PrefAlign,
1172 const DataLayout &DL) {
1173 assert(PrefAlign > Alignment);
1175 V = V->stripPointerCasts();
1177 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1178 // TODO: ideally, computeKnownBits ought to have used
1179 // AllocaInst::getAlignment() in its computation already, making
1180 // the below max redundant. But, as it turns out,
1181 // stripPointerCasts recurses through infinite layers of bitcasts,
1182 // while computeKnownBits is not allowed to traverse more than 6
1184 Alignment = std::max(AI->getAlign(), Alignment);
1185 if (PrefAlign <= Alignment)
1188 // If the preferred alignment is greater than the natural stack alignment
1189 // then don't round up. This avoids dynamic stack realignment.
1190 if (DL.exceedsNaturalStackAlignment(PrefAlign))
1192 AI->setAlignment(PrefAlign);
1196 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1197 // TODO: as above, this shouldn't be necessary.
1198 Alignment = max(GO->getAlign(), Alignment);
1199 if (PrefAlign <= Alignment)
1202 // If there is a large requested alignment and we can, bump up the alignment
1203 // of the global. If the memory we set aside for the global may not be the
1204 // memory used by the final program then it is impossible for us to reliably
1205 // enforce the preferred alignment.
1206 if (!GO->canIncreaseAlignment())
1209 GO->setAlignment(PrefAlign);
1216 Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
1217 const DataLayout &DL,
1218 const Instruction *CxtI,
1219 AssumptionCache *AC,
1220 const DominatorTree *DT) {
1221 assert(V->getType()->isPointerTy() &&
1222 "getOrEnforceKnownAlignment expects a pointer!");
1224 KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
1225 unsigned TrailZ = Known.countMinTrailingZeros();
1227 // Avoid trouble with ridiculously large TrailZ values, such as
1228 // those computed from a null pointer.
1229 // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
1230 TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
1232 Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
1234 if (PrefAlign && *PrefAlign > Alignment)
1235 Alignment = enforceKnownAlignment(V, Alignment, *PrefAlign, DL);
1237 // We don't need to make any adjustment.
1241 ///===---------------------------------------------------------------------===//
1242 /// Dbg Intrinsic utilities
1245 /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1246 static bool PhiHasDebugValue(DILocalVariable *DIVar,
1247 DIExpression *DIExpr,
1249 // Since we can't guarantee that the original dbg.declare instrinsic
1250 // is removed by LowerDbgDeclare(), we need to make sure that we are
1251 // not inserting the same dbg.value intrinsic over and over.
1252 SmallVector<DbgValueInst *, 1> DbgValues;
1253 findDbgValues(DbgValues, APN);
1254 for (auto *DVI : DbgValues) {
1255 assert(DVI->getValue() == APN);
1256 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1262 /// Check if the alloc size of \p ValTy is large enough to cover the variable
1263 /// (or fragment of the variable) described by \p DII.
1265 /// This is primarily intended as a helper for the different
1266 /// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
1267 /// converted describes an alloca'd variable, so we need to use the
1268 /// alloc size of the value when doing the comparison. E.g. an i1 value will be
1269 /// identified as covering an n-bit fragment, if the store size of i1 is at
1271 static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
1272 const DataLayout &DL = DII->getModule()->getDataLayout();
1273 uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1274 if (auto FragmentSize = DII->getFragmentSizeInBits())
1275 return ValueSize >= *FragmentSize;
1276 // We can't always calculate the size of the DI variable (e.g. if it is a
1277 // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1279 if (DII->isAddressOfVariable())
1280 if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
1281 if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
1282 return ValueSize >= *FragmentSize;
1283 // Could not determine size of variable. Conservatively return false.
1287 /// Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted
1288 /// to a dbg.value. Because no machine insts can come from debug intrinsics,
1289 /// only the scope and inlinedAt is significant. Zero line numbers are used in
1290 /// case this DebugLoc leaks into any adjacent instructions.
1291 static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) {
1292 // Original dbg.declare must have a location.
1293 DebugLoc DeclareLoc = DII->getDebugLoc();
1294 MDNode *Scope = DeclareLoc.getScope();
1295 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
1296 // Produce an unknown location with the correct scope / inlinedAt fields.
1297 return DebugLoc::get(0, 0, Scope, InlinedAt);
1300 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1301 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
1302 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1303 StoreInst *SI, DIBuilder &Builder) {
1304 assert(DII->isAddressOfVariable());
1305 auto *DIVar = DII->getVariable();
1306 assert(DIVar && "Missing variable");
1307 auto *DIExpr = DII->getExpression();
1308 Value *DV = SI->getValueOperand();
1310 DebugLoc NewLoc = getDebugValueLoc(DII, SI);
1312 if (!valueCoversEntireFragment(DV->getType(), DII)) {
1313 // FIXME: If storing to a part of the variable described by the dbg.declare,
1314 // then we want to insert a dbg.value for the corresponding fragment.
1315 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1317 // For now, when there is a store to parts of the variable (but we do not
1318 // know which part) we insert an dbg.value instrinsic to indicate that we
1319 // know nothing about the variable's content.
1320 DV = UndefValue::get(DV->getType());
1321 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1325 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1328 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1329 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
1330 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1331 LoadInst *LI, DIBuilder &Builder) {
1332 auto *DIVar = DII->getVariable();
1333 auto *DIExpr = DII->getExpression();
1334 assert(DIVar && "Missing variable");
1336 if (!valueCoversEntireFragment(LI->getType(), DII)) {
1337 // FIXME: If only referring to a part of the variable described by the
1338 // dbg.declare, then we want to insert a dbg.value for the corresponding
1340 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1345 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1347 // We are now tracking the loaded value instead of the address. In the
1348 // future if multi-location support is added to the IR, it might be
1349 // preferable to keep tracking both the loaded value and the original
1350 // address in case the alloca can not be elided.
1351 Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1352 LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr);
1353 DbgValue->insertAfter(LI);
1356 /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1357 /// llvm.dbg.declare or llvm.dbg.addr intrinsic.
1358 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1359 PHINode *APN, DIBuilder &Builder) {
1360 auto *DIVar = DII->getVariable();
1361 auto *DIExpr = DII->getExpression();
1362 assert(DIVar && "Missing variable");
1364 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1367 if (!valueCoversEntireFragment(APN->getType(), DII)) {
1368 // FIXME: If only referring to a part of the variable described by the
1369 // dbg.declare, then we want to insert a dbg.value for the corresponding
1371 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1376 BasicBlock *BB = APN->getParent();
1377 auto InsertionPt = BB->getFirstInsertionPt();
1379 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1381 // The block may be a catchswitch block, which does not have a valid
1383 // FIXME: Insert dbg.value markers in the successors when appropriate.
1384 if (InsertionPt != BB->end())
1385 Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
1388 /// Determine whether this alloca is either a VLA or an array.
1389 static bool isArray(AllocaInst *AI) {
1390 return AI->isArrayAllocation() ||
1391 (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
1394 /// Determine whether this alloca is a structure.
1395 static bool isStructure(AllocaInst *AI) {
1396 return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
1399 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1400 /// of llvm.dbg.value intrinsics.
1401 bool llvm::LowerDbgDeclare(Function &F) {
1402 bool Changed = false;
1403 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1404 SmallVector<DbgDeclareInst *, 4> Dbgs;
1406 for (Instruction &BI : FI)
1407 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1408 Dbgs.push_back(DDI);
1413 for (auto &I : Dbgs) {
1414 DbgDeclareInst *DDI = I;
1415 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1416 // If this is an alloca for a scalar variable, insert a dbg.value
1417 // at each load and store to the alloca and erase the dbg.declare.
1418 // The dbg.values allow tracking a variable even if it is not
1419 // stored on the stack, while the dbg.declare can only describe
1420 // the stack slot (and at a lexical-scope granularity). Later
1421 // passes will attempt to elide the stack slot.
1422 if (!AI || isArray(AI) || isStructure(AI))
1425 // A volatile load/store means that the alloca can't be elided anyway.
1426 if (llvm::any_of(AI->users(), [](User *U) -> bool {
1427 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1428 return LI->isVolatile();
1429 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1430 return SI->isVolatile();
1435 SmallVector<const Value *, 8> WorkList;
1436 WorkList.push_back(AI);
1437 while (!WorkList.empty()) {
1438 const Value *V = WorkList.pop_back_val();
1439 for (auto &AIUse : V->uses()) {
1440 User *U = AIUse.getUser();
1441 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1442 if (AIUse.getOperandNo() == 1)
1443 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1444 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1445 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1446 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1447 // This is a call by-value or some other instruction that takes a
1448 // pointer to the variable. Insert a *value* intrinsic that describes
1449 // the variable by dereferencing the alloca.
1450 if (!CI->isLifetimeStartOrEnd()) {
1451 DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr);
1453 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
1454 DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
1457 } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1458 if (BI->getType()->isPointerTy())
1459 WorkList.push_back(BI);
1463 DDI->eraseFromParent();
1468 for (BasicBlock &BB : F)
1469 RemoveRedundantDbgInstrs(&BB);
1474 /// Propagate dbg.value intrinsics through the newly inserted PHIs.
1475 void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1476 SmallVectorImpl<PHINode *> &InsertedPHIs) {
1477 assert(BB && "No BasicBlock to clone dbg.value(s) from.");
1478 if (InsertedPHIs.size() == 0)
1481 // Map existing PHI nodes to their dbg.values.
1482 ValueToValueMapTy DbgValueMap;
1483 for (auto &I : *BB) {
1484 if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
1485 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
1486 DbgValueMap.insert({Loc, DbgII});
1489 if (DbgValueMap.size() == 0)
1492 // Then iterate through the new PHIs and look to see if they use one of the
1493 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
1494 // propagate the info through the new PHI.
1495 LLVMContext &C = BB->getContext();
1496 for (auto PHI : InsertedPHIs) {
1497 BasicBlock *Parent = PHI->getParent();
1498 // Avoid inserting an intrinsic into an EH block.
1499 if (Parent->getFirstNonPHI()->isEHPad())
1501 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
1502 for (auto VI : PHI->operand_values()) {
1503 auto V = DbgValueMap.find(VI);
1504 if (V != DbgValueMap.end()) {
1505 auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
1506 Instruction *NewDbgII = DbgII->clone();
1507 NewDbgII->setOperand(0, PhiMAV);
1508 auto InsertionPt = Parent->getFirstInsertionPt();
1509 assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1510 NewDbgII->insertBefore(&*InsertionPt);
1516 /// Finds all intrinsics declaring local variables as living in the memory that
1517 /// 'V' points to. This may include a mix of dbg.declare and
1518 /// dbg.addr intrinsics.
1519 TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
1520 // This function is hot. Check whether the value has any metadata to avoid a
1522 if (!V->isUsedByMetadata())
1524 auto *L = LocalAsMetadata::getIfExists(V);
1527 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
1531 TinyPtrVector<DbgVariableIntrinsic *> Declares;
1532 for (User *U : MDV->users()) {
1533 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
1534 if (DII->isAddressOfVariable())
1535 Declares.push_back(DII);
1541 TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) {
1542 TinyPtrVector<DbgDeclareInst *> DDIs;
1543 for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V))
1544 if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI))
1545 DDIs.push_back(DDI);
1549 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
1550 // This function is hot. Check whether the value has any metadata to avoid a
1552 if (!V->isUsedByMetadata())
1554 if (auto *L = LocalAsMetadata::getIfExists(V))
1555 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1556 for (User *U : MDV->users())
1557 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1558 DbgValues.push_back(DVI);
1561 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
1563 // This function is hot. Check whether the value has any metadata to avoid a
1565 if (!V->isUsedByMetadata())
1567 if (auto *L = LocalAsMetadata::getIfExists(V))
1568 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1569 for (User *U : MDV->users())
1570 if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
1571 DbgUsers.push_back(DII);
1574 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1575 DIBuilder &Builder, uint8_t DIExprFlags,
1577 auto DbgAddrs = FindDbgAddrUses(Address);
1578 for (DbgVariableIntrinsic *DII : DbgAddrs) {
1579 DebugLoc Loc = DII->getDebugLoc();
1580 auto *DIVar = DII->getVariable();
1581 auto *DIExpr = DII->getExpression();
1582 assert(DIVar && "Missing variable");
1583 DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
1584 // Insert llvm.dbg.declare immediately before DII, and remove old
1585 // llvm.dbg.declare.
1586 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, DII);
1587 DII->eraseFromParent();
1589 return !DbgAddrs.empty();
1592 static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1593 DIBuilder &Builder, int Offset) {
1594 DebugLoc Loc = DVI->getDebugLoc();
1595 auto *DIVar = DVI->getVariable();
1596 auto *DIExpr = DVI->getExpression();
1597 assert(DIVar && "Missing variable");
1599 // This is an alloca-based llvm.dbg.value. The first thing it should do with
1600 // the alloca pointer is dereference it. Otherwise we don't know how to handle
1602 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1603 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1606 // Insert the offset before the first deref.
1607 // We could just change the offset argument of dbg.value, but it's unsigned...
1609 DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
1611 Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
1612 DVI->eraseFromParent();
1615 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1616 DIBuilder &Builder, int Offset) {
1617 if (auto *L = LocalAsMetadata::getIfExists(AI))
1618 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1619 for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1621 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1622 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1626 /// Wrap \p V in a ValueAsMetadata instance.
1627 static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
1628 return MetadataAsValue::get(C, ValueAsMetadata::get(V));
1631 /// Where possible to salvage debug information for \p I do so
1632 /// and return True. If not possible mark undef and return False.
1633 void llvm::salvageDebugInfo(Instruction &I) {
1634 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
1635 findDbgUsers(DbgUsers, &I);
1636 salvageDebugInfoForDbgValues(I, DbgUsers);
1639 void llvm::salvageDebugInfoForDbgValues(
1640 Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
1641 auto &Ctx = I.getContext();
1642 bool Salvaged = false;
1643 auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
1645 for (auto *DII : DbgUsers) {
1646 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
1647 // are implicitly pointing out the value as a DWARF memory location
1649 bool StackValue = isa<DbgValueInst>(DII);
1651 DIExpression *DIExpr =
1652 salvageDebugInfoImpl(I, DII->getExpression(), StackValue);
1654 // salvageDebugInfoImpl should fail on examining the first element of
1655 // DbgUsers, or none of them.
1659 DII->setOperand(0, wrapMD(I.getOperand(0)));
1660 DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
1661 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
1668 for (auto *DII : DbgUsers) {
1669 Value *Undef = UndefValue::get(I.getType());
1670 DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
1671 ValueAsMetadata::get(Undef)));
1675 DIExpression *llvm::salvageDebugInfoImpl(Instruction &I,
1676 DIExpression *SrcDIExpr,
1677 bool WithStackValue) {
1678 auto &M = *I.getModule();
1679 auto &DL = M.getDataLayout();
1681 // Apply a vector of opcodes to the source DIExpression.
1682 auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
1683 DIExpression *DIExpr = SrcDIExpr;
1685 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1690 // Apply the given offset to the source DIExpression.
1691 auto applyOffset = [&](uint64_t Offset) -> DIExpression * {
1692 SmallVector<uint64_t, 8> Ops;
1693 DIExpression::appendOffset(Ops, Offset);
1694 return doSalvage(Ops);
1697 // initializer-list helper for applying operators to the source DIExpression.
1698 auto applyOps = [&](ArrayRef<uint64_t> Opcodes) -> DIExpression * {
1699 SmallVector<uint64_t, 8> Ops(Opcodes.begin(), Opcodes.end());
1700 return doSalvage(Ops);
1703 if (auto *CI = dyn_cast<CastInst>(&I)) {
1704 // No-op casts are irrelevant for debug info.
1705 if (CI->isNoopCast(DL))
1708 Type *Type = CI->getType();
1709 // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
1710 if (Type->isVectorTy() ||
1711 !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I)))
1714 Value *FromValue = CI->getOperand(0);
1715 unsigned FromTypeBitSize = FromValue->getType()->getScalarSizeInBits();
1716 unsigned ToTypeBitSize = Type->getScalarSizeInBits();
1718 return applyOps(DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
1719 isa<SExtInst>(&I)));
1722 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1724 M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
1725 // Rewrite a constant GEP into a DIExpression.
1726 APInt Offset(BitWidth, 0);
1727 if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1728 return applyOffset(Offset.getSExtValue());
1732 } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
1733 // Rewrite binary operations with constant integer operands.
1734 auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
1735 if (!ConstInt || ConstInt->getBitWidth() > 64)
1738 uint64_t Val = ConstInt->getSExtValue();
1739 switch (BI->getOpcode()) {
1740 case Instruction::Add:
1741 return applyOffset(Val);
1742 case Instruction::Sub:
1743 return applyOffset(-int64_t(Val));
1744 case Instruction::Mul:
1745 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1746 case Instruction::SDiv:
1747 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1748 case Instruction::SRem:
1749 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1750 case Instruction::Or:
1751 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1752 case Instruction::And:
1753 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1754 case Instruction::Xor:
1755 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1756 case Instruction::Shl:
1757 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1758 case Instruction::LShr:
1759 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1760 case Instruction::AShr:
1761 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1763 // TODO: Salvage constants from each kind of binop we know about.
1766 // *Not* to do: we should not attempt to salvage load instructions,
1767 // because the validity and lifetime of a dbg.value containing
1768 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
1773 /// A replacement for a dbg.value expression.
1774 using DbgValReplacement = Optional<DIExpression *>;
1776 /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1777 /// possibly moving/undefing users to prevent use-before-def. Returns true if
1778 /// changes are made.
1779 static bool rewriteDebugUsers(
1780 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
1781 function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
1782 // Find debug users of From.
1783 SmallVector<DbgVariableIntrinsic *, 1> Users;
1784 findDbgUsers(Users, &From);
1788 // Prevent use-before-def of To.
1789 bool Changed = false;
1790 SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
1791 if (isa<Instruction>(&To)) {
1792 bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1794 for (auto *DII : Users) {
1795 // It's common to see a debug user between From and DomPoint. Move it
1796 // after DomPoint to preserve the variable update without any reordering.
1797 if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1798 LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
1799 DII->moveAfter(&DomPoint);
1802 // Users which otherwise aren't dominated by the replacement value must
1803 // be salvaged or deleted.
1804 } else if (!DT.dominates(&DomPoint, DII)) {
1805 UndefOrSalvage.insert(DII);
1810 // Update debug users without use-before-def risk.
1811 for (auto *DII : Users) {
1812 if (UndefOrSalvage.count(DII))
1815 LLVMContext &Ctx = DII->getContext();
1816 DbgValReplacement DVR = RewriteExpr(*DII);
1820 DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
1821 DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
1822 LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
1826 if (!UndefOrSalvage.empty()) {
1827 // Try to salvage the remaining debug users.
1828 salvageDebugInfo(From);
1835 /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
1836 /// losslessly preserve the bits and semantics of the value. This predicate is
1837 /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
1839 /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
1840 /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
1841 /// and also does not allow lossless pointer <-> integer conversions.
1842 static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
1844 // Trivially compatible types.
1848 // Handle compatible pointer <-> integer conversions.
1849 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
1850 bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
1851 bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
1852 !DL.isNonIntegralPointerType(ToTy);
1853 return SameSize && LosslessConversion;
1856 // TODO: This is not exhaustive.
1860 bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
1861 Instruction &DomPoint, DominatorTree &DT) {
1862 // Exit early if From has no debug users.
1863 if (!From.isUsedByMetadata())
1866 assert(&From != &To && "Can't replace something with itself");
1868 Type *FromTy = From.getType();
1869 Type *ToTy = To.getType();
1871 auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1872 return DII.getExpression();
1875 // Handle no-op conversions.
1876 Module &M = *From.getModule();
1877 const DataLayout &DL = M.getDataLayout();
1878 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
1879 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1881 // Handle integer-to-integer widening and narrowing.
1882 // FIXME: Use DW_OP_convert when it's available everywhere.
1883 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
1884 uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
1885 uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
1886 assert(FromBits != ToBits && "Unexpected no-op conversion");
1888 // When the width of the result grows, assume that a debugger will only
1889 // access the low `FromBits` bits when inspecting the source variable.
1890 if (FromBits < ToBits)
1891 return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1893 // The width of the result has shrunk. Use sign/zero extension to describe
1894 // the source variable's high bits.
1895 auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1896 DILocalVariable *Var = DII.getVariable();
1898 // Without knowing signedness, sign/zero extension isn't possible.
1899 auto Signedness = Var->getSignedness();
1903 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
1904 return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
1907 return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
1910 // TODO: Floating-point conversions, vectors.
1914 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1915 unsigned NumDeadInst = 0;
1916 // Delete the instructions backwards, as it has a reduced likelihood of
1917 // having to update as many def-use and use-def chains.
1918 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1919 while (EndInst != &BB->front()) {
1920 // Delete the next to last instruction.
1921 Instruction *Inst = &*--EndInst->getIterator();
1922 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1923 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1924 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1928 if (!isa<DbgInfoIntrinsic>(Inst))
1930 Inst->eraseFromParent();
1935 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1936 bool PreserveLCSSA, DomTreeUpdater *DTU,
1937 MemorySSAUpdater *MSSAU) {
1938 BasicBlock *BB = I->getParent();
1939 std::vector <DominatorTree::UpdateType> Updates;
1942 MSSAU->changeToUnreachable(I);
1944 // Loop over all of the successors, removing BB's entry from any PHI
1947 Updates.reserve(BB->getTerminator()->getNumSuccessors());
1948 for (BasicBlock *Successor : successors(BB)) {
1949 Successor->removePredecessor(BB, PreserveLCSSA);
1951 Updates.push_back({DominatorTree::Delete, BB, Successor});
1953 // Insert a call to llvm.trap right before this. This turns the undefined
1954 // behavior into a hard fail instead of falling through into random code.
1957 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1958 CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1959 CallTrap->setDebugLoc(I->getDebugLoc());
1961 auto *UI = new UnreachableInst(I->getContext(), I);
1962 UI->setDebugLoc(I->getDebugLoc());
1964 // All instructions after this are dead.
1965 unsigned NumInstrsRemoved = 0;
1966 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
1967 while (BBI != BBE) {
1968 if (!BBI->use_empty())
1969 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1970 BB->getInstList().erase(BBI++);
1974 DTU->applyUpdatesPermissive(Updates);
1975 return NumInstrsRemoved;
1978 CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
1979 SmallVector<Value *, 8> Args(II->arg_begin(), II->arg_end());
1980 SmallVector<OperandBundleDef, 1> OpBundles;
1981 II->getOperandBundlesAsDefs(OpBundles);
1982 CallInst *NewCall = CallInst::Create(II->getFunctionType(),
1983 II->getCalledOperand(), Args, OpBundles);
1984 NewCall->setCallingConv(II->getCallingConv());
1985 NewCall->setAttributes(II->getAttributes());
1986 NewCall->setDebugLoc(II->getDebugLoc());
1987 NewCall->copyMetadata(*II);
1989 // If the invoke had profile metadata, try converting them for CallInst.
1990 uint64_t TotalWeight;
1991 if (NewCall->extractProfTotalWeight(TotalWeight)) {
1992 // Set the total weight if it fits into i32, otherwise reset.
1993 MDBuilder MDB(NewCall->getContext());
1994 auto NewWeights = uint32_t(TotalWeight) != TotalWeight
1996 : MDB.createBranchWeights({uint32_t(TotalWeight)});
1997 NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
2003 /// changeToCall - Convert the specified invoke into a normal call.
2004 void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
2005 CallInst *NewCall = createCallMatchingInvoke(II);
2006 NewCall->takeName(II);
2007 NewCall->insertBefore(II);
2008 II->replaceAllUsesWith(NewCall);
2010 // Follow the call by a branch to the normal destination.
2011 BasicBlock *NormalDestBB = II->getNormalDest();
2012 BranchInst::Create(NormalDestBB, II);
2014 // Update PHI nodes in the unwind destination
2015 BasicBlock *BB = II->getParent();
2016 BasicBlock *UnwindDestBB = II->getUnwindDest();
2017 UnwindDestBB->removePredecessor(BB);
2018 II->eraseFromParent();
2020 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
2023 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2024 BasicBlock *UnwindEdge) {
2025 BasicBlock *BB = CI->getParent();
2027 // Convert this function call into an invoke instruction. First, split the
2030 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
2032 // Delete the unconditional branch inserted by splitBasicBlock
2033 BB->getInstList().pop_back();
2035 // Create the new invoke instruction.
2036 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
2037 SmallVector<OperandBundleDef, 1> OpBundles;
2039 CI->getOperandBundlesAsDefs(OpBundles);
2041 // Note: we're round tripping operand bundles through memory here, and that
2042 // can potentially be avoided with a cleverer API design that we do not have
2046 InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
2047 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2048 II->setDebugLoc(CI->getDebugLoc());
2049 II->setCallingConv(CI->getCallingConv());
2050 II->setAttributes(CI->getAttributes());
2052 // Make sure that anything using the call now uses the invoke! This also
2053 // updates the CallGraph if present, because it uses a WeakTrackingVH.
2054 CI->replaceAllUsesWith(II);
2056 // Delete the original call
2057 Split->getInstList().pop_front();
2061 static bool markAliveBlocks(Function &F,
2062 SmallPtrSetImpl<BasicBlock *> &Reachable,
2063 DomTreeUpdater *DTU = nullptr) {
2064 SmallVector<BasicBlock*, 128> Worklist;
2065 BasicBlock *BB = &F.front();
2066 Worklist.push_back(BB);
2067 Reachable.insert(BB);
2068 bool Changed = false;
2070 BB = Worklist.pop_back_val();
2072 // Do a quick scan of the basic block, turning any obviously unreachable
2073 // instructions into LLVM unreachable insts. The instruction combining pass
2074 // canonicalizes unreachable insts into stores to null or undef.
2075 for (Instruction &I : *BB) {
2076 if (auto *CI = dyn_cast<CallInst>(&I)) {
2077 Value *Callee = CI->getCalledOperand();
2078 // Handle intrinsic calls.
2079 if (Function *F = dyn_cast<Function>(Callee)) {
2080 auto IntrinsicID = F->getIntrinsicID();
2081 // Assumptions that are known to be false are equivalent to
2082 // unreachable. Also, if the condition is undefined, then we make the
2083 // choice most beneficial to the optimizer, and choose that to also be
2085 if (IntrinsicID == Intrinsic::assume) {
2086 if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2087 // Don't insert a call to llvm.trap right before the unreachable.
2088 changeToUnreachable(CI, false, false, DTU);
2092 } else if (IntrinsicID == Intrinsic::experimental_guard) {
2093 // A call to the guard intrinsic bails out of the current
2094 // compilation unit if the predicate passed to it is false. If the
2095 // predicate is a constant false, then we know the guard will bail
2096 // out of the current compile unconditionally, so all code following
2099 // Note: unlike in llvm.assume, it is not "obviously profitable" for
2100 // guards to treat `undef` as `false` since a guard on `undef` can
2101 // still be useful for widening.
2102 if (match(CI->getArgOperand(0), m_Zero()))
2103 if (!isa<UnreachableInst>(CI->getNextNode())) {
2104 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
2110 } else if ((isa<ConstantPointerNull>(Callee) &&
2111 !NullPointerIsDefined(CI->getFunction())) ||
2112 isa<UndefValue>(Callee)) {
2113 changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
2117 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2118 // If we found a call to a no-return function, insert an unreachable
2119 // instruction after it. Make sure there isn't *already* one there
2121 if (!isa<UnreachableInst>(CI->getNextNode())) {
2122 // Don't insert a call to llvm.trap right before the unreachable.
2123 changeToUnreachable(CI->getNextNode(), false, false, DTU);
2128 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2129 // Store to undef and store to null are undefined and used to signal
2130 // that they should be changed to unreachable by passes that can't
2133 // Don't touch volatile stores.
2134 if (SI->isVolatile()) continue;
2136 Value *Ptr = SI->getOperand(1);
2138 if (isa<UndefValue>(Ptr) ||
2139 (isa<ConstantPointerNull>(Ptr) &&
2140 !NullPointerIsDefined(SI->getFunction(),
2141 SI->getPointerAddressSpace()))) {
2142 changeToUnreachable(SI, true, false, DTU);
2149 Instruction *Terminator = BB->getTerminator();
2150 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2151 // Turn invokes that call 'nounwind' functions into ordinary calls.
2152 Value *Callee = II->getCalledOperand();
2153 if ((isa<ConstantPointerNull>(Callee) &&
2154 !NullPointerIsDefined(BB->getParent())) ||
2155 isa<UndefValue>(Callee)) {
2156 changeToUnreachable(II, true, false, DTU);
2158 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
2159 if (II->use_empty() && II->onlyReadsMemory()) {
2160 // jump to the normal destination branch.
2161 BasicBlock *NormalDestBB = II->getNormalDest();
2162 BasicBlock *UnwindDestBB = II->getUnwindDest();
2163 BranchInst::Create(NormalDestBB, II);
2164 UnwindDestBB->removePredecessor(II->getParent());
2165 II->eraseFromParent();
2167 DTU->applyUpdatesPermissive(
2168 {{DominatorTree::Delete, BB, UnwindDestBB}});
2170 changeToCall(II, DTU);
2173 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2174 // Remove catchpads which cannot be reached.
2175 struct CatchPadDenseMapInfo {
2176 static CatchPadInst *getEmptyKey() {
2177 return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2180 static CatchPadInst *getTombstoneKey() {
2181 return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2184 static unsigned getHashValue(CatchPadInst *CatchPad) {
2185 return static_cast<unsigned>(hash_combine_range(
2186 CatchPad->value_op_begin(), CatchPad->value_op_end()));
2189 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2190 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2191 RHS == getEmptyKey() || RHS == getTombstoneKey())
2193 return LHS->isIdenticalTo(RHS);
2197 // Set of unique CatchPads.
2198 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2199 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2201 detail::DenseSetEmpty Empty;
2202 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2203 E = CatchSwitch->handler_end();
2205 BasicBlock *HandlerBB = *I;
2206 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2207 if (!HandlerSet.insert({CatchPad, Empty}).second) {
2208 CatchSwitch->removeHandler(I);
2216 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
2217 for (BasicBlock *Successor : successors(BB))
2218 if (Reachable.insert(Successor).second)
2219 Worklist.push_back(Successor);
2220 } while (!Worklist.empty());
2224 void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
2225 Instruction *TI = BB->getTerminator();
2227 if (auto *II = dyn_cast<InvokeInst>(TI)) {
2228 changeToCall(II, DTU);
2233 BasicBlock *UnwindDest;
2235 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2236 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2237 UnwindDest = CRI->getUnwindDest();
2238 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2239 auto *NewCatchSwitch = CatchSwitchInst::Create(
2240 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2241 CatchSwitch->getName(), CatchSwitch);
2242 for (BasicBlock *PadBB : CatchSwitch->handlers())
2243 NewCatchSwitch->addHandler(PadBB);
2245 NewTI = NewCatchSwitch;
2246 UnwindDest = CatchSwitch->getUnwindDest();
2248 llvm_unreachable("Could not find unwind successor");
2251 NewTI->takeName(TI);
2252 NewTI->setDebugLoc(TI->getDebugLoc());
2253 UnwindDest->removePredecessor(BB);
2254 TI->replaceAllUsesWith(NewTI);
2255 TI->eraseFromParent();
2257 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
2260 /// removeUnreachableBlocks - Remove blocks that are not reachable, even
2261 /// if they are in a dead cycle. Return true if a change was made, false
2263 bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
2264 MemorySSAUpdater *MSSAU) {
2265 SmallPtrSet<BasicBlock *, 16> Reachable;
2266 bool Changed = markAliveBlocks(F, Reachable, DTU);
2268 // If there are unreachable blocks in the CFG...
2269 if (Reachable.size() == F.size())
2272 assert(Reachable.size() < F.size());
2273 NumRemoved += F.size() - Reachable.size();
2275 SmallSetVector<BasicBlock *, 8> DeadBlockSet;
2276 for (BasicBlock &BB : F) {
2277 // Skip reachable basic blocks
2278 if (Reachable.count(&BB))
2280 DeadBlockSet.insert(&BB);
2284 MSSAU->removeBlocks(DeadBlockSet);
2286 // Loop over all of the basic blocks that are not reachable, dropping all of
2287 // their internal references. Update DTU if available.
2288 std::vector<DominatorTree::UpdateType> Updates;
2289 for (auto *BB : DeadBlockSet) {
2290 for (BasicBlock *Successor : successors(BB)) {
2291 if (!DeadBlockSet.count(Successor))
2292 Successor->removePredecessor(BB);
2294 Updates.push_back({DominatorTree::Delete, BB, Successor});
2296 BB->dropAllReferences();
2298 Instruction *TI = BB->getTerminator();
2299 assert(TI && "Basic block should have a terminator");
2300 // Terminators like invoke can have users. We have to replace their users,
2301 // before removing them.
2302 if (!TI->use_empty())
2303 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
2304 TI->eraseFromParent();
2305 new UnreachableInst(BB->getContext(), BB);
2306 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2307 "applying corresponding DTU updates.");
2312 DTU->applyUpdatesPermissive(Updates);
2313 bool Deleted = false;
2314 for (auto *BB : DeadBlockSet) {
2315 if (DTU->isBBPendingDeletion(BB))
2324 for (auto *BB : DeadBlockSet)
2325 BB->eraseFromParent();
2331 void llvm::combineMetadata(Instruction *K, const Instruction *J,
2332 ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
2333 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
2334 K->dropUnknownNonDebugMetadata(KnownIDs);
2335 K->getAllMetadataOtherThanDebugLoc(Metadata);
2336 for (const auto &MD : Metadata) {
2337 unsigned Kind = MD.first;
2338 MDNode *JMD = J->getMetadata(Kind);
2339 MDNode *KMD = MD.second;
2343 K->setMetadata(Kind, nullptr); // Remove unknown metadata
2345 case LLVMContext::MD_dbg:
2346 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2347 case LLVMContext::MD_tbaa:
2348 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2350 case LLVMContext::MD_alias_scope:
2351 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2353 case LLVMContext::MD_noalias:
2354 case LLVMContext::MD_mem_parallel_loop_access:
2355 K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2357 case LLVMContext::MD_access_group:
2358 K->setMetadata(LLVMContext::MD_access_group,
2359 intersectAccessGroups(K, J));
2361 case LLVMContext::MD_range:
2363 // If K does move, use most generic range. Otherwise keep the range of
2366 // FIXME: If K does move, we should drop the range info and nonnull.
2367 // Currently this function is used with DoesKMove in passes
2368 // doing hoisting/sinking and the current behavior of using the
2369 // most generic range is correct in those cases.
2370 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
2372 case LLVMContext::MD_fpmath:
2373 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2375 case LLVMContext::MD_invariant_load:
2376 // Only set the !invariant.load if it is present in both instructions.
2377 K->setMetadata(Kind, JMD);
2379 case LLVMContext::MD_nonnull:
2380 // If K does move, keep nonull if it is present in both instructions.
2382 K->setMetadata(Kind, JMD);
2384 case LLVMContext::MD_invariant_group:
2385 // Preserve !invariant.group in K.
2387 case LLVMContext::MD_align:
2388 K->setMetadata(Kind,
2389 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2391 case LLVMContext::MD_dereferenceable:
2392 case LLVMContext::MD_dereferenceable_or_null:
2393 K->setMetadata(Kind,
2394 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2396 case LLVMContext::MD_preserve_access_index:
2397 // Preserve !preserve.access.index in K.
2401 // Set !invariant.group from J if J has it. If both instructions have it
2402 // then we will just pick it from J - even when they are different.
2403 // Also make sure that K is load or store - f.e. combining bitcast with load
2404 // could produce bitcast with invariant.group metadata, which is invalid.
2405 // FIXME: we should try to preserve both invariant.group md if they are
2406 // different, but right now instruction can only have one invariant.group.
2407 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2408 if (isa<LoadInst>(K) || isa<StoreInst>(K))
2409 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
2412 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2414 unsigned KnownIDs[] = {
2415 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2416 LLVMContext::MD_noalias, LLVMContext::MD_range,
2417 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
2418 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2419 LLVMContext::MD_dereferenceable,
2420 LLVMContext::MD_dereferenceable_or_null,
2421 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
2422 combineMetadata(K, J, KnownIDs, KDominatesJ);
2425 void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
2426 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
2427 Source.getAllMetadata(MD);
2428 MDBuilder MDB(Dest.getContext());
2429 Type *NewType = Dest.getType();
2430 const DataLayout &DL = Source.getModule()->getDataLayout();
2431 for (const auto &MDPair : MD) {
2432 unsigned ID = MDPair.first;
2433 MDNode *N = MDPair.second;
2434 // Note, essentially every kind of metadata should be preserved here! This
2435 // routine is supposed to clone a load instruction changing *only its type*.
2436 // The only metadata it makes sense to drop is metadata which is invalidated
2437 // when the pointer type changes. This should essentially never be the case
2438 // in LLVM, but we explicitly switch over only known metadata to be
2439 // conservatively correct. If you are adding metadata to LLVM which pertains
2440 // to loads, you almost certainly want to add it here.
2442 case LLVMContext::MD_dbg:
2443 case LLVMContext::MD_tbaa:
2444 case LLVMContext::MD_prof:
2445 case LLVMContext::MD_fpmath:
2446 case LLVMContext::MD_tbaa_struct:
2447 case LLVMContext::MD_invariant_load:
2448 case LLVMContext::MD_alias_scope:
2449 case LLVMContext::MD_noalias:
2450 case LLVMContext::MD_nontemporal:
2451 case LLVMContext::MD_mem_parallel_loop_access:
2452 case LLVMContext::MD_access_group:
2453 // All of these directly apply.
2454 Dest.setMetadata(ID, N);
2457 case LLVMContext::MD_nonnull:
2458 copyNonnullMetadata(Source, N, Dest);
2461 case LLVMContext::MD_align:
2462 case LLVMContext::MD_dereferenceable:
2463 case LLVMContext::MD_dereferenceable_or_null:
2464 // These only directly apply if the new type is also a pointer.
2465 if (NewType->isPointerTy())
2466 Dest.setMetadata(ID, N);
2469 case LLVMContext::MD_range:
2470 copyRangeMetadata(DL, Source, N, Dest);
2476 void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2477 auto *ReplInst = dyn_cast<Instruction>(Repl);
2481 // Patch the replacement so that it is not more restrictive than the value
2483 // Note that if 'I' is a load being replaced by some operation,
2484 // for example, by an arithmetic operation, then andIRFlags()
2485 // would just erase all math flags from the original arithmetic
2486 // operation, which is clearly not wanted and not needed.
2487 if (!isa<LoadInst>(I))
2488 ReplInst->andIRFlags(I);
2490 // FIXME: If both the original and replacement value are part of the
2491 // same control-flow region (meaning that the execution of one
2492 // guarantees the execution of the other), then we can combine the
2493 // noalias scopes here and do better than the general conservative
2494 // answer used in combineMetadata().
2496 // In general, GVN unifies expressions over different control-flow
2497 // regions, and so we need a conservative combination of the noalias
2499 static const unsigned KnownIDs[] = {
2500 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2501 LLVMContext::MD_noalias, LLVMContext::MD_range,
2502 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2503 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2504 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
2505 combineMetadata(ReplInst, I, KnownIDs, false);
2508 template <typename RootType, typename DominatesFn>
2509 static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2510 const RootType &Root,
2511 const DominatesFn &Dominates) {
2512 assert(From->getType() == To->getType());
2515 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2518 if (!Dominates(Root, U))
2521 LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
2522 << "' as " << *To << " in " << *U << "\n");
2528 unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2529 assert(From->getType() == To->getType());
2530 auto *BB = From->getParent();
2533 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2536 auto *I = cast<Instruction>(U.getUser());
2537 if (I->getParent() == BB)
2545 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2547 const BasicBlockEdge &Root) {
2548 auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2549 return DT.dominates(Root, U);
2551 return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2554 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2556 const BasicBlock *BB) {
2557 auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
2558 auto *I = cast<Instruction>(U.getUser())->getParent();
2559 return DT.properlyDominates(BB, I);
2561 return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
2564 bool llvm::callsGCLeafFunction(const CallBase *Call,
2565 const TargetLibraryInfo &TLI) {
2566 // Check if the function is specifically marked as a gc leaf function.
2567 if (Call->hasFnAttr("gc-leaf-function"))
2569 if (const Function *F = Call->getCalledFunction()) {
2570 if (F->hasFnAttribute("gc-leaf-function"))
2573 if (auto IID = F->getIntrinsicID())
2574 // Most LLVM intrinsics do not take safepoints.
2575 return IID != Intrinsic::experimental_gc_statepoint &&
2576 IID != Intrinsic::experimental_deoptimize;
2579 // Lib calls can be materialized by some passes, and won't be
2580 // marked as 'gc-leaf-function.' All available Libcalls are
2583 if (TLI.getLibFunc(*Call, LF)) {
2590 void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2592 auto *NewTy = NewLI.getType();
2594 // This only directly applies if the new type is also a pointer.
2595 if (NewTy->isPointerTy()) {
2596 NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2600 // The only other translation we can do is to integral loads with !range
2602 if (!NewTy->isIntegerTy())
2605 MDBuilder MDB(NewLI.getContext());
2606 const Value *Ptr = OldLI.getPointerOperand();
2607 auto *ITy = cast<IntegerType>(NewTy);
2608 auto *NullInt = ConstantExpr::getPtrToInt(
2609 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2610 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2611 NewLI.setMetadata(LLVMContext::MD_range,
2612 MDB.createRange(NonNullInt, NullInt));
2615 void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2616 MDNode *N, LoadInst &NewLI) {
2617 auto *NewTy = NewLI.getType();
2619 // Give up unless it is converted to a pointer where there is a single very
2620 // valuable mapping we can do reliably.
2621 // FIXME: It would be nice to propagate this in more ways, but the type
2622 // conversions make it hard.
2623 if (!NewTy->isPointerTy())
2626 unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
2627 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2628 MDNode *NN = MDNode::get(OldLI.getContext(), None);
2629 NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
2633 void llvm::dropDebugUsers(Instruction &I) {
2634 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2635 findDbgUsers(DbgUsers, &I);
2636 for (auto *DII : DbgUsers)
2637 DII->eraseFromParent();
2640 void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2642 // Since we are moving the instructions out of its basic block, we do not
2643 // retain their original debug locations (DILocations) and debug intrinsic
2646 // Doing so would degrade the debugging experience and adversely affect the
2647 // accuracy of profiling information.
2649 // Currently, when hoisting the instructions, we take the following actions:
2650 // - Remove their debug intrinsic instructions.
2651 // - Set their debug locations to the values from the insertion point.
2653 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2654 // need to be deleted, is because there will not be any instructions with a
2655 // DILocation in either branch left after performing the transformation. We
2656 // can only insert a dbg.value after the two branches are joined again.
2658 // See PR38762, PR39243 for more details.
2660 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2661 // encode predicated DIExpressions that yield different results on different
2663 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2664 Instruction *I = &*II;
2665 I->dropUnknownNonDebugMetadata();
2666 if (I->isUsedByMetadata())
2668 if (isa<DbgInfoIntrinsic>(I)) {
2669 // Remove DbgInfo Intrinsics.
2670 II = I->eraseFromParent();
2673 I->setDebugLoc(InsertPt->getDebugLoc());
2676 DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2678 BB->getTerminator()->getIterator());
2683 /// A potential constituent of a bitreverse or bswap expression. See
2684 /// collectBitParts for a fuller explanation.
2686 BitPart(Value *P, unsigned BW) : Provider(P) {
2687 Provenance.resize(BW);
2690 /// The Value that this is a bitreverse/bswap of.
2693 /// The "provenance" of each bit. Provenance[A] = B means that bit A
2694 /// in Provider becomes bit B in the result of this expression.
2695 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2697 enum { Unset = -1 };
2700 } // end anonymous namespace
2702 /// Analyze the specified subexpression and see if it is capable of providing
2703 /// pieces of a bswap or bitreverse. The subexpression provides a potential
2704 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
2705 /// the output of the expression came from a corresponding bit in some other
2706 /// value. This function is recursive, and the end result is a mapping of
2707 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
2708 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2710 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2711 /// that the expression deposits the low byte of %X into the high byte of the
2712 /// result and that all other bits are zero. This expression is accepted and a
2713 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2716 /// To avoid revisiting values, the BitPart results are memoized into the
2717 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
2718 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2719 /// store BitParts objects, not pointers. As we need the concept of a nullptr
2720 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
2721 /// type instead to provide the same functionality.
2723 /// Because we pass around references into \c BPS, we must use a container that
2724 /// does not invalidate internal references (std::map instead of DenseMap).
2725 static const Optional<BitPart> &
2726 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
2727 std::map<Value *, Optional<BitPart>> &BPS, int Depth) {
2728 auto I = BPS.find(V);
2732 auto &Result = BPS[V] = None;
2733 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2735 // Prevent stack overflow by limiting the recursion depth
2736 if (Depth == BitPartRecursionMaxDepth) {
2737 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
2741 if (Instruction *I = dyn_cast<Instruction>(V)) {
2742 // If this is an or instruction, it may be an inner node of the bswap.
2743 if (I->getOpcode() == Instruction::Or) {
2744 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
2745 MatchBitReversals, BPS, Depth + 1);
2746 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
2747 MatchBitReversals, BPS, Depth + 1);
2751 // Try and merge the two together.
2752 if (!A->Provider || A->Provider != B->Provider)
2755 Result = BitPart(A->Provider, BitWidth);
2756 for (unsigned i = 0; i < A->Provenance.size(); ++i) {
2757 if (A->Provenance[i] != BitPart::Unset &&
2758 B->Provenance[i] != BitPart::Unset &&
2759 A->Provenance[i] != B->Provenance[i])
2760 return Result = None;
2762 if (A->Provenance[i] == BitPart::Unset)
2763 Result->Provenance[i] = B->Provenance[i];
2765 Result->Provenance[i] = A->Provenance[i];
2771 // If this is a logical shift by a constant, recurse then shift the result.
2772 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2774 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2775 // Ensure the shift amount is defined.
2776 if (BitShift > BitWidth)
2779 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2780 MatchBitReversals, BPS, Depth + 1);
2785 // Perform the "shift" on BitProvenance.
2786 auto &P = Result->Provenance;
2787 if (I->getOpcode() == Instruction::Shl) {
2788 P.erase(std::prev(P.end(), BitShift), P.end());
2789 P.insert(P.begin(), BitShift, BitPart::Unset);
2791 P.erase(P.begin(), std::next(P.begin(), BitShift));
2792 P.insert(P.end(), BitShift, BitPart::Unset);
2798 // If this is a logical 'and' with a mask that clears bits, recurse then
2799 // unset the appropriate bits.
2800 if (I->getOpcode() == Instruction::And &&
2801 isa<ConstantInt>(I->getOperand(1))) {
2802 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
2803 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2805 // Check that the mask allows a multiple of 8 bits for a bswap, for an
2807 unsigned NumMaskedBits = AndMask.countPopulation();
2808 if (!MatchBitReversals && NumMaskedBits % 8 != 0)
2811 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2812 MatchBitReversals, BPS, Depth + 1);
2817 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
2818 // If the AndMask is zero for this bit, clear the bit.
2819 if ((AndMask & Bit) == 0)
2820 Result->Provenance[i] = BitPart::Unset;
2824 // If this is a zext instruction zero extend the result.
2825 if (I->getOpcode() == Instruction::ZExt) {
2826 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2827 MatchBitReversals, BPS, Depth + 1);
2831 Result = BitPart(Res->Provider, BitWidth);
2832 auto NarrowBitWidth =
2833 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
2834 for (unsigned i = 0; i < NarrowBitWidth; ++i)
2835 Result->Provenance[i] = Res->Provenance[i];
2836 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2837 Result->Provenance[i] = BitPart::Unset;
2842 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2843 // the input value to the bswap/bitreverse.
2844 Result = BitPart(V, BitWidth);
2845 for (unsigned i = 0; i < BitWidth; ++i)
2846 Result->Provenance[i] = i;
2850 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2851 unsigned BitWidth) {
2852 if (From % 8 != To % 8)
2854 // Convert from bit indices to byte indices and check for a byte reversal.
2858 return From == BitWidth - To - 1;
2861 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
2862 unsigned BitWidth) {
2863 return From == BitWidth - To - 1;
2866 bool llvm::recognizeBSwapOrBitReverseIdiom(
2867 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2868 SmallVectorImpl<Instruction *> &InsertedInsts) {
2869 if (Operator::getOpcode(I) != Instruction::Or)
2871 if (!MatchBSwaps && !MatchBitReversals)
2873 IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2874 if (!ITy || ITy->getBitWidth() > 128)
2875 return false; // Can't do vectors or integers > 128 bits.
2876 unsigned BW = ITy->getBitWidth();
2878 unsigned DemandedBW = BW;
2879 IntegerType *DemandedTy = ITy;
2880 if (I->hasOneUse()) {
2881 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2882 DemandedTy = cast<IntegerType>(Trunc->getType());
2883 DemandedBW = DemandedTy->getBitWidth();
2887 // Try to find all the pieces corresponding to the bswap.
2888 std::map<Value *, Optional<BitPart>> BPS;
2889 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
2892 auto &BitProvenance = Res->Provenance;
2894 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2895 // only byteswap values with an even number of bytes.
2896 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2897 for (unsigned i = 0; i < DemandedBW; ++i) {
2899 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
2901 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
2904 Intrinsic::ID Intrin;
2905 if (OKForBSwap && MatchBSwaps)
2906 Intrin = Intrinsic::bswap;
2907 else if (OKForBitReverse && MatchBitReversals)
2908 Intrin = Intrinsic::bitreverse;
2912 if (ITy != DemandedTy) {
2913 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2914 Value *Provider = Res->Provider;
2915 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2916 // We may need to truncate the provider.
2917 if (DemandedTy != ProviderTy) {
2918 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2920 InsertedInsts.push_back(Trunc);
2923 auto *CI = CallInst::Create(F, Provider, "rev", I);
2924 InsertedInsts.push_back(CI);
2925 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2926 InsertedInsts.push_back(ExtInst);
2930 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2931 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2935 // CodeGen has special handling for some string functions that may replace
2936 // them with target-specific intrinsics. Since that'd skip our interceptors
2937 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2938 // we mark affected calls as NoBuiltin, which will disable optimization
2940 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2941 CallInst *CI, const TargetLibraryInfo *TLI) {
2942 Function *F = CI->getCalledFunction();
2944 if (F && !F->hasLocalLinkage() && F->hasName() &&
2945 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2946 !F->doesNotAccessMemory())
2947 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
2950 bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
2951 // We can't have a PHI with a metadata type.
2952 if (I->getOperand(OpIdx)->getType()->isMetadataTy())
2956 if (!isa<Constant>(I->getOperand(OpIdx)))
2959 switch (I->getOpcode()) {
2962 case Instruction::Call:
2963 case Instruction::Invoke: {
2964 const auto &CB = cast<CallBase>(*I);
2966 // Can't handle inline asm. Skip it.
2967 if (CB.isInlineAsm())
2970 // Constant bundle operands may need to retain their constant-ness for
2972 if (CB.isBundleOperand(OpIdx))
2975 if (OpIdx < CB.getNumArgOperands()) {
2976 // Some variadic intrinsics require constants in the variadic arguments,
2977 // which currently aren't markable as immarg.
2978 if (isa<IntrinsicInst>(CB) &&
2979 OpIdx >= CB.getFunctionType()->getNumParams()) {
2980 // This is known to be OK for stackmap.
2981 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
2984 // gcroot is a special case, since it requires a constant argument which
2985 // isn't also required to be a simple ConstantInt.
2986 if (CB.getIntrinsicID() == Intrinsic::gcroot)
2989 // Some intrinsic operands are required to be immediates.
2990 return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
2993 // It is never allowed to replace the call argument to an intrinsic, but it
2994 // may be possible for a call.
2995 return !isa<IntrinsicInst>(CB);
2997 case Instruction::ShuffleVector:
2998 // Shufflevector masks are constant.
3000 case Instruction::Switch:
3001 case Instruction::ExtractValue:
3002 // All operands apart from the first are constant.
3004 case Instruction::InsertValue:
3005 // All operands apart from the first and the second are constant.
3007 case Instruction::Alloca:
3008 // Static allocas (constant size in the entry block) are handled by
3009 // prologue/epilogue insertion so they're free anyway. We definitely don't
3010 // want to make them non-constant.
3011 return !cast<AllocaInst>(I)->isStaticAlloca();
3012 case Instruction::GetElementPtr:
3015 gep_type_iterator It = gep_type_begin(I);
3016 for (auto E = std::next(It, OpIdx); It != E; ++It)
3023 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
3024 AllocaInst *llvm::findAllocaForValue(Value *V,
3025 AllocaForValueMapTy &AllocaForValue) {
3026 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
3028 // See if we've already calculated (or started to calculate) alloca for a
3030 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
3031 if (I != AllocaForValue.end())
3033 // Store 0 while we're calculating alloca for value V to avoid
3034 // infinite recursion if the value references itself.
3035 AllocaForValue[V] = nullptr;
3036 AllocaInst *Res = nullptr;
3037 if (CastInst *CI = dyn_cast<CastInst>(V))
3038 Res = findAllocaForValue(CI->getOperand(0), AllocaForValue);
3039 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
3040 for (Value *IncValue : PN->incoming_values()) {
3041 // Allow self-referencing phi-nodes.
3044 AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue);
3045 // AI for incoming values should exist and should all be equal.
3046 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3050 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3051 Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue);
3053 LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: "
3057 AllocaForValue[V] = Res;
3061 Value *llvm::invertCondition(Value *Condition) {
3062 // First: Check if it's a constant
3063 if (Constant *C = dyn_cast<Constant>(Condition))
3064 return ConstantExpr::getNot(C);
3066 // Second: If the condition is already inverted, return the original value
3067 Value *NotCondition;
3068 if (match(Condition, m_Not(m_Value(NotCondition))))
3069 return NotCondition;
3071 BasicBlock *Parent = nullptr;
3072 Instruction *Inst = dyn_cast<Instruction>(Condition);
3074 Parent = Inst->getParent();
3075 else if (Argument *Arg = dyn_cast<Argument>(Condition))
3076 Parent = &Arg->getParent()->getEntryBlock();
3077 assert(Parent && "Unsupported condition to invert");
3079 // Third: Check all the users for an invert
3080 for (User *U : Condition->users())
3081 if (Instruction *I = dyn_cast<Instruction>(U))
3082 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
3085 // Last option: Create a new instruction
3087 BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
3088 if (Inst && !isa<PHINode>(Inst))
3089 Inverted->insertAfter(Inst);
3091 Inverted->insertBefore(&*Parent->getFirstInsertionPt());