1 //===-- llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp -------*- 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 // Common functionality for different debug information format backends. 10 // LLVM currently supports DWARF and CodeView. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/DebugHandlerBase.h" 15 #include "llvm/ADT/Optional.h" 16 #include "llvm/ADT/Twine.h" 17 #include "llvm/CodeGen/AsmPrinter.h" 18 #include "llvm/CodeGen/MachineFunction.h" 19 #include "llvm/CodeGen/MachineInstr.h" 20 #include "llvm/CodeGen/MachineModuleInfo.h" 21 #include "llvm/CodeGen/TargetSubtargetInfo.h" 22 #include "llvm/IR/DebugInfo.h" 23 #include "llvm/MC/MCStreamer.h" 24 #include "llvm/Support/CommandLine.h" 25 26 using namespace llvm; 27 28 #define DEBUG_TYPE "dwarfdebug" 29 30 /// If true, we drop variable location ranges which exist entirely outside the 31 /// variable's lexical scope instruction ranges. 32 static cl::opt<bool> TrimVarLocs("trim-var-locs", cl::Hidden, cl::init(true)); 33 34 Optional<DbgVariableLocation> 35 DbgVariableLocation::extractFromMachineInstruction( 36 const MachineInstr &Instruction) { 37 DbgVariableLocation Location; 38 if (!Instruction.isDebugValue()) 39 return None; 40 if (!Instruction.getDebugOperand(0).isReg()) 41 return None; 42 Location.Register = Instruction.getDebugOperand(0).getReg(); 43 Location.FragmentInfo.reset(); 44 // We only handle expressions generated by DIExpression::appendOffset, 45 // which doesn't require a full stack machine. 46 int64_t Offset = 0; 47 const DIExpression *DIExpr = Instruction.getDebugExpression(); 48 auto Op = DIExpr->expr_op_begin(); 49 while (Op != DIExpr->expr_op_end()) { 50 switch (Op->getOp()) { 51 case dwarf::DW_OP_constu: { 52 int Value = Op->getArg(0); 53 ++Op; 54 if (Op != DIExpr->expr_op_end()) { 55 switch (Op->getOp()) { 56 case dwarf::DW_OP_minus: 57 Offset -= Value; 58 break; 59 case dwarf::DW_OP_plus: 60 Offset += Value; 61 break; 62 default: 63 continue; 64 } 65 } 66 } break; 67 case dwarf::DW_OP_plus_uconst: 68 Offset += Op->getArg(0); 69 break; 70 case dwarf::DW_OP_LLVM_fragment: 71 Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)}; 72 break; 73 case dwarf::DW_OP_deref: 74 Location.LoadChain.push_back(Offset); 75 Offset = 0; 76 break; 77 default: 78 return None; 79 } 80 ++Op; 81 } 82 83 // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE 84 // instruction. 85 // FIXME: Replace these with DIExpression. 86 if (Instruction.isIndirectDebugValue()) 87 Location.LoadChain.push_back(Offset); 88 89 return Location; 90 } 91 92 DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {} 93 94 // Each LexicalScope has first instruction and last instruction to mark 95 // beginning and end of a scope respectively. Create an inverse map that list 96 // scopes starts (and ends) with an instruction. One instruction may start (or 97 // end) multiple scopes. Ignore scopes that are not reachable. 98 void DebugHandlerBase::identifyScopeMarkers() { 99 SmallVector<LexicalScope *, 4> WorkList; 100 WorkList.push_back(LScopes.getCurrentFunctionScope()); 101 while (!WorkList.empty()) { 102 LexicalScope *S = WorkList.pop_back_val(); 103 104 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren(); 105 if (!Children.empty()) 106 WorkList.append(Children.begin(), Children.end()); 107 108 if (S->isAbstractScope()) 109 continue; 110 111 for (const InsnRange &R : S->getRanges()) { 112 assert(R.first && "InsnRange does not have first instruction!"); 113 assert(R.second && "InsnRange does not have second instruction!"); 114 requestLabelBeforeInsn(R.first); 115 requestLabelAfterInsn(R.second); 116 } 117 } 118 } 119 120 // Return Label preceding the instruction. 121 MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) { 122 MCSymbol *Label = LabelsBeforeInsn.lookup(MI); 123 assert(Label && "Didn't insert label before instruction"); 124 return Label; 125 } 126 127 // Return Label immediately following the instruction. 128 MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) { 129 return LabelsAfterInsn.lookup(MI); 130 } 131 132 /// If this type is derived from a base type then return base type size. 133 uint64_t DebugHandlerBase::getBaseTypeSize(const DIType *Ty) { 134 assert(Ty); 135 const DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty); 136 if (!DDTy) 137 return Ty->getSizeInBits(); 138 139 unsigned Tag = DDTy->getTag(); 140 141 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef && 142 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type && 143 Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type) 144 return DDTy->getSizeInBits(); 145 146 DIType *BaseType = DDTy->getBaseType(); 147 148 if (!BaseType) 149 return 0; 150 151 // If this is a derived type, go ahead and get the base type, unless it's a 152 // reference then it's just the size of the field. Pointer types have no need 153 // of this since they're a different type of qualification on the type. 154 if (BaseType->getTag() == dwarf::DW_TAG_reference_type || 155 BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type) 156 return Ty->getSizeInBits(); 157 158 return getBaseTypeSize(BaseType); 159 } 160 161 bool DebugHandlerBase::isUnsignedDIType(const DIType *Ty) { 162 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) { 163 // FIXME: Enums without a fixed underlying type have unknown signedness 164 // here, leading to incorrectly emitted constants. 165 if (CTy->getTag() == dwarf::DW_TAG_enumeration_type) 166 return false; 167 168 // (Pieces of) aggregate types that get hacked apart by SROA may be 169 // represented by a constant. Encode them as unsigned bytes. 170 return true; 171 } 172 173 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) { 174 dwarf::Tag T = (dwarf::Tag)Ty->getTag(); 175 // Encode pointer constants as unsigned bytes. This is used at least for 176 // null pointer constant emission. 177 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed 178 // here, but accept them for now due to a bug in SROA producing bogus 179 // dbg.values. 180 if (T == dwarf::DW_TAG_pointer_type || 181 T == dwarf::DW_TAG_ptr_to_member_type || 182 T == dwarf::DW_TAG_reference_type || 183 T == dwarf::DW_TAG_rvalue_reference_type) 184 return true; 185 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type || 186 T == dwarf::DW_TAG_volatile_type || 187 T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type); 188 assert(DTy->getBaseType() && "Expected valid base type"); 189 return isUnsignedDIType(DTy->getBaseType()); 190 } 191 192 auto *BTy = cast<DIBasicType>(Ty); 193 unsigned Encoding = BTy->getEncoding(); 194 assert((Encoding == dwarf::DW_ATE_unsigned || 195 Encoding == dwarf::DW_ATE_unsigned_char || 196 Encoding == dwarf::DW_ATE_signed || 197 Encoding == dwarf::DW_ATE_signed_char || 198 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF || 199 Encoding == dwarf::DW_ATE_boolean || 200 (Ty->getTag() == dwarf::DW_TAG_unspecified_type && 201 Ty->getName() == "decltype(nullptr)")) && 202 "Unsupported encoding"); 203 return Encoding == dwarf::DW_ATE_unsigned || 204 Encoding == dwarf::DW_ATE_unsigned_char || 205 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean || 206 Ty->getTag() == dwarf::DW_TAG_unspecified_type; 207 } 208 209 static bool hasDebugInfo(const MachineModuleInfo *MMI, 210 const MachineFunction *MF) { 211 if (!MMI->hasDebugInfo()) 212 return false; 213 auto *SP = MF->getFunction().getSubprogram(); 214 if (!SP) 215 return false; 216 assert(SP->getUnit()); 217 auto EK = SP->getUnit()->getEmissionKind(); 218 if (EK == DICompileUnit::NoDebug) 219 return false; 220 return true; 221 } 222 223 void DebugHandlerBase::beginFunction(const MachineFunction *MF) { 224 PrevInstBB = nullptr; 225 226 if (!Asm || !hasDebugInfo(MMI, MF)) { 227 skippedNonDebugFunction(); 228 return; 229 } 230 231 // Grab the lexical scopes for the function, if we don't have any of those 232 // then we're not going to be able to do anything. 233 LScopes.initialize(*MF); 234 if (LScopes.empty()) { 235 beginFunctionImpl(MF); 236 return; 237 } 238 239 // Make sure that each lexical scope will have a begin/end label. 240 identifyScopeMarkers(); 241 242 // Calculate history for local variables. 243 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!"); 244 assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!"); 245 calculateDbgEntityHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(), 246 DbgValues, DbgLabels); 247 InstOrdering.initialize(*MF); 248 if (TrimVarLocs) 249 DbgValues.trimLocationRanges(*MF, LScopes, InstOrdering); 250 LLVM_DEBUG(DbgValues.dump()); 251 252 // Request labels for the full history. 253 for (const auto &I : DbgValues) { 254 const auto &Entries = I.second; 255 if (Entries.empty()) 256 continue; 257 258 auto IsDescribedByReg = [](const MachineInstr *MI) { 259 return MI->getDebugOperand(0).isReg() && MI->getDebugOperand(0).getReg(); 260 }; 261 262 // The first mention of a function argument gets the CurrentFnBegin label, 263 // so arguments are visible when breaking at function entry. 264 // 265 // We do not change the label for values that are described by registers, 266 // as that could place them above their defining instructions. We should 267 // ideally not change the labels for constant debug values either, since 268 // doing that violates the ranges that are calculated in the history map. 269 // However, we currently do not emit debug values for constant arguments 270 // directly at the start of the function, so this code is still useful. 271 // FIXME: If the first mention of an argument is in a unique section basic 272 // block, we cannot always assign the CurrentFnBeginLabel as it lies in a 273 // different section. Temporarily, we disable generating loc list 274 // information or DW_AT_const_value when the block is in a different 275 // section. 276 const DILocalVariable *DIVar = 277 Entries.front().getInstr()->getDebugVariable(); 278 if (DIVar->isParameter() && 279 getDISubprogram(DIVar->getScope())->describes(&MF->getFunction()) && 280 Entries.front().getInstr()->getParent()->sameSection(&MF->front())) { 281 if (!IsDescribedByReg(Entries.front().getInstr())) 282 LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin(); 283 if (Entries.front().getInstr()->getDebugExpression()->isFragment()) { 284 // Mark all non-overlapping initial fragments. 285 for (auto I = Entries.begin(); I != Entries.end(); ++I) { 286 if (!I->isDbgValue()) 287 continue; 288 const DIExpression *Fragment = I->getInstr()->getDebugExpression(); 289 if (std::any_of(Entries.begin(), I, 290 [&](DbgValueHistoryMap::Entry Pred) { 291 return Pred.isDbgValue() && 292 Fragment->fragmentsOverlap( 293 Pred.getInstr()->getDebugExpression()); 294 })) 295 break; 296 // The code that generates location lists for DWARF assumes that the 297 // entries' start labels are monotonically increasing, and since we 298 // don't change the label for fragments that are described by 299 // registers, we must bail out when encountering such a fragment. 300 if (IsDescribedByReg(I->getInstr())) 301 break; 302 LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin(); 303 } 304 } 305 } 306 307 for (const auto &Entry : Entries) { 308 if (Entry.isDbgValue()) 309 requestLabelBeforeInsn(Entry.getInstr()); 310 else 311 requestLabelAfterInsn(Entry.getInstr()); 312 } 313 } 314 315 // Ensure there is a symbol before DBG_LABEL. 316 for (const auto &I : DbgLabels) { 317 const MachineInstr *MI = I.second; 318 requestLabelBeforeInsn(MI); 319 } 320 321 PrevInstLoc = DebugLoc(); 322 PrevLabel = Asm->getFunctionBegin(); 323 beginFunctionImpl(MF); 324 } 325 326 void DebugHandlerBase::beginInstruction(const MachineInstr *MI) { 327 if (!MMI->hasDebugInfo()) 328 return; 329 330 assert(CurMI == nullptr); 331 CurMI = MI; 332 333 // Insert labels where requested. 334 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 335 LabelsBeforeInsn.find(MI); 336 337 // No label needed. 338 if (I == LabelsBeforeInsn.end()) 339 return; 340 341 // Label already assigned. 342 if (I->second) 343 return; 344 345 if (!PrevLabel) { 346 PrevLabel = MMI->getContext().createTempSymbol(); 347 Asm->OutStreamer->emitLabel(PrevLabel); 348 } 349 I->second = PrevLabel; 350 } 351 352 void DebugHandlerBase::endInstruction() { 353 if (!MMI->hasDebugInfo()) 354 return; 355 356 assert(CurMI != nullptr); 357 // Don't create a new label after DBG_VALUE and other instructions that don't 358 // generate code. 359 if (!CurMI->isMetaInstruction()) { 360 PrevLabel = nullptr; 361 PrevInstBB = CurMI->getParent(); 362 } 363 364 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 365 LabelsAfterInsn.find(CurMI); 366 CurMI = nullptr; 367 368 // No label needed. 369 if (I == LabelsAfterInsn.end()) 370 return; 371 372 // Label already assigned. 373 if (I->second) 374 return; 375 376 // We need a label after this instruction. 377 if (!PrevLabel) { 378 PrevLabel = MMI->getContext().createTempSymbol(); 379 Asm->OutStreamer->emitLabel(PrevLabel); 380 } 381 I->second = PrevLabel; 382 } 383 384 void DebugHandlerBase::endFunction(const MachineFunction *MF) { 385 if (hasDebugInfo(MMI, MF)) 386 endFunctionImpl(MF); 387 DbgValues.clear(); 388 DbgLabels.clear(); 389 LabelsBeforeInsn.clear(); 390 LabelsAfterInsn.clear(); 391 InstOrdering.clear(); 392 } 393 394 void DebugHandlerBase::beginBasicBlock(const MachineBasicBlock &MBB) { 395 if (!MBB.isBeginSection()) 396 return; 397 398 PrevLabel = MBB.getSymbol(); 399 } 400 401 void DebugHandlerBase::endBasicBlock(const MachineBasicBlock &MBB) { 402 if (!MBB.isEndSection()) 403 return; 404 405 PrevLabel = nullptr; 406 } 407