Index: llvm/include/llvm/IR/Instruction.h =================================================================== --- llvm/include/llvm/IR/Instruction.h +++ llvm/include/llvm/IR/Instruction.h @@ -31,6 +31,7 @@ namespace llvm { class BasicBlock; +class DbgVariableIntrinsic; class FastMathFlags; class MDNode; class Module; @@ -311,6 +312,22 @@ /// Sets the metadata on this instruction from the AAMDNodes structure. void setAAMetadata(const AAMDNodes &N); + /// Given DIExpression \p DIExpr operating on this instruction, write the + /// effects of this instruction into the returned DIExpression, or return + /// nullptr if it cannot be salvaged. \p StackVal: whether DW_OP_stack_value + /// should be appended to the expression. + DIExpression *salvageDebugInfoImpl(DIExpression *SrcDIExpr, + bool WithStackValue); + + /// Implementation of salvageDebugInfo, applying only to instructions in + /// \p DbgUsers, rather than all debug users of this instruction. + bool salvageDebugInfoForDbgValues(ArrayRef DbgUsers); + + /// Assuming this instruction is going to be deleted, attempt to salvage + /// debug users by writing the effect of this instruction in a DIExpression. + /// Returns true if any debug users were updated. + bool salvageDebugInfo(); + /// Retrieve the raw weight values of a conditional branch or select. /// Returns true on success with profile weights filled in. /// Returns false if no metadata or invalid metadata was found. Index: llvm/include/llvm/IR/Value.h =================================================================== --- llvm/include/llvm/IR/Value.h +++ llvm/include/llvm/IR/Value.h @@ -15,6 +15,7 @@ #include "llvm-c/Types.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/iterator_range.h" #include "llvm/IR/Use.h" #include "llvm/Support/Alignment.h" @@ -33,6 +34,7 @@ class ConstantData; class ConstantAggregate; class DataLayout; +class DbgVariableIntrinsic; class Function; class GlobalAlias; class GlobalIFunc; @@ -313,6 +315,9 @@ } } + /// Finds the debug info intrinsics describing this value. + void findDbgUsers(SmallVectorImpl &DbgUsers); + /// replaceUsesOutsideBlock - Go through the uses list for this definition and /// make each use point to "V" instead of "this" when the use is outside the /// block. 'This's use list is expected to have at least one element. Index: llvm/include/llvm/Transforms/Utils/Local.h =================================================================== --- llvm/include/llvm/Transforms/Utils/Local.h +++ llvm/include/llvm/Transforms/Utils/Local.h @@ -315,9 +315,6 @@ /// Finds the llvm.dbg.value intrinsics describing a value. void findDbgValues(SmallVectorImpl &DbgValues, Value *V); -/// Finds the debug info intrinsics describing a value. -void findDbgUsers(SmallVectorImpl &DbgInsts, Value *V); - /// Replaces llvm.dbg.declare instruction when the address it /// describes is replaced with a new value. If Deref is true, an /// additional DW_OP_deref is prepended to the expression. If Offset @@ -349,27 +346,10 @@ AllocaInst *findAllocaForValue(Value *V, DenseMap &AllocaForValue); -/// Assuming the instruction \p I is going to be deleted, attempt to salvage -/// debug users of \p I by writing the effect of \p I in a DIExpression. -/// Returns true if any debug users were updated. -bool salvageDebugInfo(Instruction &I); - /// Salvage all debug users of the instruction \p I or mark it as undef if it /// cannot be salvaged. void salvageDebugInfoOrMarkUndef(Instruction &I); -/// Implementation of salvageDebugInfo, applying only to instructions in -/// \p Insns, rather than all debug users of \p I. -bool salvageDebugInfoForDbgValues(Instruction &I, - ArrayRef Insns); - -/// Given an instruction \p I and DIExpression \p DIExpr operating on it, write -/// the effects of \p I into the returned DIExpression, or return nullptr if -/// it cannot be salvaged. \p StackVal: whether DW_OP_stack_value should be -/// appended to the expression. -DIExpression *salvageDebugInfoImpl(Instruction &I, DIExpression *DIExpr, - bool StackVal); - /// Point debug users of \p From to \p To or salvage them. Use this function /// only when replacing all uses of \p From with \p To, with a guarantee that /// \p From is going to be deleted. Index: llvm/lib/CodeGen/CodeGenPrepare.cpp =================================================================== --- llvm/lib/CodeGen/CodeGenPrepare.cpp +++ llvm/lib/CodeGen/CodeGenPrepare.cpp @@ -1129,7 +1129,6 @@ // If we removed all uses, nuke the cast. if (CI->use_empty()) { - salvageDebugInfo(*CI); CI->eraseFromParent(); MadeChange = true; } @@ -1779,7 +1778,6 @@ // If we removed all uses, or there are none, nuke the shift. if (ShiftI->use_empty()) { - salvageDebugInfo(*ShiftI); ShiftI->eraseFromParent(); MadeChange = true; } Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp =================================================================== --- llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp +++ llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp @@ -1239,7 +1239,7 @@ // variable. FIXME: Further work could recover those too. while (isa(V)) { Instruction &VAsInst = *cast(V); - DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); + DIExpression *NewExpr = VAsInst.salvageDebugInfoImpl(Expr, StackValue); // If we cannot salvage any further, and haven't yet found a suitable debug // expression, bail out. Index: llvm/lib/IR/Instruction.cpp =================================================================== --- llvm/lib/IR/Instruction.cpp +++ llvm/lib/IR/Instruction.cpp @@ -14,8 +14,11 @@ #include "llvm/IR/IntrinsicInst.h" #include "llvm/ADT/DenseSet.h" #include "llvm/IR/Constants.h" +#include "llvm/IR/DIBuilder.h" +#include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/MDBuilder.h" +#include "llvm/IR/Module.h" #include "llvm/IR/Operator.h" #include "llvm/IR/Type.h" using namespace llvm; @@ -65,6 +68,9 @@ } iplist::iterator Instruction::eraseFromParent() { + // Try to preserve debug information attached to the instruction. + salvageDebugInfo(); + return getParent()->getInstList().erase(getIterator()); } @@ -753,3 +759,216 @@ MDBuilder MDB(getContext()); setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); } + +bool Instruction::salvageDebugInfo() { + SmallVector DbgUsers; + + // Return false if any of the operand is already deleted + for (unsigned i = 0; i < getNumOperands(); ++i) + if (!getOperand(i)) + return false; + + // preserve the information we may need later when called function from + // current function is inlined. We need this information for + // DW_OP_implicit_pointer. + if (auto DDI = dyn_cast(this)) + if (getModule()->getDwarfVersion() >= 5) + if (DDI->isAddressOfVariable()) + getModule()->insertVarAddressMap(DDI); + + findDbgUsers(DbgUsers); + if (DbgUsers.empty()) + return false; + + return salvageDebugInfoForDbgValues(DbgUsers); +} + +bool Instruction::salvageDebugInfoForDbgValues( + ArrayRef DbgUsers) { + auto &Ctx = getContext(); + auto wrapMD = [&](Value *V) { + return MetadataAsValue::get(Ctx, ValueAsMetadata::get(V)); + }; + bool Changed = false; + Value *DebugDeclareAddress = nullptr; + + if ((getModule()->getDwarfVersion() >= 5) && isa(*this)) { + for (auto *DII : DbgUsers) { + if (DII->isAddressOfVariable()) { + if (const llvm::MetadataAsValue *MDV = + dyn_cast(DII->getOperand(1))) + if (isa(MDV->getMetadata())) { + DebugDeclareAddress = DII->getOperand(1); + } + break; + } + } + if (!DebugDeclareAddress) + DebugDeclareAddress = getModule()->findVarAddressMap(this); + } + + for (auto *DII : DbgUsers) { + // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they + // are implicitly pointing out the value as a DWARF memory location + // description. + bool StackValue = isa(DII); + + DIExpression *DIExpr = + salvageDebugInfoImpl(DII->getExpression(), StackValue); + + // salvageDebugInfoImpl should fail on examining the first element of + // DbgUsers, or none of them. + if (!DIExpr) + continue; + + int64_t ExprOffset = 0; + + // It is AllocaInst and either of below is true then continue + // - We failed to get the variable description, or + // - Current instruction is not llvm.dbg.value, or + // - Current instruction doesnt have constant offset + if (isa(this) && + (!DebugDeclareAddress || DII->isAddressOfVariable() || + !DII->getExpression()->extractIfOffset(ExprOffset))) + continue; + + if (isa(this)) { + // It will cause below transformation + // + // Before transformation + // + // %a = alloca [2 x i32], align 4 + // call void @llvm.dbg.declare(metadata [2 x i32]* %arr, metadata !16, + // metadata !DIExpression()), !dbg !22 + // + // call void @llvm.dbg.value(metadata [2 x i32]* %arr, metadata !20, + // metadata !DIExpression()), !dbg !24 + // + // call void @llvm.dbg.value(metadata [2 x i32]* %arr, metadata !20, + // metadata !DIExpression(DW_OP_plus_uconst, 4, DW_OP_stack_value)), + // !dbg !24 + // + // !16 = !DILocalVariable(name: "arr", scope: !12, file: !3, line: 5, + // type: !17) !20 = !DILocalVariable(name: "ptr", scope: !12, file: !3, + // line: 6, type: !21) + // + // + // After transformation + // + // %a = alloca [2 x i32], align 4 + // call void @llvm.dbg.declare(metadata [2 x i32]* %arr, metadata !16, + // metadata !DIExpression()), !dbg !22 + // + // call void @llvm.dbg.derefval(metadata !16, metadata !20, metadata + // !DIExpression(DW_OP_LLVM_implicit_pointer, DW_OP_LLVM_arg0, 0)), !dbg + // !24 + // + // call void @llvm.dbg.derefval(metadata !16, metadata !20, metadata + // !DIExpression(DW_OP_LLVM_implicit_pointer, DW_OP_LLVM_arg0, 4)), !dbg + // !24 + // + SmallVector Ops; + Ops.push_back(dwarf::DW_OP_LLVM_implicit_pointer); + Ops.push_back(dwarf::DW_OP_LLVM_arg0); + Ops.push_back(ExprOffset); + DIExpr = DIExpression::get(DIExpr->getContext(), Ops); + DIBuilder DIB(*getModule(), /*AllowUnresolved*/ false); + DIB.insertDbgDerefValueIntrinsic(DebugDeclareAddress, + DII->getVariable(), DIExpr, + DII->getDebugLoc(), DII); + DII->eraseFromParent(); + } else { + DII->setOperand(0, wrapMD(getOperand(0))); + DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr)); + Changed = true; + } + } + + return Changed; +} + +DIExpression *Instruction::salvageDebugInfoImpl(DIExpression *SrcDIExpr, + bool WithStackValue) { + auto &M = *getModule(); + auto &DL = M.getDataLayout(); + + // Apply a vector of opcodes to the source DIExpression. + auto doSalvage = [&](SmallVectorImpl &Ops) -> DIExpression * { + DIExpression *DIExpr = SrcDIExpr; + if (!Ops.empty()) { + DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue); + } + return DIExpr; + }; + + // Apply the given offset to the source DIExpression. + auto applyOffset = [&](uint64_t Offset) -> DIExpression * { + SmallVector Ops; + DIExpression::appendOffset(Ops, Offset); + return doSalvage(Ops); + }; + + // initializer-list helper for applying operators to the source DIExpression. + auto applyOps = + [&](std::initializer_list Opcodes) -> DIExpression * { + SmallVector Ops(Opcodes); + return doSalvage(Ops); + }; + + if (auto *CI = dyn_cast(this)) { + // No-op casts and zexts are irrelevant for debug info. + if (CI->isNoopCast(DL) || isa(this)) + return SrcDIExpr; + return nullptr; + } else if (auto *GEP = dyn_cast(this)) { + unsigned BitWidth = + M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace()); + // Rewrite a constant GEP into a DIExpression. + APInt Offset(BitWidth, 0); + if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) { + return applyOffset(Offset.getSExtValue()); + } else { + return nullptr; + } + } else if (auto *BI = dyn_cast(this)) { + // Rewrite binary operations with constant integer operands. + auto *ConstInt = dyn_cast(getOperand(1)); + if (!ConstInt || ConstInt->getBitWidth() > 64) + return nullptr; + + uint64_t Val = ConstInt->getSExtValue(); + switch (BI->getOpcode()) { + case Instruction::Add: + return applyOffset(Val); + case Instruction::Sub: + return applyOffset(-int64_t(Val)); + case Instruction::Mul: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul}); + case Instruction::SDiv: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div}); + case Instruction::SRem: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod}); + case Instruction::Or: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or}); + case Instruction::And: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and}); + case Instruction::Xor: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor}); + case Instruction::Shl: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl}); + case Instruction::LShr: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr}); + case Instruction::AShr: + return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra}); + default: + // TODO: Salvage constants from each kind of binop we know about. + return nullptr; + } + // *Not* to do: we should not attempt to salvage load instructions, + // because the validity and lifetime of a dbg.value containing + // DW_OP_deref becomes difficult to analyze. See PR40628 for examples. + } else if ((M.getDwarfVersion() >= 5) && isa(this)) { + return SrcDIExpr; + } + return nullptr; +} Index: llvm/lib/IR/Value.cpp =================================================================== --- llvm/lib/IR/Value.cpp +++ llvm/lib/IR/Value.cpp @@ -452,6 +452,18 @@ }); } +void Value::findDbgUsers(SmallVectorImpl &DbgUsers) { + // This function is hot. Check whether the value has any metadata to avoid a + // DenseMap lookup. + if (!isUsedByMetadata()) + return; + if (auto *L = LocalAsMetadata::getIfExists(this)) + if (auto *MDV = MetadataAsValue::getIfExists(getContext(), L)) + for (User *U : MDV->users()) + if (DbgVariableIntrinsic *DII = dyn_cast(U)) + DbgUsers.push_back(DII); +} + namespace { // Various metrics for how much to strip off of pointers. enum PointerStripKind { Index: llvm/lib/Transforms/InstCombine/InstructionCombining.cpp =================================================================== --- llvm/lib/Transforms/InstCombine/InstructionCombining.cpp +++ llvm/lib/Transforms/InstCombine/InstructionCombining.cpp @@ -3210,7 +3210,7 @@ // mark the location undef: we know it was supposed to receive a new location // here, but that computation has been sunk. SmallVector DbgUsers; - findDbgUsers(DbgUsers, I); + I->findDbgUsers(DbgUsers); for (auto *DII : reverse(DbgUsers)) { if (DII->getParent() == SrcBlock) { if (isa(DII)) { @@ -3234,7 +3234,7 @@ SmallVector TmpUser{ cast(DII->clone())}; - if (!salvageDebugInfoForDbgValues(*I, TmpUser)) { + if (!I->salvageDebugInfoForDbgValues(TmpUser)) { // We are unable to salvage: sink the cloned dbg.value, and mark the // original as undef, terminating any earlier variable location. LLVM_DEBUG(dbgs() << "SINK: " << *DII << '\n'); Index: llvm/lib/Transforms/Scalar/DCE.cpp =================================================================== --- llvm/lib/Transforms/Scalar/DCE.cpp +++ llvm/lib/Transforms/Scalar/DCE.cpp @@ -57,7 +57,6 @@ if (isInstructionTriviallyDead(Inst, TLI)) { if (!DebugCounter::shouldExecute(DCECounter)) continue; - salvageDebugInfo(*Inst); Inst->eraseFromParent(); Changed = true; ++DIEEliminated; @@ -88,7 +87,7 @@ if (!DebugCounter::shouldExecute(DCECounter)) return false; - salvageDebugInfo(*I); + I->salvageDebugInfo(); // Null out all of the instruction's operands to see if any operand becomes // dead as we go. Index: llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp =================================================================== --- llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp +++ llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp @@ -116,7 +116,7 @@ ++NumFastOther; // Try to preserve debug information attached to the dead instruction. - salvageDebugInfo(*DeadInst); + DeadInst->salvageDebugInfo(); // This instruction is dead, zap it, in stages. Start by removing it from // MemDep, which needs to know the operands and needs it to be in the Index: llvm/lib/Transforms/Scalar/EarlyCSE.cpp =================================================================== --- llvm/lib/Transforms/Scalar/EarlyCSE.cpp +++ llvm/lib/Transforms/Scalar/EarlyCSE.cpp @@ -907,7 +907,7 @@ LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); continue; } - if (!salvageDebugInfo(*Inst)) + if (!Inst->salvageDebugInfo()) replaceDbgUsesWithUndef(Inst); removeMSSA(Inst); Inst->eraseFromParent(); Index: llvm/lib/Transforms/Scalar/GVN.cpp =================================================================== --- llvm/lib/Transforms/Scalar/GVN.cpp +++ llvm/lib/Transforms/Scalar/GVN.cpp @@ -2177,7 +2177,7 @@ for (auto *I : InstrsToErase) { assert(I->getParent() == BB && "Removing instruction from wrong block?"); LLVM_DEBUG(dbgs() << "GVN removed: " << *I << '\n'); - salvageDebugInfo(*I); + I->salvageDebugInfo(); if (MD) MD->removeInstruction(I); LLVM_DEBUG(verifyRemoved(I)); ICF->removeInstruction(I); Index: llvm/lib/Transforms/Scalar/LICM.cpp =================================================================== --- llvm/lib/Transforms/Scalar/LICM.cpp +++ llvm/lib/Transforms/Scalar/LICM.cpp @@ -529,7 +529,7 @@ // used in the loop, instead, just delete it. if (isInstructionTriviallyDead(&I, TLI)) { LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); - salvageDebugInfo(I); + I.salvageDebugInfo(); ++II; eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); Changed = true; Index: llvm/lib/Transforms/Scalar/SROA.cpp =================================================================== --- llvm/lib/Transforms/Scalar/SROA.cpp +++ llvm/lib/Transforms/Scalar/SROA.cpp @@ -4465,7 +4465,7 @@ for (Instruction *DeadUser : AS.getDeadUsers()) { // Try to preserve debug information attached to the instruction. - salvageDebugInfo(*DeadUser); + DeadUser->salvageDebugInfo(); // Free up everything used by this instruction. for (Use &DeadOp : DeadUser->operands()) @@ -4517,7 +4517,7 @@ LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n"); // Try to preserve debug information attached to the dead instruction. - salvageDebugInfo(*I); + I->salvageDebugInfo(); // If the instruction is an alloca, find the possible dbg.declare connected // to it, and remove it too. We must do this before calling RAUW or we will // not be able to find it. Index: llvm/lib/Transforms/Utils/CodeExtractor.cpp =================================================================== --- llvm/lib/Transforms/Utils/CodeExtractor.cpp +++ llvm/lib/Transforms/Utils/CodeExtractor.cpp @@ -1583,7 +1583,7 @@ // from the old function. SmallVector DbgUsers; for (Instruction &I : BB) - findDbgUsers(DbgUsers, &I); + I.findDbgUsers(DbgUsers); for (DbgVariableIntrinsic *DVI : DbgUsers) DVI->eraseFromParent(); } Index: llvm/lib/Transforms/Utils/Local.cpp =================================================================== --- llvm/lib/Transforms/Utils/Local.cpp +++ llvm/lib/Transforms/Utils/Local.cpp @@ -466,7 +466,7 @@ "Live instruction found in dead worklist!"); // Don't lose the debug info while deleting the instructions. - salvageDebugInfo(I); + I.salvageDebugInfo(); // Null out all of the instruction's operands to see if any operand becomes // dead as we go. @@ -493,7 +493,7 @@ bool llvm::replaceDbgUsesWithUndef(Instruction *I) { SmallVector DbgUsers; - findDbgUsers(DbgUsers, I); + I->findDbgUsers(DbgUsers); for (auto *DII : DbgUsers) { Value *Undef = UndefValue::get(I->getType()); DII->setOperand(0, MetadataAsValue::get(DII->getContext(), @@ -551,7 +551,7 @@ const DataLayout &DL, const TargetLibraryInfo *TLI) { if (isInstructionTriviallyDead(I, TLI)) { - salvageDebugInfo(*I); + I->salvageDebugInfo(); // Null out all of the instruction's operands to see if any operand becomes // dead as we go. @@ -1426,6 +1426,9 @@ })) continue; + // Try to preserve debug information attached to the instruction. + AI->salvageDebugInfo(); + for (auto &AIUse : AI->uses()) { User *U = AIUse.getUser(); if (StoreInst *SI = dyn_cast(U)) { @@ -1528,19 +1531,6 @@ DbgValues.push_back(DVI); } -void llvm::findDbgUsers(SmallVectorImpl &DbgUsers, - Value *V) { - // This function is hot. Check whether the value has any metadata to avoid a - // DenseMap lookup. - if (!V->isUsedByMetadata()) - return; - if (auto *L = LocalAsMetadata::getIfExists(V)) - if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) - for (User *U : MDV->users()) - if (DbgVariableIntrinsic *DII = dyn_cast(U)) - DbgUsers.push_back(DII); -} - bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress, Instruction *InsertBefore, DIBuilder &Builder, uint8_t DIExprFlags, int Offset) { @@ -1607,225 +1597,11 @@ return MetadataAsValue::get(C, ValueAsMetadata::get(V)); } -bool llvm::salvageDebugInfo(Instruction &I) { - SmallVector DbgUsers; - - // Return false if any of the operand is already deleted - for (unsigned i = 0; i < I.getNumOperands(); ++i) - if (!I.getOperand(i)) - return false; - - // Preserve the information we may need later when called function from - // current function is inlined. We need this information for - // DW_OP_LLVM_implicit_pointer. - if (auto DDI = dyn_cast(&I)) - if (I.getModule()->getDwarfVersion() >= 5) - if (DDI->isAddressOfVariable()) - I.getModule()->insertVarAddressMap(DDI); - - findDbgUsers(DbgUsers, &I); - if (DbgUsers.empty()) - return false; - - return salvageDebugInfoForDbgValues(I, DbgUsers); -} - void llvm::salvageDebugInfoOrMarkUndef(Instruction &I) { - if (!salvageDebugInfo(I)) + if (!I.salvageDebugInfo()) replaceDbgUsesWithUndef(&I); } -bool llvm::salvageDebugInfoForDbgValues( - Instruction &I, ArrayRef DbgUsers) { - auto &Ctx = I.getContext(); - auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); }; - bool Changed = false; - Value *DebugDeclareAddress = nullptr; - - if ((I.getModule()->getDwarfVersion() >= 5) && isa(I)) { - for (auto *DII : DbgUsers) { - if (DII->isAddressOfVariable()) { - if (const llvm::MetadataAsValue *MDV = - dyn_cast(DII->getOperand(1))) - if (isa(MDV->getMetadata())) { - DebugDeclareAddress = DII->getOperand(1); - } - break; - } - } - if (!DebugDeclareAddress) - DebugDeclareAddress = I.getModule()->findVarAddressMap(&I); - } - - for (auto *DII : DbgUsers) { - // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they - // are implicitly pointing out the value as a DWARF memory location - // description. - bool StackValue = isa(DII); - - DIExpression *DIExpr = - salvageDebugInfoImpl(I, DII->getExpression(), StackValue); - - // salvageDebugInfoImpl should fail on examining the first element of - // DbgUsers, or none of them. - if (!DIExpr) - continue; - - int64_t ExprOffset = 0; - - // It is AllocaInst and either of below is true then continue - // - We failed to get the variable description, or - // - Current instruction is not llvm.dbg.value, or - // - Current instruction doesnt have constant offset - if (isa(I) && - (!DebugDeclareAddress || DII->isAddressOfVariable() || - !DII->getExpression()->extractIfOffset(ExprOffset))) - continue; - - if (isa(I)) { - // It will cause below transformation - // - // Before transformation - // - // %a = alloca [2 x i32], align 4 - // call void @llvm.dbg.declare(metadata [2 x i32]* %arr, metadata !16, - // metadata !DIExpression()), !dbg !22 - // - // call void @llvm.dbg.value(metadata [2 x i32]* %arr, metadata !20, - // metadata !DIExpression()), !dbg !24 - // - // call void @llvm.dbg.value(metadata [2 x i32]* %arr, metadata !20, - // metadata !DIExpression(DW_OP_plus_uconst, 4, DW_OP_stack_value)), - // !dbg !24 - // - // !16 = !DILocalVariable(name: "arr", scope: !12, file: !3, line: 5, - // type: !17) !20 = !DILocalVariable(name: "ptr", scope: !12, file: !3, - // line: 6, type: !21) - // - // - // After transformation - // - // %a = alloca [2 x i32], align 4 - // call void @llvm.dbg.declare(metadata [2 x i32]* %arr, metadata !16, - // metadata !DIExpression()), !dbg !22 - // - // call void @llvm.dbg.deref_value(metadata !16, metadata !20, metadata - // !DIExpression(DW_OP_LLVM_implicit_pointer, DW_OP_LLVM_arg0, 0)), !dbg - // !24 - // - // call void @llvm.dbg.deref_value(metadata !16, metadata !20, metadata - // !DIExpression(DW_OP_LLVM_implicit_pointer, DW_OP_LLVM_arg0, 4)), !dbg - // !24 - // - SmallVector Ops; - Ops.push_back(dwarf::DW_OP_LLVM_implicit_pointer); - Ops.push_back(dwarf::DW_OP_LLVM_arg0); - Ops.push_back(ExprOffset); - DIExpr = DIExpression::get(DIExpr->getContext(), Ops); - DIBuilder DIB(*I.getModule(), /*AllowUnresolved*/ false); - DIB.insertDbgDerefValueIntrinsic(DebugDeclareAddress, - DII->getVariable(), DIExpr, - DII->getDebugLoc(), DII); - DII->eraseFromParent(); - } else { - DII->setOperand(0, wrapMD(I.getOperand(0))); - - DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr)); - LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n'); - } - Changed = true; - } - - return Changed; -} - -DIExpression *llvm::salvageDebugInfoImpl(Instruction &I, - DIExpression *SrcDIExpr, - bool WithStackValue) { - auto &M = *I.getModule(); - auto &DL = M.getDataLayout(); - - // Apply a vector of opcodes to the source DIExpression. - auto doSalvage = [&](SmallVectorImpl &Ops) -> DIExpression * { - DIExpression *DIExpr = SrcDIExpr; - if (!Ops.empty()) { - DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue); - } - return DIExpr; - }; - - // Apply the given offset to the source DIExpression. - auto applyOffset = [&](uint64_t Offset) -> DIExpression * { - SmallVector Ops; - DIExpression::appendOffset(Ops, Offset); - return doSalvage(Ops); - }; - - // initializer-list helper for applying operators to the source DIExpression. - auto applyOps = - [&](std::initializer_list Opcodes) -> DIExpression * { - SmallVector Ops(Opcodes); - return doSalvage(Ops); - }; - - if (auto *CI = dyn_cast(&I)) { - // No-op casts and zexts are irrelevant for debug info. - if (CI->isNoopCast(DL) || isa(&I)) - return SrcDIExpr; - return nullptr; - } else if (auto *GEP = dyn_cast(&I)) { - unsigned BitWidth = - M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace()); - // Rewrite a constant GEP into a DIExpression. - APInt Offset(BitWidth, 0); - if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) { - return applyOffset(Offset.getSExtValue()); - } else { - return nullptr; - } - } else if (auto *BI = dyn_cast(&I)) { - // Rewrite binary operations with constant integer operands. - auto *ConstInt = dyn_cast(I.getOperand(1)); - if (!ConstInt || ConstInt->getBitWidth() > 64) - return nullptr; - - uint64_t Val = ConstInt->getSExtValue(); - switch (BI->getOpcode()) { - case Instruction::Add: - return applyOffset(Val); - case Instruction::Sub: - return applyOffset(-int64_t(Val)); - case Instruction::Mul: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul}); - case Instruction::SDiv: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div}); - case Instruction::SRem: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod}); - case Instruction::Or: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or}); - case Instruction::And: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and}); - case Instruction::Xor: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor}); - case Instruction::Shl: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl}); - case Instruction::LShr: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr}); - case Instruction::AShr: - return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra}); - default: - // TODO: Salvage constants from each kind of binop we know about. - return nullptr; - } - // *Not* to do: we should not attempt to salvage load instructions, - // because the validity and lifetime of a dbg.value containing - // DW_OP_deref becomes difficult to analyze. See PR40628 for examples. - } else if ((M.getDwarfVersion() >= 5) && isa(&I)) { - return SrcDIExpr; - } - return nullptr; -} - /// A replacement for a dbg.value expression. using DbgValReplacement = Optional; @@ -1837,7 +1613,7 @@ function_ref RewriteExpr) { // Find debug users of From. SmallVector Users; - findDbgUsers(Users, &From); + From.findDbgUsers(Users); if (Users.empty()) return false; @@ -1881,7 +1657,7 @@ if (!DeleteOrSalvage.empty()) { // Try to salvage the remaining debug users. - Changed |= salvageDebugInfo(From); + Changed |= From.salvageDebugInfo(); // Delete the debug users which weren't salvaged. for (auto *DII : DeleteOrSalvage) { @@ -2684,7 +2460,7 @@ void llvm::dropDebugUsers(Instruction &I) { SmallVector DbgUsers; - findDbgUsers(DbgUsers, &I); + I.findDbgUsers(DbgUsers); for (auto *DII : DbgUsers) DII->eraseFromParent(); } Index: llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp =================================================================== --- llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp +++ llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp @@ -411,7 +411,7 @@ return false; // If not, we'll have to fall back for the remainder. // Try to preserve debug information attached to the dead instruction. - salvageDebugInfo(*AI); + AI->salvageDebugInfo(); // Record debuginfo for the store and remove the declaration's // debuginfo. @@ -510,7 +510,7 @@ } // Try to preserve debug information attached to the dead instruction. - salvageDebugInfo(*AI); + AI->salvageDebugInfo(); // Remove the (now dead) stores and alloca. while (!AI->use_empty()) { Index: llvm/test/DebugInfo/dwarfdump-implicit_pointer_instcomb.c =================================================================== --- /dev/null +++ llvm/test/DebugInfo/dwarfdump-implicit_pointer_instcomb.c @@ -0,0 +1,28 @@ +// RUN: clang %s -O2 -gdwarf-5 -o %t.o +// RUN: llvm-dwarfdump %t.o | FileCheck %s + +// CHECK-LABEL: DW_AT_name ("var") +// CHECK-LABEL: DW_TAG_variable +// CHECK-NEXT: DW_AT_location +// CHECK-NEXT: DW_OP_implicit_pointer [[DIE:0x.+]] +0 + +// CHECK-LABEL: DW_TAG_formal_parameter +// CHECK-NEXT: DW_AT_location +// CHECK-NEXT: DW_OP_implicit_pointer [[DIE]] +0 +// CHECK-NEXT: "ptr" + +volatile int gvar = 7; + +int func(int *ptr) { + gvar = *ptr; + return *ptr + 5; +} + +int main() { + int var = 4; + int *ptrVar = &var; + + int res = func(ptrVar); + + return res; +} Index: llvm/test/DebugInfo/implicit_pointer_instcomb.c =================================================================== --- /dev/null +++ llvm/test/DebugInfo/implicit_pointer_instcomb.c @@ -0,0 +1,21 @@ +// RUN: clang %s -O2 -gdwarf-5 -S -emit-llvm -o %t.ll +// RUN: FileCheck %s --input-file=%t.ll + +// CHECK: !DIExpression(DW_OP_LLVM_implicit_pointer, DW_OP_LLVM_arg0, 0) +// CHECK: !DIExpression(DW_OP_LLVM_implicit_pointer, DW_OP_LLVM_arg0, 0) + +volatile int gvar = 7; + +int func(int *ptr) { + gvar = *ptr; + return *ptr + 5; +} + +int main() { + int var = 4; + int *ptrVar = &var; + + int res = func(ptrVar); + + return res; +} Index: llvm/unittests/Transforms/Utils/LocalTest.cpp =================================================================== --- llvm/unittests/Transforms/Utils/LocalTest.cpp +++ llvm/unittests/Transforms/Utils/LocalTest.cpp @@ -732,7 +732,7 @@ EXPECT_TRUE(replaceAllDbgUsesWith(D, C, C, DT)); SmallVector CDbgVals; - findDbgUsers(CDbgVals, &C); + C.findDbgUsers(CDbgVals); EXPECT_EQ(2U, CDbgVals.size()); EXPECT_TRUE(any_of(CDbgVals, [](DbgVariableIntrinsic *DII) { return isa(DII); @@ -744,7 +744,7 @@ EXPECT_TRUE(replaceAllDbgUsesWith(C, D, D, DT)); SmallVector DDbgVals; - findDbgUsers(DDbgVals, &D); + D.findDbgUsers(DDbgVals); EXPECT_EQ(2U, DDbgVals.size()); EXPECT_TRUE(any_of(DDbgVals, [](DbgVariableIntrinsic *DII) { return isa(DII);