DIBuilder: Delete dead code, NFC
[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 static Constant *GetTagConstant(LLVMContext &VMContext, unsigned Tag) {
27   assert((Tag & LLVMDebugVersionMask) == 0 &&
28          "Tag too large for debug encoding!");
29   return ConstantInt::get(Type::getInt32Ty(VMContext), Tag | LLVMDebugVersion);
30 }
31
32 DIBuilder::DIBuilder(Module &m)
33     : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
34       TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
35       DeclareFn(nullptr), ValueFn(nullptr) {}
36
37 /// finalize - Construct any deferred debug info descriptors.
38 void DIBuilder::finalize() {
39   DIArray Enums = getOrCreateArray(AllEnumTypes);
40   DIType(TempEnumTypes).replaceAllUsesWith(Enums);
41
42   SmallVector<Value *, 16> RetainValues;
43   // Declarations and definitions of the same type may be retained. Some
44   // clients RAUW these pairs, leaving duplicates in the retained types
45   // list. Use a set to remove the duplicates while we transform the
46   // TrackingVHs back into Values.
47   SmallPtrSet<Value *, 16> RetainSet;
48   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
49     if (RetainSet.insert(AllRetainTypes[I]))
50       RetainValues.push_back(AllRetainTypes[I]);
51   DIArray RetainTypes = getOrCreateArray(RetainValues);
52   DIType(TempRetainTypes).replaceAllUsesWith(RetainTypes);
53
54   DIArray SPs = getOrCreateArray(AllSubprograms);
55   DIType(TempSubprograms).replaceAllUsesWith(SPs);
56   for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
57     DISubprogram SP(SPs.getElement(i));
58     SmallVector<Value *, 4> Variables;
59     if (NamedMDNode *NMD = getFnSpecificMDNode(M, SP)) {
60       for (unsigned ii = 0, ee = NMD->getNumOperands(); ii != ee; ++ii)
61         Variables.push_back(NMD->getOperand(ii));
62       NMD->eraseFromParent();
63     }
64     if (MDNode *Temp = SP.getVariablesNodes()) {
65       DIArray AV = getOrCreateArray(Variables);
66       DIType(Temp).replaceAllUsesWith(AV);
67     }
68   }
69
70   DIArray GVs = getOrCreateArray(AllGVs);
71   DIType(TempGVs).replaceAllUsesWith(GVs);
72
73   SmallVector<Value *, 16> RetainValuesI;
74   for (unsigned I = 0, E = AllImportedModules.size(); I < E; I++)
75     RetainValuesI.push_back(AllImportedModules[I]);
76   DIArray IMs = getOrCreateArray(RetainValuesI);
77   DIType(TempImportedModules).replaceAllUsesWith(IMs);
78 }
79
80 /// getNonCompileUnitScope - If N is compile unit return NULL otherwise return
81 /// N.
82 static MDNode *getNonCompileUnitScope(MDNode *N) {
83   if (DIDescriptor(N).isCompileUnit())
84     return nullptr;
85   return N;
86 }
87
88 static MDNode *createFilePathPair(LLVMContext &VMContext, StringRef Filename,
89                                   StringRef Directory) {
90   assert(!Filename.empty() && "Unable to create file without name");
91   Value *Pair[] = {
92     MDString::get(VMContext, Filename),
93     MDString::get(VMContext, Directory)
94   };
95   return MDNode::get(VMContext, Pair);
96 }
97
98 /// createCompileUnit - A CompileUnit provides an anchor for all debugging
99 /// information generated during this instance of compilation.
100 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
101                                            StringRef Directory,
102                                            StringRef Producer, bool isOptimized,
103                                            StringRef Flags, unsigned RunTimeVer,
104                                            StringRef SplitName,
105                                            DebugEmissionKind Kind,
106                                            bool EmitDebugInfo) {
107
108   assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) ||
109           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
110          "Invalid Language tag");
111   assert(!Filename.empty() &&
112          "Unable to create compile unit without filename");
113   Value *TElts[] = { GetTagConstant(VMContext, DW_TAG_base_type) };
114   TempEnumTypes = MDNode::getTemporary(VMContext, TElts);
115
116   TempRetainTypes = MDNode::getTemporary(VMContext, TElts);
117
118   TempSubprograms = MDNode::getTemporary(VMContext, TElts);
119
120   TempGVs = MDNode::getTemporary(VMContext, TElts);
121
122   TempImportedModules = MDNode::getTemporary(VMContext, TElts);
123
124   Value *Elts[] = {
125     GetTagConstant(VMContext, dwarf::DW_TAG_compile_unit),
126     createFilePathPair(VMContext, Filename, Directory),
127     ConstantInt::get(Type::getInt32Ty(VMContext), Lang),
128     MDString::get(VMContext, Producer),
129     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
130     MDString::get(VMContext, Flags),
131     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer),
132     TempEnumTypes,
133     TempRetainTypes,
134     TempSubprograms,
135     TempGVs,
136     TempImportedModules,
137     MDString::get(VMContext, SplitName),
138     ConstantInt::get(Type::getInt32Ty(VMContext), Kind)
139   };
140
141   MDNode *CUNode = MDNode::get(VMContext, Elts);
142
143   // Create a named metadata so that it is easier to find cu in a module.
144   // Note that we only generate this when the caller wants to actually
145   // emit debug information. When we are only interested in tracking
146   // source line locations throughout the backend, we prevent codegen from
147   // emitting debug info in the final output by not generating llvm.dbg.cu.
148   if (EmitDebugInfo) {
149     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
150     NMD->addOperand(CUNode);
151   }
152
153   return DICompileUnit(CUNode);
154 }
155
156 static DIImportedEntity
157 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
158                      Value *NS, unsigned Line, StringRef Name,
159                      SmallVectorImpl<TrackingVH<MDNode>> &AllImportedModules) {
160   const MDNode *R;
161   if (Name.empty()) {
162     Value *Elts[] = {
163       GetTagConstant(C, Tag),
164       Context,
165       NS,
166       ConstantInt::get(Type::getInt32Ty(C), Line),
167     };
168     R = MDNode::get(C, Elts);
169   } else {
170     Value *Elts[] = {
171       GetTagConstant(C, Tag),
172       Context,
173       NS,
174       ConstantInt::get(Type::getInt32Ty(C), Line),
175       MDString::get(C, Name)
176     };
177     R = MDNode::get(C, Elts);
178   }
179   DIImportedEntity M(R);
180   assert(M.Verify() && "Imported module should be valid");
181   AllImportedModules.push_back(TrackingVH<MDNode>(M));
182   return M;
183 }
184
185 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
186                                                  DINameSpace NS,
187                                                  unsigned Line) {
188   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
189                                 Context, NS, Line, StringRef(), AllImportedModules);
190 }
191
192 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
193                                                  DIImportedEntity NS,
194                                                  unsigned Line) {
195   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
196                                 Context, NS, Line, StringRef(), AllImportedModules);
197 }
198
199 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
200                                                       DIScope Decl,
201                                                       unsigned Line, StringRef Name) {
202   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
203                                 Context, Decl.getRef(), Line, Name,
204                                 AllImportedModules);
205 }
206
207 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
208                                                       DIImportedEntity Imp,
209                                                       unsigned Line, StringRef Name) {
210   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
211                                 Context, Imp, Line, Name, AllImportedModules);
212 }
213
214 /// createFile - Create a file descriptor to hold debugging information
215 /// for a file.
216 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
217   Value *Elts[] = {
218     GetTagConstant(VMContext, dwarf::DW_TAG_file_type),
219     createFilePathPair(VMContext, Filename, Directory)
220   };
221   return DIFile(MDNode::get(VMContext, Elts));
222 }
223
224 /// createEnumerator - Create a single enumerator value.
225 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
226   assert(!Name.empty() && "Unable to create enumerator without name");
227   Value *Elts[] = {
228     GetTagConstant(VMContext, dwarf::DW_TAG_enumerator),
229     MDString::get(VMContext, Name),
230     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
231   };
232   return DIEnumerator(MDNode::get(VMContext, Elts));
233 }
234
235 /// \brief Create a DWARF unspecified type.
236 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
237   assert(!Name.empty() && "Unable to create type without name");
238   // Unspecified types are encoded in DIBasicType format. Line number, filename,
239   // size, alignment, offset and flags are always empty here.
240   Value *Elts[] = {
241     GetTagConstant(VMContext, dwarf::DW_TAG_unspecified_type),
242     nullptr, // Filename
243     nullptr, // Unused
244     MDString::get(VMContext, Name),
245     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
246     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
247     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
248     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
249     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags;
250     ConstantInt::get(Type::getInt32Ty(VMContext), 0)  // Encoding
251   };
252   return DIBasicType(MDNode::get(VMContext, Elts));
253 }
254
255 /// \brief Create C++11 nullptr type.
256 DIBasicType DIBuilder::createNullPtrType() {
257   return createUnspecifiedType("decltype(nullptr)");
258 }
259
260 /// createBasicType - Create debugging information entry for a basic
261 /// type, e.g 'char'.
262 DIBasicType
263 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
264                            uint64_t AlignInBits, unsigned Encoding) {
265   assert(!Name.empty() && "Unable to create type without name");
266   // Basic types are encoded in DIBasicType format. Line number, filename,
267   // offset and flags are always empty here.
268   Value *Elts[] = {
269     GetTagConstant(VMContext, dwarf::DW_TAG_base_type),
270     nullptr, // File/directory name
271     nullptr, // Unused
272     MDString::get(VMContext, Name),
273     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
274     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
275     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
276     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
277     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags;
278     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
279   };
280   return DIBasicType(MDNode::get(VMContext, Elts));
281 }
282
283 /// createQualifiedType - Create debugging information entry for a qualified
284 /// type, e.g. 'const int'.
285 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
286   // Qualified types are encoded in DIDerivedType format.
287   Value *Elts[] = {
288     GetTagConstant(VMContext, Tag),
289     nullptr, // Filename
290     nullptr, // Unused
291     MDString::get(VMContext, StringRef()), // Empty name.
292     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
293     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
294     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
295     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
296     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
297     FromTy.getRef()
298   };
299   return DIDerivedType(MDNode::get(VMContext, Elts));
300 }
301
302 /// createPointerType - Create debugging information entry for a pointer.
303 DIDerivedType
304 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
305                              uint64_t AlignInBits, StringRef Name) {
306   // Pointer types are encoded in DIDerivedType format.
307   Value *Elts[] = {
308     GetTagConstant(VMContext, dwarf::DW_TAG_pointer_type),
309     nullptr, // Filename
310     nullptr, // Unused
311     MDString::get(VMContext, Name),
312     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
313     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
314     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
315     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
316     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
317     PointeeTy.getRef()
318   };
319   return DIDerivedType(MDNode::get(VMContext, Elts));
320 }
321
322 DIDerivedType DIBuilder::createMemberPointerType(DIType PointeeTy,
323                                                  DIType Base) {
324   // Pointer types are encoded in DIDerivedType format.
325   Value *Elts[] = {
326     GetTagConstant(VMContext, dwarf::DW_TAG_ptr_to_member_type),
327     nullptr, // Filename
328     nullptr, // Unused
329     nullptr,
330     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
331     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
332     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
333     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
334     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
335     PointeeTy.getRef(),
336     Base.getRef()
337   };
338   return DIDerivedType(MDNode::get(VMContext, Elts));
339 }
340
341 /// createReferenceType - Create debugging information entry for a reference
342 /// type.
343 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
344   assert(RTy.isType() && "Unable to create reference type");
345   // References are encoded in DIDerivedType format.
346   Value *Elts[] = {
347     GetTagConstant(VMContext, Tag),
348     nullptr, // Filename
349     nullptr, // TheCU,
350     nullptr, // Name
351     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
352     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
353     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
354     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
355     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
356     RTy.getRef()
357   };
358   return DIDerivedType(MDNode::get(VMContext, Elts));
359 }
360
361 /// createTypedef - Create debugging information entry for a typedef.
362 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
363                                        unsigned LineNo, DIDescriptor Context) {
364   // typedefs are encoded in DIDerivedType format.
365   Value *Elts[] = {
366     GetTagConstant(VMContext, dwarf::DW_TAG_typedef),
367     File.getFileNode(),
368     DIScope(getNonCompileUnitScope(Context)).getRef(),
369     MDString::get(VMContext, Name),
370     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
371     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
372     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
373     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
374     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
375     Ty.getRef()
376   };
377   return DIDerivedType(MDNode::get(VMContext, Elts));
378 }
379
380 /// createFriend - Create debugging information entry for a 'friend'.
381 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
382   // typedefs are encoded in DIDerivedType format.
383   assert(Ty.isType() && "Invalid type!");
384   assert(FriendTy.isType() && "Invalid friend type!");
385   Value *Elts[] = {
386     GetTagConstant(VMContext, dwarf::DW_TAG_friend),
387     nullptr,
388     Ty.getRef(),
389     nullptr, // Name
390     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
391     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
392     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
393     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
394     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
395     FriendTy.getRef()
396   };
397   return DIDerivedType(MDNode::get(VMContext, Elts));
398 }
399
400 /// createInheritance - Create debugging information entry to establish
401 /// inheritance relationship between two types.
402 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
403                                            uint64_t BaseOffset,
404                                            unsigned Flags) {
405   assert(Ty.isType() && "Unable to create inheritance");
406   // TAG_inheritance is encoded in DIDerivedType format.
407   Value *Elts[] = {
408     GetTagConstant(VMContext, dwarf::DW_TAG_inheritance),
409     nullptr,
410     Ty.getRef(),
411     nullptr, // Name
412     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
413     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
414     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
415     ConstantInt::get(Type::getInt64Ty(VMContext), BaseOffset),
416     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
417     BaseTy.getRef()
418   };
419   return DIDerivedType(MDNode::get(VMContext, Elts));
420 }
421
422 /// createMemberType - Create debugging information entry for a member.
423 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
424                                           DIFile File, unsigned LineNumber,
425                                           uint64_t SizeInBits,
426                                           uint64_t AlignInBits,
427                                           uint64_t OffsetInBits, unsigned Flags,
428                                           DIType Ty) {
429   // TAG_member is encoded in DIDerivedType format.
430   Value *Elts[] = {
431     GetTagConstant(VMContext, dwarf::DW_TAG_member),
432     File.getFileNode(),
433     DIScope(getNonCompileUnitScope(Scope)).getRef(),
434     MDString::get(VMContext, Name),
435     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
436     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
437     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
438     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
439     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
440     Ty.getRef()
441   };
442   return DIDerivedType(MDNode::get(VMContext, Elts));
443 }
444
445 /// createStaticMemberType - Create debugging information entry for a
446 /// C++ static data member.
447 DIDerivedType
448 DIBuilder::createStaticMemberType(DIDescriptor Scope, StringRef Name,
449                                   DIFile File, unsigned LineNumber,
450                                   DIType Ty, unsigned Flags,
451                                   llvm::Value *Val) {
452   // TAG_member is encoded in DIDerivedType format.
453   Flags |= DIDescriptor::FlagStaticMember;
454   Value *Elts[] = {
455     GetTagConstant(VMContext, dwarf::DW_TAG_member),
456     File.getFileNode(),
457     DIScope(getNonCompileUnitScope(Scope)).getRef(),
458     MDString::get(VMContext, Name),
459     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
460     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
461     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
462     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
463     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
464     Ty.getRef(),
465     Val
466   };
467   return DIDerivedType(MDNode::get(VMContext, Elts));
468 }
469
470 /// createObjCIVar - Create debugging information entry for Objective-C
471 /// instance variable.
472 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
473                                         unsigned LineNumber,
474                                         uint64_t SizeInBits,
475                                         uint64_t AlignInBits,
476                                         uint64_t OffsetInBits, unsigned Flags,
477                                         DIType Ty, MDNode *PropertyNode) {
478   // TAG_member is encoded in DIDerivedType format.
479   Value *Elts[] = {
480     GetTagConstant(VMContext, dwarf::DW_TAG_member),
481     File.getFileNode(),
482     getNonCompileUnitScope(File),
483     MDString::get(VMContext, Name),
484     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
485     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
486     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
487     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
488     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
489     Ty,
490     PropertyNode
491   };
492   return DIDerivedType(MDNode::get(VMContext, Elts));
493 }
494
495 /// createObjCProperty - Create debugging information entry for Objective-C
496 /// property.
497 DIObjCProperty
498 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
499                               StringRef GetterName, StringRef SetterName,
500                               unsigned PropertyAttributes, DIType Ty) {
501   Value *Elts[] = {
502     GetTagConstant(VMContext, dwarf::DW_TAG_APPLE_property),
503     MDString::get(VMContext, Name),
504     File,
505     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
506     MDString::get(VMContext, GetterName),
507     MDString::get(VMContext, SetterName),
508     ConstantInt::get(Type::getInt32Ty(VMContext), PropertyAttributes),
509     Ty
510   };
511   return DIObjCProperty(MDNode::get(VMContext, Elts));
512 }
513
514 /// createTemplateTypeParameter - Create debugging information for template
515 /// type parameter.
516 DITemplateTypeParameter
517 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
518                                        DIType Ty, MDNode *File, unsigned LineNo,
519                                        unsigned ColumnNo) {
520   Value *Elts[] = {
521     GetTagConstant(VMContext, dwarf::DW_TAG_template_type_parameter),
522     DIScope(getNonCompileUnitScope(Context)).getRef(),
523     MDString::get(VMContext, Name),
524     Ty.getRef(),
525     File,
526     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
527     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo)
528   };
529   return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
530 }
531
532 DITemplateValueParameter
533 DIBuilder::createTemplateValueParameter(unsigned Tag, DIDescriptor Context,
534                                         StringRef Name, DIType Ty,
535                                         Value *Val, MDNode *File,
536                                         unsigned LineNo,
537                                         unsigned ColumnNo) {
538   Value *Elts[] = {
539     GetTagConstant(VMContext, Tag),
540     DIScope(getNonCompileUnitScope(Context)).getRef(),
541     MDString::get(VMContext, Name),
542     Ty.getRef(),
543     Val,
544     File,
545     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
546     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo)
547   };
548   return DITemplateValueParameter(MDNode::get(VMContext, Elts));
549 }
550
551 /// createTemplateValueParameter - Create debugging information for template
552 /// value parameter.
553 DITemplateValueParameter
554 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
555                                         DIType Ty, Value *Val,
556                                         MDNode *File, unsigned LineNo,
557                                         unsigned ColumnNo) {
558   return createTemplateValueParameter(dwarf::DW_TAG_template_value_parameter,
559                                       Context, Name, Ty, Val, File, LineNo,
560                                       ColumnNo);
561 }
562
563 DITemplateValueParameter
564 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
565                                            DIType Ty, StringRef Val,
566                                            MDNode *File, unsigned LineNo,
567                                            unsigned ColumnNo) {
568   return createTemplateValueParameter(
569       dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
570       MDString::get(VMContext, Val), File, LineNo, ColumnNo);
571 }
572
573 DITemplateValueParameter
574 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
575                                        DIType Ty, DIArray Val,
576                                        MDNode *File, unsigned LineNo,
577                                        unsigned ColumnNo) {
578   return createTemplateValueParameter(dwarf::DW_TAG_GNU_template_parameter_pack,
579                                       Context, Name, Ty, Val, File, LineNo,
580                                       ColumnNo);
581 }
582
583 /// createClassType - Create debugging information entry for a class.
584 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
585                                            DIFile File, unsigned LineNumber,
586                                            uint64_t SizeInBits,
587                                            uint64_t AlignInBits,
588                                            uint64_t OffsetInBits,
589                                            unsigned Flags, DIType DerivedFrom,
590                                            DIArray Elements,
591                                            DIType VTableHolder,
592                                            MDNode *TemplateParams,
593                                            StringRef UniqueIdentifier) {
594   assert((!Context || Context.isScope() || Context.isType()) &&
595          "createClassType should be called with a valid Context");
596   // TAG_class_type is encoded in DICompositeType format.
597   Value *Elts[] = {
598     GetTagConstant(VMContext, dwarf::DW_TAG_class_type),
599     File.getFileNode(),
600     DIScope(getNonCompileUnitScope(Context)).getRef(),
601     MDString::get(VMContext, Name),
602     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
603     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
604     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
605     ConstantInt::get(Type::getInt32Ty(VMContext), OffsetInBits),
606     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
607     DerivedFrom.getRef(),
608     Elements,
609     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
610     VTableHolder.getRef(),
611     TemplateParams,
612     UniqueIdentifier.empty() ? nullptr
613                              : MDString::get(VMContext, UniqueIdentifier)
614   };
615   DICompositeType R(MDNode::get(VMContext, Elts));
616   assert(R.isCompositeType() &&
617          "createClassType should return a DICompositeType");
618   if (!UniqueIdentifier.empty())
619     retainType(R);
620   return R;
621 }
622
623 /// createStructType - Create debugging information entry for a struct.
624 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
625                                             StringRef Name, DIFile File,
626                                             unsigned LineNumber,
627                                             uint64_t SizeInBits,
628                                             uint64_t AlignInBits,
629                                             unsigned Flags, DIType DerivedFrom,
630                                             DIArray Elements,
631                                             unsigned RunTimeLang,
632                                             DIType VTableHolder,
633                                             StringRef UniqueIdentifier) {
634  // TAG_structure_type is encoded in DICompositeType format.
635   Value *Elts[] = {
636     GetTagConstant(VMContext, dwarf::DW_TAG_structure_type),
637     File.getFileNode(),
638     DIScope(getNonCompileUnitScope(Context)).getRef(),
639     MDString::get(VMContext, Name),
640     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
641     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
642     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
643     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
644     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
645     DerivedFrom.getRef(),
646     Elements,
647     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeLang),
648     VTableHolder.getRef(),
649     nullptr,
650     UniqueIdentifier.empty() ? nullptr
651                              : MDString::get(VMContext, UniqueIdentifier)
652   };
653   DICompositeType R(MDNode::get(VMContext, Elts));
654   assert(R.isCompositeType() &&
655          "createStructType should return a DICompositeType");
656   if (!UniqueIdentifier.empty())
657     retainType(R);
658   return R;
659 }
660
661 /// createUnionType - Create debugging information entry for an union.
662 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
663                                            DIFile File, unsigned LineNumber,
664                                            uint64_t SizeInBits,
665                                            uint64_t AlignInBits, unsigned Flags,
666                                            DIArray Elements,
667                                            unsigned RunTimeLang,
668                                            StringRef UniqueIdentifier) {
669   // TAG_union_type is encoded in DICompositeType format.
670   Value *Elts[] = {
671     GetTagConstant(VMContext, dwarf::DW_TAG_union_type),
672     File.getFileNode(),
673     DIScope(getNonCompileUnitScope(Scope)).getRef(),
674     MDString::get(VMContext, Name),
675     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
676     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
677     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
678     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
679     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
680     nullptr,
681     Elements,
682     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeLang),
683     nullptr,
684     nullptr,
685     UniqueIdentifier.empty() ? nullptr
686                              : MDString::get(VMContext, UniqueIdentifier)
687   };
688   DICompositeType R(MDNode::get(VMContext, Elts));
689   if (!UniqueIdentifier.empty())
690     retainType(R);
691   return R;
692 }
693
694 /// createSubroutineType - Create subroutine type.
695 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
696                                                  DITypeArray ParameterTypes,
697                                                  unsigned Flags) {
698   // TAG_subroutine_type is encoded in DICompositeType format.
699   Value *Elts[] = {
700     GetTagConstant(VMContext, dwarf::DW_TAG_subroutine_type),
701     Constant::getNullValue(Type::getInt32Ty(VMContext)),
702     nullptr,
703     MDString::get(VMContext, ""),
704     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
705     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
706     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
707     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
708     ConstantInt::get(Type::getInt32Ty(VMContext), Flags), // Flags
709     nullptr,
710     ParameterTypes,
711     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
712     nullptr,
713     nullptr,
714     nullptr  // Type Identifer
715   };
716   return DISubroutineType(MDNode::get(VMContext, Elts));
717 }
718
719 /// createEnumerationType - Create debugging information entry for an
720 /// enumeration.
721 DICompositeType DIBuilder::createEnumerationType(
722     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
723     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
724     DIType UnderlyingType, StringRef UniqueIdentifier) {
725   // TAG_enumeration_type is encoded in DICompositeType format.
726   Value *Elts[] = {
727     GetTagConstant(VMContext, dwarf::DW_TAG_enumeration_type),
728     File.getFileNode(),
729     DIScope(getNonCompileUnitScope(Scope)).getRef(),
730     MDString::get(VMContext, Name),
731     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
732     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
733     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
734     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
735     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
736     UnderlyingType.getRef(),
737     Elements,
738     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
739     nullptr,
740     nullptr,
741     UniqueIdentifier.empty() ? nullptr
742                              : MDString::get(VMContext, UniqueIdentifier)
743   };
744   DICompositeType CTy(MDNode::get(VMContext, Elts));
745   AllEnumTypes.push_back(CTy);
746   if (!UniqueIdentifier.empty())
747     retainType(CTy);
748   return CTy;
749 }
750
751 /// createArrayType - Create debugging information entry for an array.
752 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
753                                            DIType Ty, DIArray Subscripts) {
754   // TAG_array_type is encoded in DICompositeType format.
755   Value *Elts[] = {
756     GetTagConstant(VMContext, dwarf::DW_TAG_array_type),
757     nullptr, // Filename/Directory,
758     nullptr, // Unused
759     MDString::get(VMContext, ""),
760     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
761     ConstantInt::get(Type::getInt64Ty(VMContext), Size),
762     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
763     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
764     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
765     Ty.getRef(),
766     Subscripts,
767     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
768     nullptr,
769     nullptr,
770     nullptr  // Type Identifer
771   };
772   return DICompositeType(MDNode::get(VMContext, Elts));
773 }
774
775 /// createVectorType - Create debugging information entry for a vector.
776 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
777                                             DIType Ty, DIArray Subscripts) {
778   // A vector is an array type with the FlagVector flag applied.
779   Value *Elts[] = {
780     GetTagConstant(VMContext, dwarf::DW_TAG_array_type),
781     nullptr, // Filename/Directory,
782     nullptr, // Unused
783     MDString::get(VMContext, ""),
784     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
785     ConstantInt::get(Type::getInt64Ty(VMContext), Size),
786     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
787     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
788     ConstantInt::get(Type::getInt32Ty(VMContext), DIType::FlagVector),
789     Ty.getRef(),
790     Subscripts,
791     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
792     nullptr,
793     nullptr,
794     nullptr  // Type Identifer
795   };
796   return DICompositeType(MDNode::get(VMContext, Elts));
797 }
798
799 /// createArtificialType - Create a new DIType with "artificial" flag set.
800 DIType DIBuilder::createArtificialType(DIType Ty) {
801   if (Ty.isArtificial())
802     return Ty;
803
804   SmallVector<Value *, 9> Elts;
805   MDNode *N = Ty;
806   assert (N && "Unexpected input DIType!");
807   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
808     Elts.push_back(N->getOperand(i));
809
810   unsigned CurFlags = Ty.getFlags();
811   CurFlags = CurFlags | DIType::FlagArtificial;
812
813   // Flags are stored at this slot.
814   // FIXME: Add an enum for this magic value.
815   Elts[8] =  ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
816
817   return DIType(MDNode::get(VMContext, Elts));
818 }
819
820 /// createObjectPointerType - Create a new type with both the object pointer
821 /// and artificial flags set.
822 DIType DIBuilder::createObjectPointerType(DIType Ty) {
823   if (Ty.isObjectPointer())
824     return Ty;
825
826   SmallVector<Value *, 9> Elts;
827   MDNode *N = Ty;
828   assert (N && "Unexpected input DIType!");
829   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
830     Elts.push_back(N->getOperand(i));
831
832   unsigned CurFlags = Ty.getFlags();
833   CurFlags = CurFlags | (DIType::FlagObjectPointer | DIType::FlagArtificial);
834
835   // Flags are stored at this slot.
836   // FIXME: Add an enum for this magic value.
837   Elts[8] = ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
838
839   return DIType(MDNode::get(VMContext, Elts));
840 }
841
842 /// retainType - Retain DIType in a module even if it is not referenced
843 /// through debug info anchors.
844 void DIBuilder::retainType(DIType T) {
845   AllRetainTypes.push_back(TrackingVH<MDNode>(T));
846 }
847
848 /// createUnspecifiedParameter - Create unspeicified type descriptor
849 /// for the subroutine type.
850 DIBasicType DIBuilder::createUnspecifiedParameter() {
851   return DIBasicType();
852 }
853
854 /// createForwardDecl - Create a permanent forward-declared type.
855 DICompositeType
856 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
857                              DIFile F, unsigned Line, unsigned RuntimeLang,
858                              uint64_t SizeInBits, uint64_t AlignInBits,
859                              StringRef UniqueIdentifier) {
860   // Create a temporary MDNode.
861   Value *Elts[] = {
862     GetTagConstant(VMContext, Tag),
863     F.getFileNode(),
864     DIScope(getNonCompileUnitScope(Scope)).getRef(),
865     MDString::get(VMContext, Name),
866     ConstantInt::get(Type::getInt32Ty(VMContext), Line),
867     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
868     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
869     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
870     ConstantInt::get(Type::getInt32Ty(VMContext), DIDescriptor::FlagFwdDecl),
871     nullptr,
872     DIArray(),
873     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
874     nullptr,
875     nullptr, //TemplateParams
876     UniqueIdentifier.empty() ? nullptr
877                              : MDString::get(VMContext, UniqueIdentifier)
878   };
879   MDNode *Node = MDNode::get(VMContext, Elts);
880   DICompositeType RetTy(Node);
881   assert(RetTy.isCompositeType() &&
882          "createForwardDecl result should be a DIType");
883   if (!UniqueIdentifier.empty())
884     retainType(RetTy);
885   return RetTy;
886 }
887
888 /// createReplaceableForwardDecl - Create a temporary forward-declared type that
889 /// can be RAUW'd if the full type is seen.
890 DICompositeType DIBuilder::createReplaceableForwardDecl(
891     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
892     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
893     StringRef UniqueIdentifier) {
894   // Create a temporary MDNode.
895   Value *Elts[] = {
896     GetTagConstant(VMContext, Tag),
897     F.getFileNode(),
898     DIScope(getNonCompileUnitScope(Scope)).getRef(),
899     MDString::get(VMContext, Name),
900     ConstantInt::get(Type::getInt32Ty(VMContext), Line),
901     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
902     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
903     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
904     ConstantInt::get(Type::getInt32Ty(VMContext), DIDescriptor::FlagFwdDecl),
905     nullptr,
906     DIArray(),
907     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
908     nullptr,
909     nullptr, //TemplateParams
910     UniqueIdentifier.empty() ? nullptr
911                              : MDString::get(VMContext, UniqueIdentifier)
912   };
913   MDNode *Node = MDNode::getTemporary(VMContext, Elts);
914   DICompositeType RetTy(Node);
915   assert(RetTy.isCompositeType() &&
916          "createReplaceableForwardDecl result should be a DIType");
917   if (!UniqueIdentifier.empty())
918     retainType(RetTy);
919   return RetTy;
920 }
921
922 /// getOrCreateArray - Get a DIArray, create one if required.
923 DIArray DIBuilder::getOrCreateArray(ArrayRef<Value *> Elements) {
924   return DIArray(MDNode::get(VMContext, Elements));
925 }
926
927 /// getOrCreateTypeArray - Get a DITypeArray, create one if required.
928 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Value *> Elements) {
929   SmallVector<llvm::Value *, 16> Elts; 
930   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
931     if (Elements[i] && isa<MDNode>(Elements[i]))
932       Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
933     else
934       Elts.push_back(Elements[i]);
935   }
936   return DITypeArray(MDNode::get(VMContext, Elts));
937 }
938
939 /// getOrCreateSubrange - Create a descriptor for a value range.  This
940 /// implicitly uniques the values returned.
941 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
942   Value *Elts[] = {
943     GetTagConstant(VMContext, dwarf::DW_TAG_subrange_type),
944     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
945     ConstantInt::get(Type::getInt64Ty(VMContext), Count)
946   };
947
948   return DISubrange(MDNode::get(VMContext, Elts));
949 }
950
951 /// \brief Create a new descriptor for the specified global.
952 DIGlobalVariable DIBuilder::createGlobalVariable(StringRef Name,
953                                                  StringRef LinkageName,
954                                                  DIFile F, unsigned LineNumber,
955                                                  DITypeRef Ty, bool isLocalToUnit,
956                                                  Value *Val) {
957   Value *Elts[] = {
958     GetTagConstant(VMContext, dwarf::DW_TAG_variable),
959     Constant::getNullValue(Type::getInt32Ty(VMContext)),
960     nullptr, // TheCU,
961     MDString::get(VMContext, Name),
962     MDString::get(VMContext, Name),
963     MDString::get(VMContext, LinkageName),
964     F,
965     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
966     Ty,
967     ConstantInt::get(Type::getInt32Ty(VMContext), isLocalToUnit),
968     ConstantInt::get(Type::getInt32Ty(VMContext), 1), /* isDefinition*/
969     Val,
970     DIDescriptor()
971   };
972   MDNode *Node = MDNode::get(VMContext, Elts);
973   AllGVs.push_back(Node);
974   return DIGlobalVariable(Node);
975 }
976
977 /// \brief Create a new descriptor for the specified global.
978 DIGlobalVariable DIBuilder::createGlobalVariable(StringRef Name, DIFile F,
979                                                  unsigned LineNumber,
980                                                  DITypeRef Ty,
981                                                  bool isLocalToUnit,
982                                                  Value *Val) {
983   return createGlobalVariable(Name, Name, F, LineNumber, Ty, isLocalToUnit,
984                               Val);
985 }
986
987 static DIGlobalVariable
988 createStaticVariableHelper(LLVMContext &VMContext, DIDescriptor Context,
989                            StringRef Name, StringRef LinkageName, DIFile F,
990                            unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit,
991                            Value *Val, MDNode *Decl, bool isDefinition,
992                            std::function<MDNode *(ArrayRef<Value *>)> CreateFunc) {
993   Value *Elts[] = {
994     GetTagConstant(VMContext, dwarf::DW_TAG_variable),
995     Constant::getNullValue(Type::getInt32Ty(VMContext)),
996     getNonCompileUnitScope(Context),
997     MDString::get(VMContext, Name),
998     MDString::get(VMContext, Name),
999     MDString::get(VMContext, LinkageName),
1000     F,
1001     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
1002     Ty,
1003     ConstantInt::get(Type::getInt32Ty(VMContext), isLocalToUnit),
1004     ConstantInt::get(Type::getInt32Ty(VMContext), isDefinition),
1005     Val,
1006     DIDescriptor(Decl)
1007   };
1008
1009   return DIGlobalVariable(CreateFunc(Elts));
1010 }
1011
1012 /// createStaticVariable - Create a new descriptor for the specified
1013 /// variable.
1014 DIGlobalVariable DIBuilder::createStaticVariable(DIDescriptor Context,
1015                                                  StringRef Name,
1016                                                  StringRef LinkageName,
1017                                                  DIFile F, unsigned LineNumber,
1018                                                  DITypeRef Ty,
1019                                                  bool isLocalToUnit,
1020                                                  Value *Val, MDNode *Decl) {
1021   return createStaticVariableHelper(VMContext, Context, Name, LinkageName, F,
1022                                     LineNumber, Ty, isLocalToUnit, Val, Decl, true,
1023                                     [&] (ArrayRef<Value *> Elts) -> MDNode * {
1024                                       MDNode *Node = MDNode::get(VMContext, Elts);
1025                                       AllGVs.push_back(Node);
1026                                       return Node;
1027                                     });
1028 }
1029
1030 /// createTempStaticVariableFwdDecl - Create a new temporary descriptor for the
1031 /// specified variable declarartion.
1032 DIGlobalVariable
1033 DIBuilder::createTempStaticVariableFwdDecl(DIDescriptor Context,
1034                                            StringRef Name,
1035                                            StringRef LinkageName,
1036                                            DIFile F, unsigned LineNumber,
1037                                            DITypeRef Ty,
1038                                            bool isLocalToUnit,
1039                                            Value *Val, MDNode *Decl) {
1040   return createStaticVariableHelper(VMContext, Context, Name, LinkageName, F,
1041                                     LineNumber, Ty, isLocalToUnit, Val, Decl, false,
1042                                     [&] (ArrayRef<Value *> Elts) {
1043                                       return MDNode::getTemporary(VMContext, Elts);
1044                                     });
1045 }
1046
1047 /// createVariable - Create a new descriptor for the specified variable.
1048 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
1049                                           StringRef Name, DIFile File,
1050                                           unsigned LineNo, DITypeRef Ty,
1051                                           bool AlwaysPreserve, unsigned Flags,
1052                                           unsigned ArgNo) {
1053   DIDescriptor Context(getNonCompileUnitScope(Scope));
1054   assert((!Context || Context.isScope()) &&
1055          "createLocalVariable should be called with a valid Context");
1056   Value *Elts[] = {
1057     GetTagConstant(VMContext, Tag),
1058     getNonCompileUnitScope(Scope),
1059     MDString::get(VMContext, Name),
1060     File,
1061     ConstantInt::get(Type::getInt32Ty(VMContext), (LineNo | (ArgNo << 24))),
1062     Ty,
1063     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
1064     Constant::getNullValue(Type::getInt32Ty(VMContext))
1065   };
1066   MDNode *Node = MDNode::get(VMContext, Elts);
1067   if (AlwaysPreserve) {
1068     // The optimizer may remove local variable. If there is an interest
1069     // to preserve variable info in such situation then stash it in a
1070     // named mdnode.
1071     DISubprogram Fn(getDISubprogram(Scope));
1072     NamedMDNode *FnLocals = getOrInsertFnSpecificMDNode(M, Fn);
1073     FnLocals->addOperand(Node);
1074   }
1075   DIVariable RetVar(Node);
1076   assert(RetVar.isVariable() &&
1077          "createLocalVariable should return a valid DIVariable");
1078   return RetVar;
1079 }
1080
1081 /// createComplexVariable - Create a new descriptor for the specified variable
1082 /// which has a complex address expression for its address.
1083 DIVariable DIBuilder::createComplexVariable(unsigned Tag, DIDescriptor Scope,
1084                                             StringRef Name, DIFile F,
1085                                             unsigned LineNo,
1086                                             DITypeRef Ty,
1087                                             ArrayRef<Value *> Addr,
1088                                             unsigned ArgNo) {
1089   assert(Addr.size() > 0 && "complex address is empty");
1090   Value *Elts[] = {
1091     GetTagConstant(VMContext, Tag),
1092     getNonCompileUnitScope(Scope),
1093     MDString::get(VMContext, Name),
1094     F,
1095     ConstantInt::get(Type::getInt32Ty(VMContext),
1096                      (LineNo | (ArgNo << 24))),
1097     Ty,
1098     Constant::getNullValue(Type::getInt32Ty(VMContext)),
1099     Constant::getNullValue(Type::getInt32Ty(VMContext)),
1100     MDNode::get(VMContext, Addr)
1101   };
1102   return DIVariable(MDNode::get(VMContext, Elts));
1103 }
1104
1105 /// createVariablePiece - Create a descriptor to describe one part
1106 /// of aggregate variable that is fragmented across multiple Values.
1107 DIVariable DIBuilder::createVariablePiece(DIVariable Variable,
1108                                           unsigned OffsetInBytes,
1109                                           unsigned SizeInBytes) {
1110   assert(SizeInBytes > 0 && "zero-size piece");
1111   Value *Addr[] = {
1112     ConstantInt::get(Type::getInt32Ty(VMContext), OpPiece),
1113     ConstantInt::get(Type::getInt32Ty(VMContext), OffsetInBytes),
1114     ConstantInt::get(Type::getInt32Ty(VMContext), SizeInBytes)
1115   };
1116
1117   assert((Variable->getNumOperands() == 8 || Variable.isVariablePiece()) &&
1118          "variable already has a complex address");
1119   SmallVector<Value *, 9> Elts;
1120   for (unsigned i = 0; i < 8; ++i)
1121     Elts.push_back(Variable->getOperand(i));
1122
1123   Elts.push_back(MDNode::get(VMContext, Addr));
1124   return DIVariable(MDNode::get(VMContext, Elts));
1125 }
1126
1127 /// createFunction - Create a new descriptor for the specified function.
1128 /// FIXME: this is added for dragonegg. Once we update dragonegg
1129 /// to call resolve function, this will be removed.
1130 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
1131                                        StringRef LinkageName, DIFile File,
1132                                        unsigned LineNo, DICompositeType Ty,
1133                                        bool isLocalToUnit, bool isDefinition,
1134                                        unsigned ScopeLine, unsigned Flags,
1135                                        bool isOptimized, Function *Fn,
1136                                        MDNode *TParams, MDNode *Decl) {
1137   // dragonegg does not generate identifier for types, so using an empty map
1138   // to resolve the context should be fine.
1139   DITypeIdentifierMap EmptyMap;
1140   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
1141                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
1142                         Flags, isOptimized, Fn, TParams, Decl);
1143 }
1144
1145 static DISubprogram
1146 createFunctionHelper(LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
1147                      StringRef LinkageName, DIFile File, unsigned LineNo,
1148                      DICompositeType Ty, bool isLocalToUnit, bool isDefinition,
1149                      unsigned ScopeLine, unsigned Flags, bool isOptimized,
1150                      Function *Fn, MDNode *TParams, MDNode *Decl,
1151                      std::function<MDNode *(ArrayRef<Value *>)> CreateFunc) {
1152   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1153          "function types should be subroutines");
1154   Value *TElts[] = { GetTagConstant(VMContext, DW_TAG_base_type) };
1155   Value *Elts[] = {
1156     GetTagConstant(VMContext, dwarf::DW_TAG_subprogram),
1157     File.getFileNode(),
1158     DIScope(getNonCompileUnitScope(Context)).getRef(),
1159     MDString::get(VMContext, Name),
1160     MDString::get(VMContext, Name),
1161     MDString::get(VMContext, LinkageName),
1162     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1163     Ty,
1164     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1165     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1166     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
1167     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
1168     nullptr,
1169     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
1170     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
1171     Fn,
1172     TParams,
1173     Decl,
1174     MDNode::getTemporary(VMContext, TElts),
1175     ConstantInt::get(Type::getInt32Ty(VMContext), ScopeLine)
1176   };
1177
1178   DISubprogram S(CreateFunc(Elts));
1179   assert(S.isSubprogram() &&
1180          "createFunction should return a valid DISubprogram");
1181   return S;
1182 }
1183
1184
1185 /// createFunction - Create a new descriptor for the specified function.
1186 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
1187                                        StringRef LinkageName, DIFile File,
1188                                        unsigned LineNo, DICompositeType Ty,
1189                                        bool isLocalToUnit, bool isDefinition,
1190                                        unsigned ScopeLine, unsigned Flags,
1191                                        bool isOptimized, Function *Fn,
1192                                        MDNode *TParams, MDNode *Decl) {
1193   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1194                               LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
1195                               Flags, isOptimized, Fn, TParams, Decl,
1196                               [&] (ArrayRef<Value *> Elts) -> MDNode *{
1197                                 MDNode *Node = MDNode::get(VMContext, Elts);
1198                                 // Create a named metadata so that we
1199                                 // do not lose this mdnode.
1200                                 if (isDefinition)
1201                                   AllSubprograms.push_back(Node);
1202                                 return Node;
1203                               });
1204 }
1205
1206 /// createTempFunctionFwdDecl - Create a new temporary descriptor for
1207 /// the specified function declaration.
1208 DISubprogram
1209 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
1210                                      StringRef LinkageName, DIFile File,
1211                                      unsigned LineNo, DICompositeType Ty,
1212                                      bool isLocalToUnit, bool isDefinition,
1213                                      unsigned ScopeLine, unsigned Flags,
1214                                      bool isOptimized, Function *Fn,
1215                                      MDNode *TParams, MDNode *Decl) {
1216   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1217                               LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
1218                               Flags, isOptimized, Fn, TParams, Decl,
1219                               [&] (ArrayRef<Value *> Elts) {
1220                                 return MDNode::getTemporary(VMContext, Elts);
1221                               });
1222 }
1223
1224 /// createMethod - Create a new descriptor for the specified C++ method.
1225 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
1226                                      StringRef LinkageName, DIFile F,
1227                                      unsigned LineNo, DICompositeType Ty,
1228                                      bool isLocalToUnit, bool isDefinition,
1229                                      unsigned VK, unsigned VIndex,
1230                                      DIType VTableHolder, unsigned Flags,
1231                                      bool isOptimized, Function *Fn,
1232                                      MDNode *TParam) {
1233   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1234          "function types should be subroutines");
1235   assert(getNonCompileUnitScope(Context) &&
1236          "Methods should have both a Context and a context that isn't "
1237          "the compile unit.");
1238   Value *Elts[] = {
1239     GetTagConstant(VMContext, dwarf::DW_TAG_subprogram),
1240     F.getFileNode(),
1241     DIScope(Context).getRef(),
1242     MDString::get(VMContext, Name),
1243     MDString::get(VMContext, Name),
1244     MDString::get(VMContext, LinkageName),
1245     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1246     Ty,
1247     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1248     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1249     ConstantInt::get(Type::getInt32Ty(VMContext), VK),
1250     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
1251     VTableHolder.getRef(),
1252     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
1253     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
1254     Fn,
1255     TParam,
1256     Constant::getNullValue(Type::getInt32Ty(VMContext)),
1257     nullptr,
1258     // FIXME: Do we want to use different scope/lines?
1259     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1260   };
1261   MDNode *Node = MDNode::get(VMContext, Elts);
1262   if (isDefinition)
1263     AllSubprograms.push_back(Node);
1264   DISubprogram S(Node);
1265   assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
1266   return S;
1267 }
1268
1269 /// createNameSpace - This creates new descriptor for a namespace
1270 /// with the specified parent scope.
1271 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
1272                                        DIFile File, unsigned LineNo) {
1273   Value *Elts[] = {
1274     GetTagConstant(VMContext, dwarf::DW_TAG_namespace),
1275     File.getFileNode(),
1276     getNonCompileUnitScope(Scope),
1277     MDString::get(VMContext, Name),
1278     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1279   };
1280   DINameSpace R(MDNode::get(VMContext, Elts));
1281   assert(R.Verify() &&
1282          "createNameSpace should return a verifiable DINameSpace");
1283   return R;
1284 }
1285
1286 /// createLexicalBlockFile - This creates a new MDNode that encapsulates
1287 /// an existing scope with a new filename.
1288 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
1289                                                      DIFile File,
1290                                                      unsigned Discriminator) {
1291   Value *Elts[] = {
1292     GetTagConstant(VMContext, dwarf::DW_TAG_lexical_block),
1293     File.getFileNode(),
1294     Scope,
1295     ConstantInt::get(Type::getInt32Ty(VMContext), Discriminator),
1296   };
1297   DILexicalBlockFile R(MDNode::get(VMContext, Elts));
1298   assert(
1299       R.Verify() &&
1300       "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
1301   return R;
1302 }
1303
1304 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
1305                                              unsigned Line, unsigned Col) {
1306   // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
1307   // I believe the right way is to have a self-referential element in the node.
1308   // Also: why do we bother with line/column - they're not used and the
1309   // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
1310   // for uniquing, yet then we have this other solution (because line/col were
1311   // inadequate) anyway. Remove all 3 and replace them with a self-reference.
1312
1313   // Defeat MDNode uniquing for lexical blocks by using unique id.
1314   static unsigned int unique_id = 0;
1315   Value *Elts[] = {
1316     GetTagConstant(VMContext, dwarf::DW_TAG_lexical_block),
1317     File.getFileNode(),
1318     getNonCompileUnitScope(Scope),
1319     ConstantInt::get(Type::getInt32Ty(VMContext), Line),
1320     ConstantInt::get(Type::getInt32Ty(VMContext), Col),
1321     ConstantInt::get(Type::getInt32Ty(VMContext), unique_id++)
1322   };
1323   DILexicalBlock R(MDNode::get(VMContext, Elts));
1324   assert(R.Verify() &&
1325          "createLexicalBlock should return a verifiable DILexicalBlock");
1326   return R;
1327 }
1328
1329 /// insertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1330 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1331                                       Instruction *InsertBefore) {
1332   assert(Storage && "no storage passed to dbg.declare");
1333   assert(VarInfo.isVariable() &&
1334          "empty or invalid DIVariable passed to dbg.declare");
1335   if (!DeclareFn)
1336     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1337
1338   Value *Args[] = { MDNode::get(Storage->getContext(), Storage), VarInfo };
1339   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
1340 }
1341
1342 /// insertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1343 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1344                                       BasicBlock *InsertAtEnd) {
1345   assert(Storage && "no storage passed to dbg.declare");
1346   assert(VarInfo.isVariable() &&
1347          "empty or invalid DIVariable passed to dbg.declare");
1348   if (!DeclareFn)
1349     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1350
1351   Value *Args[] = { MDNode::get(Storage->getContext(), Storage), VarInfo };
1352
1353   // If this block already has a terminator then insert this intrinsic
1354   // before the terminator.
1355   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1356     return CallInst::Create(DeclareFn, Args, "", T);
1357   else
1358     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
1359 }
1360
1361 /// insertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1362 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1363                                                 DIVariable VarInfo,
1364                                                 Instruction *InsertBefore) {
1365   assert(V && "no value passed to dbg.value");
1366   assert(VarInfo.isVariable() &&
1367          "empty or invalid DIVariable passed to dbg.value");
1368   if (!ValueFn)
1369     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1370
1371   Value *Args[] = { MDNode::get(V->getContext(), V),
1372                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1373                     VarInfo };
1374   return CallInst::Create(ValueFn, Args, "", InsertBefore);
1375 }
1376
1377 /// insertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1378 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1379                                                 DIVariable VarInfo,
1380                                                 BasicBlock *InsertAtEnd) {
1381   assert(V && "no value passed to dbg.value");
1382   assert(VarInfo.isVariable() &&
1383          "empty or invalid DIVariable passed to dbg.value");
1384   if (!ValueFn)
1385     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1386
1387   Value *Args[] = { MDNode::get(V->getContext(), V),
1388                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1389                     VarInfo };
1390   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
1391 }