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