fa2d5a19768ccec5e171cc5c7cab186fc5f6e3cb
[oota-llvm.git] / lib / IR / DIBuilder.cpp
1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the DIBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/DIBuilder.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DebugInfo.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Dwarf.h"
22
23 using namespace llvm;
24 using namespace llvm::dwarf;
25
26 namespace {
27 class HeaderBuilder {
28   SmallVector<char, 256> Chars;
29
30 public:
31   explicit HeaderBuilder(Twine T) { T.toVector(Chars); }
32   HeaderBuilder(const HeaderBuilder &X) : Chars(X.Chars) {}
33   HeaderBuilder(HeaderBuilder &&X) : Chars(std::move(X.Chars)) {}
34
35   template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
36     Chars.push_back(0);
37     Twine(X).toVector(Chars);
38     return *this;
39   }
40
41   MDString *get(LLVMContext &Context) const {
42     return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
43   }
44
45   static HeaderBuilder get(unsigned Tag) {
46     return HeaderBuilder("0x" + Twine::utohexstr(Tag));
47   }
48 };
49 }
50
51 DIBuilder::DIBuilder(Module &m)
52     : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
53       TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
54       DeclareFn(nullptr), ValueFn(nullptr) {}
55
56 void DIBuilder::finalize() {
57   DIArray Enums = getOrCreateArray(AllEnumTypes);
58   DIType(TempEnumTypes).replaceAllUsesWith(Enums);
59
60   SmallVector<Value *, 16> RetainValues;
61   // Declarations and definitions of the same type may be retained. Some
62   // clients RAUW these pairs, leaving duplicates in the retained types
63   // list. Use a set to remove the duplicates while we transform the
64   // TrackingVHs back into Values.
65   SmallPtrSet<Value *, 16> RetainSet;
66   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
67     if (RetainSet.insert(AllRetainTypes[I]).second)
68       RetainValues.push_back(AllRetainTypes[I]);
69   DIArray RetainTypes = getOrCreateArray(RetainValues);
70   DIType(TempRetainTypes).replaceAllUsesWith(RetainTypes);
71
72   DIArray SPs = getOrCreateArray(AllSubprograms);
73   DIType(TempSubprograms).replaceAllUsesWith(SPs);
74   for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
75     DISubprogram SP(SPs.getElement(i));
76     if (MDNode *Temp = SP.getVariablesNodes()) {
77       SmallVector<Value *, 4> Variables;
78       for (Value *V : PreservedVariables.lookup(SP))
79         Variables.push_back(V);
80       DIArray AV = getOrCreateArray(Variables);
81       DIType(Temp).replaceAllUsesWith(AV);
82     }
83   }
84
85   DIArray GVs = getOrCreateArray(AllGVs);
86   DIType(TempGVs).replaceAllUsesWith(GVs);
87
88   SmallVector<Value *, 16> RetainValuesI;
89   for (unsigned I = 0, E = AllImportedModules.size(); I < E; I++)
90     RetainValuesI.push_back(AllImportedModules[I]);
91   DIArray IMs = getOrCreateArray(RetainValuesI);
92   DIType(TempImportedModules).replaceAllUsesWith(IMs);
93 }
94
95 /// If N is compile unit return NULL otherwise return N.
96 static MDNode *getNonCompileUnitScope(MDNode *N) {
97   if (DIDescriptor(N).isCompileUnit())
98     return nullptr;
99   return N;
100 }
101
102 static MDNode *createFilePathPair(LLVMContext &VMContext, StringRef Filename,
103                                   StringRef Directory) {
104   assert(!Filename.empty() && "Unable to create file without name");
105   Value *Pair[] = {
106     MDString::get(VMContext, Filename),
107     MDString::get(VMContext, Directory)
108   };
109   return MDNode::get(VMContext, Pair);
110 }
111
112 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
113                                            StringRef Directory,
114                                            StringRef Producer, bool isOptimized,
115                                            StringRef Flags, unsigned RunTimeVer,
116                                            StringRef SplitName,
117                                            DebugEmissionKind Kind,
118                                            bool EmitDebugInfo) {
119
120   assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) ||
121           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
122          "Invalid Language tag");
123   assert(!Filename.empty() &&
124          "Unable to create compile unit without filename");
125   Value *TElts[] = {HeaderBuilder::get(DW_TAG_base_type).get(VMContext)};
126   TempEnumTypes = MDNode::getTemporary(VMContext, TElts);
127
128   TempRetainTypes = MDNode::getTemporary(VMContext, TElts);
129
130   TempSubprograms = MDNode::getTemporary(VMContext, TElts);
131
132   TempGVs = MDNode::getTemporary(VMContext, TElts);
133
134   TempImportedModules = MDNode::getTemporary(VMContext, TElts);
135
136   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_compile_unit)
137                        .concat(Lang)
138                        .concat(Producer)
139                        .concat(isOptimized)
140                        .concat(Flags)
141                        .concat(RunTimeVer)
142                        .concat(SplitName)
143                        .concat(Kind)
144                        .get(VMContext),
145                    createFilePathPair(VMContext, Filename, Directory),
146                    TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs,
147                    TempImportedModules};
148
149   MDNode *CUNode = MDNode::get(VMContext, Elts);
150
151   // Create a named metadata so that it is easier to find cu in a module.
152   // Note that we only generate this when the caller wants to actually
153   // emit debug information. When we are only interested in tracking
154   // source line locations throughout the backend, we prevent codegen from
155   // emitting debug info in the final output by not generating llvm.dbg.cu.
156   if (EmitDebugInfo) {
157     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
158     NMD->addOperand(CUNode);
159   }
160
161   return DICompileUnit(CUNode);
162 }
163
164 static DIImportedEntity
165 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
166                      Value *NS, unsigned Line, StringRef Name,
167                      SmallVectorImpl<TrackingVH<MDNode>> &AllImportedModules) {
168   const MDNode *R;
169   Value *Elts[] = {HeaderBuilder::get(Tag).concat(Line).concat(Name).get(C),
170                    Context, NS};
171   R = MDNode::get(C, Elts);
172   DIImportedEntity M(R);
173   assert(M.Verify() && "Imported module should be valid");
174   AllImportedModules.push_back(TrackingVH<MDNode>(M));
175   return M;
176 }
177
178 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
179                                                  DINameSpace NS,
180                                                  unsigned Line) {
181   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
182                                 Context, NS, Line, StringRef(), AllImportedModules);
183 }
184
185 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
186                                                  DIImportedEntity NS,
187                                                  unsigned Line) {
188   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
189                                 Context, NS, Line, StringRef(), AllImportedModules);
190 }
191
192 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
193                                                       DIDescriptor Decl,
194                                                       unsigned Line, StringRef Name) {
195   // Make sure to use the unique identifier based metadata reference for
196   // types that have one.
197   Value *V = Decl.isType() ? static_cast<Value*>(DIType(Decl).getRef()) : Decl;
198   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
199                                 Context, V, Line, Name,
200                                 AllImportedModules);
201 }
202
203 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
204                                                       DIImportedEntity Imp,
205                                                       unsigned Line, StringRef Name) {
206   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
207                                 Context, Imp, Line, Name, AllImportedModules);
208 }
209
210 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
211   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_file_type).get(VMContext),
212                    createFilePathPair(VMContext, Filename, Directory)};
213   return DIFile(MDNode::get(VMContext, Elts));
214 }
215
216 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
217   assert(!Name.empty() && "Unable to create enumerator without name");
218   Value *Elts[] = {
219       HeaderBuilder::get(dwarf::DW_TAG_enumerator).concat(Name).concat(Val).get(
220           VMContext)};
221   return DIEnumerator(MDNode::get(VMContext, Elts));
222 }
223
224 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
225   assert(!Name.empty() && "Unable to create type without name");
226   // Unspecified types are encoded in DIBasicType format. Line number, filename,
227   // size, alignment, offset and flags are always empty here.
228   Value *Elts[] = {
229       HeaderBuilder::get(dwarf::DW_TAG_unspecified_type)
230           .concat(Name)
231           .concat(0)
232           .concat(0)
233           .concat(0)
234           .concat(0)
235           .concat(0)
236           .concat(0)
237           .get(VMContext),
238       nullptr, // Filename
239       nullptr  // Unused
240   };
241   return DIBasicType(MDNode::get(VMContext, Elts));
242 }
243
244 DIBasicType DIBuilder::createNullPtrType() {
245   return createUnspecifiedType("decltype(nullptr)");
246 }
247
248 DIBasicType
249 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
250                            uint64_t AlignInBits, unsigned Encoding) {
251   assert(!Name.empty() && "Unable to create type without name");
252   // Basic types are encoded in DIBasicType format. Line number, filename,
253   // offset and flags are always empty here.
254   Value *Elts[] = {
255       HeaderBuilder::get(dwarf::DW_TAG_base_type)
256           .concat(Name)
257           .concat(0) // Line
258           .concat(SizeInBits)
259           .concat(AlignInBits)
260           .concat(0) // Offset
261           .concat(0) // Flags
262           .concat(Encoding)
263           .get(VMContext),
264       nullptr, // Filename
265       nullptr  // Unused
266   };
267   return DIBasicType(MDNode::get(VMContext, Elts));
268 }
269
270 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
271   // Qualified types are encoded in DIDerivedType format.
272   Value *Elts[] = {HeaderBuilder::get(Tag)
273                        .concat(StringRef()) // Name
274                        .concat(0)           // Line
275                        .concat(0)           // Size
276                        .concat(0)           // Align
277                        .concat(0)           // Offset
278                        .concat(0)           // Flags
279                        .get(VMContext),
280                    nullptr, // Filename
281                    nullptr, // Unused
282                    FromTy.getRef()};
283   return DIDerivedType(MDNode::get(VMContext, Elts));
284 }
285
286 DIDerivedType
287 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
288                              uint64_t AlignInBits, StringRef Name) {
289   // Pointer types are encoded in DIDerivedType format.
290   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_pointer_type)
291                        .concat(Name)
292                        .concat(0) // Line
293                        .concat(SizeInBits)
294                        .concat(AlignInBits)
295                        .concat(0) // Offset
296                        .concat(0) // Flags
297                        .get(VMContext),
298                    nullptr, // Filename
299                    nullptr, // Unused
300                    PointeeTy.getRef()};
301   return DIDerivedType(MDNode::get(VMContext, Elts));
302 }
303
304 DIDerivedType DIBuilder::createMemberPointerType(DIType PointeeTy,
305                                                  DIType Base) {
306   // Pointer types are encoded in DIDerivedType format.
307   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_ptr_to_member_type)
308                        .concat(StringRef())
309                        .concat(0) // Line
310                        .concat(0) // Size
311                        .concat(0) // Align
312                        .concat(0) // Offset
313                        .concat(0) // Flags
314                        .get(VMContext),
315                    nullptr, // Filename
316                    nullptr, // Unused
317                    PointeeTy.getRef(), Base.getRef()};
318   return DIDerivedType(MDNode::get(VMContext, Elts));
319 }
320
321 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
322   assert(RTy.isType() && "Unable to create reference type");
323   // References are encoded in DIDerivedType format.
324   Value *Elts[] = {HeaderBuilder::get(Tag)
325                        .concat(StringRef()) // Name
326                        .concat(0)           // Line
327                        .concat(0)           // Size
328                        .concat(0)           // Align
329                        .concat(0)           // Offset
330                        .concat(0)           // Flags
331                        .get(VMContext),
332                    nullptr, // Filename
333                    nullptr, // TheCU,
334                    RTy.getRef()};
335   return DIDerivedType(MDNode::get(VMContext, Elts));
336 }
337
338 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
339                                        unsigned LineNo, DIDescriptor Context) {
340   // typedefs are encoded in DIDerivedType format.
341   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_typedef)
342                        .concat(Name)
343                        .concat(LineNo)
344                        .concat(0) // Size
345                        .concat(0) // Align
346                        .concat(0) // Offset
347                        .concat(0) // Flags
348                        .get(VMContext),
349                    File.getFileNode(),
350                    DIScope(getNonCompileUnitScope(Context)).getRef(),
351                    Ty.getRef()};
352   return DIDerivedType(MDNode::get(VMContext, Elts));
353 }
354
355 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
356   // typedefs are encoded in DIDerivedType format.
357   assert(Ty.isType() && "Invalid type!");
358   assert(FriendTy.isType() && "Invalid friend type!");
359   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_friend)
360                        .concat(StringRef()) // Name
361                        .concat(0)           // Line
362                        .concat(0)           // Size
363                        .concat(0)           // Align
364                        .concat(0)           // Offset
365                        .concat(0)           // Flags
366                        .get(VMContext),
367                    nullptr, Ty.getRef(), FriendTy.getRef()};
368   return DIDerivedType(MDNode::get(VMContext, Elts));
369 }
370
371 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
372                                            uint64_t BaseOffset,
373                                            unsigned Flags) {
374   assert(Ty.isType() && "Unable to create inheritance");
375   // TAG_inheritance is encoded in DIDerivedType format.
376   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_inheritance)
377                        .concat(StringRef()) // Name
378                        .concat(0)           // Line
379                        .concat(0)           // Size
380                        .concat(0)           // Align
381                        .concat(BaseOffset)
382                        .concat(Flags)
383                        .get(VMContext),
384                    nullptr, Ty.getRef(), BaseTy.getRef()};
385   return DIDerivedType(MDNode::get(VMContext, Elts));
386 }
387
388 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
389                                           DIFile File, unsigned LineNumber,
390                                           uint64_t SizeInBits,
391                                           uint64_t AlignInBits,
392                                           uint64_t OffsetInBits, unsigned Flags,
393                                           DIType Ty) {
394   // TAG_member is encoded in DIDerivedType format.
395   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
396                        .concat(Name)
397                        .concat(LineNumber)
398                        .concat(SizeInBits)
399                        .concat(AlignInBits)
400                        .concat(OffsetInBits)
401                        .concat(Flags)
402                        .get(VMContext),
403                    File.getFileNode(),
404                    DIScope(getNonCompileUnitScope(Scope)).getRef(),
405                    Ty.getRef()};
406   return DIDerivedType(MDNode::get(VMContext, Elts));
407 }
408
409 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
410                                                 StringRef Name, DIFile File,
411                                                 unsigned LineNumber, DIType Ty,
412                                                 unsigned Flags,
413                                                 llvm::Constant *Val) {
414   // TAG_member is encoded in DIDerivedType format.
415   Flags |= DIDescriptor::FlagStaticMember;
416   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
417                        .concat(Name)
418                        .concat(LineNumber)
419                        .concat(0) // Size
420                        .concat(0) // Align
421                        .concat(0) // Offset
422                        .concat(Flags)
423                        .get(VMContext),
424                    File.getFileNode(),
425                    DIScope(getNonCompileUnitScope(Scope)).getRef(), Ty.getRef(),
426                    Val};
427   return DIDerivedType(MDNode::get(VMContext, Elts));
428 }
429
430 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
431                                         unsigned LineNumber,
432                                         uint64_t SizeInBits,
433                                         uint64_t AlignInBits,
434                                         uint64_t OffsetInBits, unsigned Flags,
435                                         DIType Ty, MDNode *PropertyNode) {
436   // TAG_member is encoded in DIDerivedType format.
437   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
438                        .concat(Name)
439                        .concat(LineNumber)
440                        .concat(SizeInBits)
441                        .concat(AlignInBits)
442                        .concat(OffsetInBits)
443                        .concat(Flags)
444                        .get(VMContext),
445                    File.getFileNode(), getNonCompileUnitScope(File), Ty,
446                    PropertyNode};
447   return DIDerivedType(MDNode::get(VMContext, Elts));
448 }
449
450 DIObjCProperty
451 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
452                               StringRef GetterName, StringRef SetterName,
453                               unsigned PropertyAttributes, DIType Ty) {
454   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_APPLE_property)
455                        .concat(Name)
456                        .concat(LineNumber)
457                        .concat(GetterName)
458                        .concat(SetterName)
459                        .concat(PropertyAttributes)
460                        .get(VMContext),
461                    File, Ty};
462   return DIObjCProperty(MDNode::get(VMContext, Elts));
463 }
464
465 DITemplateTypeParameter
466 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
467                                        DIType Ty, MDNode *File, unsigned LineNo,
468                                        unsigned ColumnNo) {
469   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_template_type_parameter)
470                        .concat(Name)
471                        .concat(LineNo)
472                        .concat(ColumnNo)
473                        .get(VMContext),
474                    DIScope(getNonCompileUnitScope(Context)).getRef(),
475                    Ty.getRef(), File};
476   return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
477 }
478
479 static DITemplateValueParameter createTemplateValueParameterHelper(
480     LLVMContext &VMContext, unsigned Tag, DIDescriptor Context, StringRef Name,
481     DIType Ty, Value *Val, MDNode *File, unsigned LineNo, unsigned ColumnNo) {
482   Value *Elts[] = {
483       HeaderBuilder::get(Tag).concat(Name).concat(LineNo).concat(ColumnNo).get(
484           VMContext),
485       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty.getRef(), Val,
486       File};
487   return DITemplateValueParameter(MDNode::get(VMContext, Elts));
488 }
489
490 DITemplateValueParameter
491 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
492                                         DIType Ty, Constant *Val, MDNode *File,
493                                         unsigned LineNo, unsigned ColumnNo) {
494   return createTemplateValueParameterHelper(
495       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, Val,
496       File, LineNo, ColumnNo);
497 }
498
499 DITemplateValueParameter
500 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
501                                            DIType Ty, StringRef Val,
502                                            MDNode *File, unsigned LineNo,
503                                            unsigned ColumnNo) {
504   return createTemplateValueParameterHelper(
505       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
506       MDString::get(VMContext, Val), File, LineNo, ColumnNo);
507 }
508
509 DITemplateValueParameter
510 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
511                                        DIType Ty, DIArray Val,
512                                        MDNode *File, unsigned LineNo,
513                                        unsigned ColumnNo) {
514   return createTemplateValueParameterHelper(
515       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
516       Val, File, LineNo, ColumnNo);
517 }
518
519 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
520                                            DIFile File, unsigned LineNumber,
521                                            uint64_t SizeInBits,
522                                            uint64_t AlignInBits,
523                                            uint64_t OffsetInBits,
524                                            unsigned Flags, DIType DerivedFrom,
525                                            DIArray Elements,
526                                            DIType VTableHolder,
527                                            MDNode *TemplateParams,
528                                            StringRef UniqueIdentifier) {
529   assert((!Context || Context.isScope() || Context.isType()) &&
530          "createClassType should be called with a valid Context");
531   // TAG_class_type is encoded in DICompositeType format.
532   Value *Elts[] = {
533       HeaderBuilder::get(dwarf::DW_TAG_class_type)
534           .concat(Name)
535           .concat(LineNumber)
536           .concat(SizeInBits)
537           .concat(AlignInBits)
538           .concat(OffsetInBits)
539           .concat(Flags)
540           .concat(0)
541           .get(VMContext),
542       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
543       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), TemplateParams,
544       UniqueIdentifier.empty() ? nullptr
545                                : MDString::get(VMContext, UniqueIdentifier)};
546   DICompositeType R(MDNode::get(VMContext, Elts));
547   assert(R.isCompositeType() &&
548          "createClassType should return a DICompositeType");
549   if (!UniqueIdentifier.empty())
550     retainType(R);
551   return R;
552 }
553
554 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
555                                             StringRef Name, DIFile File,
556                                             unsigned LineNumber,
557                                             uint64_t SizeInBits,
558                                             uint64_t AlignInBits,
559                                             unsigned Flags, DIType DerivedFrom,
560                                             DIArray Elements,
561                                             unsigned RunTimeLang,
562                                             DIType VTableHolder,
563                                             StringRef UniqueIdentifier) {
564  // TAG_structure_type is encoded in DICompositeType format.
565   Value *Elts[] = {
566       HeaderBuilder::get(dwarf::DW_TAG_structure_type)
567           .concat(Name)
568           .concat(LineNumber)
569           .concat(SizeInBits)
570           .concat(AlignInBits)
571           .concat(0)
572           .concat(Flags)
573           .concat(RunTimeLang)
574           .get(VMContext),
575       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
576       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), nullptr,
577       UniqueIdentifier.empty() ? nullptr
578                                : MDString::get(VMContext, UniqueIdentifier)};
579   DICompositeType R(MDNode::get(VMContext, Elts));
580   assert(R.isCompositeType() &&
581          "createStructType should return a DICompositeType");
582   if (!UniqueIdentifier.empty())
583     retainType(R);
584   return R;
585 }
586
587 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
588                                            DIFile File, unsigned LineNumber,
589                                            uint64_t SizeInBits,
590                                            uint64_t AlignInBits, unsigned Flags,
591                                            DIArray Elements,
592                                            unsigned RunTimeLang,
593                                            StringRef UniqueIdentifier) {
594   // TAG_union_type is encoded in DICompositeType format.
595   Value *Elts[] = {
596       HeaderBuilder::get(dwarf::DW_TAG_union_type)
597           .concat(Name)
598           .concat(LineNumber)
599           .concat(SizeInBits)
600           .concat(AlignInBits)
601           .concat(0) // Offset
602           .concat(Flags)
603           .concat(RunTimeLang)
604           .get(VMContext),
605       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
606       nullptr, Elements, nullptr, nullptr,
607       UniqueIdentifier.empty() ? nullptr
608                                : MDString::get(VMContext, UniqueIdentifier)};
609   DICompositeType R(MDNode::get(VMContext, Elts));
610   if (!UniqueIdentifier.empty())
611     retainType(R);
612   return R;
613 }
614
615 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
616                                                  DITypeArray ParameterTypes,
617                                                  unsigned Flags) {
618   // TAG_subroutine_type is encoded in DICompositeType format.
619   Value *Elts[] = {
620       HeaderBuilder::get(dwarf::DW_TAG_subroutine_type)
621           .concat(StringRef())
622           .concat(0)     // Line
623           .concat(0)     // Size
624           .concat(0)     // Align
625           .concat(0)     // Offset
626           .concat(Flags) // Flags
627           .concat(0)
628           .get(VMContext),
629       nullptr, nullptr, nullptr, ParameterTypes, nullptr, nullptr,
630       nullptr // Type Identifer
631   };
632   return DISubroutineType(MDNode::get(VMContext, Elts));
633 }
634
635 DICompositeType DIBuilder::createEnumerationType(
636     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
637     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
638     DIType UnderlyingType, StringRef UniqueIdentifier) {
639   // TAG_enumeration_type is encoded in DICompositeType format.
640   Value *Elts[] = {
641       HeaderBuilder::get(dwarf::DW_TAG_enumeration_type)
642           .concat(Name)
643           .concat(LineNumber)
644           .concat(SizeInBits)
645           .concat(AlignInBits)
646           .concat(0) // Offset
647           .concat(0) // Flags
648           .concat(0)
649           .get(VMContext),
650       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
651       UnderlyingType.getRef(), Elements, nullptr, nullptr,
652       UniqueIdentifier.empty() ? nullptr
653                                : MDString::get(VMContext, UniqueIdentifier)};
654   DICompositeType CTy(MDNode::get(VMContext, Elts));
655   AllEnumTypes.push_back(CTy);
656   if (!UniqueIdentifier.empty())
657     retainType(CTy);
658   return CTy;
659 }
660
661 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
662                                            DIType Ty, DIArray Subscripts) {
663   // TAG_array_type is encoded in DICompositeType format.
664   Value *Elts[] = {
665       HeaderBuilder::get(dwarf::DW_TAG_array_type)
666           .concat(StringRef())
667           .concat(0) // Line
668           .concat(Size)
669           .concat(AlignInBits)
670           .concat(0) // Offset
671           .concat(0) // Flags
672           .concat(0)
673           .get(VMContext),
674       nullptr, // Filename/Directory,
675       nullptr, // Unused
676       Ty.getRef(), Subscripts, nullptr, nullptr,
677       nullptr // Type Identifer
678   };
679   return DICompositeType(MDNode::get(VMContext, Elts));
680 }
681
682 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
683                                             DIType Ty, DIArray Subscripts) {
684   // A vector is an array type with the FlagVector flag applied.
685   Value *Elts[] = {
686       HeaderBuilder::get(dwarf::DW_TAG_array_type)
687           .concat("")
688           .concat(0) // Line
689           .concat(Size)
690           .concat(AlignInBits)
691           .concat(0) // Offset
692           .concat(DIType::FlagVector)
693           .concat(0)
694           .get(VMContext),
695       nullptr, // Filename/Directory,
696       nullptr, // Unused
697       Ty.getRef(), Subscripts, nullptr, nullptr,
698       nullptr // Type Identifer
699   };
700   return DICompositeType(MDNode::get(VMContext, Elts));
701 }
702
703 static HeaderBuilder setTypeFlagsInHeader(StringRef Header,
704                                           unsigned FlagsToSet) {
705   DIHeaderFieldIterator I(Header);
706   std::advance(I, 6);
707
708   unsigned Flags;
709   if (I->getAsInteger(0, Flags))
710     Flags = 0;
711   Flags |= FlagsToSet;
712
713   return HeaderBuilder(Twine(I.getPrefix())).concat(Flags).concat(
714       I.getSuffix());
715 }
716
717 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
718                                   unsigned FlagsToSet) {
719   SmallVector<Value *, 9> Elts;
720   MDNode *N = Ty;
721   assert(N && "Unexpected input DIType!");
722   // Update header field.
723   Elts.push_back(setTypeFlagsInHeader(Ty.getHeader(), FlagsToSet).get(Context));
724   for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I)
725     Elts.push_back(N->getOperand(I));
726
727   return DIType(MDNode::get(Context, Elts));
728 }
729
730 DIType DIBuilder::createArtificialType(DIType Ty) {
731   if (Ty.isArtificial())
732     return Ty;
733   return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
734 }
735
736 DIType DIBuilder::createObjectPointerType(DIType Ty) {
737   if (Ty.isObjectPointer())
738     return Ty;
739   unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
740   return createTypeWithFlags(VMContext, Ty, Flags);
741 }
742
743 void DIBuilder::retainType(DIType T) {
744   AllRetainTypes.push_back(TrackingVH<MDNode>(T));
745 }
746
747 DIBasicType DIBuilder::createUnspecifiedParameter() {
748   return DIBasicType();
749 }
750
751 DICompositeType
752 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
753                              DIFile F, unsigned Line, unsigned RuntimeLang,
754                              uint64_t SizeInBits, uint64_t AlignInBits,
755                              StringRef UniqueIdentifier) {
756   // Create a temporary MDNode.
757   Value *Elts[] = {
758       HeaderBuilder::get(Tag)
759           .concat(Name)
760           .concat(Line)
761           .concat(SizeInBits)
762           .concat(AlignInBits)
763           .concat(0) // Offset
764           .concat(DIDescriptor::FlagFwdDecl)
765           .concat(RuntimeLang)
766           .get(VMContext),
767       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
768       DIArray(), nullptr,
769       nullptr, // TemplateParams
770       UniqueIdentifier.empty() ? nullptr
771                                : MDString::get(VMContext, UniqueIdentifier)};
772   MDNode *Node = MDNode::get(VMContext, Elts);
773   DICompositeType RetTy(Node);
774   assert(RetTy.isCompositeType() &&
775          "createForwardDecl result should be a DIType");
776   if (!UniqueIdentifier.empty())
777     retainType(RetTy);
778   return RetTy;
779 }
780
781 DICompositeType DIBuilder::createReplaceableForwardDecl(
782     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
783     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
784     StringRef UniqueIdentifier) {
785   // Create a temporary MDNode.
786   Value *Elts[] = {
787       HeaderBuilder::get(Tag)
788           .concat(Name)
789           .concat(Line)
790           .concat(SizeInBits)
791           .concat(AlignInBits)
792           .concat(0) // Offset
793           .concat(DIDescriptor::FlagFwdDecl)
794           .concat(RuntimeLang)
795           .get(VMContext),
796       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
797       DIArray(), nullptr,
798       nullptr, // TemplateParams
799       UniqueIdentifier.empty() ? nullptr
800                                : MDString::get(VMContext, UniqueIdentifier)};
801   MDNode *Node = MDNode::getTemporary(VMContext, Elts);
802   DICompositeType RetTy(Node);
803   assert(RetTy.isCompositeType() &&
804          "createReplaceableForwardDecl result should be a DIType");
805   if (!UniqueIdentifier.empty())
806     retainType(RetTy);
807   return RetTy;
808 }
809
810 DIArray DIBuilder::getOrCreateArray(ArrayRef<Value *> Elements) {
811   return DIArray(MDNode::get(VMContext, Elements));
812 }
813
814 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Value *> Elements) {
815   SmallVector<llvm::Value *, 16> Elts; 
816   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
817     if (Elements[i] && isa<MDNode>(Elements[i]))
818       Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
819     else
820       Elts.push_back(Elements[i]);
821   }
822   return DITypeArray(MDNode::get(VMContext, Elts));
823 }
824
825 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
826   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subrange_type)
827                        .concat(Lo)
828                        .concat(Count)
829                        .get(VMContext)};
830
831   return DISubrange(MDNode::get(VMContext, Elts));
832 }
833
834 static DIGlobalVariable createGlobalVariableHelper(
835     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
836     StringRef LinkageName, DIFile F, unsigned LineNumber, DITypeRef Ty,
837     bool isLocalToUnit, Constant *Val, MDNode *Decl, bool isDefinition,
838     std::function<MDNode *(ArrayRef<Value *>)> CreateFunc) {
839
840   MDNode *TheCtx = getNonCompileUnitScope(Context);
841   if (DIScope(TheCtx).isCompositeType()) {
842     assert(!DICompositeType(TheCtx).getIdentifier() &&
843            "Context of a global variable should not be a type with identifier");
844   }
845
846   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_variable)
847                        .concat(Name)
848                        .concat(Name)
849                        .concat(LinkageName)
850                        .concat(LineNumber)
851                        .concat(isLocalToUnit)
852                        .concat(isDefinition)
853                        .get(VMContext),
854                    TheCtx, F, Ty, Val,
855                    DIDescriptor(Decl)};
856
857   return DIGlobalVariable(CreateFunc(Elts));
858 }
859
860 DIGlobalVariable DIBuilder::createGlobalVariable(
861     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
862     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
863     MDNode *Decl) {
864   return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
865                                     LineNumber, Ty, isLocalToUnit, Val, Decl, true,
866                                     [&] (ArrayRef<Value *> Elts) -> MDNode * {
867                                       MDNode *Node = MDNode::get(VMContext, Elts);
868                                       AllGVs.push_back(Node);
869                                       return Node;
870                                     });
871 }
872
873 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
874     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
875     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
876     MDNode *Decl) {
877   return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
878                                     LineNumber, Ty, isLocalToUnit, Val, Decl, false,
879                                     [&] (ArrayRef<Value *> Elts) {
880                                       return MDNode::getTemporary(VMContext, Elts);
881                                     });
882 }
883
884 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
885                                           StringRef Name, DIFile File,
886                                           unsigned LineNo, DITypeRef Ty,
887                                           bool AlwaysPreserve, unsigned Flags,
888                                           unsigned ArgNo) {
889   DIDescriptor Context(getNonCompileUnitScope(Scope));
890   assert((!Context || Context.isScope()) &&
891          "createLocalVariable should be called with a valid Context");
892   Value *Elts[] = {HeaderBuilder::get(Tag)
893                        .concat(Name)
894                        .concat(LineNo | (ArgNo << 24))
895                        .concat(Flags)
896                        .get(VMContext),
897                    getNonCompileUnitScope(Scope), File, Ty};
898   MDNode *Node = MDNode::get(VMContext, Elts);
899   if (AlwaysPreserve) {
900     // The optimizer may remove local variable. If there is an interest
901     // to preserve variable info in such situation then stash it in a
902     // named mdnode.
903     DISubprogram Fn(getDISubprogram(Scope));
904     assert(Fn && "Missing subprogram for local variable");
905     PreservedVariables[Fn].push_back(Node);
906   }
907   DIVariable RetVar(Node);
908   assert(RetVar.isVariable() &&
909          "createLocalVariable should return a valid DIVariable");
910   return RetVar;
911 }
912
913 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Addr) {
914   auto Header = HeaderBuilder::get(DW_TAG_expression);
915   for (int64_t I : Addr)
916     Header.concat(I);
917   Value *Elts[] = {Header.get(VMContext)};
918   return DIExpression(MDNode::get(VMContext, Elts));
919 }
920
921 DIExpression DIBuilder::createPieceExpression(unsigned OffsetInBytes,
922                                               unsigned SizeInBytes) {
923   int64_t Addr[] = {dwarf::DW_OP_piece, OffsetInBytes, SizeInBytes};
924   return createExpression(Addr);
925 }
926
927 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
928                                        StringRef LinkageName, DIFile File,
929                                        unsigned LineNo, DICompositeType Ty,
930                                        bool isLocalToUnit, bool isDefinition,
931                                        unsigned ScopeLine, unsigned Flags,
932                                        bool isOptimized, Function *Fn,
933                                        MDNode *TParams, MDNode *Decl) {
934   // dragonegg does not generate identifier for types, so using an empty map
935   // to resolve the context should be fine.
936   DITypeIdentifierMap EmptyMap;
937   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
938                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
939                         Flags, isOptimized, Fn, TParams, Decl);
940 }
941
942 static DISubprogram
943 createFunctionHelper(LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
944                      StringRef LinkageName, DIFile File, unsigned LineNo,
945                      DICompositeType Ty, bool isLocalToUnit, bool isDefinition,
946                      unsigned ScopeLine, unsigned Flags, bool isOptimized,
947                      Function *Fn, MDNode *TParams, MDNode *Decl, MDNode *Vars,
948                      std::function<MDNode *(ArrayRef<Value *>)> CreateFunc) {
949   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
950          "function types should be subroutines");
951   Value *Elts[] = {
952       HeaderBuilder::get(dwarf::DW_TAG_subprogram)
953           .concat(Name)
954           .concat(Name)
955           .concat(LinkageName)
956           .concat(LineNo)
957           .concat(isLocalToUnit)
958           .concat(isDefinition)
959           .concat(0)
960           .concat(0)
961           .concat(Flags)
962           .concat(isOptimized)
963           .concat(ScopeLine)
964           .get(VMContext),
965       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(), Ty,
966       nullptr, Fn, TParams, Decl, Vars};
967
968   DISubprogram S(CreateFunc(Elts));
969   assert(S.isSubprogram() &&
970          "createFunction should return a valid DISubprogram");
971   return S;
972 }
973
974
975 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
976                                        StringRef LinkageName, DIFile File,
977                                        unsigned LineNo, DICompositeType Ty,
978                                        bool isLocalToUnit, bool isDefinition,
979                                        unsigned ScopeLine, unsigned Flags,
980                                        bool isOptimized, Function *Fn,
981                                        MDNode *TParams, MDNode *Decl) {
982   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
983                               LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
984                               Flags, isOptimized, Fn, TParams, Decl,
985                               MDNode::getTemporary(VMContext, None),
986                               [&] (ArrayRef<Value *> Elts) -> MDNode *{
987                                 MDNode *Node = MDNode::get(VMContext, Elts);
988                                 // Create a named metadata so that we
989                                 // do not lose this mdnode.
990                                 if (isDefinition)
991                                   AllSubprograms.push_back(Node);
992                                 return Node;
993                               });
994 }
995
996 DISubprogram
997 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
998                                      StringRef LinkageName, DIFile File,
999                                      unsigned LineNo, DICompositeType Ty,
1000                                      bool isLocalToUnit, bool isDefinition,
1001                                      unsigned ScopeLine, unsigned Flags,
1002                                      bool isOptimized, Function *Fn,
1003                                      MDNode *TParams, MDNode *Decl) {
1004   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1005                               LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
1006                               Flags, isOptimized, Fn, TParams, Decl, nullptr,
1007                               [&] (ArrayRef<Value *> Elts) {
1008                                 return MDNode::getTemporary(VMContext, Elts);
1009                               });
1010 }
1011
1012 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
1013                                      StringRef LinkageName, DIFile F,
1014                                      unsigned LineNo, DICompositeType Ty,
1015                                      bool isLocalToUnit, bool isDefinition,
1016                                      unsigned VK, unsigned VIndex,
1017                                      DIType VTableHolder, unsigned Flags,
1018                                      bool isOptimized, Function *Fn,
1019                                      MDNode *TParam) {
1020   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1021          "function types should be subroutines");
1022   assert(getNonCompileUnitScope(Context) &&
1023          "Methods should have both a Context and a context that isn't "
1024          "the compile unit.");
1025   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
1026                        .concat(Name)
1027                        .concat(Name)
1028                        .concat(LinkageName)
1029                        .concat(LineNo)
1030                        .concat(isLocalToUnit)
1031                        .concat(isDefinition)
1032                        .concat(VK)
1033                        .concat(VIndex)
1034                        .concat(Flags)
1035                        .concat(isOptimized)
1036                        .concat(LineNo)
1037                        // FIXME: Do we want to use different scope/lines?
1038                        .get(VMContext),
1039                    F.getFileNode(), DIScope(Context).getRef(), Ty,
1040                    VTableHolder.getRef(), Fn, TParam, nullptr, nullptr};
1041   MDNode *Node = MDNode::get(VMContext, Elts);
1042   if (isDefinition)
1043     AllSubprograms.push_back(Node);
1044   DISubprogram S(Node);
1045   assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
1046   return S;
1047 }
1048
1049 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
1050                                        DIFile File, unsigned LineNo) {
1051   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_namespace)
1052                        .concat(Name)
1053                        .concat(LineNo)
1054                        .get(VMContext),
1055                    File.getFileNode(), getNonCompileUnitScope(Scope)};
1056   DINameSpace R(MDNode::get(VMContext, Elts));
1057   assert(R.Verify() &&
1058          "createNameSpace should return a verifiable DINameSpace");
1059   return R;
1060 }
1061
1062 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
1063                                                      DIFile File,
1064                                                      unsigned Discriminator) {
1065   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1066                        .concat(Discriminator)
1067                        .get(VMContext),
1068                    File.getFileNode(), Scope};
1069   DILexicalBlockFile R(MDNode::get(VMContext, Elts));
1070   assert(
1071       R.Verify() &&
1072       "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
1073   return R;
1074 }
1075
1076 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
1077                                              unsigned Line, unsigned Col) {
1078   // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
1079   // I believe the right way is to have a self-referential element in the node.
1080   // Also: why do we bother with line/column - they're not used and the
1081   // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
1082   // for uniquing, yet then we have this other solution (because line/col were
1083   // inadequate) anyway. Remove all 3 and replace them with a self-reference.
1084
1085   // Defeat MDNode uniquing for lexical blocks by using unique id.
1086   static unsigned int unique_id = 0;
1087   Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1088                        .concat(Line)
1089                        .concat(Col)
1090                        .concat(unique_id++)
1091                        .get(VMContext),
1092                    File.getFileNode(), getNonCompileUnitScope(Scope)};
1093   DILexicalBlock R(MDNode::get(VMContext, Elts));
1094   assert(R.Verify() &&
1095          "createLexicalBlock should return a verifiable DILexicalBlock");
1096   return R;
1097 }
1098
1099 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1100                                       DIExpression Expr,
1101                                       Instruction *InsertBefore) {
1102   assert(Storage && "no storage passed to dbg.declare");
1103   assert(VarInfo.isVariable() &&
1104          "empty or invalid DIVariable passed to dbg.declare");
1105   if (!DeclareFn)
1106     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1107
1108   Value *Args[] = {MDNode::get(Storage->getContext(), Storage), VarInfo, Expr};
1109   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
1110 }
1111
1112 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1113                                       DIExpression Expr,
1114                                       BasicBlock *InsertAtEnd) {
1115   assert(Storage && "no storage passed to dbg.declare");
1116   assert(VarInfo.isVariable() &&
1117          "empty or invalid DIVariable passed to dbg.declare");
1118   if (!DeclareFn)
1119     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1120
1121   Value *Args[] = {MDNode::get(Storage->getContext(), Storage), VarInfo, Expr};
1122
1123   // If this block already has a terminator then insert this intrinsic
1124   // before the terminator.
1125   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1126     return CallInst::Create(DeclareFn, Args, "", T);
1127   else
1128     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
1129 }
1130
1131 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1132                                                 DIVariable VarInfo,
1133                                                 DIExpression Expr,
1134                                                 Instruction *InsertBefore) {
1135   assert(V && "no value passed to dbg.value");
1136   assert(VarInfo.isVariable() &&
1137          "empty or invalid DIVariable passed to dbg.value");
1138   if (!ValueFn)
1139     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1140
1141   Value *Args[] = {MDNode::get(V->getContext(), V),
1142                    ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1143                    VarInfo, Expr};
1144   return CallInst::Create(ValueFn, Args, "", InsertBefore);
1145 }
1146
1147 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1148                                                 DIVariable VarInfo,
1149                                                 DIExpression Expr,
1150                                                 BasicBlock *InsertAtEnd) {
1151   assert(V && "no value passed to dbg.value");
1152   assert(VarInfo.isVariable() &&
1153          "empty or invalid DIVariable passed to dbg.value");
1154   if (!ValueFn)
1155     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1156
1157   Value *Args[] = {MDNode::get(V->getContext(), V),
1158                    ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1159                    VarInfo, Expr};
1160   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
1161 }