xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/IR/DebugInfo.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
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 "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DebugInfoMetadata.h"
25 #include "llvm/IR/DebugLoc.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GVMaterializer.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Casting.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <utility>
39 
40 using namespace llvm;
41 using namespace llvm::dwarf;
42 
43 /// Finds all intrinsics declaring local variables as living in the memory that
44 /// 'V' points to. This may include a mix of dbg.declare and
45 /// dbg.addr intrinsics.
FindDbgAddrUses(Value * V)46 TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
47   // This function is hot. Check whether the value has any metadata to avoid a
48   // DenseMap lookup.
49   if (!V->isUsedByMetadata())
50     return {};
51   auto *L = LocalAsMetadata::getIfExists(V);
52   if (!L)
53     return {};
54   auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
55   if (!MDV)
56     return {};
57 
58   TinyPtrVector<DbgVariableIntrinsic *> Declares;
59   for (User *U : MDV->users()) {
60     if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
61       if (DII->isAddressOfVariable())
62         Declares.push_back(DII);
63   }
64 
65   return Declares;
66 }
67 
FindDbgDeclareUses(Value * V)68 TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) {
69   TinyPtrVector<DbgDeclareInst *> DDIs;
70   for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V))
71     if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI))
72       DDIs.push_back(DDI);
73   return DDIs;
74 }
75 
findDbgValues(SmallVectorImpl<DbgValueInst * > & DbgValues,Value * V)76 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
77   // This function is hot. Check whether the value has any metadata to avoid a
78   // DenseMap lookup.
79   if (!V->isUsedByMetadata())
80     return;
81   // TODO: If this value appears multiple times in a DIArgList, we should still
82   // only add the owning DbgValueInst once; use this set to track ArgListUsers.
83   // This behaviour can be removed when we can automatically remove duplicates.
84   SmallPtrSet<DbgValueInst *, 4> EncounteredDbgValues;
85   if (auto *L = LocalAsMetadata::getIfExists(V)) {
86     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
87       for (User *U : MDV->users())
88         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
89           DbgValues.push_back(DVI);
90     }
91     for (Metadata *AL : L->getAllArgListUsers()) {
92       if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
93         for (User *U : MDV->users())
94           if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
95             if (EncounteredDbgValues.insert(DVI).second)
96               DbgValues.push_back(DVI);
97       }
98     }
99   }
100 }
101 
findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic * > & DbgUsers,Value * V)102 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
103                         Value *V) {
104   // This function is hot. Check whether the value has any metadata to avoid a
105   // DenseMap lookup.
106   if (!V->isUsedByMetadata())
107     return;
108   // TODO: If this value appears multiple times in a DIArgList, we should still
109   // only add the owning DbgValueInst once; use this set to track ArgListUsers.
110   // This behaviour can be removed when we can automatically remove duplicates.
111   SmallPtrSet<DbgVariableIntrinsic *, 4> EncounteredDbgValues;
112   if (auto *L = LocalAsMetadata::getIfExists(V)) {
113     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
114       for (User *U : MDV->users())
115         if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
116           DbgUsers.push_back(DII);
117     }
118     for (Metadata *AL : L->getAllArgListUsers()) {
119       if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
120         for (User *U : MDV->users())
121           if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
122             if (EncounteredDbgValues.insert(DII).second)
123               DbgUsers.push_back(DII);
124       }
125     }
126   }
127 }
128 
getDISubprogram(const MDNode * Scope)129 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
130   if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
131     return LocalScope->getSubprogram();
132   return nullptr;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 // DebugInfoFinder implementations.
137 //===----------------------------------------------------------------------===//
138 
reset()139 void DebugInfoFinder::reset() {
140   CUs.clear();
141   SPs.clear();
142   GVs.clear();
143   TYs.clear();
144   Scopes.clear();
145   NodesSeen.clear();
146 }
147 
processModule(const Module & M)148 void DebugInfoFinder::processModule(const Module &M) {
149   for (auto *CU : M.debug_compile_units())
150     processCompileUnit(CU);
151   for (auto &F : M.functions()) {
152     if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
153       processSubprogram(SP);
154     // There could be subprograms from inlined functions referenced from
155     // instructions only. Walk the function to find them.
156     for (const BasicBlock &BB : F)
157       for (const Instruction &I : BB)
158         processInstruction(M, I);
159   }
160 }
161 
processCompileUnit(DICompileUnit * CU)162 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
163   if (!addCompileUnit(CU))
164     return;
165   for (auto DIG : CU->getGlobalVariables()) {
166     if (!addGlobalVariable(DIG))
167       continue;
168     auto *GV = DIG->getVariable();
169     processScope(GV->getScope());
170     processType(GV->getType());
171   }
172   for (auto *ET : CU->getEnumTypes())
173     processType(ET);
174   for (auto *RT : CU->getRetainedTypes())
175     if (auto *T = dyn_cast<DIType>(RT))
176       processType(T);
177     else
178       processSubprogram(cast<DISubprogram>(RT));
179   for (auto *Import : CU->getImportedEntities()) {
180     auto *Entity = Import->getEntity();
181     if (auto *T = dyn_cast<DIType>(Entity))
182       processType(T);
183     else if (auto *SP = dyn_cast<DISubprogram>(Entity))
184       processSubprogram(SP);
185     else if (auto *NS = dyn_cast<DINamespace>(Entity))
186       processScope(NS->getScope());
187     else if (auto *M = dyn_cast<DIModule>(Entity))
188       processScope(M->getScope());
189   }
190 }
191 
processInstruction(const Module & M,const Instruction & I)192 void DebugInfoFinder::processInstruction(const Module &M,
193                                          const Instruction &I) {
194   if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
195     processVariable(M, *DVI);
196 
197   if (auto DbgLoc = I.getDebugLoc())
198     processLocation(M, DbgLoc.get());
199 }
200 
processLocation(const Module & M,const DILocation * Loc)201 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
202   if (!Loc)
203     return;
204   processScope(Loc->getScope());
205   processLocation(M, Loc->getInlinedAt());
206 }
207 
processType(DIType * DT)208 void DebugInfoFinder::processType(DIType *DT) {
209   if (!addType(DT))
210     return;
211   processScope(DT->getScope());
212   if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
213     for (DIType *Ref : ST->getTypeArray())
214       processType(Ref);
215     return;
216   }
217   if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
218     processType(DCT->getBaseType());
219     for (Metadata *D : DCT->getElements()) {
220       if (auto *T = dyn_cast<DIType>(D))
221         processType(T);
222       else if (auto *SP = dyn_cast<DISubprogram>(D))
223         processSubprogram(SP);
224     }
225     return;
226   }
227   if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
228     processType(DDT->getBaseType());
229   }
230 }
231 
processScope(DIScope * Scope)232 void DebugInfoFinder::processScope(DIScope *Scope) {
233   if (!Scope)
234     return;
235   if (auto *Ty = dyn_cast<DIType>(Scope)) {
236     processType(Ty);
237     return;
238   }
239   if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
240     addCompileUnit(CU);
241     return;
242   }
243   if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
244     processSubprogram(SP);
245     return;
246   }
247   if (!addScope(Scope))
248     return;
249   if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
250     processScope(LB->getScope());
251   } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
252     processScope(NS->getScope());
253   } else if (auto *M = dyn_cast<DIModule>(Scope)) {
254     processScope(M->getScope());
255   }
256 }
257 
processSubprogram(DISubprogram * SP)258 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
259   if (!addSubprogram(SP))
260     return;
261   processScope(SP->getScope());
262   // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
263   // ValueMap containing identity mappings for all of the DICompileUnit's, not
264   // just DISubprogram's, referenced from anywhere within the Function being
265   // cloned prior to calling MapMetadata / RemapInstruction to avoid their
266   // duplication later as DICompileUnit's are also directly referenced by
267   // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
268   // Also, DICompileUnit's may reference DISubprogram's too and therefore need
269   // to be at least looked through.
270   processCompileUnit(SP->getUnit());
271   processType(SP->getType());
272   for (auto *Element : SP->getTemplateParams()) {
273     if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
274       processType(TType->getType());
275     } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
276       processType(TVal->getType());
277     }
278   }
279 }
280 
processVariable(const Module & M,const DbgVariableIntrinsic & DVI)281 void DebugInfoFinder::processVariable(const Module &M,
282                                       const DbgVariableIntrinsic &DVI) {
283   auto *N = dyn_cast<MDNode>(DVI.getVariable());
284   if (!N)
285     return;
286 
287   auto *DV = dyn_cast<DILocalVariable>(N);
288   if (!DV)
289     return;
290 
291   if (!NodesSeen.insert(DV).second)
292     return;
293   processScope(DV->getScope());
294   processType(DV->getType());
295 }
296 
addType(DIType * DT)297 bool DebugInfoFinder::addType(DIType *DT) {
298   if (!DT)
299     return false;
300 
301   if (!NodesSeen.insert(DT).second)
302     return false;
303 
304   TYs.push_back(const_cast<DIType *>(DT));
305   return true;
306 }
307 
addCompileUnit(DICompileUnit * CU)308 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
309   if (!CU)
310     return false;
311   if (!NodesSeen.insert(CU).second)
312     return false;
313 
314   CUs.push_back(CU);
315   return true;
316 }
317 
addGlobalVariable(DIGlobalVariableExpression * DIG)318 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
319   if (!NodesSeen.insert(DIG).second)
320     return false;
321 
322   GVs.push_back(DIG);
323   return true;
324 }
325 
addSubprogram(DISubprogram * SP)326 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
327   if (!SP)
328     return false;
329 
330   if (!NodesSeen.insert(SP).second)
331     return false;
332 
333   SPs.push_back(SP);
334   return true;
335 }
336 
addScope(DIScope * Scope)337 bool DebugInfoFinder::addScope(DIScope *Scope) {
338   if (!Scope)
339     return false;
340   // FIXME: Ocaml binding generates a scope with no content, we treat it
341   // as null for now.
342   if (Scope->getNumOperands() == 0)
343     return false;
344   if (!NodesSeen.insert(Scope).second)
345     return false;
346   Scopes.push_back(Scope);
347   return true;
348 }
349 
updateLoopMetadataDebugLocationsImpl(MDNode * OrigLoopID,function_ref<DILocation * (const DILocation &)> Updater)350 static MDNode *updateLoopMetadataDebugLocationsImpl(
351     MDNode *OrigLoopID,
352     function_ref<DILocation *(const DILocation &)> Updater) {
353   assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
354          "Loop ID needs at least one operand");
355   assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
356          "Loop ID should refer to itself");
357 
358   // Save space for the self-referential LoopID.
359   SmallVector<Metadata *, 4> MDs = {nullptr};
360 
361   for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
362     Metadata *MD = OrigLoopID->getOperand(i);
363     if (DILocation *DL = dyn_cast<DILocation>(MD)) {
364       if (DILocation *NewDL = Updater(*DL))
365         MDs.push_back(NewDL);
366     } else
367       MDs.push_back(MD);
368   }
369 
370   MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
371   // Insert the self-referential LoopID.
372   NewLoopID->replaceOperandWith(0, NewLoopID);
373   return NewLoopID;
374 }
375 
updateLoopMetadataDebugLocations(Instruction & I,function_ref<DILocation * (const DILocation &)> Updater)376 void llvm::updateLoopMetadataDebugLocations(
377     Instruction &I, function_ref<DILocation *(const DILocation &)> Updater) {
378   MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
379   if (!OrigLoopID)
380     return;
381   MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
382   I.setMetadata(LLVMContext::MD_loop, NewLoopID);
383 }
384 
stripDebugLocFromLoopID(MDNode * N)385 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
386   assert(!N->operands().empty() && "Missing self reference?");
387 
388   // if there is no debug location, we do not have to rewrite this MDNode.
389   if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
390         return isa<DILocation>(Op.get());
391       }))
392     return N;
393 
394   // If there is only the debug location without any actual loop metadata, we
395   // can remove the metadata.
396   if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
397         return !isa<DILocation>(Op.get());
398       }))
399     return nullptr;
400 
401   auto dropDebugLoc = [](const DILocation &) -> DILocation * {
402     return nullptr;
403   };
404   return updateLoopMetadataDebugLocationsImpl(N, dropDebugLoc);
405 }
406 
stripDebugInfo(Function & F)407 bool llvm::stripDebugInfo(Function &F) {
408   bool Changed = false;
409   if (F.hasMetadata(LLVMContext::MD_dbg)) {
410     Changed = true;
411     F.setSubprogram(nullptr);
412   }
413 
414   DenseMap<MDNode*, MDNode*> LoopIDsMap;
415   for (BasicBlock &BB : F) {
416     for (auto II = BB.begin(), End = BB.end(); II != End;) {
417       Instruction &I = *II++; // We may delete the instruction, increment now.
418       if (isa<DbgInfoIntrinsic>(&I)) {
419         I.eraseFromParent();
420         Changed = true;
421         continue;
422       }
423       if (I.getDebugLoc()) {
424         Changed = true;
425         I.setDebugLoc(DebugLoc());
426       }
427       if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
428         auto *NewLoopID = LoopIDsMap.lookup(LoopID);
429         if (!NewLoopID)
430           NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
431         if (NewLoopID != LoopID)
432           I.setMetadata(LLVMContext::MD_loop, NewLoopID);
433       }
434       // Strip heapallocsite attachments, they point into the DIType system.
435       if (I.hasMetadataOtherThanDebugLoc())
436         I.setMetadata("heapallocsite", nullptr);
437     }
438   }
439   return Changed;
440 }
441 
StripDebugInfo(Module & M)442 bool llvm::StripDebugInfo(Module &M) {
443   bool Changed = false;
444 
445   for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
446     // We're stripping debug info, and without them, coverage information
447     // doesn't quite make sense.
448     if (NMD.getName().startswith("llvm.dbg.") ||
449         NMD.getName() == "llvm.gcov") {
450       NMD.eraseFromParent();
451       Changed = true;
452     }
453   }
454 
455   for (Function &F : M)
456     Changed |= stripDebugInfo(F);
457 
458   for (auto &GV : M.globals()) {
459     Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
460   }
461 
462   if (GVMaterializer *Materializer = M.getMaterializer())
463     Materializer->setStripDebugInfo();
464 
465   return Changed;
466 }
467 
468 namespace {
469 
470 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
471 class DebugTypeInfoRemoval {
472   DenseMap<Metadata *, Metadata *> Replacements;
473 
474 public:
475   /// The (void)() type.
476   MDNode *EmptySubroutineType;
477 
478 private:
479   /// Remember what linkage name we originally had before stripping. If we end
480   /// up making two subprograms identical who originally had different linkage
481   /// names, then we need to make one of them distinct, to avoid them getting
482   /// uniqued. Maps the new node to the old linkage name.
483   DenseMap<DISubprogram *, StringRef> NewToLinkageName;
484 
485   // TODO: Remember the distinct subprogram we created for a given linkage name,
486   // so that we can continue to unique whenever possible. Map <newly created
487   // node, old linkage name> to the first (possibly distinct) mdsubprogram
488   // created for that combination. This is not strictly needed for correctness,
489   // but can cut down on the number of MDNodes and let us diff cleanly with the
490   // output of -gline-tables-only.
491 
492 public:
DebugTypeInfoRemoval(LLVMContext & C)493   DebugTypeInfoRemoval(LLVMContext &C)
494       : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
495                                                   MDNode::get(C, {}))) {}
496 
map(Metadata * M)497   Metadata *map(Metadata *M) {
498     if (!M)
499       return nullptr;
500     auto Replacement = Replacements.find(M);
501     if (Replacement != Replacements.end())
502       return Replacement->second;
503 
504     return M;
505   }
mapNode(Metadata * N)506   MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
507 
508   /// Recursively remap N and all its referenced children. Does a DF post-order
509   /// traversal, so as to remap bottoms up.
traverseAndRemap(MDNode * N)510   void traverseAndRemap(MDNode *N) { traverse(N); }
511 
512 private:
513   // Create a new DISubprogram, to replace the one given.
getReplacementSubprogram(DISubprogram * MDS)514   DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
515     auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
516     StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
517     DISubprogram *Declaration = nullptr;
518     auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
519     DIType *ContainingType =
520         cast_or_null<DIType>(map(MDS->getContainingType()));
521     auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
522     auto Variables = nullptr;
523     auto TemplateParams = nullptr;
524 
525     // Make a distinct DISubprogram, for situations that warrent it.
526     auto distinctMDSubprogram = [&]() {
527       return DISubprogram::getDistinct(
528           MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
529           FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
530           ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
531           MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
532           Variables);
533     };
534 
535     if (MDS->isDistinct())
536       return distinctMDSubprogram();
537 
538     auto *NewMDS = DISubprogram::get(
539         MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
540         FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
541         MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
542         MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
543 
544     StringRef OldLinkageName = MDS->getLinkageName();
545 
546     // See if we need to make a distinct one.
547     auto OrigLinkage = NewToLinkageName.find(NewMDS);
548     if (OrigLinkage != NewToLinkageName.end()) {
549       if (OrigLinkage->second == OldLinkageName)
550         // We're good.
551         return NewMDS;
552 
553       // Otherwise, need to make a distinct one.
554       // TODO: Query the map to see if we already have one.
555       return distinctMDSubprogram();
556     }
557 
558     NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
559     return NewMDS;
560   }
561 
562   /// Create a new compile unit, to replace the one given
getReplacementCU(DICompileUnit * CU)563   DICompileUnit *getReplacementCU(DICompileUnit *CU) {
564     // Drop skeleton CUs.
565     if (CU->getDWOId())
566       return nullptr;
567 
568     auto *File = cast_or_null<DIFile>(map(CU->getFile()));
569     MDTuple *EnumTypes = nullptr;
570     MDTuple *RetainedTypes = nullptr;
571     MDTuple *GlobalVariables = nullptr;
572     MDTuple *ImportedEntities = nullptr;
573     return DICompileUnit::getDistinct(
574         CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
575         CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
576         CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
577         RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
578         CU->getDWOId(), CU->getSplitDebugInlining(),
579         CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
580         CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
581   }
582 
getReplacementMDLocation(DILocation * MLD)583   DILocation *getReplacementMDLocation(DILocation *MLD) {
584     auto *Scope = map(MLD->getScope());
585     auto *InlinedAt = map(MLD->getInlinedAt());
586     if (MLD->isDistinct())
587       return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
588                                      MLD->getColumn(), Scope, InlinedAt);
589     return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
590                            Scope, InlinedAt);
591   }
592 
593   /// Create a new generic MDNode, to replace the one given
getReplacementMDNode(MDNode * N)594   MDNode *getReplacementMDNode(MDNode *N) {
595     SmallVector<Metadata *, 8> Ops;
596     Ops.reserve(N->getNumOperands());
597     for (auto &I : N->operands())
598       if (I)
599         Ops.push_back(map(I));
600     auto *Ret = MDNode::get(N->getContext(), Ops);
601     return Ret;
602   }
603 
604   /// Attempt to re-map N to a newly created node.
remap(MDNode * N)605   void remap(MDNode *N) {
606     if (Replacements.count(N))
607       return;
608 
609     auto doRemap = [&](MDNode *N) -> MDNode * {
610       if (!N)
611         return nullptr;
612       if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
613         remap(MDSub->getUnit());
614         return getReplacementSubprogram(MDSub);
615       }
616       if (isa<DISubroutineType>(N))
617         return EmptySubroutineType;
618       if (auto *CU = dyn_cast<DICompileUnit>(N))
619         return getReplacementCU(CU);
620       if (isa<DIFile>(N))
621         return N;
622       if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
623         // Remap to our referenced scope (recursively).
624         return mapNode(MDLB->getScope());
625       if (auto *MLD = dyn_cast<DILocation>(N))
626         return getReplacementMDLocation(MLD);
627 
628       // Otherwise, if we see these, just drop them now. Not strictly necessary,
629       // but this speeds things up a little.
630       if (isa<DINode>(N))
631         return nullptr;
632 
633       return getReplacementMDNode(N);
634     };
635     Replacements[N] = doRemap(N);
636   }
637 
638   /// Do the remapping traversal.
639   void traverse(MDNode *);
640 };
641 
642 } // end anonymous namespace
643 
traverse(MDNode * N)644 void DebugTypeInfoRemoval::traverse(MDNode *N) {
645   if (!N || Replacements.count(N))
646     return;
647 
648   // To avoid cycles, as well as for efficiency sake, we will sometimes prune
649   // parts of the graph.
650   auto prune = [](MDNode *Parent, MDNode *Child) {
651     if (auto *MDS = dyn_cast<DISubprogram>(Parent))
652       return Child == MDS->getRetainedNodes().get();
653     return false;
654   };
655 
656   SmallVector<MDNode *, 16> ToVisit;
657   DenseSet<MDNode *> Opened;
658 
659   // Visit each node starting at N in post order, and map them.
660   ToVisit.push_back(N);
661   while (!ToVisit.empty()) {
662     auto *N = ToVisit.back();
663     if (!Opened.insert(N).second) {
664       // Close it.
665       remap(N);
666       ToVisit.pop_back();
667       continue;
668     }
669     for (auto &I : N->operands())
670       if (auto *MDN = dyn_cast_or_null<MDNode>(I))
671         if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
672             !isa<DICompileUnit>(MDN))
673           ToVisit.push_back(MDN);
674   }
675 }
676 
stripNonLineTableDebugInfo(Module & M)677 bool llvm::stripNonLineTableDebugInfo(Module &M) {
678   bool Changed = false;
679 
680   // First off, delete the debug intrinsics.
681   auto RemoveUses = [&](StringRef Name) {
682     if (auto *DbgVal = M.getFunction(Name)) {
683       while (!DbgVal->use_empty())
684         cast<Instruction>(DbgVal->user_back())->eraseFromParent();
685       DbgVal->eraseFromParent();
686       Changed = true;
687     }
688   };
689   RemoveUses("llvm.dbg.addr");
690   RemoveUses("llvm.dbg.declare");
691   RemoveUses("llvm.dbg.label");
692   RemoveUses("llvm.dbg.value");
693 
694   // Delete non-CU debug info named metadata nodes.
695   for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
696        NMI != NME;) {
697     NamedMDNode *NMD = &*NMI;
698     ++NMI;
699     // Specifically keep dbg.cu around.
700     if (NMD->getName() == "llvm.dbg.cu")
701       continue;
702   }
703 
704   // Drop all dbg attachments from global variables.
705   for (auto &GV : M.globals())
706     GV.eraseMetadata(LLVMContext::MD_dbg);
707 
708   DebugTypeInfoRemoval Mapper(M.getContext());
709   auto remap = [&](MDNode *Node) -> MDNode * {
710     if (!Node)
711       return nullptr;
712     Mapper.traverseAndRemap(Node);
713     auto *NewNode = Mapper.mapNode(Node);
714     Changed |= Node != NewNode;
715     Node = NewNode;
716     return NewNode;
717   };
718 
719   // Rewrite the DebugLocs to be equivalent to what
720   // -gline-tables-only would have created.
721   for (auto &F : M) {
722     if (auto *SP = F.getSubprogram()) {
723       Mapper.traverseAndRemap(SP);
724       auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
725       Changed |= SP != NewSP;
726       F.setSubprogram(NewSP);
727     }
728     for (auto &BB : F) {
729       for (auto &I : BB) {
730         auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
731           auto *Scope = DL.getScope();
732           MDNode *InlinedAt = DL.getInlinedAt();
733           Scope = remap(Scope);
734           InlinedAt = remap(InlinedAt);
735           return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
736                                  Scope, InlinedAt);
737         };
738 
739         if (I.getDebugLoc() != DebugLoc())
740           I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
741 
742         // Remap DILocations in llvm.loop attachments.
743         updateLoopMetadataDebugLocations(I, [&](const DILocation &Loc) {
744           return remapDebugLoc(&Loc).get();
745         });
746 
747         // Strip heapallocsite attachments, they point into the DIType system.
748         if (I.hasMetadataOtherThanDebugLoc())
749           I.setMetadata("heapallocsite", nullptr);
750       }
751     }
752   }
753 
754   // Create a new llvm.dbg.cu, which is equivalent to the one
755   // -gline-tables-only would have created.
756   for (auto &NMD : M.getNamedMDList()) {
757     SmallVector<MDNode *, 8> Ops;
758     for (MDNode *Op : NMD.operands())
759       Ops.push_back(remap(Op));
760 
761     if (!Changed)
762       continue;
763 
764     NMD.clearOperands();
765     for (auto *Op : Ops)
766       if (Op)
767         NMD.addOperand(Op);
768   }
769   return Changed;
770 }
771 
getDebugMetadataVersionFromModule(const Module & M)772 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
773   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
774           M.getModuleFlag("Debug Info Version")))
775     return Val->getZExtValue();
776   return 0;
777 }
778 
applyMergedLocation(const DILocation * LocA,const DILocation * LocB)779 void Instruction::applyMergedLocation(const DILocation *LocA,
780                                       const DILocation *LocB) {
781   setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
782 }
783 
updateLocationAfterHoist()784 void Instruction::updateLocationAfterHoist() { dropLocation(); }
785 
dropLocation()786 void Instruction::dropLocation() {
787   const DebugLoc &DL = getDebugLoc();
788   if (!DL)
789     return;
790 
791   // If this isn't a call, drop the location to allow a location from a
792   // preceding instruction to propagate.
793   if (!isa<CallBase>(this)) {
794     setDebugLoc(DebugLoc());
795     return;
796   }
797 
798   // Set a line 0 location for calls to preserve scope information in case
799   // inlining occurs.
800   DISubprogram *SP = getFunction()->getSubprogram();
801   if (SP)
802     // If a function scope is available, set it on the line 0 location. When
803     // hoisting a call to a predecessor block, using the function scope avoids
804     // making it look like the callee was reached earlier than it should be.
805     setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
806   else
807     // The parent function has no scope. Go ahead and drop the location. If
808     // the parent function is inlined, and the callee has a subprogram, the
809     // inliner will attach a location to the call.
810     //
811     // One alternative is to set a line 0 location with the existing scope and
812     // inlinedAt info. The location might be sensitive to when inlining occurs.
813     setDebugLoc(DebugLoc());
814 }
815 
816 //===----------------------------------------------------------------------===//
817 // LLVM C API implementations.
818 //===----------------------------------------------------------------------===//
819 
map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang)820 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
821   switch (lang) {
822 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR)                 \
823   case LLVMDWARFSourceLanguage##NAME:                                          \
824     return ID;
825 #include "llvm/BinaryFormat/Dwarf.def"
826 #undef HANDLE_DW_LANG
827   }
828   llvm_unreachable("Unhandled Tag");
829 }
830 
unwrapDI(LLVMMetadataRef Ref)831 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
832   return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
833 }
834 
map_from_llvmDIFlags(LLVMDIFlags Flags)835 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
836   return static_cast<DINode::DIFlags>(Flags);
837 }
838 
map_to_llvmDIFlags(DINode::DIFlags Flags)839 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
840   return static_cast<LLVMDIFlags>(Flags);
841 }
842 
843 static DISubprogram::DISPFlags
pack_into_DISPFlags(bool IsLocalToUnit,bool IsDefinition,bool IsOptimized)844 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
845   return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
846 }
847 
LLVMDebugMetadataVersion()848 unsigned LLVMDebugMetadataVersion() {
849   return DEBUG_METADATA_VERSION;
850 }
851 
LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M)852 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
853   return wrap(new DIBuilder(*unwrap(M), false));
854 }
855 
LLVMCreateDIBuilder(LLVMModuleRef M)856 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
857   return wrap(new DIBuilder(*unwrap(M)));
858 }
859 
LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M)860 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
861   return getDebugMetadataVersionFromModule(*unwrap(M));
862 }
863 
LLVMStripModuleDebugInfo(LLVMModuleRef M)864 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
865   return StripDebugInfo(*unwrap(M));
866 }
867 
LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder)868 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
869   delete unwrap(Builder);
870 }
871 
LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder)872 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
873   unwrap(Builder)->finalize();
874 }
875 
LLVMDIBuilderCreateCompileUnit(LLVMDIBuilderRef Builder,LLVMDWARFSourceLanguage Lang,LLVMMetadataRef FileRef,const char * Producer,size_t ProducerLen,LLVMBool isOptimized,const char * Flags,size_t FlagsLen,unsigned RuntimeVer,const char * SplitName,size_t SplitNameLen,LLVMDWARFEmissionKind Kind,unsigned DWOId,LLVMBool SplitDebugInlining,LLVMBool DebugInfoForProfiling,const char * SysRoot,size_t SysRootLen,const char * SDK,size_t SDKLen)876 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
877     LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
878     LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
879     LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
880     unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
881     LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
882     LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
883     const char *SDK, size_t SDKLen) {
884   auto File = unwrapDI<DIFile>(FileRef);
885 
886   return wrap(unwrap(Builder)->createCompileUnit(
887       map_from_llvmDWARFsourcelanguage(Lang), File,
888       StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
889       RuntimeVer, StringRef(SplitName, SplitNameLen),
890       static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
891       SplitDebugInlining, DebugInfoForProfiling,
892       DICompileUnit::DebugNameTableKind::Default, false,
893       StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
894 }
895 
896 LLVMMetadataRef
LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder,const char * Filename,size_t FilenameLen,const char * Directory,size_t DirectoryLen)897 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
898                         size_t FilenameLen, const char *Directory,
899                         size_t DirectoryLen) {
900   return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
901                                           StringRef(Directory, DirectoryLen)));
902 }
903 
904 LLVMMetadataRef
LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentScope,const char * Name,size_t NameLen,const char * ConfigMacros,size_t ConfigMacrosLen,const char * IncludePath,size_t IncludePathLen,const char * APINotesFile,size_t APINotesFileLen)905 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
906                           const char *Name, size_t NameLen,
907                           const char *ConfigMacros, size_t ConfigMacrosLen,
908                           const char *IncludePath, size_t IncludePathLen,
909                           const char *APINotesFile, size_t APINotesFileLen) {
910   return wrap(unwrap(Builder)->createModule(
911       unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
912       StringRef(ConfigMacros, ConfigMacrosLen),
913       StringRef(IncludePath, IncludePathLen),
914       StringRef(APINotesFile, APINotesFileLen)));
915 }
916 
LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentScope,const char * Name,size_t NameLen,LLVMBool ExportSymbols)917 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
918                                              LLVMMetadataRef ParentScope,
919                                              const char *Name, size_t NameLen,
920                                              LLVMBool ExportSymbols) {
921   return wrap(unwrap(Builder)->createNameSpace(
922       unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
923 }
924 
LLVMDIBuilderCreateFunction(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,const char * LinkageName,size_t LinkageNameLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool IsLocalToUnit,LLVMBool IsDefinition,unsigned ScopeLine,LLVMDIFlags Flags,LLVMBool IsOptimized)925 LLVMMetadataRef LLVMDIBuilderCreateFunction(
926     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
927     size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
928     LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
929     LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
930     unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
931   return wrap(unwrap(Builder)->createFunction(
932       unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
933       unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
934       map_from_llvmDIFlags(Flags),
935       pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
936       nullptr, nullptr));
937 }
938 
939 
LLVMDIBuilderCreateLexicalBlock(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Line,unsigned Col)940 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
941     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
942     LLVMMetadataRef File, unsigned Line, unsigned Col) {
943   return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
944                                                   unwrapDI<DIFile>(File),
945                                                   Line, Col));
946 }
947 
948 LLVMMetadataRef
LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Discriminator)949 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
950                                     LLVMMetadataRef Scope,
951                                     LLVMMetadataRef File,
952                                     unsigned Discriminator) {
953   return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
954                                                       unwrapDI<DIFile>(File),
955                                                       Discriminator));
956 }
957 
958 LLVMMetadataRef
LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef NS,LLVMMetadataRef File,unsigned Line)959 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
960                                                LLVMMetadataRef Scope,
961                                                LLVMMetadataRef NS,
962                                                LLVMMetadataRef File,
963                                                unsigned Line) {
964   return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
965                                                     unwrapDI<DINamespace>(NS),
966                                                     unwrapDI<DIFile>(File),
967                                                     Line));
968 }
969 
970 LLVMMetadataRef
LLVMDIBuilderCreateImportedModuleFromAlias(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef ImportedEntity,LLVMMetadataRef File,unsigned Line)971 LLVMDIBuilderCreateImportedModuleFromAlias(LLVMDIBuilderRef Builder,
972                                            LLVMMetadataRef Scope,
973                                            LLVMMetadataRef ImportedEntity,
974                                            LLVMMetadataRef File,
975                                            unsigned Line) {
976   return wrap(unwrap(Builder)->createImportedModule(
977                   unwrapDI<DIScope>(Scope),
978                   unwrapDI<DIImportedEntity>(ImportedEntity),
979                   unwrapDI<DIFile>(File), Line));
980 }
981 
982 LLVMMetadataRef
LLVMDIBuilderCreateImportedModuleFromModule(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef M,LLVMMetadataRef File,unsigned Line)983 LLVMDIBuilderCreateImportedModuleFromModule(LLVMDIBuilderRef Builder,
984                                             LLVMMetadataRef Scope,
985                                             LLVMMetadataRef M,
986                                             LLVMMetadataRef File,
987                                             unsigned Line) {
988   return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
989                                                     unwrapDI<DIModule>(M),
990                                                     unwrapDI<DIFile>(File),
991                                                     Line));
992 }
993 
994 LLVMMetadataRef
LLVMDIBuilderCreateImportedDeclaration(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef Decl,LLVMMetadataRef File,unsigned Line,const char * Name,size_t NameLen)995 LLVMDIBuilderCreateImportedDeclaration(LLVMDIBuilderRef Builder,
996                                        LLVMMetadataRef Scope,
997                                        LLVMMetadataRef Decl,
998                                        LLVMMetadataRef File,
999                                        unsigned Line,
1000                                        const char *Name, size_t NameLen) {
1001   return wrap(unwrap(Builder)->createImportedDeclaration(
1002                   unwrapDI<DIScope>(Scope),
1003                   unwrapDI<DINode>(Decl),
1004                   unwrapDI<DIFile>(File), Line, {Name, NameLen}));
1005 }
1006 
1007 LLVMMetadataRef
LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx,unsigned Line,unsigned Column,LLVMMetadataRef Scope,LLVMMetadataRef InlinedAt)1008 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
1009                                  unsigned Column, LLVMMetadataRef Scope,
1010                                  LLVMMetadataRef InlinedAt) {
1011   return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
1012                               unwrap(InlinedAt)));
1013 }
1014 
LLVMDILocationGetLine(LLVMMetadataRef Location)1015 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
1016   return unwrapDI<DILocation>(Location)->getLine();
1017 }
1018 
LLVMDILocationGetColumn(LLVMMetadataRef Location)1019 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
1020   return unwrapDI<DILocation>(Location)->getColumn();
1021 }
1022 
LLVMDILocationGetScope(LLVMMetadataRef Location)1023 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
1024   return wrap(unwrapDI<DILocation>(Location)->getScope());
1025 }
1026 
LLVMDILocationGetInlinedAt(LLVMMetadataRef Location)1027 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
1028   return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
1029 }
1030 
LLVMDIScopeGetFile(LLVMMetadataRef Scope)1031 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
1032   return wrap(unwrapDI<DIScope>(Scope)->getFile());
1033 }
1034 
LLVMDIFileGetDirectory(LLVMMetadataRef File,unsigned * Len)1035 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
1036   auto Dir = unwrapDI<DIFile>(File)->getDirectory();
1037   *Len = Dir.size();
1038   return Dir.data();
1039 }
1040 
LLVMDIFileGetFilename(LLVMMetadataRef File,unsigned * Len)1041 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
1042   auto Name = unwrapDI<DIFile>(File)->getFilename();
1043   *Len = Name.size();
1044   return Name.data();
1045 }
1046 
LLVMDIFileGetSource(LLVMMetadataRef File,unsigned * Len)1047 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
1048   if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
1049     *Len = Src->size();
1050     return Src->data();
1051   }
1052   *Len = 0;
1053   return "";
1054 }
1055 
LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentMacroFile,unsigned Line,LLVMDWARFMacinfoRecordType RecordType,const char * Name,size_t NameLen,const char * Value,size_t ValueLen)1056 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
1057                                          LLVMMetadataRef ParentMacroFile,
1058                                          unsigned Line,
1059                                          LLVMDWARFMacinfoRecordType RecordType,
1060                                          const char *Name, size_t NameLen,
1061                                          const char *Value, size_t ValueLen) {
1062   return wrap(
1063       unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
1064                                    static_cast<MacinfoRecordType>(RecordType),
1065                                    {Name, NameLen}, {Value, ValueLen}));
1066 }
1067 
1068 LLVMMetadataRef
LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentMacroFile,unsigned Line,LLVMMetadataRef File)1069 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
1070                                  LLVMMetadataRef ParentMacroFile, unsigned Line,
1071                                  LLVMMetadataRef File) {
1072   return wrap(unwrap(Builder)->createTempMacroFile(
1073       unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
1074 }
1075 
LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,int64_t Value,LLVMBool IsUnsigned)1076 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
1077                                               const char *Name, size_t NameLen,
1078                                               int64_t Value,
1079                                               LLVMBool IsUnsigned) {
1080   return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
1081                                                 IsUnsigned != 0));
1082 }
1083 
LLVMDIBuilderCreateEnumerationType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,LLVMMetadataRef * Elements,unsigned NumElements,LLVMMetadataRef ClassTy)1084 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
1085   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1086   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1087   uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
1088   unsigned NumElements, LLVMMetadataRef ClassTy) {
1089 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1090                                                NumElements});
1091 return wrap(unwrap(Builder)->createEnumerationType(
1092     unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1093     LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
1094 }
1095 
LLVMDIBuilderCreateUnionType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags,LLVMMetadataRef * Elements,unsigned NumElements,unsigned RunTimeLang,const char * UniqueId,size_t UniqueIdLen)1096 LLVMMetadataRef LLVMDIBuilderCreateUnionType(
1097   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1098   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1099   uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1100   LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
1101   const char *UniqueId, size_t UniqueIdLen) {
1102   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1103                                                  NumElements});
1104   return wrap(unwrap(Builder)->createUnionType(
1105      unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1106      LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1107      Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
1108 }
1109 
1110 
1111 LLVMMetadataRef
LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder,uint64_t Size,uint32_t AlignInBits,LLVMMetadataRef Ty,LLVMMetadataRef * Subscripts,unsigned NumSubscripts)1112 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
1113                              uint32_t AlignInBits, LLVMMetadataRef Ty,
1114                              LLVMMetadataRef *Subscripts,
1115                              unsigned NumSubscripts) {
1116   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1117                                                  NumSubscripts});
1118   return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
1119                                                unwrapDI<DIType>(Ty), Subs));
1120 }
1121 
1122 LLVMMetadataRef
LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder,uint64_t Size,uint32_t AlignInBits,LLVMMetadataRef Ty,LLVMMetadataRef * Subscripts,unsigned NumSubscripts)1123 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
1124                               uint32_t AlignInBits, LLVMMetadataRef Ty,
1125                               LLVMMetadataRef *Subscripts,
1126                               unsigned NumSubscripts) {
1127   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1128                                                  NumSubscripts});
1129   return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
1130                                                 unwrapDI<DIType>(Ty), Subs));
1131 }
1132 
1133 LLVMMetadataRef
LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,uint64_t SizeInBits,LLVMDWARFTypeEncoding Encoding,LLVMDIFlags Flags)1134 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
1135                              size_t NameLen, uint64_t SizeInBits,
1136                              LLVMDWARFTypeEncoding Encoding,
1137                              LLVMDIFlags Flags) {
1138   return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
1139                                                SizeInBits, Encoding,
1140                                                map_from_llvmDIFlags(Flags)));
1141 }
1142 
LLVMDIBuilderCreatePointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef PointeeTy,uint64_t SizeInBits,uint32_t AlignInBits,unsigned AddressSpace,const char * Name,size_t NameLen)1143 LLVMMetadataRef LLVMDIBuilderCreatePointerType(
1144     LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
1145     uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
1146     const char *Name, size_t NameLen) {
1147   return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
1148                                          SizeInBits, AlignInBits,
1149                                          AddressSpace, {Name, NameLen}));
1150 }
1151 
LLVMDIBuilderCreateStructType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags,LLVMMetadataRef DerivedFrom,LLVMMetadataRef * Elements,unsigned NumElements,unsigned RunTimeLang,LLVMMetadataRef VTableHolder,const char * UniqueId,size_t UniqueIdLen)1152 LLVMMetadataRef LLVMDIBuilderCreateStructType(
1153     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1154     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1155     uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1156     LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
1157     unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
1158     const char *UniqueId, size_t UniqueIdLen) {
1159   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1160                                                  NumElements});
1161   return wrap(unwrap(Builder)->createStructType(
1162       unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1163       LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1164       unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
1165       unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
1166 }
1167 
LLVMDIBuilderCreateMemberType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,LLVMDIFlags Flags,LLVMMetadataRef Ty)1168 LLVMMetadataRef LLVMDIBuilderCreateMemberType(
1169     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1170     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1171     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1172     LLVMMetadataRef Ty) {
1173   return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
1174       {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
1175       OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
1176 }
1177 
1178 LLVMMetadataRef
LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen)1179 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
1180                                    size_t NameLen) {
1181   return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
1182 }
1183 
1184 LLVMMetadataRef
LLVMDIBuilderCreateStaticMemberType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,LLVMMetadataRef Type,LLVMDIFlags Flags,LLVMValueRef ConstantVal,uint32_t AlignInBits)1185 LLVMDIBuilderCreateStaticMemberType(
1186     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1187     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1188     LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
1189     uint32_t AlignInBits) {
1190   return wrap(unwrap(Builder)->createStaticMemberType(
1191                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1192                   unwrapDI<DIFile>(File), LineNumber, unwrapDI<DIType>(Type),
1193                   map_from_llvmDIFlags(Flags), unwrap<Constant>(ConstantVal),
1194                   AlignInBits));
1195 }
1196 
1197 LLVMMetadataRef
LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,LLVMDIFlags Flags,LLVMMetadataRef Ty,LLVMMetadataRef PropertyNode)1198 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
1199                             const char *Name, size_t NameLen,
1200                             LLVMMetadataRef File, unsigned LineNo,
1201                             uint64_t SizeInBits, uint32_t AlignInBits,
1202                             uint64_t OffsetInBits, LLVMDIFlags Flags,
1203                             LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
1204   return wrap(unwrap(Builder)->createObjCIVar(
1205                   {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1206                   SizeInBits, AlignInBits, OffsetInBits,
1207                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
1208                   unwrapDI<MDNode>(PropertyNode)));
1209 }
1210 
1211 LLVMMetadataRef
LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,const char * GetterName,size_t GetterNameLen,const char * SetterName,size_t SetterNameLen,unsigned PropertyAttributes,LLVMMetadataRef Ty)1212 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
1213                                 const char *Name, size_t NameLen,
1214                                 LLVMMetadataRef File, unsigned LineNo,
1215                                 const char *GetterName, size_t GetterNameLen,
1216                                 const char *SetterName, size_t SetterNameLen,
1217                                 unsigned PropertyAttributes,
1218                                 LLVMMetadataRef Ty) {
1219   return wrap(unwrap(Builder)->createObjCProperty(
1220                   {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1221                   {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
1222                   PropertyAttributes, unwrapDI<DIType>(Ty)));
1223 }
1224 
1225 LLVMMetadataRef
LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef Type)1226 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
1227                                      LLVMMetadataRef Type) {
1228   return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
1229 }
1230 
1231 LLVMMetadataRef
LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder,LLVMMetadataRef Type,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Scope,uint32_t AlignInBits)1232 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
1233                            const char *Name, size_t NameLen,
1234                            LLVMMetadataRef File, unsigned LineNo,
1235                            LLVMMetadataRef Scope, uint32_t AlignInBits) {
1236   return wrap(unwrap(Builder)->createTypedef(
1237       unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1238       unwrapDI<DIScope>(Scope), AlignInBits));
1239 }
1240 
1241 LLVMMetadataRef
LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,LLVMMetadataRef Ty,LLVMMetadataRef BaseTy,uint64_t BaseOffset,uint32_t VBPtrOffset,LLVMDIFlags Flags)1242 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
1243                                LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
1244                                uint64_t BaseOffset, uint32_t VBPtrOffset,
1245                                LLVMDIFlags Flags) {
1246   return wrap(unwrap(Builder)->createInheritance(
1247                   unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
1248                   BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
1249 }
1250 
1251 LLVMMetadataRef
LLVMDIBuilderCreateForwardDecl(LLVMDIBuilderRef Builder,unsigned Tag,const char * Name,size_t NameLen,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint32_t AlignInBits,const char * UniqueIdentifier,size_t UniqueIdentifierLen)1252 LLVMDIBuilderCreateForwardDecl(
1253     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1254     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1255     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1256     const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1257   return wrap(unwrap(Builder)->createForwardDecl(
1258                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1259                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1260                   AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
1261 }
1262 
1263 LLVMMetadataRef
LLVMDIBuilderCreateReplaceableCompositeType(LLVMDIBuilderRef Builder,unsigned Tag,const char * Name,size_t NameLen,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags,const char * UniqueIdentifier,size_t UniqueIdentifierLen)1264 LLVMDIBuilderCreateReplaceableCompositeType(
1265     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1266     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1267     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1268     LLVMDIFlags Flags, const char *UniqueIdentifier,
1269     size_t UniqueIdentifierLen) {
1270   return wrap(unwrap(Builder)->createReplaceableCompositeType(
1271                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1272                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1273                   AlignInBits, map_from_llvmDIFlags(Flags),
1274                   {UniqueIdentifier, UniqueIdentifierLen}));
1275 }
1276 
1277 LLVMMetadataRef
LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder,unsigned Tag,LLVMMetadataRef Type)1278 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
1279                                  LLVMMetadataRef Type) {
1280   return wrap(unwrap(Builder)->createQualifiedType(Tag,
1281                                                    unwrapDI<DIType>(Type)));
1282 }
1283 
1284 LLVMMetadataRef
LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder,unsigned Tag,LLVMMetadataRef Type)1285 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
1286                                  LLVMMetadataRef Type) {
1287   return wrap(unwrap(Builder)->createReferenceType(Tag,
1288                                                    unwrapDI<DIType>(Type)));
1289 }
1290 
1291 LLVMMetadataRef
LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder)1292 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
1293   return wrap(unwrap(Builder)->createNullPtrType());
1294 }
1295 
1296 LLVMMetadataRef
LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef PointeeType,LLVMMetadataRef ClassType,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags)1297 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
1298                                      LLVMMetadataRef PointeeType,
1299                                      LLVMMetadataRef ClassType,
1300                                      uint64_t SizeInBits,
1301                                      uint32_t AlignInBits,
1302                                      LLVMDIFlags Flags) {
1303   return wrap(unwrap(Builder)->createMemberPointerType(
1304                   unwrapDI<DIType>(PointeeType),
1305                   unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
1306                   map_from_llvmDIFlags(Flags)));
1307 }
1308 
1309 LLVMMetadataRef
LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint64_t OffsetInBits,uint64_t StorageOffsetInBits,LLVMDIFlags Flags,LLVMMetadataRef Type)1310 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
1311                                       LLVMMetadataRef Scope,
1312                                       const char *Name, size_t NameLen,
1313                                       LLVMMetadataRef File, unsigned LineNumber,
1314                                       uint64_t SizeInBits,
1315                                       uint64_t OffsetInBits,
1316                                       uint64_t StorageOffsetInBits,
1317                                       LLVMDIFlags Flags, LLVMMetadataRef Type) {
1318   return wrap(unwrap(Builder)->createBitFieldMemberType(
1319                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1320                   unwrapDI<DIFile>(File), LineNumber,
1321                   SizeInBits, OffsetInBits, StorageOffsetInBits,
1322                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
1323 }
1324 
LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,LLVMDIFlags Flags,LLVMMetadataRef DerivedFrom,LLVMMetadataRef * Elements,unsigned NumElements,LLVMMetadataRef VTableHolder,LLVMMetadataRef TemplateParamsNode,const char * UniqueIdentifier,size_t UniqueIdentifierLen)1325 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
1326     LLVMMetadataRef Scope, const char *Name, size_t NameLen,
1327     LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1328     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1329     LLVMMetadataRef DerivedFrom,
1330     LLVMMetadataRef *Elements, unsigned NumElements,
1331     LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
1332     const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1333   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1334                                                  NumElements});
1335   return wrap(unwrap(Builder)->createClassType(
1336                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1337                   unwrapDI<DIFile>(File), LineNumber,
1338                   SizeInBits, AlignInBits, OffsetInBits,
1339                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom),
1340                   Elts, unwrapDI<DIType>(VTableHolder),
1341                   unwrapDI<MDNode>(TemplateParamsNode),
1342                   {UniqueIdentifier, UniqueIdentifierLen}));
1343 }
1344 
1345 LLVMMetadataRef
LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,LLVMMetadataRef Type)1346 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
1347                                   LLVMMetadataRef Type) {
1348   return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
1349 }
1350 
LLVMDITypeGetName(LLVMMetadataRef DType,size_t * Length)1351 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
1352   StringRef Str = unwrap<DIType>(DType)->getName();
1353   *Length = Str.size();
1354   return Str.data();
1355 }
1356 
LLVMDITypeGetSizeInBits(LLVMMetadataRef DType)1357 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
1358   return unwrapDI<DIType>(DType)->getSizeInBits();
1359 }
1360 
LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType)1361 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
1362   return unwrapDI<DIType>(DType)->getOffsetInBits();
1363 }
1364 
LLVMDITypeGetAlignInBits(LLVMMetadataRef DType)1365 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
1366   return unwrapDI<DIType>(DType)->getAlignInBits();
1367 }
1368 
LLVMDITypeGetLine(LLVMMetadataRef DType)1369 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
1370   return unwrapDI<DIType>(DType)->getLine();
1371 }
1372 
LLVMDITypeGetFlags(LLVMMetadataRef DType)1373 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
1374   return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
1375 }
1376 
LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,LLVMMetadataRef * Types,size_t Length)1377 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
1378                                                   LLVMMetadataRef *Types,
1379                                                   size_t Length) {
1380   return wrap(
1381       unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
1382 }
1383 
1384 LLVMMetadataRef
LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,LLVMMetadataRef File,LLVMMetadataRef * ParameterTypes,unsigned NumParameterTypes,LLVMDIFlags Flags)1385 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
1386                                   LLVMMetadataRef File,
1387                                   LLVMMetadataRef *ParameterTypes,
1388                                   unsigned NumParameterTypes,
1389                                   LLVMDIFlags Flags) {
1390   auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
1391                                                      NumParameterTypes});
1392   return wrap(unwrap(Builder)->createSubroutineType(
1393     Elts, map_from_llvmDIFlags(Flags)));
1394 }
1395 
LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,int64_t * Addr,size_t Length)1396 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
1397                                               int64_t *Addr, size_t Length) {
1398   return wrap(unwrap(Builder)->createExpression(ArrayRef<int64_t>(Addr,
1399                                                                   Length)));
1400 }
1401 
1402 LLVMMetadataRef
LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,int64_t Value)1403 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
1404                                            int64_t Value) {
1405   return wrap(unwrap(Builder)->createConstantValueExpression(Value));
1406 }
1407 
LLVMDIBuilderCreateGlobalVariableExpression(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,const char * Linkage,size_t LinkLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool LocalToUnit,LLVMMetadataRef Expr,LLVMMetadataRef Decl,uint32_t AlignInBits)1408 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
1409     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1410     size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
1411     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1412     LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
1413   return wrap(unwrap(Builder)->createGlobalVariableExpression(
1414       unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
1415       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1416       true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
1417       nullptr, AlignInBits));
1418 }
1419 
LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE)1420 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
1421   return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
1422 }
1423 
LLVMDIGlobalVariableExpressionGetExpression(LLVMMetadataRef GVE)1424 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
1425     LLVMMetadataRef GVE) {
1426   return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
1427 }
1428 
LLVMDIVariableGetFile(LLVMMetadataRef Var)1429 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
1430   return wrap(unwrapDI<DIVariable>(Var)->getFile());
1431 }
1432 
LLVMDIVariableGetScope(LLVMMetadataRef Var)1433 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
1434   return wrap(unwrapDI<DIVariable>(Var)->getScope());
1435 }
1436 
LLVMDIVariableGetLine(LLVMMetadataRef Var)1437 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
1438   return unwrapDI<DIVariable>(Var)->getLine();
1439 }
1440 
LLVMTemporaryMDNode(LLVMContextRef Ctx,LLVMMetadataRef * Data,size_t Count)1441 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
1442                                     size_t Count) {
1443   return wrap(
1444       MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
1445 }
1446 
LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode)1447 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
1448   MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
1449 }
1450 
LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,LLVMMetadataRef Replacement)1451 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
1452                                     LLVMMetadataRef Replacement) {
1453   auto *Node = unwrapDI<MDNode>(TargetMetadata);
1454   Node->replaceAllUsesWith(unwrap<Metadata>(Replacement));
1455   MDNode::deleteTemporary(Node);
1456 }
1457 
LLVMDIBuilderCreateTempGlobalVariableFwdDecl(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,const char * Linkage,size_t LnkLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool LocalToUnit,LLVMMetadataRef Decl,uint32_t AlignInBits)1458 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
1459     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1460     size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
1461     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1462     LLVMMetadataRef Decl, uint32_t AlignInBits) {
1463   return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
1464       unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
1465       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1466       unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
1467 }
1468 
1469 LLVMValueRef
LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder,LLVMValueRef Storage,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DL,LLVMValueRef Instr)1470 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
1471                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
1472                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
1473   return wrap(unwrap(Builder)->insertDeclare(
1474                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1475                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1476                   unwrap<Instruction>(Instr)));
1477 }
1478 
LLVMDIBuilderInsertDeclareAtEnd(LLVMDIBuilderRef Builder,LLVMValueRef Storage,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DL,LLVMBasicBlockRef Block)1479 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
1480     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
1481     LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
1482   return wrap(unwrap(Builder)->insertDeclare(
1483                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1484                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1485                   unwrap(Block)));
1486 }
1487 
LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,LLVMValueRef Val,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DebugLoc,LLVMValueRef Instr)1488 LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
1489                                                LLVMValueRef Val,
1490                                                LLVMMetadataRef VarInfo,
1491                                                LLVMMetadataRef Expr,
1492                                                LLVMMetadataRef DebugLoc,
1493                                                LLVMValueRef Instr) {
1494   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1495                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1496                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1497                   unwrap<Instruction>(Instr)));
1498 }
1499 
LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,LLVMValueRef Val,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DebugLoc,LLVMBasicBlockRef Block)1500 LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
1501                                               LLVMValueRef Val,
1502                                               LLVMMetadataRef VarInfo,
1503                                               LLVMMetadataRef Expr,
1504                                               LLVMMetadataRef DebugLoc,
1505                                               LLVMBasicBlockRef Block) {
1506   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1507                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1508                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1509                   unwrap(Block)));
1510 }
1511 
LLVMDIBuilderCreateAutoVariable(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool AlwaysPreserve,LLVMDIFlags Flags,uint32_t AlignInBits)1512 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
1513     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1514     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1515     LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
1516   return wrap(unwrap(Builder)->createAutoVariable(
1517                   unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
1518                   LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1519                   map_from_llvmDIFlags(Flags), AlignInBits));
1520 }
1521 
LLVMDIBuilderCreateParameterVariable(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,unsigned ArgNo,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool AlwaysPreserve,LLVMDIFlags Flags)1522 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
1523     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1524     size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
1525     LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
1526   return wrap(unwrap(Builder)->createParameterVariable(
1527                   unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
1528                   LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1529                   map_from_llvmDIFlags(Flags)));
1530 }
1531 
LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,int64_t Lo,int64_t Count)1532 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
1533                                                  int64_t Lo, int64_t Count) {
1534   return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
1535 }
1536 
LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,LLVMMetadataRef * Data,size_t Length)1537 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
1538                                               LLVMMetadataRef *Data,
1539                                               size_t Length) {
1540   Metadata **DataValue = unwrap(Data);
1541   return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
1542 }
1543 
LLVMGetSubprogram(LLVMValueRef Func)1544 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
1545   return wrap(unwrap<Function>(Func)->getSubprogram());
1546 }
1547 
LLVMSetSubprogram(LLVMValueRef Func,LLVMMetadataRef SP)1548 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
1549   unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1550 }
1551 
LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram)1552 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
1553   return unwrapDI<DISubprogram>(Subprogram)->getLine();
1554 }
1555 
LLVMInstructionGetDebugLoc(LLVMValueRef Inst)1556 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
1557   return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
1558 }
1559 
LLVMInstructionSetDebugLoc(LLVMValueRef Inst,LLVMMetadataRef Loc)1560 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
1561   if (Loc)
1562     unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
1563   else
1564     unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
1565 }
1566 
LLVMGetMetadataKind(LLVMMetadataRef Metadata)1567 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
1568   switch(unwrap(Metadata)->getMetadataID()) {
1569 #define HANDLE_METADATA_LEAF(CLASS) \
1570   case Metadata::CLASS##Kind: \
1571     return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
1572 #include "llvm/IR/Metadata.def"
1573   default:
1574     return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
1575   }
1576 }
1577