Add DIBuilder functions to build RAUWable DIVariables and DIFunctions.
[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
473 DIBuilder::createObjCIVar(StringRef Name, DIFile File, unsigned LineNumber,
474                           uint64_t SizeInBits, uint64_t AlignInBits,
475                           uint64_t OffsetInBits, unsigned Flags, DIType Ty,
476                           StringRef PropertyName, StringRef GetterName,
477                           StringRef SetterName, unsigned PropertyAttributes) {
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     MDString::get(VMContext, PropertyName),
491     MDString::get(VMContext, GetterName),
492     MDString::get(VMContext, SetterName),
493     ConstantInt::get(Type::getInt32Ty(VMContext), PropertyAttributes)
494   };
495   return DIDerivedType(MDNode::get(VMContext, Elts));
496 }
497
498 /// createObjCIVar - Create debugging information entry for Objective-C
499 /// instance variable.
500 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
501                                         unsigned LineNumber,
502                                         uint64_t SizeInBits,
503                                         uint64_t AlignInBits,
504                                         uint64_t OffsetInBits, unsigned Flags,
505                                         DIType Ty, MDNode *PropertyNode) {
506   // TAG_member is encoded in DIDerivedType format.
507   Value *Elts[] = {
508     GetTagConstant(VMContext, dwarf::DW_TAG_member),
509     File.getFileNode(),
510     getNonCompileUnitScope(File),
511     MDString::get(VMContext, Name),
512     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
513     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
514     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
515     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
516     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
517     Ty,
518     PropertyNode
519   };
520   return DIDerivedType(MDNode::get(VMContext, Elts));
521 }
522
523 /// createObjCProperty - Create debugging information entry for Objective-C
524 /// property.
525 DIObjCProperty
526 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
527                               StringRef GetterName, StringRef SetterName,
528                               unsigned PropertyAttributes, DIType Ty) {
529   Value *Elts[] = {
530     GetTagConstant(VMContext, dwarf::DW_TAG_APPLE_property),
531     MDString::get(VMContext, Name),
532     File,
533     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
534     MDString::get(VMContext, GetterName),
535     MDString::get(VMContext, SetterName),
536     ConstantInt::get(Type::getInt32Ty(VMContext), PropertyAttributes),
537     Ty
538   };
539   return DIObjCProperty(MDNode::get(VMContext, Elts));
540 }
541
542 /// createTemplateTypeParameter - Create debugging information for template
543 /// type parameter.
544 DITemplateTypeParameter
545 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
546                                        DIType Ty, MDNode *File, unsigned LineNo,
547                                        unsigned ColumnNo) {
548   Value *Elts[] = {
549     GetTagConstant(VMContext, dwarf::DW_TAG_template_type_parameter),
550     DIScope(getNonCompileUnitScope(Context)).getRef(),
551     MDString::get(VMContext, Name),
552     Ty.getRef(),
553     File,
554     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
555     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo)
556   };
557   return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
558 }
559
560 DITemplateValueParameter
561 DIBuilder::createTemplateValueParameter(unsigned Tag, DIDescriptor Context,
562                                         StringRef Name, DIType Ty,
563                                         Value *Val, MDNode *File,
564                                         unsigned LineNo,
565                                         unsigned ColumnNo) {
566   Value *Elts[] = {
567     GetTagConstant(VMContext, Tag),
568     DIScope(getNonCompileUnitScope(Context)).getRef(),
569     MDString::get(VMContext, Name),
570     Ty.getRef(),
571     Val,
572     File,
573     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
574     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo)
575   };
576   return DITemplateValueParameter(MDNode::get(VMContext, Elts));
577 }
578
579 /// createTemplateValueParameter - Create debugging information for template
580 /// value parameter.
581 DITemplateValueParameter
582 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
583                                         DIType Ty, Value *Val,
584                                         MDNode *File, unsigned LineNo,
585                                         unsigned ColumnNo) {
586   return createTemplateValueParameter(dwarf::DW_TAG_template_value_parameter,
587                                       Context, Name, Ty, Val, File, LineNo,
588                                       ColumnNo);
589 }
590
591 DITemplateValueParameter
592 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
593                                            DIType Ty, StringRef Val,
594                                            MDNode *File, unsigned LineNo,
595                                            unsigned ColumnNo) {
596   return createTemplateValueParameter(
597       dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
598       MDString::get(VMContext, Val), File, LineNo, ColumnNo);
599 }
600
601 DITemplateValueParameter
602 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
603                                        DIType Ty, DIArray Val,
604                                        MDNode *File, unsigned LineNo,
605                                        unsigned ColumnNo) {
606   return createTemplateValueParameter(dwarf::DW_TAG_GNU_template_parameter_pack,
607                                       Context, Name, Ty, Val, File, LineNo,
608                                       ColumnNo);
609 }
610
611 /// createClassType - Create debugging information entry for a class.
612 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
613                                            DIFile File, unsigned LineNumber,
614                                            uint64_t SizeInBits,
615                                            uint64_t AlignInBits,
616                                            uint64_t OffsetInBits,
617                                            unsigned Flags, DIType DerivedFrom,
618                                            DIArray Elements,
619                                            DIType VTableHolder,
620                                            MDNode *TemplateParams,
621                                            StringRef UniqueIdentifier) {
622   assert((!Context || Context.isScope() || Context.isType()) &&
623          "createClassType should be called with a valid Context");
624   // TAG_class_type is encoded in DICompositeType format.
625   Value *Elts[] = {
626     GetTagConstant(VMContext, dwarf::DW_TAG_class_type),
627     File.getFileNode(),
628     DIScope(getNonCompileUnitScope(Context)).getRef(),
629     MDString::get(VMContext, Name),
630     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
631     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
632     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
633     ConstantInt::get(Type::getInt32Ty(VMContext), OffsetInBits),
634     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
635     DerivedFrom.getRef(),
636     Elements,
637     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
638     VTableHolder.getRef(),
639     TemplateParams,
640     UniqueIdentifier.empty() ? nullptr
641                              : MDString::get(VMContext, UniqueIdentifier)
642   };
643   DICompositeType R(MDNode::get(VMContext, Elts));
644   assert(R.isCompositeType() &&
645          "createClassType should return a DICompositeType");
646   if (!UniqueIdentifier.empty())
647     retainType(R);
648   return R;
649 }
650
651 /// createStructType - Create debugging information entry for a struct.
652 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
653                                             StringRef Name, DIFile File,
654                                             unsigned LineNumber,
655                                             uint64_t SizeInBits,
656                                             uint64_t AlignInBits,
657                                             unsigned Flags, DIType DerivedFrom,
658                                             DIArray Elements,
659                                             unsigned RunTimeLang,
660                                             DIType VTableHolder,
661                                             StringRef UniqueIdentifier) {
662  // TAG_structure_type is encoded in DICompositeType format.
663   Value *Elts[] = {
664     GetTagConstant(VMContext, dwarf::DW_TAG_structure_type),
665     File.getFileNode(),
666     DIScope(getNonCompileUnitScope(Context)).getRef(),
667     MDString::get(VMContext, Name),
668     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
669     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
670     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
671     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
672     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
673     DerivedFrom.getRef(),
674     Elements,
675     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeLang),
676     VTableHolder.getRef(),
677     nullptr,
678     UniqueIdentifier.empty() ? nullptr
679                              : MDString::get(VMContext, UniqueIdentifier)
680   };
681   DICompositeType R(MDNode::get(VMContext, Elts));
682   assert(R.isCompositeType() &&
683          "createStructType should return a DICompositeType");
684   if (!UniqueIdentifier.empty())
685     retainType(R);
686   return R;
687 }
688
689 /// createUnionType - Create debugging information entry for an union.
690 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
691                                            DIFile File, unsigned LineNumber,
692                                            uint64_t SizeInBits,
693                                            uint64_t AlignInBits, unsigned Flags,
694                                            DIArray Elements,
695                                            unsigned RunTimeLang,
696                                            StringRef UniqueIdentifier) {
697   // TAG_union_type is encoded in DICompositeType format.
698   Value *Elts[] = {
699     GetTagConstant(VMContext, dwarf::DW_TAG_union_type),
700     File.getFileNode(),
701     DIScope(getNonCompileUnitScope(Scope)).getRef(),
702     MDString::get(VMContext, Name),
703     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
704     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
705     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
706     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
707     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
708     nullptr,
709     Elements,
710     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeLang),
711     nullptr,
712     nullptr,
713     UniqueIdentifier.empty() ? nullptr
714                              : MDString::get(VMContext, UniqueIdentifier)
715   };
716   DICompositeType R(MDNode::get(VMContext, Elts));
717   if (!UniqueIdentifier.empty())
718     retainType(R);
719   return R;
720 }
721
722 /// createSubroutineType - Create subroutine type.
723 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
724                                                  DITypeArray ParameterTypes,
725                                                  unsigned Flags) {
726   // TAG_subroutine_type is encoded in DICompositeType format.
727   Value *Elts[] = {
728     GetTagConstant(VMContext, dwarf::DW_TAG_subroutine_type),
729     Constant::getNullValue(Type::getInt32Ty(VMContext)),
730     nullptr,
731     MDString::get(VMContext, ""),
732     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
733     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Size
734     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Align
735     ConstantInt::get(Type::getInt64Ty(VMContext), 0), // Offset
736     ConstantInt::get(Type::getInt32Ty(VMContext), Flags), // Flags
737     nullptr,
738     ParameterTypes,
739     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
740     nullptr,
741     nullptr,
742     nullptr  // Type Identifer
743   };
744   return DISubroutineType(MDNode::get(VMContext, Elts));
745 }
746
747 /// createEnumerationType - Create debugging information entry for an
748 /// enumeration.
749 DICompositeType DIBuilder::createEnumerationType(
750     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
751     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
752     DIType UnderlyingType, StringRef UniqueIdentifier) {
753   // TAG_enumeration_type is encoded in DICompositeType format.
754   Value *Elts[] = {
755     GetTagConstant(VMContext, dwarf::DW_TAG_enumeration_type),
756     File.getFileNode(),
757     DIScope(getNonCompileUnitScope(Scope)).getRef(),
758     MDString::get(VMContext, Name),
759     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
760     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
761     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
762     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
763     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
764     UnderlyingType.getRef(),
765     Elements,
766     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
767     nullptr,
768     nullptr,
769     UniqueIdentifier.empty() ? nullptr
770                              : MDString::get(VMContext, UniqueIdentifier)
771   };
772   DICompositeType CTy(MDNode::get(VMContext, Elts));
773   AllEnumTypes.push_back(CTy);
774   if (!UniqueIdentifier.empty())
775     retainType(CTy);
776   return CTy;
777 }
778
779 /// createArrayType - Create debugging information entry for an array.
780 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
781                                            DIType Ty, DIArray Subscripts) {
782   // TAG_array_type is encoded in DICompositeType format.
783   Value *Elts[] = {
784     GetTagConstant(VMContext, dwarf::DW_TAG_array_type),
785     nullptr, // Filename/Directory,
786     nullptr, // Unused
787     MDString::get(VMContext, ""),
788     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
789     ConstantInt::get(Type::getInt64Ty(VMContext), Size),
790     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
791     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
792     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Flags
793     Ty.getRef(),
794     Subscripts,
795     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
796     nullptr,
797     nullptr,
798     nullptr  // Type Identifer
799   };
800   return DICompositeType(MDNode::get(VMContext, Elts));
801 }
802
803 /// createVectorType - Create debugging information entry for a vector.
804 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
805                                             DIType Ty, DIArray Subscripts) {
806   // A vector is an array type with the FlagVector flag applied.
807   Value *Elts[] = {
808     GetTagConstant(VMContext, dwarf::DW_TAG_array_type),
809     nullptr, // Filename/Directory,
810     nullptr, // Unused
811     MDString::get(VMContext, ""),
812     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Line
813     ConstantInt::get(Type::getInt64Ty(VMContext), Size),
814     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
815     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
816     ConstantInt::get(Type::getInt32Ty(VMContext), DIType::FlagVector),
817     Ty.getRef(),
818     Subscripts,
819     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
820     nullptr,
821     nullptr,
822     nullptr  // Type Identifer
823   };
824   return DICompositeType(MDNode::get(VMContext, Elts));
825 }
826
827 /// createArtificialType - Create a new DIType with "artificial" flag set.
828 DIType DIBuilder::createArtificialType(DIType Ty) {
829   if (Ty.isArtificial())
830     return Ty;
831
832   SmallVector<Value *, 9> Elts;
833   MDNode *N = Ty;
834   assert (N && "Unexpected input DIType!");
835   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
836     Elts.push_back(N->getOperand(i));
837
838   unsigned CurFlags = Ty.getFlags();
839   CurFlags = CurFlags | DIType::FlagArtificial;
840
841   // Flags are stored at this slot.
842   // FIXME: Add an enum for this magic value.
843   Elts[8] =  ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
844
845   return DIType(MDNode::get(VMContext, Elts));
846 }
847
848 /// createObjectPointerType - Create a new type with both the object pointer
849 /// and artificial flags set.
850 DIType DIBuilder::createObjectPointerType(DIType Ty) {
851   if (Ty.isObjectPointer())
852     return Ty;
853
854   SmallVector<Value *, 9> Elts;
855   MDNode *N = Ty;
856   assert (N && "Unexpected input DIType!");
857   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
858     Elts.push_back(N->getOperand(i));
859
860   unsigned CurFlags = Ty.getFlags();
861   CurFlags = CurFlags | (DIType::FlagObjectPointer | DIType::FlagArtificial);
862
863   // Flags are stored at this slot.
864   // FIXME: Add an enum for this magic value.
865   Elts[8] = ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
866
867   return DIType(MDNode::get(VMContext, Elts));
868 }
869
870 /// retainType - Retain DIType in a module even if it is not referenced
871 /// through debug info anchors.
872 void DIBuilder::retainType(DIType T) {
873   AllRetainTypes.push_back(TrackingVH<MDNode>(T));
874 }
875
876 /// createUnspecifiedParameter - Create unspeicified type descriptor
877 /// for the subroutine type.
878 DIBasicType DIBuilder::createUnspecifiedParameter() {
879   return DIBasicType();
880 }
881
882 /// createForwardDecl - Create a permanent forward-declared type.
883 DICompositeType
884 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
885                              DIFile F, unsigned Line, unsigned RuntimeLang,
886                              uint64_t SizeInBits, uint64_t AlignInBits,
887                              StringRef UniqueIdentifier) {
888   // Create a temporary MDNode.
889   Value *Elts[] = {
890     GetTagConstant(VMContext, Tag),
891     F.getFileNode(),
892     DIScope(getNonCompileUnitScope(Scope)).getRef(),
893     MDString::get(VMContext, Name),
894     ConstantInt::get(Type::getInt32Ty(VMContext), Line),
895     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
896     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
897     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
898     ConstantInt::get(Type::getInt32Ty(VMContext), DIDescriptor::FlagFwdDecl),
899     nullptr,
900     DIArray(),
901     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
902     nullptr,
903     nullptr, //TemplateParams
904     UniqueIdentifier.empty() ? nullptr
905                              : MDString::get(VMContext, UniqueIdentifier)
906   };
907   MDNode *Node = MDNode::get(VMContext, Elts);
908   DICompositeType RetTy(Node);
909   assert(RetTy.isCompositeType() &&
910          "createForwardDecl result should be a DIType");
911   if (!UniqueIdentifier.empty())
912     retainType(RetTy);
913   return RetTy;
914 }
915
916 /// createReplaceableForwardDecl - Create a temporary forward-declared type that
917 /// can be RAUW'd if the full type is seen.
918 DICompositeType DIBuilder::createReplaceableForwardDecl(
919     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
920     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
921     StringRef UniqueIdentifier) {
922   // Create a temporary MDNode.
923   Value *Elts[] = {
924     GetTagConstant(VMContext, Tag),
925     F.getFileNode(),
926     DIScope(getNonCompileUnitScope(Scope)).getRef(),
927     MDString::get(VMContext, Name),
928     ConstantInt::get(Type::getInt32Ty(VMContext), Line),
929     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
930     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
931     ConstantInt::get(Type::getInt32Ty(VMContext), 0), // Offset
932     ConstantInt::get(Type::getInt32Ty(VMContext), DIDescriptor::FlagFwdDecl),
933     nullptr,
934     DIArray(),
935     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
936     nullptr,
937     nullptr, //TemplateParams
938     UniqueIdentifier.empty() ? nullptr
939                              : MDString::get(VMContext, UniqueIdentifier)
940   };
941   MDNode *Node = MDNode::getTemporary(VMContext, Elts);
942   DICompositeType RetTy(Node);
943   assert(RetTy.isCompositeType() &&
944          "createReplaceableForwardDecl result should be a DIType");
945   if (!UniqueIdentifier.empty())
946     retainType(RetTy);
947   return RetTy;
948 }
949
950 /// getOrCreateArray - Get a DIArray, create one if required.
951 DIArray DIBuilder::getOrCreateArray(ArrayRef<Value *> Elements) {
952   return DIArray(MDNode::get(VMContext, Elements));
953 }
954
955 /// getOrCreateTypeArray - Get a DITypeArray, create one if required.
956 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Value *> Elements) {
957   SmallVector<llvm::Value *, 16> Elts; 
958   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
959     if (Elements[i] && isa<MDNode>(Elements[i]))
960       Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
961     else
962       Elts.push_back(Elements[i]);
963   }
964   return DITypeArray(MDNode::get(VMContext, Elts));
965 }
966
967 /// getOrCreateSubrange - Create a descriptor for a value range.  This
968 /// implicitly uniques the values returned.
969 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
970   Value *Elts[] = {
971     GetTagConstant(VMContext, dwarf::DW_TAG_subrange_type),
972     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
973     ConstantInt::get(Type::getInt64Ty(VMContext), Count)
974   };
975
976   return DISubrange(MDNode::get(VMContext, Elts));
977 }
978
979 /// \brief Create a new descriptor for the specified global.
980 DIGlobalVariable DIBuilder::createGlobalVariable(StringRef Name,
981                                                  StringRef LinkageName,
982                                                  DIFile F, unsigned LineNumber,
983                                                  DITypeRef Ty, bool isLocalToUnit,
984                                                  Value *Val) {
985   Value *Elts[] = {
986     GetTagConstant(VMContext, dwarf::DW_TAG_variable),
987     Constant::getNullValue(Type::getInt32Ty(VMContext)),
988     nullptr, // TheCU,
989     MDString::get(VMContext, Name),
990     MDString::get(VMContext, Name),
991     MDString::get(VMContext, LinkageName),
992     F,
993     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
994     Ty,
995     ConstantInt::get(Type::getInt32Ty(VMContext), isLocalToUnit),
996     ConstantInt::get(Type::getInt32Ty(VMContext), 1), /* isDefinition*/
997     Val,
998     DIDescriptor()
999   };
1000   MDNode *Node = MDNode::get(VMContext, Elts);
1001   AllGVs.push_back(Node);
1002   return DIGlobalVariable(Node);
1003 }
1004
1005 /// \brief Create a new descriptor for the specified global.
1006 DIGlobalVariable DIBuilder::createGlobalVariable(StringRef Name, DIFile F,
1007                                                  unsigned LineNumber,
1008                                                  DITypeRef Ty,
1009                                                  bool isLocalToUnit,
1010                                                  Value *Val) {
1011   return createGlobalVariable(Name, Name, F, LineNumber, Ty, isLocalToUnit,
1012                               Val);
1013 }
1014
1015 static DIGlobalVariable
1016 createStaticVariableHelper(LLVMContext &VMContext, DIDescriptor Context,
1017                            StringRef Name, StringRef LinkageName, DIFile F,
1018                            unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit,
1019                            Value *Val, MDNode *Decl, bool isDefinition,
1020                            std::function<MDNode *(ArrayRef<Value *>)> CreateFunc) {
1021   Value *Elts[] = {
1022     GetTagConstant(VMContext, dwarf::DW_TAG_variable),
1023     Constant::getNullValue(Type::getInt32Ty(VMContext)),
1024     getNonCompileUnitScope(Context),
1025     MDString::get(VMContext, Name),
1026     MDString::get(VMContext, Name),
1027     MDString::get(VMContext, LinkageName),
1028     F,
1029     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
1030     Ty,
1031     ConstantInt::get(Type::getInt32Ty(VMContext), isLocalToUnit),
1032     ConstantInt::get(Type::getInt32Ty(VMContext), isDefinition),
1033     Val,
1034     DIDescriptor(Decl)
1035   };
1036
1037   return DIGlobalVariable(CreateFunc(Elts));
1038 }
1039
1040 /// createStaticVariable - Create a new descriptor for the specified
1041 /// variable.
1042 DIGlobalVariable DIBuilder::createStaticVariable(DIDescriptor Context,
1043                                                  StringRef Name,
1044                                                  StringRef LinkageName,
1045                                                  DIFile F, unsigned LineNumber,
1046                                                  DITypeRef Ty,
1047                                                  bool isLocalToUnit,
1048                                                  Value *Val, MDNode *Decl) {
1049   return createStaticVariableHelper(VMContext, Context, Name, LinkageName, F,
1050                                     LineNumber, Ty, isLocalToUnit, Val, Decl, true,
1051                                     [&] (ArrayRef<Value *> Elts) -> MDNode * {
1052                                       MDNode *Node = MDNode::get(VMContext, Elts);
1053                                       AllGVs.push_back(Node);
1054                                       return Node;
1055                                     });
1056 }
1057
1058 /// createTempStaticVariableFwdDecl - Create a new temporary descriptor for the
1059 /// specified variable declarartion.
1060 DIGlobalVariable
1061 DIBuilder::createTempStaticVariableFwdDecl(DIDescriptor Context,
1062                                            StringRef Name,
1063                                            StringRef LinkageName,
1064                                            DIFile F, unsigned LineNumber,
1065                                            DITypeRef Ty,
1066                                            bool isLocalToUnit,
1067                                            Value *Val, MDNode *Decl) {
1068   return createStaticVariableHelper(VMContext, Context, Name, LinkageName, F,
1069                                     LineNumber, Ty, isLocalToUnit, Val, Decl, false,
1070                                     [&] (ArrayRef<Value *> Elts) {
1071                                       return MDNode::getTemporary(VMContext, Elts);
1072                                     });
1073 }
1074
1075 /// createVariable - Create a new descriptor for the specified variable.
1076 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
1077                                           StringRef Name, DIFile File,
1078                                           unsigned LineNo, DITypeRef Ty,
1079                                           bool AlwaysPreserve, unsigned Flags,
1080                                           unsigned ArgNo) {
1081   DIDescriptor Context(getNonCompileUnitScope(Scope));
1082   assert((!Context || Context.isScope()) &&
1083          "createLocalVariable should be called with a valid Context");
1084   Value *Elts[] = {
1085     GetTagConstant(VMContext, Tag),
1086     getNonCompileUnitScope(Scope),
1087     MDString::get(VMContext, Name),
1088     File,
1089     ConstantInt::get(Type::getInt32Ty(VMContext), (LineNo | (ArgNo << 24))),
1090     Ty,
1091     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
1092     Constant::getNullValue(Type::getInt32Ty(VMContext))
1093   };
1094   MDNode *Node = MDNode::get(VMContext, Elts);
1095   if (AlwaysPreserve) {
1096     // The optimizer may remove local variable. If there is an interest
1097     // to preserve variable info in such situation then stash it in a
1098     // named mdnode.
1099     DISubprogram Fn(getDISubprogram(Scope));
1100     NamedMDNode *FnLocals = getOrInsertFnSpecificMDNode(M, Fn);
1101     FnLocals->addOperand(Node);
1102   }
1103   DIVariable RetVar(Node);
1104   assert(RetVar.isVariable() &&
1105          "createLocalVariable should return a valid DIVariable");
1106   return RetVar;
1107 }
1108
1109 /// createComplexVariable - Create a new descriptor for the specified variable
1110 /// which has a complex address expression for its address.
1111 DIVariable DIBuilder::createComplexVariable(unsigned Tag, DIDescriptor Scope,
1112                                             StringRef Name, DIFile F,
1113                                             unsigned LineNo,
1114                                             DITypeRef Ty,
1115                                             ArrayRef<Value *> Addr,
1116                                             unsigned ArgNo) {
1117   assert(Addr.size() > 0 && "complex address is empty");
1118   Value *Elts[] = {
1119     GetTagConstant(VMContext, Tag),
1120     getNonCompileUnitScope(Scope),
1121     MDString::get(VMContext, Name),
1122     F,
1123     ConstantInt::get(Type::getInt32Ty(VMContext),
1124                      (LineNo | (ArgNo << 24))),
1125     Ty,
1126     Constant::getNullValue(Type::getInt32Ty(VMContext)),
1127     Constant::getNullValue(Type::getInt32Ty(VMContext)),
1128     MDNode::get(VMContext, Addr)
1129   };
1130   return DIVariable(MDNode::get(VMContext, Elts));
1131 }
1132
1133 /// createVariablePiece - Create a descriptor to describe one part
1134 /// of aggregate variable that is fragmented across multiple Values.
1135 DIVariable DIBuilder::createVariablePiece(DIVariable Variable,
1136                                           unsigned OffsetInBytes,
1137                                           unsigned SizeInBytes) {
1138   assert(SizeInBytes > 0 && "zero-size piece");
1139   Value *Addr[] = {
1140     ConstantInt::get(Type::getInt32Ty(VMContext), OpPiece),
1141     ConstantInt::get(Type::getInt32Ty(VMContext), OffsetInBytes),
1142     ConstantInt::get(Type::getInt32Ty(VMContext), SizeInBytes)
1143   };
1144
1145   assert((Variable->getNumOperands() == 8 || Variable.isVariablePiece()) &&
1146          "variable already has a complex address");
1147   SmallVector<Value *, 9> Elts;
1148   for (unsigned i = 0; i < 8; ++i)
1149     Elts.push_back(Variable->getOperand(i));
1150
1151   Elts.push_back(MDNode::get(VMContext, Addr));
1152   return DIVariable(MDNode::get(VMContext, Elts));
1153 }
1154
1155 /// createFunction - Create a new descriptor for the specified function.
1156 /// FIXME: this is added for dragonegg. Once we update dragonegg
1157 /// to call resolve function, this will be removed.
1158 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
1159                                        StringRef LinkageName, DIFile File,
1160                                        unsigned LineNo, DICompositeType Ty,
1161                                        bool isLocalToUnit, bool isDefinition,
1162                                        unsigned ScopeLine, unsigned Flags,
1163                                        bool isOptimized, Function *Fn,
1164                                        MDNode *TParams, MDNode *Decl) {
1165   // dragonegg does not generate identifier for types, so using an empty map
1166   // to resolve the context should be fine.
1167   DITypeIdentifierMap EmptyMap;
1168   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
1169                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
1170                         Flags, isOptimized, Fn, TParams, Decl);
1171 }
1172
1173 static DISubprogram
1174 createFunctionHelper(LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
1175                      StringRef LinkageName, DIFile File, unsigned LineNo,
1176                      DICompositeType Ty, bool isLocalToUnit, bool isDefinition,
1177                      unsigned ScopeLine, unsigned Flags, bool isOptimized,
1178                      Function *Fn, MDNode *TParams, MDNode *Decl,
1179                      std::function<MDNode *(ArrayRef<Value *>)> CreateFunc) {
1180   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1181          "function types should be subroutines");
1182   Value *TElts[] = { GetTagConstant(VMContext, DW_TAG_base_type) };
1183   Value *Elts[] = {
1184     GetTagConstant(VMContext, dwarf::DW_TAG_subprogram),
1185     File.getFileNode(),
1186     DIScope(getNonCompileUnitScope(Context)).getRef(),
1187     MDString::get(VMContext, Name),
1188     MDString::get(VMContext, Name),
1189     MDString::get(VMContext, LinkageName),
1190     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1191     Ty,
1192     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1193     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1194     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
1195     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
1196     nullptr,
1197     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
1198     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
1199     Fn,
1200     TParams,
1201     Decl,
1202     MDNode::getTemporary(VMContext, TElts),
1203     ConstantInt::get(Type::getInt32Ty(VMContext), ScopeLine)
1204   };
1205
1206   DISubprogram S(CreateFunc(Elts));
1207   assert(S.isSubprogram() &&
1208          "createFunction should return a valid DISubprogram");
1209   return S;
1210 }
1211
1212
1213 /// createFunction - Create a new descriptor for the specified function.
1214 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
1215                                        StringRef LinkageName, DIFile File,
1216                                        unsigned LineNo, DICompositeType Ty,
1217                                        bool isLocalToUnit, bool isDefinition,
1218                                        unsigned ScopeLine, unsigned Flags,
1219                                        bool isOptimized, Function *Fn,
1220                                        MDNode *TParams, MDNode *Decl) {
1221   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1222                               LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
1223                               Flags, isOptimized, Fn, TParams, Decl,
1224                               [&] (ArrayRef<Value *> Elts) -> MDNode *{
1225                                 MDNode *Node = MDNode::get(VMContext, Elts);
1226                                 // Create a named metadata so that we
1227                                 // do not lose this mdnode.
1228                                 if (isDefinition)
1229                                   AllSubprograms.push_back(Node);
1230                                 return Node;
1231                               });
1232 }
1233
1234 /// createTempFunctionFwdDecl - Create a new temporary descriptor for
1235 /// the specified function declaration.
1236 DISubprogram
1237 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
1238                                      StringRef LinkageName, DIFile File,
1239                                      unsigned LineNo, DICompositeType Ty,
1240                                      bool isLocalToUnit, bool isDefinition,
1241                                      unsigned ScopeLine, unsigned Flags,
1242                                      bool isOptimized, Function *Fn,
1243                                      MDNode *TParams, MDNode *Decl) {
1244   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1245                               LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
1246                               Flags, isOptimized, Fn, TParams, Decl,
1247                               [&] (ArrayRef<Value *> Elts) {
1248                                 return MDNode::getTemporary(VMContext, Elts);
1249                               });
1250 }
1251
1252 /// createMethod - Create a new descriptor for the specified C++ method.
1253 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
1254                                      StringRef LinkageName, DIFile F,
1255                                      unsigned LineNo, DICompositeType Ty,
1256                                      bool isLocalToUnit, bool isDefinition,
1257                                      unsigned VK, unsigned VIndex,
1258                                      DIType VTableHolder, unsigned Flags,
1259                                      bool isOptimized, Function *Fn,
1260                                      MDNode *TParam) {
1261   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1262          "function types should be subroutines");
1263   assert(getNonCompileUnitScope(Context) &&
1264          "Methods should have both a Context and a context that isn't "
1265          "the compile unit.");
1266   Value *Elts[] = {
1267     GetTagConstant(VMContext, dwarf::DW_TAG_subprogram),
1268     F.getFileNode(),
1269     DIScope(Context).getRef(),
1270     MDString::get(VMContext, Name),
1271     MDString::get(VMContext, Name),
1272     MDString::get(VMContext, LinkageName),
1273     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1274     Ty,
1275     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1276     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1277     ConstantInt::get(Type::getInt32Ty(VMContext), VK),
1278     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
1279     VTableHolder.getRef(),
1280     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
1281     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
1282     Fn,
1283     TParam,
1284     Constant::getNullValue(Type::getInt32Ty(VMContext)),
1285     nullptr,
1286     // FIXME: Do we want to use different scope/lines?
1287     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1288   };
1289   MDNode *Node = MDNode::get(VMContext, Elts);
1290   if (isDefinition)
1291     AllSubprograms.push_back(Node);
1292   DISubprogram S(Node);
1293   assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
1294   return S;
1295 }
1296
1297 /// createNameSpace - This creates new descriptor for a namespace
1298 /// with the specified parent scope.
1299 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
1300                                        DIFile File, unsigned LineNo) {
1301   Value *Elts[] = {
1302     GetTagConstant(VMContext, dwarf::DW_TAG_namespace),
1303     File.getFileNode(),
1304     getNonCompileUnitScope(Scope),
1305     MDString::get(VMContext, Name),
1306     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1307   };
1308   DINameSpace R(MDNode::get(VMContext, Elts));
1309   assert(R.Verify() &&
1310          "createNameSpace should return a verifiable DINameSpace");
1311   return R;
1312 }
1313
1314 /// createLexicalBlockFile - This creates a new MDNode that encapsulates
1315 /// an existing scope with a new filename.
1316 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
1317                                                      DIFile File,
1318                                                      unsigned Discriminator) {
1319   Value *Elts[] = {
1320     GetTagConstant(VMContext, dwarf::DW_TAG_lexical_block),
1321     File.getFileNode(),
1322     Scope,
1323     ConstantInt::get(Type::getInt32Ty(VMContext), Discriminator),
1324   };
1325   DILexicalBlockFile R(MDNode::get(VMContext, Elts));
1326   assert(
1327       R.Verify() &&
1328       "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
1329   return R;
1330 }
1331
1332 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
1333                                              unsigned Line, unsigned Col) {
1334   // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
1335   // I believe the right way is to have a self-referential element in the node.
1336   // Also: why do we bother with line/column - they're not used and the
1337   // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
1338   // for uniquing, yet then we have this other solution (because line/col were
1339   // inadequate) anyway. Remove all 3 and replace them with a self-reference.
1340
1341   // Defeat MDNode uniquing for lexical blocks by using unique id.
1342   static unsigned int unique_id = 0;
1343   Value *Elts[] = {
1344     GetTagConstant(VMContext, dwarf::DW_TAG_lexical_block),
1345     File.getFileNode(),
1346     getNonCompileUnitScope(Scope),
1347     ConstantInt::get(Type::getInt32Ty(VMContext), Line),
1348     ConstantInt::get(Type::getInt32Ty(VMContext), Col),
1349     ConstantInt::get(Type::getInt32Ty(VMContext), unique_id++)
1350   };
1351   DILexicalBlock R(MDNode::get(VMContext, Elts));
1352   assert(R.Verify() &&
1353          "createLexicalBlock should return a verifiable DILexicalBlock");
1354   return R;
1355 }
1356
1357 /// insertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1358 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1359                                       Instruction *InsertBefore) {
1360   assert(Storage && "no storage passed to dbg.declare");
1361   assert(VarInfo.isVariable() &&
1362          "empty or invalid DIVariable passed to dbg.declare");
1363   if (!DeclareFn)
1364     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1365
1366   Value *Args[] = { MDNode::get(Storage->getContext(), Storage), VarInfo };
1367   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
1368 }
1369
1370 /// insertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1371 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1372                                       BasicBlock *InsertAtEnd) {
1373   assert(Storage && "no storage passed to dbg.declare");
1374   assert(VarInfo.isVariable() &&
1375          "empty or invalid DIVariable passed to dbg.declare");
1376   if (!DeclareFn)
1377     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1378
1379   Value *Args[] = { MDNode::get(Storage->getContext(), Storage), VarInfo };
1380
1381   // If this block already has a terminator then insert this intrinsic
1382   // before the terminator.
1383   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1384     return CallInst::Create(DeclareFn, Args, "", T);
1385   else
1386     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
1387 }
1388
1389 /// insertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1390 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1391                                                 DIVariable VarInfo,
1392                                                 Instruction *InsertBefore) {
1393   assert(V && "no value passed to dbg.value");
1394   assert(VarInfo.isVariable() &&
1395          "empty or invalid DIVariable passed to dbg.value");
1396   if (!ValueFn)
1397     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1398
1399   Value *Args[] = { MDNode::get(V->getContext(), V),
1400                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1401                     VarInfo };
1402   return CallInst::Create(ValueFn, Args, "", InsertBefore);
1403 }
1404
1405 /// insertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1406 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1407                                                 DIVariable VarInfo,
1408                                                 BasicBlock *InsertAtEnd) {
1409   assert(V && "no value passed to dbg.value");
1410   assert(VarInfo.isVariable() &&
1411          "empty or invalid DIVariable passed to dbg.value");
1412   if (!ValueFn)
1413     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1414
1415   Value *Args[] = { MDNode::get(V->getContext(), V),
1416                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1417                     VarInfo };
1418   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
1419 }