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