1 //===-- llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp -------*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Common functionality for different debug information format backends.
11 // LLVM currently supports DWARF and CodeView.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "DebugHandlerBase.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
25 
26 using namespace llvm;
27 
28 Optional<DbgVariableLocation>
29 DbgVariableLocation::extractFromMachineInstruction(
30     const MachineInstr &Instruction) {
31   DbgVariableLocation Location;
32   if (!Instruction.isDebugValue())
33     return None;
34   if (!Instruction.getOperand(0).isReg())
35     return None;
36   Location.Register = Instruction.getOperand(0).getReg();
37   Location.InMemory = Instruction.getOperand(1).isImm();
38   Location.Deref = false;
39   Location.FragmentInfo.reset();
40   // We only handle expressions generated by DIExpression::appendOffset,
41   // which doesn't require a full stack machine.
42   int64_t Offset = 0;
43   const DIExpression *DIExpr = Instruction.getDebugExpression();
44   auto Op = DIExpr->expr_op_begin();
45   while (Op != DIExpr->expr_op_end()) {
46     switch (Op->getOp()) {
47     case dwarf::DW_OP_constu: {
48       int Value = Op->getArg(0);
49       ++Op;
50       if (Op != DIExpr->expr_op_end()) {
51         switch (Op->getOp()) {
52         case dwarf::DW_OP_minus:
53           Offset -= Value;
54           break;
55         case dwarf::DW_OP_plus:
56           Offset += Value;
57           break;
58         default:
59           continue;
60         }
61       }
62     } break;
63     case dwarf::DW_OP_plus_uconst:
64       Offset += Op->getArg(0);
65       break;
66     case dwarf::DW_OP_LLVM_fragment:
67       Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)};
68       break;
69     case dwarf::DW_OP_deref:
70       Location.Deref = true;
71       break;
72     default:
73       return None;
74     }
75     ++Op;
76   }
77 
78   Location.Offset = Offset;
79   return Location;
80 }
81 
82 DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
83 
84 // Each LexicalScope has first instruction and last instruction to mark
85 // beginning and end of a scope respectively. Create an inverse map that list
86 // scopes starts (and ends) with an instruction. One instruction may start (or
87 // end) multiple scopes. Ignore scopes that are not reachable.
88 void DebugHandlerBase::identifyScopeMarkers() {
89   SmallVector<LexicalScope *, 4> WorkList;
90   WorkList.push_back(LScopes.getCurrentFunctionScope());
91   while (!WorkList.empty()) {
92     LexicalScope *S = WorkList.pop_back_val();
93 
94     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
95     if (!Children.empty())
96       WorkList.append(Children.begin(), Children.end());
97 
98     if (S->isAbstractScope())
99       continue;
100 
101     for (const InsnRange &R : S->getRanges()) {
102       assert(R.first && "InsnRange does not have first instruction!");
103       assert(R.second && "InsnRange does not have second instruction!");
104       requestLabelBeforeInsn(R.first);
105       requestLabelAfterInsn(R.second);
106     }
107   }
108 }
109 
110 // Return Label preceding the instruction.
111 MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) {
112   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
113   assert(Label && "Didn't insert label before instruction");
114   return Label;
115 }
116 
117 // Return Label immediately following the instruction.
118 MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) {
119   return LabelsAfterInsn.lookup(MI);
120 }
121 
122 int DebugHandlerBase::fragmentCmp(const DIExpression *P1,
123                                   const DIExpression *P2) {
124   auto Fragment1 = *P1->getFragmentInfo();
125   auto Fragment2 = *P2->getFragmentInfo();
126   unsigned l1 = Fragment1.OffsetInBits;
127   unsigned l2 = Fragment2.OffsetInBits;
128   unsigned r1 = l1 + Fragment1.SizeInBits;
129   unsigned r2 = l2 + Fragment2.SizeInBits;
130   if (r1 <= l2)
131     return -1;
132   else if (r2 <= l1)
133     return 1;
134   else
135     return 0;
136 }
137 
138 bool DebugHandlerBase::fragmentsOverlap(const DIExpression *P1,
139                                         const DIExpression *P2) {
140   if (!P1->isFragment() || !P2->isFragment())
141     return true;
142   return fragmentCmp(P1, P2) == 0;
143 }
144 
145 /// If this type is derived from a base type then return base type size.
146 uint64_t DebugHandlerBase::getBaseTypeSize(const DITypeRef TyRef) {
147   DIType *Ty = TyRef.resolve();
148   assert(Ty);
149   DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
150   if (!DDTy)
151     return Ty->getSizeInBits();
152 
153   unsigned Tag = DDTy->getTag();
154 
155   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
156       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
157       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type)
158     return DDTy->getSizeInBits();
159 
160   DIType *BaseType = DDTy->getBaseType().resolve();
161 
162   assert(BaseType && "Unexpected invalid base type");
163 
164   // If this is a derived type, go ahead and get the base type, unless it's a
165   // reference then it's just the size of the field. Pointer types have no need
166   // of this since they're a different type of qualification on the type.
167   if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
168       BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
169     return Ty->getSizeInBits();
170 
171   return getBaseTypeSize(BaseType);
172 }
173 
174 static bool hasDebugInfo(const MachineModuleInfo *MMI,
175                          const MachineFunction *MF) {
176   if (!MMI->hasDebugInfo())
177     return false;
178   auto *SP = MF->getFunction()->getSubprogram();
179   if (!SP)
180     return false;
181   assert(SP->getUnit());
182   auto EK = SP->getUnit()->getEmissionKind();
183   if (EK == DICompileUnit::NoDebug)
184     return false;
185   return true;
186 }
187 
188 void DebugHandlerBase::beginFunction(const MachineFunction *MF) {
189   PrevInstBB = nullptr;
190 
191   if (!Asm || !hasDebugInfo(MMI, MF)) {
192     skippedNonDebugFunction();
193     return;
194   }
195 
196   // Grab the lexical scopes for the function, if we don't have any of those
197   // then we're not going to be able to do anything.
198   LScopes.initialize(*MF);
199   if (LScopes.empty()) {
200     beginFunctionImpl(MF);
201     return;
202   }
203 
204   // Make sure that each lexical scope will have a begin/end label.
205   identifyScopeMarkers();
206 
207   // Calculate history for local variables.
208   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
209   calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
210                            DbgValues);
211 
212   // Request labels for the full history.
213   for (const auto &I : DbgValues) {
214     const auto &Ranges = I.second;
215     if (Ranges.empty())
216       continue;
217 
218     // The first mention of a function argument gets the CurrentFnBegin
219     // label, so arguments are visible when breaking at function entry.
220     const DILocalVariable *DIVar = Ranges.front().first->getDebugVariable();
221     if (DIVar->isParameter() &&
222         getDISubprogram(DIVar->getScope())->describes(MF->getFunction())) {
223       LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
224       if (Ranges.front().first->getDebugExpression()->isFragment()) {
225         // Mark all non-overlapping initial fragments.
226         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
227           const DIExpression *Fragment = I->first->getDebugExpression();
228           if (std::all_of(Ranges.begin(), I,
229                           [&](DbgValueHistoryMap::InstrRange Pred) {
230                             return !fragmentsOverlap(
231                                 Fragment, Pred.first->getDebugExpression());
232                           }))
233             LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
234           else
235             break;
236         }
237       }
238     }
239 
240     for (const auto &Range : Ranges) {
241       requestLabelBeforeInsn(Range.first);
242       if (Range.second)
243         requestLabelAfterInsn(Range.second);
244     }
245   }
246 
247   PrevInstLoc = DebugLoc();
248   PrevLabel = Asm->getFunctionBegin();
249   beginFunctionImpl(MF);
250 }
251 
252 void DebugHandlerBase::beginInstruction(const MachineInstr *MI) {
253   if (!MMI->hasDebugInfo())
254     return;
255 
256   assert(CurMI == nullptr);
257   CurMI = MI;
258 
259   // Insert labels where requested.
260   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
261       LabelsBeforeInsn.find(MI);
262 
263   // No label needed.
264   if (I == LabelsBeforeInsn.end())
265     return;
266 
267   // Label already assigned.
268   if (I->second)
269     return;
270 
271   if (!PrevLabel) {
272     PrevLabel = MMI->getContext().createTempSymbol();
273     Asm->OutStreamer->EmitLabel(PrevLabel);
274   }
275   I->second = PrevLabel;
276 }
277 
278 void DebugHandlerBase::endInstruction() {
279   if (!MMI->hasDebugInfo())
280     return;
281 
282   assert(CurMI != nullptr);
283   // Don't create a new label after DBG_VALUE and other instructions that don't
284   // generate code.
285   if (!CurMI->isMetaInstruction()) {
286     PrevLabel = nullptr;
287     PrevInstBB = CurMI->getParent();
288   }
289 
290   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
291       LabelsAfterInsn.find(CurMI);
292   CurMI = nullptr;
293 
294   // No label needed.
295   if (I == LabelsAfterInsn.end())
296     return;
297 
298   // Label already assigned.
299   if (I->second)
300     return;
301 
302   // We need a label after this instruction.
303   if (!PrevLabel) {
304     PrevLabel = MMI->getContext().createTempSymbol();
305     Asm->OutStreamer->EmitLabel(PrevLabel);
306   }
307   I->second = PrevLabel;
308 }
309 
310 void DebugHandlerBase::endFunction(const MachineFunction *MF) {
311   if (hasDebugInfo(MMI, MF))
312     endFunctionImpl(MF);
313   DbgValues.clear();
314   LabelsBeforeInsn.clear();
315   LabelsAfterInsn.clear();
316 }
317