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