1//===--- DXILDebugInfo.cpp - analysis&lowering for Debug info -*- C++ -*- ---=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "../DirectX.h"
10#include "DXILAttributes.h"
11#include "llvm/ADT/DenseSet.h"
12#include "llvm/BinaryFormat/Dwarf.h"
13#include "llvm/IR/AttributeMask.h"
14#include "llvm/IR/Attributes.h"
15#include "llvm/IR/DebugInfo.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/Module.h"
18#include "llvm/Pass.h"
19#include "llvm/Support/Casting.h"
20#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21
22#define DEBUG_TYPE "dx-debug-info"
23
24using namespace llvm;
25using namespace llvm::dxil;
26
27static bool lowerDXILDebugInfo(Module &M) {
28 // Convert debug markers back to dbg.value intrinsics. Record whether any
29 // changes were made.
30 bool Modified = M.convertFromNewDbgValues();
31 DebugInfoFinder DIF;
32 DIF.processModule(M);
33
34 {
35 Function *DVDecl = nullptr;
36
37 // Logically these should be variables in the
38 // for (BasicBlock &BB : F) loop.
39 // They are defined here and cleared at the start of the loop body to avoid
40 // the cost of deconstruction and reconstruction.
41 DenseMap<DILocalVariable *, std::pair<Instruction *, DbgValueInst *>>
42 DbgValues;
43 DenseMap<std::pair<DILocalVariable *, DIExpression *>,
44 std::pair<Instruction *, DbgValueInst *>>
45 DbgValueFragments;
46 // Likewise, logically, this should be a variable in the
47 // for (Function &F : M) loop.
48 DenseSet<DILocalVariable *> DbgVariablesSeen;
49
50 const AttributeMask &AttrMask = getNonDXILAttributeMask();
51
52 for (Function &F : M) {
53 F.removeFnAttrs(Attrs: AttrMask);
54 F.removeRetAttrs(Attrs: AttrMask);
55 for (unsigned ArgNo = 0; ArgNo != F.arg_size(); ++ArgNo)
56 F.removeParamAttrs(ArgNo, Attrs: AttrMask);
57
58 bool IsEntryBlock = true;
59 DbgVariablesSeen.clear();
60 for (BasicBlock &BB : F) {
61 Instruction *NextNonDebugInst = nullptr;
62 DbgValues.clear();
63 DbgValueFragments.clear();
64 for (Instruction &I : make_early_inc_range(Range: reverse(C&: BB))) {
65 I.eraseMetadataIf(Pred: [](unsigned KindID, MDNode *) {
66 return KindID == LLVMContext::MD_DIAssignID;
67 });
68 if (!isa<DbgInfoIntrinsic>(Val: I)) {
69 NextNonDebugInst = &I;
70 continue;
71 }
72 if (auto *DL = dyn_cast<DbgLabelInst>(Val: &I)) {
73 DL->eraseFromParent();
74 Modified = true;
75 continue;
76 }
77 // Process both llvm.dbg.value and llvm.dbg.assign here. We convert
78 // llvm.dbg.assign to llvm.dbg.value by dropping the last arguments,
79 // and remove redundant llvm.dbg.values.
80 if (auto *DV = dyn_cast<DbgValueInst>(Val: &I)) {
81 // Keep track of the last location where we saw any debug value for
82 // a variable.
83 DILocalVariable *V = DV->getVariable();
84 DIExpression *E = DV->getExpression();
85 // If this is already an llvm.dbg.value instruction that we can
86 // keep, just do that, otherwise convert it.
87 auto *Val = cast<MetadataAsValue>(Val: DV->getArgOperand(i: 0));
88 auto *Var = cast<MetadataAsValue>(Val: DV->getArgOperand(i: 1));
89 auto *Expr = cast<MetadataAsValue>(Val: DV->getArgOperand(i: 2));
90 bool Replace = DV->getIntrinsicID() != Intrinsic::dbg_value;
91 if (!isa<ValueAsMetadata>(Val: Val->getMetadata())) {
92 // This may be a DIArgList which is not supported in LLVM 3.7. If
93 // it is, we cannot record the new value, but we still need to
94 // kill any old value. Do this by poison. We do not know the
95 // correct type to use here and arbitrarily use i1.
96 // This should never be anything other than ValueAsMetadata or
97 // DIArgList, but in manually constructed LLVM IR, it can be.
98 // Handle this gracefully by also replacing it with poison.
99 Val = MetadataAsValue::get(
100 Context&: M.getContext(), MD: ConstantAsMetadata::get(C: PoisonValue::get(
101 T: Type::getInt1Ty(C&: M.getContext()))));
102 E = DIExpression::get(Context&: M.getContext(), Elements: {});
103 Expr = MetadataAsValue::get(Context&: M.getContext(), MD: E);
104 Replace = true;
105 }
106 std::pair<Instruction *, DbgValueInst *> &DbgValue = DbgValues[V];
107 std::pair<Instruction *, DbgValueInst *> &DbgValueFragment =
108 DbgValueFragments[{V, E}];
109 if (DbgValue.second) {
110 // If there is a later value of the same fragment at the same
111 // location, this value is redundant.
112 if (DbgValueFragment.first == NextNonDebugInst) {
113 DV->eraseFromParent();
114 Modified = true;
115 continue;
116 }
117 // If there is a later identical value of the same fragment at a
118 // later point, and there have been no intervening values of
119 // different possibly overlapping fragments, that later value is
120 // redundant.
121 if (DbgValueFragment.second &&
122 DbgValueFragment.second == DbgValue.second &&
123 DbgValueFragment.second->getValue() == DV->getValue()) {
124 DbgValue.second->eraseFromParent();
125 Modified = true;
126 }
127 }
128 DbgValueInst *NewDV;
129 if (Replace) {
130 if (!DVDecl) {
131 DVDecl =
132 Intrinsic::getOrInsertDeclaration(M: &M, id: Intrinsic::dbg_value);
133 AttributeMask AM;
134 for (Attribute A : DVDecl->getAttributes().getFnAttrs())
135 if (A.isStringAttribute() ||
136 (A.getKindAsEnum() != Attribute::NoUnwind &&
137 A.getKindAsEnum() != Attribute::Memory))
138 AM.addAttribute(A);
139 DVDecl->removeFnAttrs(Attrs: AM);
140 }
141 NewDV = cast<DbgValueInst>(
142 Val: CallInst::Create(Func: DVDecl, Args: {Val, Var, Expr}, Bundles: {}, NameStr: "",
143 InsertBefore: std::next(x: DV->getIterator())));
144 NewDV->setTailCall();
145 NewDV->setDebugLoc(DV->getDebugLoc());
146 DV->eraseFromParent();
147 Modified = true;
148 } else {
149 NewDV = DV;
150 }
151 DbgValue = DbgValueFragment = {NextNonDebugInst, NewDV};
152 continue;
153 }
154 }
155 // If this is the entry block, if the first value we see for each debug
156 // value is undef, it is redundant.
157 if (IsEntryBlock) {
158 for (Instruction &I : make_early_inc_range(Range&: BB)) {
159 auto *DV = dyn_cast<DbgValueInst>(Val: &I);
160 if (!DV || DbgVariablesSeen.contains(V: DV->getVariable()))
161 continue;
162 if (isa<UndefValue>(Val: DV->getValue())) {
163 DV->eraseFromParent();
164 Modified = true;
165 continue;
166 }
167 DbgVariablesSeen.insert(V: DV->getVariable());
168 }
169 }
170 IsEntryBlock = false;
171 }
172 }
173 }
174
175 for (DISubprogram *SP : DIF.subprograms()) {
176 if (MDTuple *RN = cast_or_null<MDTuple>(Val: SP->getRawRetainedNodes())) {
177 SmallVector<Metadata *> MDs(RN->operands());
178 MDs.erase(CS: std::remove_if(first: MDs.begin(), last: MDs.end(),
179 pred: [](Metadata *M) { return isa<DILabel>(Val: M); }),
180 CE: MDs.end());
181 SP->replaceRetainedNodes(N: MDTuple::get(Context&: M.getContext(), MDs));
182 Modified = true;
183 }
184 }
185
186 return Modified;
187}
188
189PreservedAnalyses DXILDebugInfoPass::run(Module &M, ModuleAnalysisManager &) {
190 return lowerDXILDebugInfo(M) ? PreservedAnalyses::none()
191 : PreservedAnalyses::all();
192}
193
194namespace {
195class DXILDebugInfoLegacy : public ModulePass {
196public:
197 static char ID;
198
199 DXILDebugInfoLegacy() : ModulePass(ID) {}
200
201 bool runOnModule(Module &M) override { return lowerDXILDebugInfo(M); }
202
203 void getAnalysisUsage(AnalysisUsage &AU) const override {
204 AU.setPreservesAll();
205 }
206};
207} // namespace
208
209char DXILDebugInfoLegacy::ID = 0;
210
211INITIALIZE_PASS(DXILDebugInfoLegacy, DEBUG_TYPE, "DXIL Debug Info", false,
212 false)
213
214ModulePass *llvm::createDXILDebugInfoLegacyPass() {
215 return new DXILDebugInfoLegacy();
216}
217