xref: /freebsd/contrib/llvm-project/llvm/lib/IR/DebugInfo.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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.
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 
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 
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 
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 
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 
139 void DebugInfoFinder::reset() {
140   CUs.clear();
141   SPs.clear();
142   GVs.clear();
143   TYs.clear();
144   Scopes.clear();
145   NodesSeen.clear();
146 }
147 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
350 static MDNode *updateLoopMetadataDebugLocationsImpl(
351     MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {
352   assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
353          "Loop ID needs at least one operand");
354   assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
355          "Loop ID should refer to itself");
356 
357   // Save space for the self-referential LoopID.
358   SmallVector<Metadata *, 4> MDs = {nullptr};
359 
360   for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
361     Metadata *MD = OrigLoopID->getOperand(i);
362     if (!MD)
363       MDs.push_back(nullptr);
364     else if (Metadata *NewMD = Updater(MD))
365       MDs.push_back(NewMD);
366   }
367 
368   MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
369   // Insert the self-referential LoopID.
370   NewLoopID->replaceOperandWith(0, NewLoopID);
371   return NewLoopID;
372 }
373 
374 void llvm::updateLoopMetadataDebugLocations(
375     Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {
376   MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
377   if (!OrigLoopID)
378     return;
379   MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
380   I.setMetadata(LLVMContext::MD_loop, NewLoopID);
381 }
382 
383 /// Return true if a node is a DILocation or if a DILocation is
384 /// indirectly referenced by one of the node's children.
385 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
386                                   SmallPtrSetImpl<Metadata *> &Reachable,
387                                   Metadata *MD) {
388   MDNode *N = dyn_cast_or_null<MDNode>(MD);
389   if (!N)
390     return false;
391   if (isa<DILocation>(N) || Reachable.count(N))
392     return true;
393   if (!Visited.insert(N).second)
394     return false;
395   for (auto &OpIt : N->operands()) {
396     Metadata *Op = OpIt.get();
397     if (isDILocationReachable(Visited, Reachable, Op)) {
398       Reachable.insert(N);
399       return true;
400     }
401   }
402   return false;
403 }
404 
405 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
406   assert(!N->operands().empty() && "Missing self reference?");
407   SmallPtrSet<Metadata *, 8> Visited, DILocationReachable;
408   // If we already visited N, there is nothing to do.
409   if (!Visited.insert(N).second)
410     return N;
411 
412   // If there is no debug location, we do not have to rewrite this
413   // MDNode. This loop also initializes DILocationReachable, later
414   // needed by updateLoopMetadataDebugLocationsImpl; the use of
415   // count_if avoids an early exit.
416   if (!std::count_if(N->op_begin() + 1, N->op_end(),
417                      [&Visited, &DILocationReachable](const MDOperand &Op) {
418                        return isDILocationReachable(
419                                   Visited, DILocationReachable, Op.get());
420                      }))
421     return N;
422 
423   // If there is only the debug location without any actual loop metadata, we
424   // can remove the metadata.
425   if (std::all_of(
426           N->op_begin() + 1, N->op_end(),
427           [&Visited, &DILocationReachable](const MDOperand &Op) {
428             return isDILocationReachable(Visited, DILocationReachable,
429                                          Op.get());
430           }))
431     return nullptr;
432 
433   return updateLoopMetadataDebugLocationsImpl(
434       N, [&DILocationReachable](Metadata *MD) -> Metadata * {
435         if (isa<DILocation>(MD) || DILocationReachable.count(MD))
436           return nullptr;
437         return MD;
438       });
439 }
440 
441 bool llvm::stripDebugInfo(Function &F) {
442   bool Changed = false;
443   if (F.hasMetadata(LLVMContext::MD_dbg)) {
444     Changed = true;
445     F.setSubprogram(nullptr);
446   }
447 
448   DenseMap<MDNode *, MDNode *> LoopIDsMap;
449   for (BasicBlock &BB : F) {
450     for (Instruction &I : llvm::make_early_inc_range(BB)) {
451       if (isa<DbgInfoIntrinsic>(&I)) {
452         I.eraseFromParent();
453         Changed = true;
454         continue;
455       }
456       if (I.getDebugLoc()) {
457         Changed = true;
458         I.setDebugLoc(DebugLoc());
459       }
460       if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
461         auto *NewLoopID = LoopIDsMap.lookup(LoopID);
462         if (!NewLoopID)
463           NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
464         if (NewLoopID != LoopID)
465           I.setMetadata(LLVMContext::MD_loop, NewLoopID);
466       }
467       // Strip heapallocsite attachments, they point into the DIType system.
468       if (I.hasMetadataOtherThanDebugLoc())
469         I.setMetadata("heapallocsite", nullptr);
470     }
471   }
472   return Changed;
473 }
474 
475 bool llvm::StripDebugInfo(Module &M) {
476   bool Changed = false;
477 
478   for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
479     // We're stripping debug info, and without them, coverage information
480     // doesn't quite make sense.
481     if (NMD.getName().startswith("llvm.dbg.") ||
482         NMD.getName() == "llvm.gcov") {
483       NMD.eraseFromParent();
484       Changed = true;
485     }
486   }
487 
488   for (Function &F : M)
489     Changed |= stripDebugInfo(F);
490 
491   for (auto &GV : M.globals()) {
492     Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
493   }
494 
495   if (GVMaterializer *Materializer = M.getMaterializer())
496     Materializer->setStripDebugInfo();
497 
498   return Changed;
499 }
500 
501 namespace {
502 
503 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
504 class DebugTypeInfoRemoval {
505   DenseMap<Metadata *, Metadata *> Replacements;
506 
507 public:
508   /// The (void)() type.
509   MDNode *EmptySubroutineType;
510 
511 private:
512   /// Remember what linkage name we originally had before stripping. If we end
513   /// up making two subprograms identical who originally had different linkage
514   /// names, then we need to make one of them distinct, to avoid them getting
515   /// uniqued. Maps the new node to the old linkage name.
516   DenseMap<DISubprogram *, StringRef> NewToLinkageName;
517 
518   // TODO: Remember the distinct subprogram we created for a given linkage name,
519   // so that we can continue to unique whenever possible. Map <newly created
520   // node, old linkage name> to the first (possibly distinct) mdsubprogram
521   // created for that combination. This is not strictly needed for correctness,
522   // but can cut down on the number of MDNodes and let us diff cleanly with the
523   // output of -gline-tables-only.
524 
525 public:
526   DebugTypeInfoRemoval(LLVMContext &C)
527       : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
528                                                   MDNode::get(C, {}))) {}
529 
530   Metadata *map(Metadata *M) {
531     if (!M)
532       return nullptr;
533     auto Replacement = Replacements.find(M);
534     if (Replacement != Replacements.end())
535       return Replacement->second;
536 
537     return M;
538   }
539   MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
540 
541   /// Recursively remap N and all its referenced children. Does a DF post-order
542   /// traversal, so as to remap bottoms up.
543   void traverseAndRemap(MDNode *N) { traverse(N); }
544 
545 private:
546   // Create a new DISubprogram, to replace the one given.
547   DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
548     auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
549     StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
550     DISubprogram *Declaration = nullptr;
551     auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
552     DIType *ContainingType =
553         cast_or_null<DIType>(map(MDS->getContainingType()));
554     auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
555     auto Variables = nullptr;
556     auto TemplateParams = nullptr;
557 
558     // Make a distinct DISubprogram, for situations that warrent it.
559     auto distinctMDSubprogram = [&]() {
560       return DISubprogram::getDistinct(
561           MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
562           FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
563           ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
564           MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
565           Variables);
566     };
567 
568     if (MDS->isDistinct())
569       return distinctMDSubprogram();
570 
571     auto *NewMDS = DISubprogram::get(
572         MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
573         FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
574         MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
575         MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
576 
577     StringRef OldLinkageName = MDS->getLinkageName();
578 
579     // See if we need to make a distinct one.
580     auto OrigLinkage = NewToLinkageName.find(NewMDS);
581     if (OrigLinkage != NewToLinkageName.end()) {
582       if (OrigLinkage->second == OldLinkageName)
583         // We're good.
584         return NewMDS;
585 
586       // Otherwise, need to make a distinct one.
587       // TODO: Query the map to see if we already have one.
588       return distinctMDSubprogram();
589     }
590 
591     NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
592     return NewMDS;
593   }
594 
595   /// Create a new compile unit, to replace the one given
596   DICompileUnit *getReplacementCU(DICompileUnit *CU) {
597     // Drop skeleton CUs.
598     if (CU->getDWOId())
599       return nullptr;
600 
601     auto *File = cast_or_null<DIFile>(map(CU->getFile()));
602     MDTuple *EnumTypes = nullptr;
603     MDTuple *RetainedTypes = nullptr;
604     MDTuple *GlobalVariables = nullptr;
605     MDTuple *ImportedEntities = nullptr;
606     return DICompileUnit::getDistinct(
607         CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
608         CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
609         CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
610         RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
611         CU->getDWOId(), CU->getSplitDebugInlining(),
612         CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
613         CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
614   }
615 
616   DILocation *getReplacementMDLocation(DILocation *MLD) {
617     auto *Scope = map(MLD->getScope());
618     auto *InlinedAt = map(MLD->getInlinedAt());
619     if (MLD->isDistinct())
620       return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
621                                      MLD->getColumn(), Scope, InlinedAt);
622     return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
623                            Scope, InlinedAt);
624   }
625 
626   /// Create a new generic MDNode, to replace the one given
627   MDNode *getReplacementMDNode(MDNode *N) {
628     SmallVector<Metadata *, 8> Ops;
629     Ops.reserve(N->getNumOperands());
630     for (auto &I : N->operands())
631       if (I)
632         Ops.push_back(map(I));
633     auto *Ret = MDNode::get(N->getContext(), Ops);
634     return Ret;
635   }
636 
637   /// Attempt to re-map N to a newly created node.
638   void remap(MDNode *N) {
639     if (Replacements.count(N))
640       return;
641 
642     auto doRemap = [&](MDNode *N) -> MDNode * {
643       if (!N)
644         return nullptr;
645       if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
646         remap(MDSub->getUnit());
647         return getReplacementSubprogram(MDSub);
648       }
649       if (isa<DISubroutineType>(N))
650         return EmptySubroutineType;
651       if (auto *CU = dyn_cast<DICompileUnit>(N))
652         return getReplacementCU(CU);
653       if (isa<DIFile>(N))
654         return N;
655       if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
656         // Remap to our referenced scope (recursively).
657         return mapNode(MDLB->getScope());
658       if (auto *MLD = dyn_cast<DILocation>(N))
659         return getReplacementMDLocation(MLD);
660 
661       // Otherwise, if we see these, just drop them now. Not strictly necessary,
662       // but this speeds things up a little.
663       if (isa<DINode>(N))
664         return nullptr;
665 
666       return getReplacementMDNode(N);
667     };
668     Replacements[N] = doRemap(N);
669   }
670 
671   /// Do the remapping traversal.
672   void traverse(MDNode *);
673 };
674 
675 } // end anonymous namespace
676 
677 void DebugTypeInfoRemoval::traverse(MDNode *N) {
678   if (!N || Replacements.count(N))
679     return;
680 
681   // To avoid cycles, as well as for efficiency sake, we will sometimes prune
682   // parts of the graph.
683   auto prune = [](MDNode *Parent, MDNode *Child) {
684     if (auto *MDS = dyn_cast<DISubprogram>(Parent))
685       return Child == MDS->getRetainedNodes().get();
686     return false;
687   };
688 
689   SmallVector<MDNode *, 16> ToVisit;
690   DenseSet<MDNode *> Opened;
691 
692   // Visit each node starting at N in post order, and map them.
693   ToVisit.push_back(N);
694   while (!ToVisit.empty()) {
695     auto *N = ToVisit.back();
696     if (!Opened.insert(N).second) {
697       // Close it.
698       remap(N);
699       ToVisit.pop_back();
700       continue;
701     }
702     for (auto &I : N->operands())
703       if (auto *MDN = dyn_cast_or_null<MDNode>(I))
704         if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
705             !isa<DICompileUnit>(MDN))
706           ToVisit.push_back(MDN);
707   }
708 }
709 
710 bool llvm::stripNonLineTableDebugInfo(Module &M) {
711   bool Changed = false;
712 
713   // First off, delete the debug intrinsics.
714   auto RemoveUses = [&](StringRef Name) {
715     if (auto *DbgVal = M.getFunction(Name)) {
716       while (!DbgVal->use_empty())
717         cast<Instruction>(DbgVal->user_back())->eraseFromParent();
718       DbgVal->eraseFromParent();
719       Changed = true;
720     }
721   };
722   RemoveUses("llvm.dbg.addr");
723   RemoveUses("llvm.dbg.declare");
724   RemoveUses("llvm.dbg.label");
725   RemoveUses("llvm.dbg.value");
726 
727   // Delete non-CU debug info named metadata nodes.
728   for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
729        NMI != NME;) {
730     NamedMDNode *NMD = &*NMI;
731     ++NMI;
732     // Specifically keep dbg.cu around.
733     if (NMD->getName() == "llvm.dbg.cu")
734       continue;
735   }
736 
737   // Drop all dbg attachments from global variables.
738   for (auto &GV : M.globals())
739     GV.eraseMetadata(LLVMContext::MD_dbg);
740 
741   DebugTypeInfoRemoval Mapper(M.getContext());
742   auto remap = [&](MDNode *Node) -> MDNode * {
743     if (!Node)
744       return nullptr;
745     Mapper.traverseAndRemap(Node);
746     auto *NewNode = Mapper.mapNode(Node);
747     Changed |= Node != NewNode;
748     Node = NewNode;
749     return NewNode;
750   };
751 
752   // Rewrite the DebugLocs to be equivalent to what
753   // -gline-tables-only would have created.
754   for (auto &F : M) {
755     if (auto *SP = F.getSubprogram()) {
756       Mapper.traverseAndRemap(SP);
757       auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
758       Changed |= SP != NewSP;
759       F.setSubprogram(NewSP);
760     }
761     for (auto &BB : F) {
762       for (auto &I : BB) {
763         auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
764           auto *Scope = DL.getScope();
765           MDNode *InlinedAt = DL.getInlinedAt();
766           Scope = remap(Scope);
767           InlinedAt = remap(InlinedAt);
768           return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
769                                  Scope, InlinedAt);
770         };
771 
772         if (I.getDebugLoc() != DebugLoc())
773           I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
774 
775         // Remap DILocations in llvm.loop attachments.
776         updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
777           if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
778             return remapDebugLoc(Loc).get();
779           return MD;
780         });
781 
782         // Strip heapallocsite attachments, they point into the DIType system.
783         if (I.hasMetadataOtherThanDebugLoc())
784           I.setMetadata("heapallocsite", nullptr);
785       }
786     }
787   }
788 
789   // Create a new llvm.dbg.cu, which is equivalent to the one
790   // -gline-tables-only would have created.
791   for (auto &NMD : M.getNamedMDList()) {
792     SmallVector<MDNode *, 8> Ops;
793     for (MDNode *Op : NMD.operands())
794       Ops.push_back(remap(Op));
795 
796     if (!Changed)
797       continue;
798 
799     NMD.clearOperands();
800     for (auto *Op : Ops)
801       if (Op)
802         NMD.addOperand(Op);
803   }
804   return Changed;
805 }
806 
807 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
808   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
809           M.getModuleFlag("Debug Info Version")))
810     return Val->getZExtValue();
811   return 0;
812 }
813 
814 void Instruction::applyMergedLocation(const DILocation *LocA,
815                                       const DILocation *LocB) {
816   setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
817 }
818 
819 void Instruction::updateLocationAfterHoist() { dropLocation(); }
820 
821 void Instruction::dropLocation() {
822   const DebugLoc &DL = getDebugLoc();
823   if (!DL)
824     return;
825 
826   // If this isn't a call, drop the location to allow a location from a
827   // preceding instruction to propagate.
828   if (!isa<CallBase>(this)) {
829     setDebugLoc(DebugLoc());
830     return;
831   }
832 
833   // Set a line 0 location for calls to preserve scope information in case
834   // inlining occurs.
835   DISubprogram *SP = getFunction()->getSubprogram();
836   if (SP)
837     // If a function scope is available, set it on the line 0 location. When
838     // hoisting a call to a predecessor block, using the function scope avoids
839     // making it look like the callee was reached earlier than it should be.
840     setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
841   else
842     // The parent function has no scope. Go ahead and drop the location. If
843     // the parent function is inlined, and the callee has a subprogram, the
844     // inliner will attach a location to the call.
845     //
846     // One alternative is to set a line 0 location with the existing scope and
847     // inlinedAt info. The location might be sensitive to when inlining occurs.
848     setDebugLoc(DebugLoc());
849 }
850 
851 //===----------------------------------------------------------------------===//
852 // LLVM C API implementations.
853 //===----------------------------------------------------------------------===//
854 
855 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
856   switch (lang) {
857 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR)                 \
858   case LLVMDWARFSourceLanguage##NAME:                                          \
859     return ID;
860 #include "llvm/BinaryFormat/Dwarf.def"
861 #undef HANDLE_DW_LANG
862   }
863   llvm_unreachable("Unhandled Tag");
864 }
865 
866 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
867   return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
868 }
869 
870 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
871   return static_cast<DINode::DIFlags>(Flags);
872 }
873 
874 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
875   return static_cast<LLVMDIFlags>(Flags);
876 }
877 
878 static DISubprogram::DISPFlags
879 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
880   return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
881 }
882 
883 unsigned LLVMDebugMetadataVersion() {
884   return DEBUG_METADATA_VERSION;
885 }
886 
887 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
888   return wrap(new DIBuilder(*unwrap(M), false));
889 }
890 
891 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
892   return wrap(new DIBuilder(*unwrap(M)));
893 }
894 
895 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
896   return getDebugMetadataVersionFromModule(*unwrap(M));
897 }
898 
899 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
900   return StripDebugInfo(*unwrap(M));
901 }
902 
903 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
904   delete unwrap(Builder);
905 }
906 
907 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
908   unwrap(Builder)->finalize();
909 }
910 
911 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
912                                      LLVMMetadataRef subprogram) {
913   unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
914 }
915 
916 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
917     LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
918     LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
919     LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
920     unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
921     LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
922     LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
923     const char *SDK, size_t SDKLen) {
924   auto File = unwrapDI<DIFile>(FileRef);
925 
926   return wrap(unwrap(Builder)->createCompileUnit(
927       map_from_llvmDWARFsourcelanguage(Lang), File,
928       StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
929       RuntimeVer, StringRef(SplitName, SplitNameLen),
930       static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
931       SplitDebugInlining, DebugInfoForProfiling,
932       DICompileUnit::DebugNameTableKind::Default, false,
933       StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
934 }
935 
936 LLVMMetadataRef
937 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
938                         size_t FilenameLen, const char *Directory,
939                         size_t DirectoryLen) {
940   return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
941                                           StringRef(Directory, DirectoryLen)));
942 }
943 
944 LLVMMetadataRef
945 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
946                           const char *Name, size_t NameLen,
947                           const char *ConfigMacros, size_t ConfigMacrosLen,
948                           const char *IncludePath, size_t IncludePathLen,
949                           const char *APINotesFile, size_t APINotesFileLen) {
950   return wrap(unwrap(Builder)->createModule(
951       unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
952       StringRef(ConfigMacros, ConfigMacrosLen),
953       StringRef(IncludePath, IncludePathLen),
954       StringRef(APINotesFile, APINotesFileLen)));
955 }
956 
957 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
958                                              LLVMMetadataRef ParentScope,
959                                              const char *Name, size_t NameLen,
960                                              LLVMBool ExportSymbols) {
961   return wrap(unwrap(Builder)->createNameSpace(
962       unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
963 }
964 
965 LLVMMetadataRef LLVMDIBuilderCreateFunction(
966     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
967     size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
968     LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
969     LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
970     unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
971   return wrap(unwrap(Builder)->createFunction(
972       unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
973       unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
974       map_from_llvmDIFlags(Flags),
975       pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
976       nullptr, nullptr));
977 }
978 
979 
980 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
981     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
982     LLVMMetadataRef File, unsigned Line, unsigned Col) {
983   return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
984                                                   unwrapDI<DIFile>(File),
985                                                   Line, Col));
986 }
987 
988 LLVMMetadataRef
989 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
990                                     LLVMMetadataRef Scope,
991                                     LLVMMetadataRef File,
992                                     unsigned Discriminator) {
993   return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
994                                                       unwrapDI<DIFile>(File),
995                                                       Discriminator));
996 }
997 
998 LLVMMetadataRef
999 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
1000                                                LLVMMetadataRef Scope,
1001                                                LLVMMetadataRef NS,
1002                                                LLVMMetadataRef File,
1003                                                unsigned Line) {
1004   return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
1005                                                     unwrapDI<DINamespace>(NS),
1006                                                     unwrapDI<DIFile>(File),
1007                                                     Line));
1008 }
1009 
1010 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
1011     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1012     LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
1013     LLVMMetadataRef *Elements, unsigned NumElements) {
1014   auto Elts =
1015       (NumElements > 0)
1016           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1017           : nullptr;
1018   return wrap(unwrap(Builder)->createImportedModule(
1019       unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
1020       unwrapDI<DIFile>(File), Line, Elts));
1021 }
1022 
1023 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
1024     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
1025     LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
1026     unsigned NumElements) {
1027   auto Elts =
1028       (NumElements > 0)
1029           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1030           : nullptr;
1031   return wrap(unwrap(Builder)->createImportedModule(
1032       unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
1033       Line, Elts));
1034 }
1035 
1036 LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
1037     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
1038     LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
1039     LLVMMetadataRef *Elements, unsigned NumElements) {
1040   auto Elts =
1041       (NumElements > 0)
1042           ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1043           : nullptr;
1044   return wrap(unwrap(Builder)->createImportedDeclaration(
1045       unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
1046       Line, {Name, NameLen}, Elts));
1047 }
1048 
1049 LLVMMetadataRef
1050 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
1051                                  unsigned Column, LLVMMetadataRef Scope,
1052                                  LLVMMetadataRef InlinedAt) {
1053   return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
1054                               unwrap(InlinedAt)));
1055 }
1056 
1057 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
1058   return unwrapDI<DILocation>(Location)->getLine();
1059 }
1060 
1061 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
1062   return unwrapDI<DILocation>(Location)->getColumn();
1063 }
1064 
1065 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
1066   return wrap(unwrapDI<DILocation>(Location)->getScope());
1067 }
1068 
1069 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
1070   return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
1071 }
1072 
1073 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
1074   return wrap(unwrapDI<DIScope>(Scope)->getFile());
1075 }
1076 
1077 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
1078   auto Dir = unwrapDI<DIFile>(File)->getDirectory();
1079   *Len = Dir.size();
1080   return Dir.data();
1081 }
1082 
1083 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
1084   auto Name = unwrapDI<DIFile>(File)->getFilename();
1085   *Len = Name.size();
1086   return Name.data();
1087 }
1088 
1089 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
1090   if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
1091     *Len = Src->size();
1092     return Src->data();
1093   }
1094   *Len = 0;
1095   return "";
1096 }
1097 
1098 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
1099                                          LLVMMetadataRef ParentMacroFile,
1100                                          unsigned Line,
1101                                          LLVMDWARFMacinfoRecordType RecordType,
1102                                          const char *Name, size_t NameLen,
1103                                          const char *Value, size_t ValueLen) {
1104   return wrap(
1105       unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
1106                                    static_cast<MacinfoRecordType>(RecordType),
1107                                    {Name, NameLen}, {Value, ValueLen}));
1108 }
1109 
1110 LLVMMetadataRef
1111 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
1112                                  LLVMMetadataRef ParentMacroFile, unsigned Line,
1113                                  LLVMMetadataRef File) {
1114   return wrap(unwrap(Builder)->createTempMacroFile(
1115       unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
1116 }
1117 
1118 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
1119                                               const char *Name, size_t NameLen,
1120                                               int64_t Value,
1121                                               LLVMBool IsUnsigned) {
1122   return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
1123                                                 IsUnsigned != 0));
1124 }
1125 
1126 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
1127   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1128   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1129   uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
1130   unsigned NumElements, LLVMMetadataRef ClassTy) {
1131 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1132                                                NumElements});
1133 return wrap(unwrap(Builder)->createEnumerationType(
1134     unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1135     LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
1136 }
1137 
1138 LLVMMetadataRef LLVMDIBuilderCreateUnionType(
1139   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1140   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1141   uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1142   LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
1143   const char *UniqueId, size_t UniqueIdLen) {
1144   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1145                                                  NumElements});
1146   return wrap(unwrap(Builder)->createUnionType(
1147      unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1148      LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1149      Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
1150 }
1151 
1152 
1153 LLVMMetadataRef
1154 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
1155                              uint32_t AlignInBits, LLVMMetadataRef Ty,
1156                              LLVMMetadataRef *Subscripts,
1157                              unsigned NumSubscripts) {
1158   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1159                                                  NumSubscripts});
1160   return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
1161                                                unwrapDI<DIType>(Ty), Subs));
1162 }
1163 
1164 LLVMMetadataRef
1165 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
1166                               uint32_t AlignInBits, LLVMMetadataRef Ty,
1167                               LLVMMetadataRef *Subscripts,
1168                               unsigned NumSubscripts) {
1169   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1170                                                  NumSubscripts});
1171   return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
1172                                                 unwrapDI<DIType>(Ty), Subs));
1173 }
1174 
1175 LLVMMetadataRef
1176 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
1177                              size_t NameLen, uint64_t SizeInBits,
1178                              LLVMDWARFTypeEncoding Encoding,
1179                              LLVMDIFlags Flags) {
1180   return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
1181                                                SizeInBits, Encoding,
1182                                                map_from_llvmDIFlags(Flags)));
1183 }
1184 
1185 LLVMMetadataRef LLVMDIBuilderCreatePointerType(
1186     LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
1187     uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
1188     const char *Name, size_t NameLen) {
1189   return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
1190                                          SizeInBits, AlignInBits,
1191                                          AddressSpace, {Name, NameLen}));
1192 }
1193 
1194 LLVMMetadataRef LLVMDIBuilderCreateStructType(
1195     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1196     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1197     uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1198     LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
1199     unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
1200     const char *UniqueId, size_t UniqueIdLen) {
1201   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1202                                                  NumElements});
1203   return wrap(unwrap(Builder)->createStructType(
1204       unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1205       LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1206       unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
1207       unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
1208 }
1209 
1210 LLVMMetadataRef LLVMDIBuilderCreateMemberType(
1211     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1212     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1213     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1214     LLVMMetadataRef Ty) {
1215   return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
1216       {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
1217       OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
1218 }
1219 
1220 LLVMMetadataRef
1221 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
1222                                    size_t NameLen) {
1223   return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
1224 }
1225 
1226 LLVMMetadataRef
1227 LLVMDIBuilderCreateStaticMemberType(
1228     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1229     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1230     LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
1231     uint32_t AlignInBits) {
1232   return wrap(unwrap(Builder)->createStaticMemberType(
1233                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1234                   unwrapDI<DIFile>(File), LineNumber, unwrapDI<DIType>(Type),
1235                   map_from_llvmDIFlags(Flags), unwrap<Constant>(ConstantVal),
1236                   AlignInBits));
1237 }
1238 
1239 LLVMMetadataRef
1240 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
1241                             const char *Name, size_t NameLen,
1242                             LLVMMetadataRef File, unsigned LineNo,
1243                             uint64_t SizeInBits, uint32_t AlignInBits,
1244                             uint64_t OffsetInBits, LLVMDIFlags Flags,
1245                             LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
1246   return wrap(unwrap(Builder)->createObjCIVar(
1247                   {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1248                   SizeInBits, AlignInBits, OffsetInBits,
1249                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
1250                   unwrapDI<MDNode>(PropertyNode)));
1251 }
1252 
1253 LLVMMetadataRef
1254 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
1255                                 const char *Name, size_t NameLen,
1256                                 LLVMMetadataRef File, unsigned LineNo,
1257                                 const char *GetterName, size_t GetterNameLen,
1258                                 const char *SetterName, size_t SetterNameLen,
1259                                 unsigned PropertyAttributes,
1260                                 LLVMMetadataRef Ty) {
1261   return wrap(unwrap(Builder)->createObjCProperty(
1262                   {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1263                   {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
1264                   PropertyAttributes, unwrapDI<DIType>(Ty)));
1265 }
1266 
1267 LLVMMetadataRef
1268 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
1269                                      LLVMMetadataRef Type) {
1270   return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
1271 }
1272 
1273 LLVMMetadataRef
1274 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
1275                            const char *Name, size_t NameLen,
1276                            LLVMMetadataRef File, unsigned LineNo,
1277                            LLVMMetadataRef Scope, uint32_t AlignInBits) {
1278   return wrap(unwrap(Builder)->createTypedef(
1279       unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1280       unwrapDI<DIScope>(Scope), AlignInBits));
1281 }
1282 
1283 LLVMMetadataRef
1284 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
1285                                LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
1286                                uint64_t BaseOffset, uint32_t VBPtrOffset,
1287                                LLVMDIFlags Flags) {
1288   return wrap(unwrap(Builder)->createInheritance(
1289                   unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
1290                   BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
1291 }
1292 
1293 LLVMMetadataRef
1294 LLVMDIBuilderCreateForwardDecl(
1295     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1296     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1297     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1298     const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1299   return wrap(unwrap(Builder)->createForwardDecl(
1300                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1301                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1302                   AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
1303 }
1304 
1305 LLVMMetadataRef
1306 LLVMDIBuilderCreateReplaceableCompositeType(
1307     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1308     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1309     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1310     LLVMDIFlags Flags, const char *UniqueIdentifier,
1311     size_t UniqueIdentifierLen) {
1312   return wrap(unwrap(Builder)->createReplaceableCompositeType(
1313                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1314                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1315                   AlignInBits, map_from_llvmDIFlags(Flags),
1316                   {UniqueIdentifier, UniqueIdentifierLen}));
1317 }
1318 
1319 LLVMMetadataRef
1320 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
1321                                  LLVMMetadataRef Type) {
1322   return wrap(unwrap(Builder)->createQualifiedType(Tag,
1323                                                    unwrapDI<DIType>(Type)));
1324 }
1325 
1326 LLVMMetadataRef
1327 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
1328                                  LLVMMetadataRef Type) {
1329   return wrap(unwrap(Builder)->createReferenceType(Tag,
1330                                                    unwrapDI<DIType>(Type)));
1331 }
1332 
1333 LLVMMetadataRef
1334 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
1335   return wrap(unwrap(Builder)->createNullPtrType());
1336 }
1337 
1338 LLVMMetadataRef
1339 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
1340                                      LLVMMetadataRef PointeeType,
1341                                      LLVMMetadataRef ClassType,
1342                                      uint64_t SizeInBits,
1343                                      uint32_t AlignInBits,
1344                                      LLVMDIFlags Flags) {
1345   return wrap(unwrap(Builder)->createMemberPointerType(
1346                   unwrapDI<DIType>(PointeeType),
1347                   unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
1348                   map_from_llvmDIFlags(Flags)));
1349 }
1350 
1351 LLVMMetadataRef
1352 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
1353                                       LLVMMetadataRef Scope,
1354                                       const char *Name, size_t NameLen,
1355                                       LLVMMetadataRef File, unsigned LineNumber,
1356                                       uint64_t SizeInBits,
1357                                       uint64_t OffsetInBits,
1358                                       uint64_t StorageOffsetInBits,
1359                                       LLVMDIFlags Flags, LLVMMetadataRef Type) {
1360   return wrap(unwrap(Builder)->createBitFieldMemberType(
1361                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1362                   unwrapDI<DIFile>(File), LineNumber,
1363                   SizeInBits, OffsetInBits, StorageOffsetInBits,
1364                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
1365 }
1366 
1367 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
1368     LLVMMetadataRef Scope, const char *Name, size_t NameLen,
1369     LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1370     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1371     LLVMMetadataRef DerivedFrom,
1372     LLVMMetadataRef *Elements, unsigned NumElements,
1373     LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
1374     const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1375   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1376                                                  NumElements});
1377   return wrap(unwrap(Builder)->createClassType(
1378                   unwrapDI<DIScope>(Scope), {Name, NameLen},
1379                   unwrapDI<DIFile>(File), LineNumber,
1380                   SizeInBits, AlignInBits, OffsetInBits,
1381                   map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom),
1382                   Elts, unwrapDI<DIType>(VTableHolder),
1383                   unwrapDI<MDNode>(TemplateParamsNode),
1384                   {UniqueIdentifier, UniqueIdentifierLen}));
1385 }
1386 
1387 LLVMMetadataRef
1388 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
1389                                   LLVMMetadataRef Type) {
1390   return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
1391 }
1392 
1393 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
1394   StringRef Str = unwrap<DIType>(DType)->getName();
1395   *Length = Str.size();
1396   return Str.data();
1397 }
1398 
1399 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
1400   return unwrapDI<DIType>(DType)->getSizeInBits();
1401 }
1402 
1403 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
1404   return unwrapDI<DIType>(DType)->getOffsetInBits();
1405 }
1406 
1407 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
1408   return unwrapDI<DIType>(DType)->getAlignInBits();
1409 }
1410 
1411 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
1412   return unwrapDI<DIType>(DType)->getLine();
1413 }
1414 
1415 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
1416   return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
1417 }
1418 
1419 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
1420                                                   LLVMMetadataRef *Types,
1421                                                   size_t Length) {
1422   return wrap(
1423       unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
1424 }
1425 
1426 LLVMMetadataRef
1427 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
1428                                   LLVMMetadataRef File,
1429                                   LLVMMetadataRef *ParameterTypes,
1430                                   unsigned NumParameterTypes,
1431                                   LLVMDIFlags Flags) {
1432   auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
1433                                                      NumParameterTypes});
1434   return wrap(unwrap(Builder)->createSubroutineType(
1435     Elts, map_from_llvmDIFlags(Flags)));
1436 }
1437 
1438 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
1439                                               int64_t *Addr, size_t Length) {
1440   return wrap(unwrap(Builder)->createExpression(ArrayRef<int64_t>(Addr,
1441                                                                   Length)));
1442 }
1443 
1444 LLVMMetadataRef
1445 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
1446                                            int64_t Value) {
1447   return wrap(unwrap(Builder)->createConstantValueExpression(Value));
1448 }
1449 
1450 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
1451     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1452     size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
1453     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1454     LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
1455   return wrap(unwrap(Builder)->createGlobalVariableExpression(
1456       unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
1457       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1458       true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
1459       nullptr, AlignInBits));
1460 }
1461 
1462 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
1463   return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
1464 }
1465 
1466 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
1467     LLVMMetadataRef GVE) {
1468   return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
1469 }
1470 
1471 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
1472   return wrap(unwrapDI<DIVariable>(Var)->getFile());
1473 }
1474 
1475 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
1476   return wrap(unwrapDI<DIVariable>(Var)->getScope());
1477 }
1478 
1479 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
1480   return unwrapDI<DIVariable>(Var)->getLine();
1481 }
1482 
1483 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
1484                                     size_t Count) {
1485   return wrap(
1486       MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
1487 }
1488 
1489 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
1490   MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
1491 }
1492 
1493 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
1494                                     LLVMMetadataRef Replacement) {
1495   auto *Node = unwrapDI<MDNode>(TargetMetadata);
1496   Node->replaceAllUsesWith(unwrap<Metadata>(Replacement));
1497   MDNode::deleteTemporary(Node);
1498 }
1499 
1500 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
1501     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1502     size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
1503     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1504     LLVMMetadataRef Decl, uint32_t AlignInBits) {
1505   return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
1506       unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
1507       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1508       unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
1509 }
1510 
1511 LLVMValueRef
1512 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
1513                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
1514                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
1515   return wrap(unwrap(Builder)->insertDeclare(
1516                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1517                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1518                   unwrap<Instruction>(Instr)));
1519 }
1520 
1521 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
1522     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
1523     LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
1524   return wrap(unwrap(Builder)->insertDeclare(
1525                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1526                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1527                   unwrap(Block)));
1528 }
1529 
1530 LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
1531                                                LLVMValueRef Val,
1532                                                LLVMMetadataRef VarInfo,
1533                                                LLVMMetadataRef Expr,
1534                                                LLVMMetadataRef DebugLoc,
1535                                                LLVMValueRef Instr) {
1536   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1537                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1538                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1539                   unwrap<Instruction>(Instr)));
1540 }
1541 
1542 LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
1543                                               LLVMValueRef Val,
1544                                               LLVMMetadataRef VarInfo,
1545                                               LLVMMetadataRef Expr,
1546                                               LLVMMetadataRef DebugLoc,
1547                                               LLVMBasicBlockRef Block) {
1548   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1549                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1550                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1551                   unwrap(Block)));
1552 }
1553 
1554 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
1555     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1556     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1557     LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
1558   return wrap(unwrap(Builder)->createAutoVariable(
1559                   unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
1560                   LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1561                   map_from_llvmDIFlags(Flags), AlignInBits));
1562 }
1563 
1564 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
1565     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1566     size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
1567     LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
1568   return wrap(unwrap(Builder)->createParameterVariable(
1569                   unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
1570                   LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1571                   map_from_llvmDIFlags(Flags)));
1572 }
1573 
1574 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
1575                                                  int64_t Lo, int64_t Count) {
1576   return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
1577 }
1578 
1579 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
1580                                               LLVMMetadataRef *Data,
1581                                               size_t Length) {
1582   Metadata **DataValue = unwrap(Data);
1583   return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
1584 }
1585 
1586 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
1587   return wrap(unwrap<Function>(Func)->getSubprogram());
1588 }
1589 
1590 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
1591   unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1592 }
1593 
1594 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
1595   return unwrapDI<DISubprogram>(Subprogram)->getLine();
1596 }
1597 
1598 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
1599   return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
1600 }
1601 
1602 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
1603   if (Loc)
1604     unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
1605   else
1606     unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
1607 }
1608 
1609 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
1610   switch(unwrap(Metadata)->getMetadataID()) {
1611 #define HANDLE_METADATA_LEAF(CLASS) \
1612   case Metadata::CLASS##Kind: \
1613     return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
1614 #include "llvm/IR/Metadata.def"
1615   default:
1616     return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
1617   }
1618 }
1619