1 //===- DebugInfo.cpp - Debug Information Helper Classes -------------------===// 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 // This file implements the helper classes used to build and interpret debug 10 // information in LLVM IR form. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm-c/DebugInfo.h" 15 #include "LLVMContextImpl.h" 16 #include "llvm/ADT/APSInt.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/IR/BasicBlock.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/DIBuilder.h" 26 #include "llvm/IR/DebugInfo.h" 27 #include "llvm/IR/DebugInfoMetadata.h" 28 #include "llvm/IR/DebugLoc.h" 29 #include "llvm/IR/DebugProgramInstruction.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/GVMaterializer.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/Metadata.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/PassManager.h" 38 #include "llvm/Support/Casting.h" 39 #include <algorithm> 40 #include <cassert> 41 #include <optional> 42 #include <utility> 43 44 using namespace llvm; 45 using namespace llvm::at; 46 using namespace llvm::dwarf; 47 48 TinyPtrVector<DbgDeclareInst *> llvm::findDbgDeclares(Value *V) { 49 // This function is hot. Check whether the value has any metadata to avoid a 50 // DenseMap lookup. This check is a bitfield datamember lookup. 51 if (!V->isUsedByMetadata()) 52 return {}; 53 auto *L = ValueAsMetadata::getIfExists(V); 54 if (!L) 55 return {}; 56 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L); 57 if (!MDV) 58 return {}; 59 60 TinyPtrVector<DbgDeclareInst *> Declares; 61 for (User *U : MDV->users()) 62 if (auto *DDI = dyn_cast<DbgDeclareInst>(U)) 63 Declares.push_back(DDI); 64 65 return Declares; 66 } 67 TinyPtrVector<DbgVariableRecord *> llvm::findDVRDeclares(Value *V) { 68 // This function is hot. Check whether the value has any metadata to avoid a 69 // DenseMap lookup. This check is a bitfield datamember lookup. 70 if (!V->isUsedByMetadata()) 71 return {}; 72 auto *L = ValueAsMetadata::getIfExists(V); 73 if (!L) 74 return {}; 75 76 TinyPtrVector<DbgVariableRecord *> Declares; 77 for (DbgVariableRecord *DVR : L->getAllDbgVariableRecordUsers()) 78 if (DVR->getType() == DbgVariableRecord::LocationType::Declare) 79 Declares.push_back(DVR); 80 81 return Declares; 82 } 83 84 TinyPtrVector<DbgVariableRecord *> llvm::findDVRValues(Value *V) { 85 // This function is hot. Check whether the value has any metadata to avoid a 86 // DenseMap lookup. This check is a bitfield datamember lookup. 87 if (!V->isUsedByMetadata()) 88 return {}; 89 auto *L = ValueAsMetadata::getIfExists(V); 90 if (!L) 91 return {}; 92 93 TinyPtrVector<DbgVariableRecord *> Values; 94 for (DbgVariableRecord *DVR : L->getAllDbgVariableRecordUsers()) 95 if (DVR->isValueOfVariable()) 96 Values.push_back(DVR); 97 98 return Values; 99 } 100 101 template <typename IntrinsicT, bool DbgAssignAndValuesOnly> 102 static void 103 findDbgIntrinsics(SmallVectorImpl<IntrinsicT *> &Result, Value *V, 104 SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) { 105 // This function is hot. Check whether the value has any metadata to avoid a 106 // DenseMap lookup. 107 if (!V->isUsedByMetadata()) 108 return; 109 110 LLVMContext &Ctx = V->getContext(); 111 // TODO: If this value appears multiple times in a DIArgList, we should still 112 // only add the owning DbgValueInst once; use this set to track ArgListUsers. 113 // This behaviour can be removed when we can automatically remove duplicates. 114 // V will also appear twice in a dbg.assign if its used in the both the value 115 // and address components. 116 SmallPtrSet<IntrinsicT *, 4> EncounteredIntrinsics; 117 SmallPtrSet<DbgVariableRecord *, 4> EncounteredDbgVariableRecords; 118 119 /// Append IntrinsicT users of MetadataAsValue(MD). 120 auto AppendUsers = [&Ctx, &EncounteredIntrinsics, 121 &EncounteredDbgVariableRecords, &Result, 122 DbgVariableRecords](Metadata *MD) { 123 if (auto *MDV = MetadataAsValue::getIfExists(Ctx, MD)) { 124 for (User *U : MDV->users()) 125 if (IntrinsicT *DVI = dyn_cast<IntrinsicT>(U)) 126 if (EncounteredIntrinsics.insert(DVI).second) 127 Result.push_back(DVI); 128 } 129 if (!DbgVariableRecords) 130 return; 131 // Get DbgVariableRecords that use this as a single value. 132 if (LocalAsMetadata *L = dyn_cast<LocalAsMetadata>(MD)) { 133 for (DbgVariableRecord *DVR : L->getAllDbgVariableRecordUsers()) { 134 if (!DbgAssignAndValuesOnly || DVR->isDbgValue() || DVR->isDbgAssign()) 135 if (EncounteredDbgVariableRecords.insert(DVR).second) 136 DbgVariableRecords->push_back(DVR); 137 } 138 } 139 }; 140 141 if (auto *L = LocalAsMetadata::getIfExists(V)) { 142 AppendUsers(L); 143 for (Metadata *AL : L->getAllArgListUsers()) { 144 AppendUsers(AL); 145 if (!DbgVariableRecords) 146 continue; 147 DIArgList *DI = cast<DIArgList>(AL); 148 for (DbgVariableRecord *DVR : DI->getAllDbgVariableRecordUsers()) 149 if (!DbgAssignAndValuesOnly || DVR->isDbgValue() || DVR->isDbgAssign()) 150 if (EncounteredDbgVariableRecords.insert(DVR).second) 151 DbgVariableRecords->push_back(DVR); 152 } 153 } 154 } 155 156 void llvm::findDbgValues( 157 SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V, 158 SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) { 159 findDbgIntrinsics<DbgValueInst, /*DbgAssignAndValuesOnly=*/true>( 160 DbgValues, V, DbgVariableRecords); 161 } 162 163 void llvm::findDbgUsers( 164 SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers, Value *V, 165 SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) { 166 findDbgIntrinsics<DbgVariableIntrinsic, /*DbgAssignAndValuesOnly=*/false>( 167 DbgUsers, V, DbgVariableRecords); 168 } 169 170 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) { 171 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope)) 172 return LocalScope->getSubprogram(); 173 return nullptr; 174 } 175 176 DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) { 177 // Original dbg.declare must have a location. 178 const DebugLoc &DeclareLoc = DII->getDebugLoc(); 179 MDNode *Scope = DeclareLoc.getScope(); 180 DILocation *InlinedAt = DeclareLoc.getInlinedAt(); 181 // Because no machine insts can come from debug intrinsics, only the scope 182 // and inlinedAt is significant. Zero line numbers are used in case this 183 // DebugLoc leaks into any adjacent instructions. Produce an unknown location 184 // with the correct scope / inlinedAt fields. 185 return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt); 186 } 187 188 DebugLoc llvm::getDebugValueLoc(DbgVariableRecord *DVR) { 189 // Original dbg.declare must have a location. 190 const DebugLoc &DeclareLoc = DVR->getDebugLoc(); 191 MDNode *Scope = DeclareLoc.getScope(); 192 DILocation *InlinedAt = DeclareLoc.getInlinedAt(); 193 // Because no machine insts can come from debug intrinsics, only the scope 194 // and inlinedAt is significant. Zero line numbers are used in case this 195 // DebugLoc leaks into any adjacent instructions. Produce an unknown location 196 // with the correct scope / inlinedAt fields. 197 return DILocation::get(DVR->getContext(), 0, 0, Scope, InlinedAt); 198 } 199 200 //===----------------------------------------------------------------------===// 201 // DebugInfoFinder implementations. 202 //===----------------------------------------------------------------------===// 203 204 void DebugInfoFinder::reset() { 205 CUs.clear(); 206 SPs.clear(); 207 GVs.clear(); 208 TYs.clear(); 209 Scopes.clear(); 210 NodesSeen.clear(); 211 } 212 213 void DebugInfoFinder::processModule(const Module &M) { 214 for (auto *CU : M.debug_compile_units()) 215 processCompileUnit(CU); 216 for (auto &F : M.functions()) { 217 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram())) 218 processSubprogram(SP); 219 // There could be subprograms from inlined functions referenced from 220 // instructions only. Walk the function to find them. 221 for (const BasicBlock &BB : F) 222 for (const Instruction &I : BB) 223 processInstruction(M, I); 224 } 225 } 226 227 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) { 228 if (!addCompileUnit(CU)) 229 return; 230 for (auto *DIG : CU->getGlobalVariables()) { 231 if (!addGlobalVariable(DIG)) 232 continue; 233 auto *GV = DIG->getVariable(); 234 processScope(GV->getScope()); 235 processType(GV->getType()); 236 } 237 for (auto *ET : CU->getEnumTypes()) 238 processType(ET); 239 for (auto *RT : CU->getRetainedTypes()) 240 if (auto *T = dyn_cast<DIType>(RT)) 241 processType(T); 242 else 243 processSubprogram(cast<DISubprogram>(RT)); 244 for (auto *Import : CU->getImportedEntities()) 245 processImportedEntity(Import); 246 } 247 248 void DebugInfoFinder::processInstruction(const Module &M, 249 const Instruction &I) { 250 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I)) 251 processVariable(DVI->getVariable()); 252 253 if (auto DbgLoc = I.getDebugLoc()) 254 processLocation(M, DbgLoc.get()); 255 256 for (const DbgRecord &DPR : I.getDbgRecordRange()) 257 processDbgRecord(M, DPR); 258 } 259 260 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) { 261 if (!Loc) 262 return; 263 processScope(Loc->getScope()); 264 processLocation(M, Loc->getInlinedAt()); 265 } 266 267 void DebugInfoFinder::processDbgRecord(const Module &M, const DbgRecord &DR) { 268 if (const DbgVariableRecord *DVR = dyn_cast<const DbgVariableRecord>(&DR)) 269 processVariable(DVR->getVariable()); 270 processLocation(M, DR.getDebugLoc().get()); 271 } 272 273 void DebugInfoFinder::processType(DIType *DT) { 274 if (!addType(DT)) 275 return; 276 processScope(DT->getScope()); 277 if (auto *ST = dyn_cast<DISubroutineType>(DT)) { 278 for (DIType *Ref : ST->getTypeArray()) 279 processType(Ref); 280 return; 281 } 282 if (auto *DCT = dyn_cast<DICompositeType>(DT)) { 283 processType(DCT->getBaseType()); 284 for (Metadata *D : DCT->getElements()) { 285 if (auto *T = dyn_cast<DIType>(D)) 286 processType(T); 287 else if (auto *SP = dyn_cast<DISubprogram>(D)) 288 processSubprogram(SP); 289 } 290 return; 291 } 292 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) { 293 processType(DDT->getBaseType()); 294 } 295 } 296 297 void DebugInfoFinder::processImportedEntity(DIImportedEntity *Import) { 298 auto *Entity = Import->getEntity(); 299 if (auto *T = dyn_cast<DIType>(Entity)) 300 processType(T); 301 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 302 processSubprogram(SP); 303 else if (auto *NS = dyn_cast<DINamespace>(Entity)) 304 processScope(NS->getScope()); 305 else if (auto *M = dyn_cast<DIModule>(Entity)) 306 processScope(M->getScope()); 307 } 308 309 void DebugInfoFinder::processScope(DIScope *Scope) { 310 if (!Scope) 311 return; 312 if (auto *Ty = dyn_cast<DIType>(Scope)) { 313 processType(Ty); 314 return; 315 } 316 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) { 317 addCompileUnit(CU); 318 return; 319 } 320 if (auto *SP = dyn_cast<DISubprogram>(Scope)) { 321 processSubprogram(SP); 322 return; 323 } 324 if (!addScope(Scope)) 325 return; 326 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) { 327 processScope(LB->getScope()); 328 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) { 329 processScope(NS->getScope()); 330 } else if (auto *M = dyn_cast<DIModule>(Scope)) { 331 processScope(M->getScope()); 332 } 333 } 334 335 void DebugInfoFinder::processSubprogram(DISubprogram *SP) { 336 if (!addSubprogram(SP)) 337 return; 338 processScope(SP->getScope()); 339 // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a 340 // ValueMap containing identity mappings for all of the DICompileUnit's, not 341 // just DISubprogram's, referenced from anywhere within the Function being 342 // cloned prior to calling MapMetadata / RemapInstruction to avoid their 343 // duplication later as DICompileUnit's are also directly referenced by 344 // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well. 345 // Also, DICompileUnit's may reference DISubprogram's too and therefore need 346 // to be at least looked through. 347 processCompileUnit(SP->getUnit()); 348 processType(SP->getType()); 349 for (auto *Element : SP->getTemplateParams()) { 350 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) { 351 processType(TType->getType()); 352 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) { 353 processType(TVal->getType()); 354 } 355 } 356 357 for (auto *N : SP->getRetainedNodes()) { 358 if (auto *Var = dyn_cast_or_null<DILocalVariable>(N)) 359 processVariable(Var); 360 else if (auto *Import = dyn_cast_or_null<DIImportedEntity>(N)) 361 processImportedEntity(Import); 362 } 363 } 364 365 void DebugInfoFinder::processVariable(DILocalVariable *DV) { 366 if (!NodesSeen.insert(DV).second) 367 return; 368 processScope(DV->getScope()); 369 processType(DV->getType()); 370 } 371 372 bool DebugInfoFinder::addType(DIType *DT) { 373 if (!DT) 374 return false; 375 376 if (!NodesSeen.insert(DT).second) 377 return false; 378 379 TYs.push_back(DT); 380 return true; 381 } 382 383 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) { 384 if (!CU) 385 return false; 386 if (!NodesSeen.insert(CU).second) 387 return false; 388 389 CUs.push_back(CU); 390 return true; 391 } 392 393 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) { 394 if (!NodesSeen.insert(DIG).second) 395 return false; 396 397 GVs.push_back(DIG); 398 return true; 399 } 400 401 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) { 402 if (!SP) 403 return false; 404 405 if (!NodesSeen.insert(SP).second) 406 return false; 407 408 SPs.push_back(SP); 409 return true; 410 } 411 412 bool DebugInfoFinder::addScope(DIScope *Scope) { 413 if (!Scope) 414 return false; 415 // FIXME: Ocaml binding generates a scope with no content, we treat it 416 // as null for now. 417 if (Scope->getNumOperands() == 0) 418 return false; 419 if (!NodesSeen.insert(Scope).second) 420 return false; 421 Scopes.push_back(Scope); 422 return true; 423 } 424 425 static MDNode *updateLoopMetadataDebugLocationsImpl( 426 MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) { 427 assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 && 428 "Loop ID needs at least one operand"); 429 assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID && 430 "Loop ID should refer to itself"); 431 432 // Save space for the self-referential LoopID. 433 SmallVector<Metadata *, 4> MDs = {nullptr}; 434 435 for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) { 436 Metadata *MD = OrigLoopID->getOperand(i); 437 if (!MD) 438 MDs.push_back(nullptr); 439 else if (Metadata *NewMD = Updater(MD)) 440 MDs.push_back(NewMD); 441 } 442 443 MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs); 444 // Insert the self-referential LoopID. 445 NewLoopID->replaceOperandWith(0, NewLoopID); 446 return NewLoopID; 447 } 448 449 void llvm::updateLoopMetadataDebugLocations( 450 Instruction &I, function_ref<Metadata *(Metadata *)> Updater) { 451 MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop); 452 if (!OrigLoopID) 453 return; 454 MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater); 455 I.setMetadata(LLVMContext::MD_loop, NewLoopID); 456 } 457 458 /// Return true if a node is a DILocation or if a DILocation is 459 /// indirectly referenced by one of the node's children. 460 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited, 461 SmallPtrSetImpl<Metadata *> &Reachable, 462 Metadata *MD) { 463 MDNode *N = dyn_cast_or_null<MDNode>(MD); 464 if (!N) 465 return false; 466 if (isa<DILocation>(N) || Reachable.count(N)) 467 return true; 468 if (!Visited.insert(N).second) 469 return false; 470 for (auto &OpIt : N->operands()) { 471 Metadata *Op = OpIt.get(); 472 if (isDILocationReachable(Visited, Reachable, Op)) { 473 // Don't return just yet as we want to visit all MD's children to 474 // initialize DILocationReachable in stripDebugLocFromLoopID 475 Reachable.insert(N); 476 } 477 } 478 return Reachable.count(N); 479 } 480 481 static bool isAllDILocation(SmallPtrSetImpl<Metadata *> &Visited, 482 SmallPtrSetImpl<Metadata *> &AllDILocation, 483 const SmallPtrSetImpl<Metadata *> &DIReachable, 484 Metadata *MD) { 485 MDNode *N = dyn_cast_or_null<MDNode>(MD); 486 if (!N) 487 return false; 488 if (isa<DILocation>(N) || AllDILocation.count(N)) 489 return true; 490 if (!DIReachable.count(N)) 491 return false; 492 if (!Visited.insert(N).second) 493 return false; 494 for (auto &OpIt : N->operands()) { 495 Metadata *Op = OpIt.get(); 496 if (Op == MD) 497 continue; 498 if (!isAllDILocation(Visited, AllDILocation, DIReachable, Op)) { 499 return false; 500 } 501 } 502 AllDILocation.insert(N); 503 return true; 504 } 505 506 static Metadata * 507 stripLoopMDLoc(const SmallPtrSetImpl<Metadata *> &AllDILocation, 508 const SmallPtrSetImpl<Metadata *> &DIReachable, Metadata *MD) { 509 if (isa<DILocation>(MD) || AllDILocation.count(MD)) 510 return nullptr; 511 512 if (!DIReachable.count(MD)) 513 return MD; 514 515 MDNode *N = dyn_cast_or_null<MDNode>(MD); 516 if (!N) 517 return MD; 518 519 SmallVector<Metadata *, 4> Args; 520 bool HasSelfRef = false; 521 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 522 Metadata *A = N->getOperand(i); 523 if (!A) { 524 Args.push_back(nullptr); 525 } else if (A == MD) { 526 assert(i == 0 && "expected i==0 for self-reference"); 527 HasSelfRef = true; 528 Args.push_back(nullptr); 529 } else if (Metadata *NewArg = 530 stripLoopMDLoc(AllDILocation, DIReachable, A)) { 531 Args.push_back(NewArg); 532 } 533 } 534 if (Args.empty() || (HasSelfRef && Args.size() == 1)) 535 return nullptr; 536 537 MDNode *NewMD = N->isDistinct() ? MDNode::getDistinct(N->getContext(), Args) 538 : MDNode::get(N->getContext(), Args); 539 if (HasSelfRef) 540 NewMD->replaceOperandWith(0, NewMD); 541 return NewMD; 542 } 543 544 static MDNode *stripDebugLocFromLoopID(MDNode *N) { 545 assert(!N->operands().empty() && "Missing self reference?"); 546 SmallPtrSet<Metadata *, 8> Visited, DILocationReachable, AllDILocation; 547 // If we already visited N, there is nothing to do. 548 if (!Visited.insert(N).second) 549 return N; 550 551 // If there is no debug location, we do not have to rewrite this 552 // MDNode. This loop also initializes DILocationReachable, later 553 // needed by updateLoopMetadataDebugLocationsImpl; the use of 554 // count_if avoids an early exit. 555 if (!llvm::count_if(llvm::drop_begin(N->operands()), 556 [&Visited, &DILocationReachable](const MDOperand &Op) { 557 return isDILocationReachable( 558 Visited, DILocationReachable, Op.get()); 559 })) 560 return N; 561 562 Visited.clear(); 563 // If there is only the debug location without any actual loop metadata, we 564 // can remove the metadata. 565 if (llvm::all_of(llvm::drop_begin(N->operands()), 566 [&Visited, &AllDILocation, 567 &DILocationReachable](const MDOperand &Op) { 568 return isAllDILocation(Visited, AllDILocation, 569 DILocationReachable, Op.get()); 570 })) 571 return nullptr; 572 573 return updateLoopMetadataDebugLocationsImpl( 574 N, [&AllDILocation, &DILocationReachable](Metadata *MD) -> Metadata * { 575 return stripLoopMDLoc(AllDILocation, DILocationReachable, MD); 576 }); 577 } 578 579 bool llvm::stripDebugInfo(Function &F) { 580 bool Changed = false; 581 if (F.hasMetadata(LLVMContext::MD_dbg)) { 582 Changed = true; 583 F.setSubprogram(nullptr); 584 } 585 586 DenseMap<MDNode *, MDNode *> LoopIDsMap; 587 for (BasicBlock &BB : F) { 588 for (Instruction &I : llvm::make_early_inc_range(BB)) { 589 if (I.getDebugLoc()) { 590 Changed = true; 591 I.setDebugLoc(DebugLoc()); 592 } 593 if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) { 594 auto *NewLoopID = LoopIDsMap.lookup(LoopID); 595 if (!NewLoopID) 596 NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID); 597 if (NewLoopID != LoopID) 598 I.setMetadata(LLVMContext::MD_loop, NewLoopID); 599 } 600 // Strip other attachments that are or use debug info. 601 if (I.hasMetadataOtherThanDebugLoc()) { 602 // Heapallocsites point into the DIType system. 603 I.setMetadata("heapallocsite", nullptr); 604 // DIAssignID are debug info metadata primitives. 605 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr); 606 } 607 I.dropDbgRecords(); 608 } 609 } 610 return Changed; 611 } 612 613 bool llvm::StripDebugInfo(Module &M) { 614 bool Changed = false; 615 616 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) { 617 // We're stripping debug info, and without them, coverage information 618 // doesn't quite make sense. 619 if (NMD.getName().starts_with("llvm.dbg.") || 620 NMD.getName() == "llvm.gcov") { 621 NMD.eraseFromParent(); 622 Changed = true; 623 } 624 } 625 626 for (Function &F : M) 627 Changed |= stripDebugInfo(F); 628 629 for (auto &GV : M.globals()) { 630 Changed |= GV.eraseMetadata(LLVMContext::MD_dbg); 631 } 632 633 if (GVMaterializer *Materializer = M.getMaterializer()) 634 Materializer->setStripDebugInfo(); 635 636 return Changed; 637 } 638 639 namespace { 640 641 /// Helper class to downgrade -g metadata to -gline-tables-only metadata. 642 class DebugTypeInfoRemoval { 643 DenseMap<Metadata *, Metadata *> Replacements; 644 645 public: 646 /// The (void)() type. 647 MDNode *EmptySubroutineType; 648 649 private: 650 /// Remember what linkage name we originally had before stripping. If we end 651 /// up making two subprograms identical who originally had different linkage 652 /// names, then we need to make one of them distinct, to avoid them getting 653 /// uniqued. Maps the new node to the old linkage name. 654 DenseMap<DISubprogram *, StringRef> NewToLinkageName; 655 656 // TODO: Remember the distinct subprogram we created for a given linkage name, 657 // so that we can continue to unique whenever possible. Map <newly created 658 // node, old linkage name> to the first (possibly distinct) mdsubprogram 659 // created for that combination. This is not strictly needed for correctness, 660 // but can cut down on the number of MDNodes and let us diff cleanly with the 661 // output of -gline-tables-only. 662 663 public: 664 DebugTypeInfoRemoval(LLVMContext &C) 665 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0, 666 MDNode::get(C, {}))) {} 667 668 Metadata *map(Metadata *M) { 669 if (!M) 670 return nullptr; 671 auto Replacement = Replacements.find(M); 672 if (Replacement != Replacements.end()) 673 return Replacement->second; 674 675 return M; 676 } 677 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); } 678 679 /// Recursively remap N and all its referenced children. Does a DF post-order 680 /// traversal, so as to remap bottoms up. 681 void traverseAndRemap(MDNode *N) { traverse(N); } 682 683 private: 684 // Create a new DISubprogram, to replace the one given. 685 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) { 686 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile())); 687 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : ""; 688 DISubprogram *Declaration = nullptr; 689 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType())); 690 DIType *ContainingType = 691 cast_or_null<DIType>(map(MDS->getContainingType())); 692 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit())); 693 auto Variables = nullptr; 694 auto TemplateParams = nullptr; 695 696 // Make a distinct DISubprogram, for situations that warrent it. 697 auto distinctMDSubprogram = [&]() { 698 return DISubprogram::getDistinct( 699 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName, 700 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), 701 ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(), 702 MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration, 703 Variables); 704 }; 705 706 if (MDS->isDistinct()) 707 return distinctMDSubprogram(); 708 709 auto *NewMDS = DISubprogram::get( 710 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName, 711 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType, 712 MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(), 713 MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables); 714 715 StringRef OldLinkageName = MDS->getLinkageName(); 716 717 // See if we need to make a distinct one. 718 auto OrigLinkage = NewToLinkageName.find(NewMDS); 719 if (OrigLinkage != NewToLinkageName.end()) { 720 if (OrigLinkage->second == OldLinkageName) 721 // We're good. 722 return NewMDS; 723 724 // Otherwise, need to make a distinct one. 725 // TODO: Query the map to see if we already have one. 726 return distinctMDSubprogram(); 727 } 728 729 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()}); 730 return NewMDS; 731 } 732 733 /// Create a new compile unit, to replace the one given 734 DICompileUnit *getReplacementCU(DICompileUnit *CU) { 735 // Drop skeleton CUs. 736 if (CU->getDWOId()) 737 return nullptr; 738 739 auto *File = cast_or_null<DIFile>(map(CU->getFile())); 740 MDTuple *EnumTypes = nullptr; 741 MDTuple *RetainedTypes = nullptr; 742 MDTuple *GlobalVariables = nullptr; 743 MDTuple *ImportedEntities = nullptr; 744 return DICompileUnit::getDistinct( 745 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(), 746 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(), 747 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes, 748 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(), 749 CU->getDWOId(), CU->getSplitDebugInlining(), 750 CU->getDebugInfoForProfiling(), CU->getNameTableKind(), 751 CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK()); 752 } 753 754 DILocation *getReplacementMDLocation(DILocation *MLD) { 755 auto *Scope = map(MLD->getScope()); 756 auto *InlinedAt = map(MLD->getInlinedAt()); 757 if (MLD->isDistinct()) 758 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(), 759 MLD->getColumn(), Scope, InlinedAt); 760 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(), 761 Scope, InlinedAt); 762 } 763 764 /// Create a new generic MDNode, to replace the one given 765 MDNode *getReplacementMDNode(MDNode *N) { 766 SmallVector<Metadata *, 8> Ops; 767 Ops.reserve(N->getNumOperands()); 768 for (auto &I : N->operands()) 769 if (I) 770 Ops.push_back(map(I)); 771 auto *Ret = MDNode::get(N->getContext(), Ops); 772 return Ret; 773 } 774 775 /// Attempt to re-map N to a newly created node. 776 void remap(MDNode *N) { 777 if (Replacements.count(N)) 778 return; 779 780 auto doRemap = [&](MDNode *N) -> MDNode * { 781 if (!N) 782 return nullptr; 783 if (auto *MDSub = dyn_cast<DISubprogram>(N)) { 784 remap(MDSub->getUnit()); 785 return getReplacementSubprogram(MDSub); 786 } 787 if (isa<DISubroutineType>(N)) 788 return EmptySubroutineType; 789 if (auto *CU = dyn_cast<DICompileUnit>(N)) 790 return getReplacementCU(CU); 791 if (isa<DIFile>(N)) 792 return N; 793 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N)) 794 // Remap to our referenced scope (recursively). 795 return mapNode(MDLB->getScope()); 796 if (auto *MLD = dyn_cast<DILocation>(N)) 797 return getReplacementMDLocation(MLD); 798 799 // Otherwise, if we see these, just drop them now. Not strictly necessary, 800 // but this speeds things up a little. 801 if (isa<DINode>(N)) 802 return nullptr; 803 804 return getReplacementMDNode(N); 805 }; 806 // Seperate recursive doRemap and operator [] into 2 lines to avoid 807 // out-of-order evaluations since both of them can access the same memory 808 // location in map Replacements. 809 auto Value = doRemap(N); 810 Replacements[N] = Value; 811 } 812 813 /// Do the remapping traversal. 814 void traverse(MDNode *); 815 }; 816 817 } // end anonymous namespace 818 819 void DebugTypeInfoRemoval::traverse(MDNode *N) { 820 if (!N || Replacements.count(N)) 821 return; 822 823 // To avoid cycles, as well as for efficiency sake, we will sometimes prune 824 // parts of the graph. 825 auto prune = [](MDNode *Parent, MDNode *Child) { 826 if (auto *MDS = dyn_cast<DISubprogram>(Parent)) 827 return Child == MDS->getRetainedNodes().get(); 828 return false; 829 }; 830 831 SmallVector<MDNode *, 16> ToVisit; 832 DenseSet<MDNode *> Opened; 833 834 // Visit each node starting at N in post order, and map them. 835 ToVisit.push_back(N); 836 while (!ToVisit.empty()) { 837 auto *N = ToVisit.back(); 838 if (!Opened.insert(N).second) { 839 // Close it. 840 remap(N); 841 ToVisit.pop_back(); 842 continue; 843 } 844 for (auto &I : N->operands()) 845 if (auto *MDN = dyn_cast_or_null<MDNode>(I)) 846 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) && 847 !isa<DICompileUnit>(MDN)) 848 ToVisit.push_back(MDN); 849 } 850 } 851 852 bool llvm::stripNonLineTableDebugInfo(Module &M) { 853 bool Changed = false; 854 855 // First off, delete the debug intrinsics. 856 auto RemoveUses = [&](StringRef Name) { 857 if (auto *DbgVal = M.getFunction(Name)) { 858 while (!DbgVal->use_empty()) 859 cast<Instruction>(DbgVal->user_back())->eraseFromParent(); 860 DbgVal->eraseFromParent(); 861 Changed = true; 862 } 863 }; 864 RemoveUses("llvm.dbg.declare"); 865 RemoveUses("llvm.dbg.label"); 866 RemoveUses("llvm.dbg.value"); 867 868 // Delete non-CU debug info named metadata nodes. 869 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end(); 870 NMI != NME;) { 871 NamedMDNode *NMD = &*NMI; 872 ++NMI; 873 // Specifically keep dbg.cu around. 874 if (NMD->getName() == "llvm.dbg.cu") 875 continue; 876 } 877 878 // Drop all dbg attachments from global variables. 879 for (auto &GV : M.globals()) 880 GV.eraseMetadata(LLVMContext::MD_dbg); 881 882 DebugTypeInfoRemoval Mapper(M.getContext()); 883 auto remap = [&](MDNode *Node) -> MDNode * { 884 if (!Node) 885 return nullptr; 886 Mapper.traverseAndRemap(Node); 887 auto *NewNode = Mapper.mapNode(Node); 888 Changed |= Node != NewNode; 889 Node = NewNode; 890 return NewNode; 891 }; 892 893 // Rewrite the DebugLocs to be equivalent to what 894 // -gline-tables-only would have created. 895 for (auto &F : M) { 896 if (auto *SP = F.getSubprogram()) { 897 Mapper.traverseAndRemap(SP); 898 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP)); 899 Changed |= SP != NewSP; 900 F.setSubprogram(NewSP); 901 } 902 for (auto &BB : F) { 903 for (auto &I : BB) { 904 auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc { 905 auto *Scope = DL.getScope(); 906 MDNode *InlinedAt = DL.getInlinedAt(); 907 Scope = remap(Scope); 908 InlinedAt = remap(InlinedAt); 909 return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(), 910 Scope, InlinedAt); 911 }; 912 913 if (I.getDebugLoc() != DebugLoc()) 914 I.setDebugLoc(remapDebugLoc(I.getDebugLoc())); 915 916 // Remap DILocations in llvm.loop attachments. 917 updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * { 918 if (auto *Loc = dyn_cast_or_null<DILocation>(MD)) 919 return remapDebugLoc(Loc).get(); 920 return MD; 921 }); 922 923 // Strip heapallocsite attachments, they point into the DIType system. 924 if (I.hasMetadataOtherThanDebugLoc()) 925 I.setMetadata("heapallocsite", nullptr); 926 927 // Strip any DbgRecords attached. 928 I.dropDbgRecords(); 929 } 930 } 931 } 932 933 // Create a new llvm.dbg.cu, which is equivalent to the one 934 // -gline-tables-only would have created. 935 for (auto &NMD : M.named_metadata()) { 936 SmallVector<MDNode *, 8> Ops; 937 for (MDNode *Op : NMD.operands()) 938 Ops.push_back(remap(Op)); 939 940 if (!Changed) 941 continue; 942 943 NMD.clearOperands(); 944 for (auto *Op : Ops) 945 if (Op) 946 NMD.addOperand(Op); 947 } 948 return Changed; 949 } 950 951 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) { 952 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>( 953 M.getModuleFlag("Debug Info Version"))) 954 return Val->getZExtValue(); 955 return 0; 956 } 957 958 void Instruction::applyMergedLocation(DebugLoc LocA, DebugLoc LocB) { 959 setDebugLoc(DebugLoc::getMergedLocation(LocA, LocB)); 960 } 961 962 void Instruction::mergeDIAssignID( 963 ArrayRef<const Instruction *> SourceInstructions) { 964 // Replace all uses (and attachments) of all the DIAssignIDs 965 // on SourceInstructions with a single merged value. 966 assert(getFunction() && "Uninserted instruction merged"); 967 // Collect up the DIAssignID tags. 968 SmallVector<DIAssignID *, 4> IDs; 969 for (const Instruction *I : SourceInstructions) { 970 if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID)) 971 IDs.push_back(cast<DIAssignID>(MD)); 972 assert(getFunction() == I->getFunction() && 973 "Merging with instruction from another function not allowed"); 974 } 975 976 // Add this instruction's DIAssignID too, if it has one. 977 if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID)) 978 IDs.push_back(cast<DIAssignID>(MD)); 979 980 if (IDs.empty()) 981 return; // No DIAssignID tags to process. 982 983 DIAssignID *MergeID = IDs[0]; 984 for (DIAssignID *AssignID : drop_begin(IDs)) { 985 if (AssignID != MergeID) 986 at::RAUW(AssignID, MergeID); 987 } 988 setMetadata(LLVMContext::MD_DIAssignID, MergeID); 989 } 990 991 void Instruction::updateLocationAfterHoist() { dropLocation(); } 992 993 void Instruction::dropLocation() { 994 const DebugLoc &DL = getDebugLoc(); 995 if (!DL) { 996 setDebugLoc(DebugLoc::getDropped()); 997 return; 998 } 999 1000 // If this isn't a call, drop the location to allow a location from a 1001 // preceding instruction to propagate. 1002 bool MayLowerToCall = false; 1003 if (isa<CallBase>(this)) { 1004 auto *II = dyn_cast<IntrinsicInst>(this); 1005 MayLowerToCall = 1006 !II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID()); 1007 } 1008 1009 if (!MayLowerToCall) { 1010 setDebugLoc(DebugLoc::getDropped()); 1011 return; 1012 } 1013 1014 // Set a line 0 location for calls to preserve scope information in case 1015 // inlining occurs. 1016 DISubprogram *SP = getFunction()->getSubprogram(); 1017 if (SP) 1018 // If a function scope is available, set it on the line 0 location. When 1019 // hoisting a call to a predecessor block, using the function scope avoids 1020 // making it look like the callee was reached earlier than it should be. 1021 setDebugLoc(DILocation::get(getContext(), 0, 0, SP)); 1022 else 1023 // The parent function has no scope. Go ahead and drop the location. If 1024 // the parent function is inlined, and the callee has a subprogram, the 1025 // inliner will attach a location to the call. 1026 // 1027 // One alternative is to set a line 0 location with the existing scope and 1028 // inlinedAt info. The location might be sensitive to when inlining occurs. 1029 setDebugLoc(DebugLoc::getDropped()); 1030 } 1031 1032 //===----------------------------------------------------------------------===// 1033 // LLVM C API implementations. 1034 //===----------------------------------------------------------------------===// 1035 1036 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) { 1037 switch (lang) { 1038 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \ 1039 case LLVMDWARFSourceLanguage##NAME: \ 1040 return ID; 1041 #include "llvm/BinaryFormat/Dwarf.def" 1042 #undef HANDLE_DW_LANG 1043 } 1044 llvm_unreachable("Unhandled Tag"); 1045 } 1046 1047 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) { 1048 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr); 1049 } 1050 1051 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) { 1052 return static_cast<DINode::DIFlags>(Flags); 1053 } 1054 1055 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) { 1056 return static_cast<LLVMDIFlags>(Flags); 1057 } 1058 1059 static DISubprogram::DISPFlags 1060 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) { 1061 return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized); 1062 } 1063 1064 unsigned LLVMDebugMetadataVersion() { 1065 return DEBUG_METADATA_VERSION; 1066 } 1067 1068 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) { 1069 return wrap(new DIBuilder(*unwrap(M), false)); 1070 } 1071 1072 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) { 1073 return wrap(new DIBuilder(*unwrap(M))); 1074 } 1075 1076 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) { 1077 return getDebugMetadataVersionFromModule(*unwrap(M)); 1078 } 1079 1080 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) { 1081 return StripDebugInfo(*unwrap(M)); 1082 } 1083 1084 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) { 1085 delete unwrap(Builder); 1086 } 1087 1088 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) { 1089 unwrap(Builder)->finalize(); 1090 } 1091 1092 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder, 1093 LLVMMetadataRef subprogram) { 1094 unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram)); 1095 } 1096 1097 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit( 1098 LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang, 1099 LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen, 1100 LLVMBool isOptimized, const char *Flags, size_t FlagsLen, 1101 unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen, 1102 LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining, 1103 LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen, 1104 const char *SDK, size_t SDKLen) { 1105 auto File = unwrapDI<DIFile>(FileRef); 1106 1107 return wrap(unwrap(Builder)->createCompileUnit( 1108 map_from_llvmDWARFsourcelanguage(Lang), File, 1109 StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen), 1110 RuntimeVer, StringRef(SplitName, SplitNameLen), 1111 static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId, 1112 SplitDebugInlining, DebugInfoForProfiling, 1113 DICompileUnit::DebugNameTableKind::Default, false, 1114 StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen))); 1115 } 1116 1117 LLVMMetadataRef 1118 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename, 1119 size_t FilenameLen, const char *Directory, 1120 size_t DirectoryLen) { 1121 return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen), 1122 StringRef(Directory, DirectoryLen))); 1123 } 1124 1125 LLVMMetadataRef 1126 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope, 1127 const char *Name, size_t NameLen, 1128 const char *ConfigMacros, size_t ConfigMacrosLen, 1129 const char *IncludePath, size_t IncludePathLen, 1130 const char *APINotesFile, size_t APINotesFileLen) { 1131 return wrap(unwrap(Builder)->createModule( 1132 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), 1133 StringRef(ConfigMacros, ConfigMacrosLen), 1134 StringRef(IncludePath, IncludePathLen), 1135 StringRef(APINotesFile, APINotesFileLen))); 1136 } 1137 1138 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder, 1139 LLVMMetadataRef ParentScope, 1140 const char *Name, size_t NameLen, 1141 LLVMBool ExportSymbols) { 1142 return wrap(unwrap(Builder)->createNameSpace( 1143 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols)); 1144 } 1145 1146 LLVMMetadataRef LLVMDIBuilderCreateFunction( 1147 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1148 size_t NameLen, const char *LinkageName, size_t LinkageNameLen, 1149 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, 1150 LLVMBool IsLocalToUnit, LLVMBool IsDefinition, 1151 unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) { 1152 return wrap(unwrap(Builder)->createFunction( 1153 unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen}, 1154 unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine, 1155 map_from_llvmDIFlags(Flags), 1156 pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr, 1157 nullptr, nullptr)); 1158 } 1159 1160 1161 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock( 1162 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, 1163 LLVMMetadataRef File, unsigned Line, unsigned Col) { 1164 return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope), 1165 unwrapDI<DIFile>(File), 1166 Line, Col)); 1167 } 1168 1169 LLVMMetadataRef 1170 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder, 1171 LLVMMetadataRef Scope, 1172 LLVMMetadataRef File, 1173 unsigned Discriminator) { 1174 return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope), 1175 unwrapDI<DIFile>(File), 1176 Discriminator)); 1177 } 1178 1179 LLVMMetadataRef 1180 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder, 1181 LLVMMetadataRef Scope, 1182 LLVMMetadataRef NS, 1183 LLVMMetadataRef File, 1184 unsigned Line) { 1185 return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope), 1186 unwrapDI<DINamespace>(NS), 1187 unwrapDI<DIFile>(File), 1188 Line)); 1189 } 1190 1191 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias( 1192 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, 1193 LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line, 1194 LLVMMetadataRef *Elements, unsigned NumElements) { 1195 auto Elts = 1196 (NumElements > 0) 1197 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements}) 1198 : nullptr; 1199 return wrap(unwrap(Builder)->createImportedModule( 1200 unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity), 1201 unwrapDI<DIFile>(File), Line, Elts)); 1202 } 1203 1204 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule( 1205 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M, 1206 LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements, 1207 unsigned NumElements) { 1208 auto Elts = 1209 (NumElements > 0) 1210 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements}) 1211 : nullptr; 1212 return wrap(unwrap(Builder)->createImportedModule( 1213 unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File), 1214 Line, Elts)); 1215 } 1216 1217 LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration( 1218 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl, 1219 LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen, 1220 LLVMMetadataRef *Elements, unsigned NumElements) { 1221 auto Elts = 1222 (NumElements > 0) 1223 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements}) 1224 : nullptr; 1225 return wrap(unwrap(Builder)->createImportedDeclaration( 1226 unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File), 1227 Line, {Name, NameLen}, Elts)); 1228 } 1229 1230 LLVMMetadataRef 1231 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line, 1232 unsigned Column, LLVMMetadataRef Scope, 1233 LLVMMetadataRef InlinedAt) { 1234 return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope), 1235 unwrap(InlinedAt))); 1236 } 1237 1238 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) { 1239 return unwrapDI<DILocation>(Location)->getLine(); 1240 } 1241 1242 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) { 1243 return unwrapDI<DILocation>(Location)->getColumn(); 1244 } 1245 1246 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) { 1247 return wrap(unwrapDI<DILocation>(Location)->getScope()); 1248 } 1249 1250 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) { 1251 return wrap(unwrapDI<DILocation>(Location)->getInlinedAt()); 1252 } 1253 1254 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) { 1255 return wrap(unwrapDI<DIScope>(Scope)->getFile()); 1256 } 1257 1258 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) { 1259 auto Dir = unwrapDI<DIFile>(File)->getDirectory(); 1260 *Len = Dir.size(); 1261 return Dir.data(); 1262 } 1263 1264 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) { 1265 auto Name = unwrapDI<DIFile>(File)->getFilename(); 1266 *Len = Name.size(); 1267 return Name.data(); 1268 } 1269 1270 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) { 1271 if (auto Src = unwrapDI<DIFile>(File)->getSource()) { 1272 *Len = Src->size(); 1273 return Src->data(); 1274 } 1275 *Len = 0; 1276 return ""; 1277 } 1278 1279 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder, 1280 LLVMMetadataRef ParentMacroFile, 1281 unsigned Line, 1282 LLVMDWARFMacinfoRecordType RecordType, 1283 const char *Name, size_t NameLen, 1284 const char *Value, size_t ValueLen) { 1285 return wrap( 1286 unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line, 1287 static_cast<MacinfoRecordType>(RecordType), 1288 {Name, NameLen}, {Value, ValueLen})); 1289 } 1290 1291 LLVMMetadataRef 1292 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder, 1293 LLVMMetadataRef ParentMacroFile, unsigned Line, 1294 LLVMMetadataRef File) { 1295 return wrap(unwrap(Builder)->createTempMacroFile( 1296 unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File))); 1297 } 1298 1299 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder, 1300 const char *Name, size_t NameLen, 1301 int64_t Value, 1302 LLVMBool IsUnsigned) { 1303 return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value, 1304 IsUnsigned != 0)); 1305 } 1306 1307 LLVMMetadataRef LLVMDIBuilderCreateEnumeratorOfArbitraryPrecision( 1308 LLVMDIBuilderRef Builder, const char *Name, size_t NameLen, 1309 uint64_t SizeInBits, const uint64_t Words[], LLVMBool IsUnsigned) { 1310 uint64_t NumWords = (SizeInBits + 63) / 64; 1311 return wrap(unwrap(Builder)->createEnumerator( 1312 {Name, NameLen}, 1313 APSInt(APInt(SizeInBits, ArrayRef(Words, NumWords)), IsUnsigned != 0))); 1314 } 1315 1316 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType( 1317 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1318 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1319 uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements, 1320 unsigned NumElements, LLVMMetadataRef ClassTy) { 1321 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements), 1322 NumElements}); 1323 return wrap(unwrap(Builder)->createEnumerationType( 1324 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1325 LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy))); 1326 } 1327 1328 LLVMMetadataRef LLVMDIBuilderCreateSetType( 1329 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1330 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1331 uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef BaseTy) { 1332 return wrap(unwrap(Builder)->createSetType( 1333 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1334 LineNumber, SizeInBits, AlignInBits, unwrapDI<DIType>(BaseTy))); 1335 } 1336 1337 LLVMMetadataRef LLVMDIBuilderCreateSubrangeType( 1338 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1339 size_t NameLen, unsigned LineNo, LLVMMetadataRef File, uint64_t SizeInBits, 1340 uint32_t AlignInBits, LLVMDIFlags Flags, LLVMMetadataRef BaseTy, 1341 LLVMMetadataRef LowerBound, LLVMMetadataRef UpperBound, 1342 LLVMMetadataRef Stride, LLVMMetadataRef Bias) { 1343 return wrap(unwrap(Builder)->createSubrangeType( 1344 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, unwrapDI<DIScope>(Scope), 1345 SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags), 1346 unwrapDI<DIType>(BaseTy), unwrap(LowerBound), unwrap(UpperBound), 1347 unwrap(Stride), unwrap(Bias))); 1348 } 1349 1350 /// MD may be nullptr, a DIExpression or DIVariable. 1351 PointerUnion<DIExpression *, DIVariable *> unwrapExprVar(LLVMMetadataRef MD) { 1352 if (!MD) 1353 return nullptr; 1354 MDNode *MDN = unwrapDI<MDNode>(MD); 1355 if (auto *E = dyn_cast<DIExpression>(MDN)) 1356 return E; 1357 assert(isa<DIVariable>(MDN) && "Expected DIExpression or DIVariable"); 1358 return cast<DIVariable>(MDN); 1359 } 1360 1361 LLVMMetadataRef LLVMDIBuilderCreateDynamicArrayType( 1362 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1363 size_t NameLen, unsigned LineNo, LLVMMetadataRef File, uint64_t Size, 1364 uint32_t AlignInBits, LLVMMetadataRef Ty, LLVMMetadataRef *Subscripts, 1365 unsigned NumSubscripts, LLVMMetadataRef DataLocation, 1366 LLVMMetadataRef Associated, LLVMMetadataRef Allocated, LLVMMetadataRef Rank, 1367 LLVMMetadataRef BitStride) { 1368 auto Subs = 1369 unwrap(Builder)->getOrCreateArray({unwrap(Subscripts), NumSubscripts}); 1370 return wrap(unwrap(Builder)->createArrayType( 1371 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, 1372 Size, AlignInBits, unwrapDI<DIType>(Ty), Subs, 1373 unwrapExprVar(DataLocation), unwrapExprVar(Associated), 1374 unwrapExprVar(Allocated), unwrapExprVar(Rank), unwrap(BitStride))); 1375 } 1376 1377 void LLVMReplaceArrays(LLVMDIBuilderRef Builder, LLVMMetadataRef *T, 1378 LLVMMetadataRef *Elements, unsigned NumElements) { 1379 auto CT = unwrap<DICompositeType>(*T); 1380 auto Elts = 1381 unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements}); 1382 unwrap(Builder)->replaceArrays(CT, Elts); 1383 } 1384 1385 LLVMMetadataRef LLVMDIBuilderCreateUnionType( 1386 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1387 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1388 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags, 1389 LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang, 1390 const char *UniqueId, size_t UniqueIdLen) { 1391 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements), 1392 NumElements}); 1393 return wrap(unwrap(Builder)->createUnionType( 1394 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1395 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags), 1396 Elts, RunTimeLang, {UniqueId, UniqueIdLen})); 1397 } 1398 1399 1400 LLVMMetadataRef 1401 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size, 1402 uint32_t AlignInBits, LLVMMetadataRef Ty, 1403 LLVMMetadataRef *Subscripts, 1404 unsigned NumSubscripts) { 1405 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts), 1406 NumSubscripts}); 1407 return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits, 1408 unwrapDI<DIType>(Ty), Subs)); 1409 } 1410 1411 LLVMMetadataRef 1412 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size, 1413 uint32_t AlignInBits, LLVMMetadataRef Ty, 1414 LLVMMetadataRef *Subscripts, 1415 unsigned NumSubscripts) { 1416 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts), 1417 NumSubscripts}); 1418 return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits, 1419 unwrapDI<DIType>(Ty), Subs)); 1420 } 1421 1422 LLVMMetadataRef 1423 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name, 1424 size_t NameLen, uint64_t SizeInBits, 1425 LLVMDWARFTypeEncoding Encoding, 1426 LLVMDIFlags Flags) { 1427 return wrap(unwrap(Builder)->createBasicType({Name, NameLen}, 1428 SizeInBits, Encoding, 1429 map_from_llvmDIFlags(Flags))); 1430 } 1431 1432 LLVMMetadataRef LLVMDIBuilderCreatePointerType( 1433 LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy, 1434 uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace, 1435 const char *Name, size_t NameLen) { 1436 return wrap(unwrap(Builder)->createPointerType( 1437 unwrapDI<DIType>(PointeeTy), SizeInBits, AlignInBits, AddressSpace, 1438 {Name, NameLen})); 1439 } 1440 1441 LLVMMetadataRef LLVMDIBuilderCreateStructType( 1442 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1443 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1444 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags, 1445 LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements, 1446 unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder, 1447 const char *UniqueId, size_t UniqueIdLen) { 1448 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements), 1449 NumElements}); 1450 return wrap(unwrap(Builder)->createStructType( 1451 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1452 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags), 1453 unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang, 1454 unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen})); 1455 } 1456 1457 LLVMMetadataRef LLVMDIBuilderCreateMemberType( 1458 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1459 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, 1460 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags, 1461 LLVMMetadataRef Ty) { 1462 return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope), 1463 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits, 1464 OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty))); 1465 } 1466 1467 LLVMMetadataRef 1468 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name, 1469 size_t NameLen) { 1470 return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen})); 1471 } 1472 1473 LLVMMetadataRef LLVMDIBuilderCreateStaticMemberType( 1474 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1475 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1476 LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal, 1477 uint32_t AlignInBits) { 1478 return wrap(unwrap(Builder)->createStaticMemberType( 1479 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1480 LineNumber, unwrapDI<DIType>(Type), map_from_llvmDIFlags(Flags), 1481 unwrap<Constant>(ConstantVal), DW_TAG_member, AlignInBits)); 1482 } 1483 1484 LLVMMetadataRef 1485 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder, 1486 const char *Name, size_t NameLen, 1487 LLVMMetadataRef File, unsigned LineNo, 1488 uint64_t SizeInBits, uint32_t AlignInBits, 1489 uint64_t OffsetInBits, LLVMDIFlags Flags, 1490 LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) { 1491 return wrap(unwrap(Builder)->createObjCIVar( 1492 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, 1493 SizeInBits, AlignInBits, OffsetInBits, 1494 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty), 1495 unwrapDI<MDNode>(PropertyNode))); 1496 } 1497 1498 LLVMMetadataRef 1499 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder, 1500 const char *Name, size_t NameLen, 1501 LLVMMetadataRef File, unsigned LineNo, 1502 const char *GetterName, size_t GetterNameLen, 1503 const char *SetterName, size_t SetterNameLen, 1504 unsigned PropertyAttributes, 1505 LLVMMetadataRef Ty) { 1506 return wrap(unwrap(Builder)->createObjCProperty( 1507 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, 1508 {GetterName, GetterNameLen}, {SetterName, SetterNameLen}, 1509 PropertyAttributes, unwrapDI<DIType>(Ty))); 1510 } 1511 1512 LLVMMetadataRef LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder, 1513 LLVMMetadataRef Type, 1514 LLVMBool Implicit) { 1515 return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type), 1516 Implicit)); 1517 } 1518 1519 LLVMMetadataRef 1520 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type, 1521 const char *Name, size_t NameLen, 1522 LLVMMetadataRef File, unsigned LineNo, 1523 LLVMMetadataRef Scope, uint32_t AlignInBits) { 1524 return wrap(unwrap(Builder)->createTypedef( 1525 unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, 1526 unwrapDI<DIScope>(Scope), AlignInBits)); 1527 } 1528 1529 LLVMMetadataRef 1530 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder, 1531 LLVMMetadataRef Ty, LLVMMetadataRef BaseTy, 1532 uint64_t BaseOffset, uint32_t VBPtrOffset, 1533 LLVMDIFlags Flags) { 1534 return wrap(unwrap(Builder)->createInheritance( 1535 unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy), 1536 BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags))); 1537 } 1538 1539 LLVMMetadataRef 1540 LLVMDIBuilderCreateForwardDecl( 1541 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name, 1542 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line, 1543 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, 1544 const char *UniqueIdentifier, size_t UniqueIdentifierLen) { 1545 return wrap(unwrap(Builder)->createForwardDecl( 1546 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope), 1547 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits, 1548 AlignInBits, {UniqueIdentifier, UniqueIdentifierLen})); 1549 } 1550 1551 LLVMMetadataRef 1552 LLVMDIBuilderCreateReplaceableCompositeType( 1553 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name, 1554 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line, 1555 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, 1556 LLVMDIFlags Flags, const char *UniqueIdentifier, 1557 size_t UniqueIdentifierLen) { 1558 return wrap(unwrap(Builder)->createReplaceableCompositeType( 1559 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope), 1560 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits, 1561 AlignInBits, map_from_llvmDIFlags(Flags), 1562 {UniqueIdentifier, UniqueIdentifierLen})); 1563 } 1564 1565 LLVMMetadataRef 1566 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag, 1567 LLVMMetadataRef Type) { 1568 return wrap(unwrap(Builder)->createQualifiedType(Tag, 1569 unwrapDI<DIType>(Type))); 1570 } 1571 1572 LLVMMetadataRef 1573 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag, 1574 LLVMMetadataRef Type) { 1575 return wrap(unwrap(Builder)->createReferenceType(Tag, 1576 unwrapDI<DIType>(Type))); 1577 } 1578 1579 LLVMMetadataRef 1580 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) { 1581 return wrap(unwrap(Builder)->createNullPtrType()); 1582 } 1583 1584 LLVMMetadataRef 1585 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder, 1586 LLVMMetadataRef PointeeType, 1587 LLVMMetadataRef ClassType, 1588 uint64_t SizeInBits, 1589 uint32_t AlignInBits, 1590 LLVMDIFlags Flags) { 1591 return wrap(unwrap(Builder)->createMemberPointerType( 1592 unwrapDI<DIType>(PointeeType), 1593 unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits, 1594 map_from_llvmDIFlags(Flags))); 1595 } 1596 1597 LLVMMetadataRef 1598 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder, 1599 LLVMMetadataRef Scope, 1600 const char *Name, size_t NameLen, 1601 LLVMMetadataRef File, unsigned LineNumber, 1602 uint64_t SizeInBits, 1603 uint64_t OffsetInBits, 1604 uint64_t StorageOffsetInBits, 1605 LLVMDIFlags Flags, LLVMMetadataRef Type) { 1606 return wrap(unwrap(Builder)->createBitFieldMemberType( 1607 unwrapDI<DIScope>(Scope), {Name, NameLen}, 1608 unwrapDI<DIFile>(File), LineNumber, 1609 SizeInBits, OffsetInBits, StorageOffsetInBits, 1610 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type))); 1611 } 1612 1613 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder, 1614 LLVMMetadataRef Scope, const char *Name, size_t NameLen, 1615 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, 1616 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags, 1617 LLVMMetadataRef DerivedFrom, 1618 LLVMMetadataRef *Elements, unsigned NumElements, 1619 LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode, 1620 const char *UniqueIdentifier, size_t UniqueIdentifierLen) { 1621 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements), 1622 NumElements}); 1623 return wrap(unwrap(Builder)->createClassType( 1624 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1625 LineNumber, SizeInBits, AlignInBits, OffsetInBits, 1626 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom), Elts, 1627 /*RunTimeLang=*/0, unwrapDI<DIType>(VTableHolder), 1628 unwrapDI<MDNode>(TemplateParamsNode), 1629 {UniqueIdentifier, UniqueIdentifierLen})); 1630 } 1631 1632 LLVMMetadataRef 1633 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder, 1634 LLVMMetadataRef Type) { 1635 return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type))); 1636 } 1637 1638 uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD) { 1639 return unwrapDI<DINode>(MD)->getTag(); 1640 } 1641 1642 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) { 1643 StringRef Str = unwrapDI<DIType>(DType)->getName(); 1644 *Length = Str.size(); 1645 return Str.data(); 1646 } 1647 1648 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) { 1649 return unwrapDI<DIType>(DType)->getSizeInBits(); 1650 } 1651 1652 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) { 1653 return unwrapDI<DIType>(DType)->getOffsetInBits(); 1654 } 1655 1656 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) { 1657 return unwrapDI<DIType>(DType)->getAlignInBits(); 1658 } 1659 1660 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) { 1661 return unwrapDI<DIType>(DType)->getLine(); 1662 } 1663 1664 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) { 1665 return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags()); 1666 } 1667 1668 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder, 1669 LLVMMetadataRef *Types, 1670 size_t Length) { 1671 return wrap( 1672 unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get()); 1673 } 1674 1675 LLVMMetadataRef 1676 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder, 1677 LLVMMetadataRef File, 1678 LLVMMetadataRef *ParameterTypes, 1679 unsigned NumParameterTypes, 1680 LLVMDIFlags Flags) { 1681 auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes), 1682 NumParameterTypes}); 1683 return wrap(unwrap(Builder)->createSubroutineType( 1684 Elts, map_from_llvmDIFlags(Flags))); 1685 } 1686 1687 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder, 1688 uint64_t *Addr, size_t Length) { 1689 return wrap( 1690 unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length))); 1691 } 1692 1693 LLVMMetadataRef 1694 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder, 1695 uint64_t Value) { 1696 return wrap(unwrap(Builder)->createConstantValueExpression(Value)); 1697 } 1698 1699 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression( 1700 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1701 size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File, 1702 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit, 1703 LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) { 1704 return wrap(unwrap(Builder)->createGlobalVariableExpression( 1705 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen}, 1706 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit, 1707 true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl), 1708 nullptr, AlignInBits)); 1709 } 1710 1711 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) { 1712 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable()); 1713 } 1714 1715 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression( 1716 LLVMMetadataRef GVE) { 1717 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression()); 1718 } 1719 1720 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) { 1721 return wrap(unwrapDI<DIVariable>(Var)->getFile()); 1722 } 1723 1724 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) { 1725 return wrap(unwrapDI<DIVariable>(Var)->getScope()); 1726 } 1727 1728 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) { 1729 return unwrapDI<DIVariable>(Var)->getLine(); 1730 } 1731 1732 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data, 1733 size_t Count) { 1734 return wrap( 1735 MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release()); 1736 } 1737 1738 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) { 1739 MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode)); 1740 } 1741 1742 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata, 1743 LLVMMetadataRef Replacement) { 1744 auto *Node = unwrapDI<MDNode>(TargetMetadata); 1745 Node->replaceAllUsesWith(unwrap(Replacement)); 1746 MDNode::deleteTemporary(Node); 1747 } 1748 1749 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl( 1750 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1751 size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File, 1752 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit, 1753 LLVMMetadataRef Decl, uint32_t AlignInBits) { 1754 return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl( 1755 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen}, 1756 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit, 1757 unwrapDI<MDNode>(Decl), nullptr, AlignInBits)); 1758 } 1759 1760 LLVMDbgRecordRef LLVMDIBuilderInsertDeclareRecordBefore( 1761 LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo, 1762 LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMValueRef Instr) { 1763 DbgInstPtr DbgInst = unwrap(Builder)->insertDeclare( 1764 unwrap(Storage), unwrap<DILocalVariable>(VarInfo), 1765 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), 1766 Instr ? InsertPosition(unwrap<Instruction>(Instr)->getIterator()) 1767 : nullptr); 1768 // This assert will fail if the module is in the old debug info format. 1769 // This function should only be called if the module is in the new 1770 // debug info format. 1771 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1772 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1773 assert(isa<DbgRecord *>(DbgInst) && 1774 "Function unexpectedly in old debug info format"); 1775 return wrap(cast<DbgRecord *>(DbgInst)); 1776 } 1777 1778 LLVMDbgRecordRef LLVMDIBuilderInsertDeclareRecordAtEnd( 1779 LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo, 1780 LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) { 1781 DbgInstPtr DbgInst = unwrap(Builder)->insertDeclare( 1782 unwrap(Storage), unwrap<DILocalVariable>(VarInfo), 1783 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), unwrap(Block)); 1784 // This assert will fail if the module is in the old debug info format. 1785 // This function should only be called if the module is in the new 1786 // debug info format. 1787 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1788 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1789 assert(isa<DbgRecord *>(DbgInst) && 1790 "Function unexpectedly in old debug info format"); 1791 return wrap(cast<DbgRecord *>(DbgInst)); 1792 } 1793 1794 LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueRecordBefore( 1795 LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo, 1796 LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) { 1797 DbgInstPtr DbgInst = unwrap(Builder)->insertDbgValueIntrinsic( 1798 unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr), 1799 unwrap<DILocation>(DebugLoc), 1800 Instr ? InsertPosition(unwrap<Instruction>(Instr)->getIterator()) 1801 : nullptr); 1802 // This assert will fail if the module is in the old debug info format. 1803 // This function should only be called if the module is in the new 1804 // debug info format. 1805 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1806 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1807 assert(isa<DbgRecord *>(DbgInst) && 1808 "Function unexpectedly in old debug info format"); 1809 return wrap(cast<DbgRecord *>(DbgInst)); 1810 } 1811 1812 LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueRecordAtEnd( 1813 LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo, 1814 LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) { 1815 DbgInstPtr DbgInst = unwrap(Builder)->insertDbgValueIntrinsic( 1816 unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr), 1817 unwrap<DILocation>(DebugLoc), 1818 Block ? InsertPosition(unwrap(Block)->end()) : nullptr); 1819 // This assert will fail if the module is in the old debug info format. 1820 // This function should only be called if the module is in the new 1821 // debug info format. 1822 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1823 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1824 assert(isa<DbgRecord *>(DbgInst) && 1825 "Function unexpectedly in old debug info format"); 1826 return wrap(cast<DbgRecord *>(DbgInst)); 1827 } 1828 1829 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable( 1830 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1831 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, 1832 LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) { 1833 return wrap(unwrap(Builder)->createAutoVariable( 1834 unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File), 1835 LineNo, unwrap<DIType>(Ty), AlwaysPreserve, 1836 map_from_llvmDIFlags(Flags), AlignInBits)); 1837 } 1838 1839 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable( 1840 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1841 size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo, 1842 LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) { 1843 return wrap(unwrap(Builder)->createParameterVariable( 1844 unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File), 1845 LineNo, unwrap<DIType>(Ty), AlwaysPreserve, 1846 map_from_llvmDIFlags(Flags))); 1847 } 1848 1849 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder, 1850 int64_t Lo, int64_t Count) { 1851 return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count)); 1852 } 1853 1854 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder, 1855 LLVMMetadataRef *Data, 1856 size_t Length) { 1857 Metadata **DataValue = unwrap(Data); 1858 return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get()); 1859 } 1860 1861 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) { 1862 return wrap(unwrap<Function>(Func)->getSubprogram()); 1863 } 1864 1865 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) { 1866 unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP)); 1867 } 1868 1869 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) { 1870 return unwrapDI<DISubprogram>(Subprogram)->getLine(); 1871 } 1872 1873 void LLVMDISubprogramReplaceType(LLVMMetadataRef Subprogram, 1874 LLVMMetadataRef SubroutineType) { 1875 unwrapDI<DISubprogram>(Subprogram) 1876 ->replaceType(unwrapDI<DISubroutineType>(SubroutineType)); 1877 } 1878 1879 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) { 1880 return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode()); 1881 } 1882 1883 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) { 1884 if (Loc) 1885 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc))); 1886 else 1887 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc()); 1888 } 1889 1890 LLVMMetadataRef LLVMDIBuilderCreateLabel(LLVMDIBuilderRef Builder, 1891 LLVMMetadataRef Context, 1892 const char *Name, size_t NameLen, 1893 LLVMMetadataRef File, unsigned LineNo, 1894 LLVMBool AlwaysPreserve) { 1895 return wrap(unwrap(Builder)->createLabel( 1896 unwrapDI<DIScope>(Context), StringRef(Name, NameLen), 1897 unwrapDI<DIFile>(File), LineNo, /*Column*/ 0, /*IsArtificial*/ false, 1898 /*CoroSuspendIdx*/ std::nullopt, AlwaysPreserve)); 1899 } 1900 1901 LLVMDbgRecordRef LLVMDIBuilderInsertLabelBefore(LLVMDIBuilderRef Builder, 1902 LLVMMetadataRef LabelInfo, 1903 LLVMMetadataRef Location, 1904 LLVMValueRef InsertBefore) { 1905 DbgInstPtr DbgInst = unwrap(Builder)->insertLabel( 1906 unwrapDI<DILabel>(LabelInfo), unwrapDI<DILocation>(Location), 1907 InsertBefore 1908 ? InsertPosition(unwrap<Instruction>(InsertBefore)->getIterator()) 1909 : nullptr); 1910 // This assert will fail if the module is in the old debug info format. 1911 // This function should only be called if the module is in the new 1912 // debug info format. 1913 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1914 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1915 assert(isa<DbgRecord *>(DbgInst) && 1916 "Function unexpectedly in old debug info format"); 1917 return wrap(cast<DbgRecord *>(DbgInst)); 1918 } 1919 1920 LLVMDbgRecordRef LLVMDIBuilderInsertLabelAtEnd(LLVMDIBuilderRef Builder, 1921 LLVMMetadataRef LabelInfo, 1922 LLVMMetadataRef Location, 1923 LLVMBasicBlockRef InsertAtEnd) { 1924 DbgInstPtr DbgInst = unwrap(Builder)->insertLabel( 1925 unwrapDI<DILabel>(LabelInfo), unwrapDI<DILocation>(Location), 1926 InsertAtEnd ? InsertPosition(unwrap(InsertAtEnd)->end()) : nullptr); 1927 // This assert will fail if the module is in the old debug info format. 1928 // This function should only be called if the module is in the new 1929 // debug info format. 1930 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1931 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1932 assert(isa<DbgRecord *>(DbgInst) && 1933 "Function unexpectedly in old debug info format"); 1934 return wrap(cast<DbgRecord *>(DbgInst)); 1935 } 1936 1937 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) { 1938 switch(unwrap(Metadata)->getMetadataID()) { 1939 #define HANDLE_METADATA_LEAF(CLASS) \ 1940 case Metadata::CLASS##Kind: \ 1941 return (LLVMMetadataKind)LLVM##CLASS##MetadataKind; 1942 #include "llvm/IR/Metadata.def" 1943 default: 1944 return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind; 1945 } 1946 } 1947 1948 AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) { 1949 assert(ID && "Expected non-null ID"); 1950 LLVMContext &Ctx = ID->getContext(); 1951 auto &Map = Ctx.pImpl->AssignmentIDToInstrs; 1952 1953 auto MapIt = Map.find(ID); 1954 if (MapIt == Map.end()) 1955 return make_range(nullptr, nullptr); 1956 1957 return make_range(MapIt->second.begin(), MapIt->second.end()); 1958 } 1959 1960 AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) { 1961 assert(ID && "Expected non-null ID"); 1962 LLVMContext &Ctx = ID->getContext(); 1963 1964 auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID); 1965 1966 // The ID is only used wrapped in MetadataAsValue(ID), so lets check that 1967 // one of those already exists first. 1968 if (!IDAsValue) 1969 return make_range(Value::user_iterator(), Value::user_iterator()); 1970 1971 return make_range(IDAsValue->user_begin(), IDAsValue->user_end()); 1972 } 1973 1974 void at::deleteAssignmentMarkers(const Instruction *Inst) { 1975 auto Range = getAssignmentMarkers(Inst); 1976 SmallVector<DbgVariableRecord *> DVRAssigns = getDVRAssignmentMarkers(Inst); 1977 if (Range.empty() && DVRAssigns.empty()) 1978 return; 1979 SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end()); 1980 for (auto *DAI : ToDelete) 1981 DAI->eraseFromParent(); 1982 for (auto *DVR : DVRAssigns) 1983 DVR->eraseFromParent(); 1984 } 1985 1986 void at::RAUW(DIAssignID *Old, DIAssignID *New) { 1987 // Replace attachments. 1988 AssignmentInstRange InstRange = getAssignmentInsts(Old); 1989 // Use intermediate storage for the instruction ptrs because the 1990 // getAssignmentInsts range iterators will be invalidated by adding and 1991 // removing DIAssignID attachments. 1992 SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end()); 1993 for (auto *I : InstVec) 1994 I->setMetadata(LLVMContext::MD_DIAssignID, New); 1995 1996 Old->replaceAllUsesWith(New); 1997 } 1998 1999 void at::deleteAll(Function *F) { 2000 SmallVector<DbgAssignIntrinsic *, 12> ToDelete; 2001 SmallVector<DbgVariableRecord *, 12> DPToDelete; 2002 for (BasicBlock &BB : *F) { 2003 for (Instruction &I : BB) { 2004 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) 2005 if (DVR.isDbgAssign()) 2006 DPToDelete.push_back(&DVR); 2007 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I)) 2008 ToDelete.push_back(DAI); 2009 else 2010 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr); 2011 } 2012 } 2013 for (auto *DAI : ToDelete) 2014 DAI->eraseFromParent(); 2015 for (auto *DVR : DPToDelete) 2016 DVR->eraseFromParent(); 2017 } 2018 2019 /// FIXME: Remove this wrapper function and call 2020 /// DIExpression::calculateFragmentIntersect directly. 2021 template <typename T> 2022 bool calculateFragmentIntersectImpl( 2023 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits, 2024 uint64_t SliceSizeInBits, const T *AssignRecord, 2025 std::optional<DIExpression::FragmentInfo> &Result) { 2026 // No overlap if this DbgRecord describes a killed location. 2027 if (AssignRecord->isKillAddress()) 2028 return false; 2029 2030 int64_t AddrOffsetInBits; 2031 { 2032 int64_t AddrOffsetInBytes; 2033 SmallVector<uint64_t> PostOffsetOps; //< Unused. 2034 // Bail if we can't find a constant offset (or none) in the expression. 2035 if (!AssignRecord->getAddressExpression()->extractLeadingOffset( 2036 AddrOffsetInBytes, PostOffsetOps)) 2037 return false; 2038 AddrOffsetInBits = AddrOffsetInBytes * 8; 2039 } 2040 2041 Value *Addr = AssignRecord->getAddress(); 2042 // FIXME: It may not always be zero. 2043 int64_t BitExtractOffsetInBits = 0; 2044 DIExpression::FragmentInfo VarFrag = 2045 AssignRecord->getFragmentOrEntireVariable(); 2046 2047 int64_t OffsetFromLocationInBits; //< Unused. 2048 return DIExpression::calculateFragmentIntersect( 2049 DL, Dest, SliceOffsetInBits, SliceSizeInBits, Addr, AddrOffsetInBits, 2050 BitExtractOffsetInBits, VarFrag, Result, OffsetFromLocationInBits); 2051 } 2052 2053 /// FIXME: Remove this wrapper function and call 2054 /// DIExpression::calculateFragmentIntersect directly. 2055 bool at::calculateFragmentIntersect( 2056 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits, 2057 uint64_t SliceSizeInBits, const DbgAssignIntrinsic *DbgAssign, 2058 std::optional<DIExpression::FragmentInfo> &Result) { 2059 return calculateFragmentIntersectImpl(DL, Dest, SliceOffsetInBits, 2060 SliceSizeInBits, DbgAssign, Result); 2061 } 2062 2063 /// FIXME: Remove this wrapper function and call 2064 /// DIExpression::calculateFragmentIntersect directly. 2065 bool at::calculateFragmentIntersect( 2066 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits, 2067 uint64_t SliceSizeInBits, const DbgVariableRecord *DVRAssign, 2068 std::optional<DIExpression::FragmentInfo> &Result) { 2069 return calculateFragmentIntersectImpl(DL, Dest, SliceOffsetInBits, 2070 SliceSizeInBits, DVRAssign, Result); 2071 } 2072 2073 /// Update inlined instructions' DIAssignID metadata. We need to do this 2074 /// otherwise a function inlined more than once into the same function 2075 /// will cause DIAssignID to be shared by many instructions. 2076 void at::remapAssignID(DenseMap<DIAssignID *, DIAssignID *> &Map, 2077 Instruction &I) { 2078 auto GetNewID = [&Map](Metadata *Old) { 2079 DIAssignID *OldID = cast<DIAssignID>(Old); 2080 if (DIAssignID *NewID = Map.lookup(OldID)) 2081 return NewID; 2082 DIAssignID *NewID = DIAssignID::getDistinct(OldID->getContext()); 2083 Map[OldID] = NewID; 2084 return NewID; 2085 }; 2086 // If we find a DIAssignID attachment or use, replace it with a new version. 2087 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) { 2088 if (DVR.isDbgAssign()) 2089 DVR.setAssignId(GetNewID(DVR.getAssignID())); 2090 } 2091 if (auto *ID = I.getMetadata(LLVMContext::MD_DIAssignID)) 2092 I.setMetadata(LLVMContext::MD_DIAssignID, GetNewID(ID)); 2093 else if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I)) 2094 DAI->setAssignId(GetNewID(DAI->getAssignID())); 2095 } 2096 2097 /// Collect constant properies (base, size, offset) of \p StoreDest. 2098 /// Return std::nullopt if any properties are not constants or the 2099 /// offset from the base pointer is negative. 2100 static std::optional<AssignmentInfo> 2101 getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest, 2102 TypeSize SizeInBits) { 2103 if (SizeInBits.isScalable()) 2104 return std::nullopt; 2105 APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0); 2106 const Value *Base = StoreDest->stripAndAccumulateConstantOffsets( 2107 DL, GEPOffset, /*AllowNonInbounds*/ true); 2108 2109 if (GEPOffset.isNegative()) 2110 return std::nullopt; 2111 2112 uint64_t OffsetInBytes = GEPOffset.getLimitedValue(); 2113 // Check for overflow. 2114 if (OffsetInBytes == UINT64_MAX) 2115 return std::nullopt; 2116 if (const auto *Alloca = dyn_cast<AllocaInst>(Base)) 2117 return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits); 2118 return std::nullopt; 2119 } 2120 2121 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL, 2122 const MemIntrinsic *I) { 2123 const Value *StoreDest = I->getRawDest(); 2124 // Assume 8 bit bytes. 2125 auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength()); 2126 if (!ConstLengthInBytes) 2127 // We can't use a non-const size, bail. 2128 return std::nullopt; 2129 uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue(); 2130 return getAssignmentInfoImpl(DL, StoreDest, TypeSize::getFixed(SizeInBits)); 2131 } 2132 2133 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL, 2134 const StoreInst *SI) { 2135 TypeSize SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType()); 2136 return getAssignmentInfoImpl(DL, SI->getPointerOperand(), SizeInBits); 2137 } 2138 2139 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL, 2140 const AllocaInst *AI) { 2141 TypeSize SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType()); 2142 return getAssignmentInfoImpl(DL, AI, SizeInBits); 2143 } 2144 2145 /// Returns nullptr if the assignment shouldn't be attributed to this variable. 2146 static void emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest, 2147 Instruction &StoreLikeInst, const VarRecord &VarRec, 2148 DIBuilder &DIB) { 2149 auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID); 2150 assert(ID && "Store instruction must have DIAssignID metadata"); 2151 (void)ID; 2152 2153 const uint64_t StoreStartBit = Info.OffsetInBits; 2154 const uint64_t StoreEndBit = Info.OffsetInBits + Info.SizeInBits; 2155 2156 uint64_t FragStartBit = StoreStartBit; 2157 uint64_t FragEndBit = StoreEndBit; 2158 2159 bool StoreToWholeVariable = Info.StoreToWholeAlloca; 2160 if (auto Size = VarRec.Var->getSizeInBits()) { 2161 // NOTE: trackAssignments doesn't understand base expressions yet, so all 2162 // variables that reach here are guaranteed to start at offset 0 in the 2163 // alloca. 2164 const uint64_t VarStartBit = 0; 2165 const uint64_t VarEndBit = *Size; 2166 2167 // FIXME: trim FragStartBit when nonzero VarStartBit is supported. 2168 FragEndBit = std::min(FragEndBit, VarEndBit); 2169 2170 // Discard stores to bits outside this variable. 2171 if (FragStartBit >= FragEndBit) 2172 return; 2173 2174 StoreToWholeVariable = FragStartBit <= VarStartBit && FragEndBit >= *Size; 2175 } 2176 2177 DIExpression *Expr = DIExpression::get(StoreLikeInst.getContext(), {}); 2178 if (!StoreToWholeVariable) { 2179 auto R = DIExpression::createFragmentExpression(Expr, FragStartBit, 2180 FragEndBit - FragStartBit); 2181 assert(R.has_value() && "failed to create fragment expression"); 2182 Expr = *R; 2183 } 2184 DIExpression *AddrExpr = DIExpression::get(StoreLikeInst.getContext(), {}); 2185 auto *Assign = DbgVariableRecord::createLinkedDVRAssign( 2186 &StoreLikeInst, Val, VarRec.Var, Expr, Dest, AddrExpr, VarRec.DL); 2187 (void)Assign; 2188 LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n"); 2189 } 2190 2191 #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h). 2192 #define DEBUG_TYPE "assignment-tracking" 2193 2194 void at::trackAssignments(Function::iterator Start, Function::iterator End, 2195 const StorageToVarsMap &Vars, const DataLayout &DL, 2196 bool DebugPrints) { 2197 // Early-exit if there are no interesting variables. 2198 if (Vars.empty()) 2199 return; 2200 2201 auto &Ctx = Start->getContext(); 2202 auto &Module = *Start->getModule(); 2203 2204 // Poison type doesn't matter, so long as it isn't void. Let's just use i1. 2205 auto *Poison = PoisonValue::get(Type::getInt1Ty(Ctx)); 2206 DIBuilder DIB(Module, /*AllowUnresolved*/ false); 2207 2208 // Scan the instructions looking for stores to local variables' storage. 2209 LLVM_DEBUG(errs() << "# Scanning instructions\n"); 2210 for (auto BBI = Start; BBI != End; ++BBI) { 2211 for (Instruction &I : *BBI) { 2212 2213 std::optional<AssignmentInfo> Info; 2214 Value *ValueComponent = nullptr; 2215 Value *DestComponent = nullptr; 2216 if (auto *AI = dyn_cast<AllocaInst>(&I)) { 2217 // We want to track the variable's stack home from its alloca's 2218 // position onwards so we treat it as an assignment (where the stored 2219 // value is poison). 2220 Info = getAssignmentInfo(DL, AI); 2221 ValueComponent = Poison; 2222 DestComponent = AI; 2223 } else if (auto *SI = dyn_cast<StoreInst>(&I)) { 2224 Info = getAssignmentInfo(DL, SI); 2225 ValueComponent = SI->getValueOperand(); 2226 DestComponent = SI->getPointerOperand(); 2227 } else if (auto *MI = dyn_cast<MemTransferInst>(&I)) { 2228 Info = getAssignmentInfo(DL, MI); 2229 // May not be able to represent this value easily. 2230 ValueComponent = Poison; 2231 DestComponent = MI->getOperand(0); 2232 } else if (auto *MI = dyn_cast<MemSetInst>(&I)) { 2233 Info = getAssignmentInfo(DL, MI); 2234 // If we're zero-initing we can state the assigned value is zero, 2235 // otherwise use undef. 2236 auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1)); 2237 if (ConstValue && ConstValue->isZero()) 2238 ValueComponent = ConstValue; 2239 else 2240 ValueComponent = Poison; 2241 DestComponent = MI->getOperand(0); 2242 } else { 2243 // Not a store-like instruction. 2244 continue; 2245 } 2246 2247 assert(ValueComponent && DestComponent); 2248 LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n"); 2249 2250 // Check if getAssignmentInfo failed to understand this store. 2251 if (!Info.has_value()) { 2252 LLVM_DEBUG( 2253 errs() 2254 << " | SKIP: Untrackable store (e.g. through non-const gep)\n"); 2255 continue; 2256 } 2257 LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n"); 2258 2259 // Check if the store destination is a local variable with debug info. 2260 auto LocalIt = Vars.find(Info->Base); 2261 if (LocalIt == Vars.end()) { 2262 LLVM_DEBUG( 2263 errs() 2264 << " | SKIP: Base address not associated with local variable\n"); 2265 continue; 2266 } 2267 2268 DIAssignID *ID = 2269 cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID)); 2270 if (!ID) { 2271 ID = DIAssignID::getDistinct(Ctx); 2272 I.setMetadata(LLVMContext::MD_DIAssignID, ID); 2273 } 2274 2275 for (const VarRecord &R : LocalIt->second) 2276 emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB); 2277 } 2278 } 2279 } 2280 2281 bool AssignmentTrackingPass::runOnFunction(Function &F) { 2282 // No value in assignment tracking without optimisations. 2283 if (F.hasFnAttribute(Attribute::OptimizeNone)) 2284 return /*Changed*/ false; 2285 2286 bool Changed = false; 2287 auto *DL = &F.getDataLayout(); 2288 // Collect a map of {backing storage : dbg.declares} (currently "backing 2289 // storage" is limited to Allocas). We'll use this to find dbg.declares to 2290 // delete after running `trackAssignments`. 2291 DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares; 2292 DenseMap<const AllocaInst *, SmallPtrSet<DbgVariableRecord *, 2>> DVRDeclares; 2293 // Create another similar map of {storage : variables} that we'll pass to 2294 // trackAssignments. 2295 StorageToVarsMap Vars; 2296 auto ProcessDeclare = [&](auto *Declare, auto &DeclareList) { 2297 // FIXME: trackAssignments doesn't let you specify any modifiers to the 2298 // variable (e.g. fragment) or location (e.g. offset), so we have to 2299 // leave dbg.declares with non-empty expressions in place. 2300 if (Declare->getExpression()->getNumElements() != 0) 2301 return; 2302 if (!Declare->getAddress()) 2303 return; 2304 if (AllocaInst *Alloca = 2305 dyn_cast<AllocaInst>(Declare->getAddress()->stripPointerCasts())) { 2306 // FIXME: Skip VLAs for now (let these variables use dbg.declares). 2307 if (!Alloca->isStaticAlloca()) 2308 return; 2309 // Similarly, skip scalable vectors (use dbg.declares instead). 2310 if (auto Sz = Alloca->getAllocationSize(*DL); Sz && Sz->isScalable()) 2311 return; 2312 DeclareList[Alloca].insert(Declare); 2313 Vars[Alloca].insert(VarRecord(Declare)); 2314 } 2315 }; 2316 for (auto &BB : F) { 2317 for (auto &I : BB) { 2318 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) { 2319 if (DVR.isDbgDeclare()) 2320 ProcessDeclare(&DVR, DVRDeclares); 2321 } 2322 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I)) 2323 ProcessDeclare(DDI, DbgDeclares); 2324 } 2325 } 2326 2327 // FIXME: Locals can be backed by caller allocas (sret, byval). 2328 // Note: trackAssignments doesn't respect dbg.declare's IR positions (as it 2329 // doesn't "understand" dbg.declares). However, this doesn't appear to break 2330 // any rules given this description of dbg.declare from 2331 // llvm/docs/SourceLevelDebugging.rst: 2332 // 2333 // It is not control-dependent, meaning that if a call to llvm.dbg.declare 2334 // exists and has a valid location argument, that address is considered to 2335 // be the true home of the variable across its entire lifetime. 2336 trackAssignments(F.begin(), F.end(), Vars, *DL); 2337 2338 // Delete dbg.declares for variables now tracked with assignment tracking. 2339 auto DeleteSubsumedDeclare = [&](const auto &Markers, auto &Declares) { 2340 (void)Markers; 2341 for (auto *Declare : Declares) { 2342 // Assert that the alloca that Declare uses is now linked to a dbg.assign 2343 // describing the same variable (i.e. check that this dbg.declare has 2344 // been replaced by a dbg.assign). Use DebugVariableAggregate to Discard 2345 // the fragment part because trackAssignments may alter the 2346 // fragment. e.g. if the alloca is smaller than the variable, then 2347 // trackAssignments will create an alloca-sized fragment for the 2348 // dbg.assign. 2349 assert(llvm::any_of(Markers, [Declare](auto *Assign) { 2350 return DebugVariableAggregate(Assign) == 2351 DebugVariableAggregate(Declare); 2352 })); 2353 // Delete Declare because the variable location is now tracked using 2354 // assignment tracking. 2355 Declare->eraseFromParent(); 2356 Changed = true; 2357 } 2358 }; 2359 for (auto &P : DbgDeclares) 2360 DeleteSubsumedDeclare(at::getAssignmentMarkers(P.first), P.second); 2361 for (auto &P : DVRDeclares) 2362 DeleteSubsumedDeclare(at::getDVRAssignmentMarkers(P.first), P.second); 2363 return Changed; 2364 } 2365 2366 static const char *AssignmentTrackingModuleFlag = 2367 "debug-info-assignment-tracking"; 2368 2369 static void setAssignmentTrackingModuleFlag(Module &M) { 2370 M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag, 2371 ConstantAsMetadata::get( 2372 ConstantInt::get(Type::getInt1Ty(M.getContext()), 1))); 2373 } 2374 2375 static bool getAssignmentTrackingModuleFlag(const Module &M) { 2376 Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag); 2377 return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue(); 2378 } 2379 2380 bool llvm::isAssignmentTrackingEnabled(const Module &M) { 2381 return getAssignmentTrackingModuleFlag(M); 2382 } 2383 2384 PreservedAnalyses AssignmentTrackingPass::run(Function &F, 2385 FunctionAnalysisManager &AM) { 2386 if (!runOnFunction(F)) 2387 return PreservedAnalyses::all(); 2388 2389 // Record that this module uses assignment tracking. It doesn't matter that 2390 // some functons in the module may not use it - the debug info in those 2391 // functions will still be handled properly. 2392 setAssignmentTrackingModuleFlag(*F.getParent()); 2393 2394 // Q: Can we return a less conservative set than just CFGAnalyses? Can we 2395 // return PreservedAnalyses::all()? 2396 PreservedAnalyses PA; 2397 PA.preserveSet<CFGAnalyses>(); 2398 return PA; 2399 } 2400 2401 PreservedAnalyses AssignmentTrackingPass::run(Module &M, 2402 ModuleAnalysisManager &AM) { 2403 bool Changed = false; 2404 for (auto &F : M) 2405 Changed |= runOnFunction(F); 2406 2407 if (!Changed) 2408 return PreservedAnalyses::all(); 2409 2410 // Record that this module uses assignment tracking. 2411 setAssignmentTrackingModuleFlag(M); 2412 2413 // Q: Can we return a less conservative set than just CFGAnalyses? Can we 2414 // return PreservedAnalyses::all()? 2415 PreservedAnalyses PA; 2416 PA.preserveSet<CFGAnalyses>(); 2417 return PA; 2418 } 2419 2420 #undef DEBUG_TYPE 2421