1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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 coordinates the debug information generation while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "CGBlocks.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Module.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 using namespace clang;
40 using namespace clang::CodeGen;
41 
42 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43   : CGM(CGM), DBuilder(CGM.getModule()),
44     BlockLiteralGenericSet(false) {
45   CreateCompileUnit();
46 }
47 
48 CGDebugInfo::~CGDebugInfo() {
49   assert(LexicalBlockStack.empty() &&
50          "Region stack mismatch, stack not empty!");
51 }
52 
53 void CGDebugInfo::setLocation(SourceLocation Loc) {
54   // If the new location isn't valid return.
55   if (!Loc.isValid()) return;
56 
57   CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
58 
59   // If we've changed files in the middle of a lexical scope go ahead
60   // and create a new lexical scope with file node if it's different
61   // from the one in the scope.
62   if (LexicalBlockStack.empty()) return;
63 
64   SourceManager &SM = CGM.getContext().getSourceManager();
65   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
66   PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
67 
68   if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
69       !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
70     return;
71 
72   llvm::MDNode *LB = LexicalBlockStack.back();
73   llvm::DIScope Scope = llvm::DIScope(LB);
74   if (Scope.isLexicalBlockFile()) {
75     llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
76     llvm::DIDescriptor D
77       = DBuilder.createLexicalBlockFile(LBF.getScope(),
78 					getOrCreateFile(CurLoc));
79     llvm::MDNode *N = D;
80     LexicalBlockStack.pop_back();
81     LexicalBlockStack.push_back(N);
82   } else if (Scope.isLexicalBlock()) {
83     llvm::DIDescriptor D
84       = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
85     llvm::MDNode *N = D;
86     LexicalBlockStack.pop_back();
87     LexicalBlockStack.push_back(N);
88   }
89 }
90 
91 /// getContextDescriptor - Get context info for the decl.
92 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
93   if (!Context)
94     return TheCU;
95 
96   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
97     I = RegionMap.find(Context);
98   if (I != RegionMap.end())
99     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
100 
101   // Check namespace.
102   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
103     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
104 
105   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
106     if (!RDecl->isDependentType()) {
107       llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
108                                         getOrCreateMainFile());
109       return llvm::DIDescriptor(Ty);
110     }
111   }
112   return TheCU;
113 }
114 
115 /// getFunctionName - Get function name for the given FunctionDecl. If the
116 /// name is constructred on demand (e.g. C++ destructor) then the name
117 /// is stored on the side.
118 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
119   assert (FD && "Invalid FunctionDecl!");
120   IdentifierInfo *FII = FD->getIdentifier();
121   if (FII)
122     return FII->getName();
123 
124   // Otherwise construct human readable name for debug info.
125   std::string NS = FD->getNameAsString();
126 
127   // Copy this name on the side and use its reference.
128   char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
129   memcpy(StrPtr, NS.data(), NS.length());
130   return StringRef(StrPtr, NS.length());
131 }
132 
133 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
134   llvm::SmallString<256> MethodName;
135   llvm::raw_svector_ostream OS(MethodName);
136   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
137   const DeclContext *DC = OMD->getDeclContext();
138   if (const ObjCImplementationDecl *OID =
139       dyn_cast<const ObjCImplementationDecl>(DC)) {
140      OS << OID->getName();
141   } else if (const ObjCInterfaceDecl *OID =
142              dyn_cast<const ObjCInterfaceDecl>(DC)) {
143       OS << OID->getName();
144   } else if (const ObjCCategoryImplDecl *OCD =
145              dyn_cast<const ObjCCategoryImplDecl>(DC)){
146       OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
147           OCD->getIdentifier()->getNameStart() << ')';
148   }
149   OS << ' ' << OMD->getSelector().getAsString() << ']';
150 
151   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
152   memcpy(StrPtr, MethodName.begin(), OS.tell());
153   return StringRef(StrPtr, OS.tell());
154 }
155 
156 /// getSelectorName - Return selector name. This is used for debugging
157 /// info.
158 StringRef CGDebugInfo::getSelectorName(Selector S) {
159   const std::string &SName = S.getAsString();
160   char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
161   memcpy(StrPtr, SName.data(), SName.size());
162   return StringRef(StrPtr, SName.size());
163 }
164 
165 /// getClassName - Get class name including template argument list.
166 StringRef
167 CGDebugInfo::getClassName(RecordDecl *RD) {
168   ClassTemplateSpecializationDecl *Spec
169     = dyn_cast<ClassTemplateSpecializationDecl>(RD);
170   if (!Spec)
171     return RD->getName();
172 
173   const TemplateArgument *Args;
174   unsigned NumArgs;
175   std::string Buffer;
176   if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
177     const TemplateSpecializationType *TST =
178       cast<TemplateSpecializationType>(TAW->getType());
179     Args = TST->getArgs();
180     NumArgs = TST->getNumArgs();
181   } else {
182     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
183     Args = TemplateArgs.data();
184     NumArgs = TemplateArgs.size();
185   }
186   Buffer = RD->getIdentifier()->getNameStart();
187   PrintingPolicy Policy(CGM.getLangOptions());
188   Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
189                                                                   NumArgs,
190                                                                   Policy);
191 
192   // Copy this name on the side and use its reference.
193   char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
194   memcpy(StrPtr, Buffer.data(), Buffer.length());
195   return StringRef(StrPtr, Buffer.length());
196 }
197 
198 /// getOrCreateFile - Get the file debug info descriptor for the input location.
199 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
200   if (!Loc.isValid())
201     // If Location is not valid then use main input file.
202     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
203 
204   SourceManager &SM = CGM.getContext().getSourceManager();
205   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
206 
207   if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
208     // If the location is not valid then use main input file.
209     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
210 
211   // Cache the results.
212   const char *fname = PLoc.getFilename();
213   llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
214     DIFileCache.find(fname);
215 
216   if (it != DIFileCache.end()) {
217     // Verify that the information still exists.
218     if (&*it->second)
219       return llvm::DIFile(cast<llvm::MDNode>(it->second));
220   }
221 
222   llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
223 
224   DIFileCache[fname] = F;
225   return F;
226 }
227 
228 /// getOrCreateMainFile - Get the file info for main compile unit.
229 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
230   return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
231 }
232 
233 /// getLineNumber - Get line number for the location. If location is invalid
234 /// then use current location.
235 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
236   assert((Loc.isValid() || CurLoc.isValid()) && "Invalid current location!");
237   SourceManager &SM = CGM.getContext().getSourceManager();
238   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
239   return PLoc.isValid()? PLoc.getLine() : 0;
240 }
241 
242 /// getColumnNumber - Get column number for the location. If location is
243 /// invalid then use current location.
244 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
245   assert((Loc.isValid() || CurLoc.isValid()) && "Invalid current location!");
246   SourceManager &SM = CGM.getContext().getSourceManager();
247   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
248   return PLoc.isValid()? PLoc.getColumn() : 0;
249 }
250 
251 StringRef CGDebugInfo::getCurrentDirname() {
252   if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
253     return CGM.getCodeGenOpts().DebugCompilationDir;
254 
255   if (!CWDName.empty())
256     return CWDName;
257   llvm::SmallString<256> CWD;
258   llvm::sys::fs::current_path(CWD);
259   char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
260   memcpy(CompDirnamePtr, CWD.data(), CWD.size());
261   return CWDName = StringRef(CompDirnamePtr, CWD.size());
262 }
263 
264 /// CreateCompileUnit - Create new compile unit.
265 void CGDebugInfo::CreateCompileUnit() {
266 
267   // Get absolute path name.
268   SourceManager &SM = CGM.getContext().getSourceManager();
269   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
270   if (MainFileName.empty())
271     MainFileName = "<unknown>";
272 
273   // The main file name provided via the "-main-file-name" option contains just
274   // the file name itself with no path information. This file name may have had
275   // a relative path, so we look into the actual file entry for the main
276   // file to determine the real absolute path for the file.
277   std::string MainFileDir;
278   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
279     MainFileDir = MainFile->getDir()->getName();
280     if (MainFileDir != ".")
281       MainFileName = MainFileDir + "/" + MainFileName;
282   }
283 
284   // Save filename string.
285   char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
286   memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
287   StringRef Filename(FilenamePtr, MainFileName.length());
288 
289   unsigned LangTag;
290   const LangOptions &LO = CGM.getLangOptions();
291   if (LO.CPlusPlus) {
292     if (LO.ObjC1)
293       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
294     else
295       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
296   } else if (LO.ObjC1) {
297     LangTag = llvm::dwarf::DW_LANG_ObjC;
298   } else if (LO.C99) {
299     LangTag = llvm::dwarf::DW_LANG_C99;
300   } else {
301     LangTag = llvm::dwarf::DW_LANG_C89;
302   }
303 
304   std::string Producer = getClangFullVersion();
305 
306   // Figure out which version of the ObjC runtime we have.
307   unsigned RuntimeVers = 0;
308   if (LO.ObjC1)
309     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
310 
311   // Create new compile unit.
312   DBuilder.createCompileUnit(
313     LangTag, Filename, getCurrentDirname(),
314     Producer,
315     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
316   // FIXME - Eliminate TheCU.
317   TheCU = llvm::DICompileUnit(DBuilder.getCU());
318 }
319 
320 /// CreateType - Get the Basic type from the cache or create a new
321 /// one if necessary.
322 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
323   unsigned Encoding = 0;
324   const char *BTName = NULL;
325   switch (BT->getKind()) {
326 #define BUILTIN_TYPE(Id, SingletonId)
327 #define PLACEHOLDER_TYPE(Id, SingletonId) \
328   case BuiltinType::Id:
329 #include "clang/AST/BuiltinTypes.def"
330   case BuiltinType::Dependent:
331     llvm_unreachable("Unexpected builtin type");
332   case BuiltinType::NullPtr:
333     return DBuilder.
334       createNullPtrType(BT->getName(CGM.getContext().getLangOptions()));
335   case BuiltinType::Void:
336     return llvm::DIType();
337   case BuiltinType::ObjCClass:
338     return DBuilder.createStructType(TheCU, "objc_class",
339                                      getOrCreateMainFile(), 0, 0, 0,
340                                      llvm::DIDescriptor::FlagFwdDecl,
341                                      llvm::DIArray());
342   case BuiltinType::ObjCId: {
343     // typedef struct objc_class *Class;
344     // typedef struct objc_object {
345     //  Class isa;
346     // } *id;
347 
348     llvm::DIType OCTy =
349       DBuilder.createStructType(TheCU, "objc_class",
350                                 getOrCreateMainFile(), 0, 0, 0,
351                                 llvm::DIDescriptor::FlagFwdDecl,
352                                 llvm::DIArray());
353     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
354 
355     llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
356 
357     SmallVector<llvm::Value *, 16> EltTys;
358     llvm::DIType FieldTy =
359       DBuilder.createMemberType(getOrCreateMainFile(), "isa",
360                                 getOrCreateMainFile(), 0, Size,
361                                 0, 0, 0, ISATy);
362     EltTys.push_back(FieldTy);
363     llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
364 
365     return DBuilder.createStructType(TheCU, "objc_object",
366                                      getOrCreateMainFile(),
367                                      0, 0, 0, 0, Elements);
368   }
369   case BuiltinType::ObjCSel: {
370     return  DBuilder.createStructType(TheCU, "objc_selector",
371                                       getOrCreateMainFile(), 0, 0, 0,
372                                       llvm::DIDescriptor::FlagFwdDecl,
373                                       llvm::DIArray());
374   }
375   case BuiltinType::UChar:
376   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
377   case BuiltinType::Char_S:
378   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
379   case BuiltinType::Char16:
380   case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
381   case BuiltinType::UShort:
382   case BuiltinType::UInt:
383   case BuiltinType::UInt128:
384   case BuiltinType::ULong:
385   case BuiltinType::WChar_U:
386   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
387   case BuiltinType::Short:
388   case BuiltinType::Int:
389   case BuiltinType::Int128:
390   case BuiltinType::Long:
391   case BuiltinType::WChar_S:
392   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
393   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
394   case BuiltinType::Half:
395   case BuiltinType::Float:
396   case BuiltinType::LongDouble:
397   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
398   }
399 
400   switch (BT->getKind()) {
401   case BuiltinType::Long:      BTName = "long int"; break;
402   case BuiltinType::LongLong:  BTName = "long long int"; break;
403   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
404   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
405   default:
406     BTName = BT->getName(CGM.getContext().getLangOptions());
407     break;
408   }
409   // Bit size, align and offset of the type.
410   uint64_t Size = CGM.getContext().getTypeSize(BT);
411   uint64_t Align = CGM.getContext().getTypeAlign(BT);
412   llvm::DIType DbgTy =
413     DBuilder.createBasicType(BTName, Size, Align, Encoding);
414   return DbgTy;
415 }
416 
417 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
418   // Bit size, align and offset of the type.
419   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
420   if (Ty->isComplexIntegerType())
421     Encoding = llvm::dwarf::DW_ATE_lo_user;
422 
423   uint64_t Size = CGM.getContext().getTypeSize(Ty);
424   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
425   llvm::DIType DbgTy =
426     DBuilder.createBasicType("complex", Size, Align, Encoding);
427 
428   return DbgTy;
429 }
430 
431 /// CreateCVRType - Get the qualified type from the cache or create
432 /// a new one if necessary.
433 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
434   QualifierCollector Qc;
435   const Type *T = Qc.strip(Ty);
436 
437   // Ignore these qualifiers for now.
438   Qc.removeObjCGCAttr();
439   Qc.removeAddressSpace();
440   Qc.removeObjCLifetime();
441 
442   // We will create one Derived type for one qualifier and recurse to handle any
443   // additional ones.
444   unsigned Tag;
445   if (Qc.hasConst()) {
446     Tag = llvm::dwarf::DW_TAG_const_type;
447     Qc.removeConst();
448   } else if (Qc.hasVolatile()) {
449     Tag = llvm::dwarf::DW_TAG_volatile_type;
450     Qc.removeVolatile();
451   } else if (Qc.hasRestrict()) {
452     Tag = llvm::dwarf::DW_TAG_restrict_type;
453     Qc.removeRestrict();
454   } else {
455     assert(Qc.empty() && "Unknown type qualifier for debug info");
456     return getOrCreateType(QualType(T, 0), Unit);
457   }
458 
459   llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
460 
461   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
462   // CVR derived types.
463   llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
464 
465   return DbgTy;
466 }
467 
468 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
469                                      llvm::DIFile Unit) {
470   llvm::DIType DbgTy =
471     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
472                           Ty->getPointeeType(), Unit);
473   return DbgTy;
474 }
475 
476 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
477                                      llvm::DIFile Unit) {
478   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
479                                Ty->getPointeeType(), Unit);
480 }
481 
482 /// CreatePointeeType - Create Pointee type. If Pointee is a record
483 /// then emit record's fwd if debug info size reduction is enabled.
484 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
485                                             llvm::DIFile Unit) {
486   if (!CGM.getCodeGenOpts().LimitDebugInfo)
487     return getOrCreateType(PointeeTy, Unit);
488 
489   // Limit debug info for the pointee type.
490 
491   // Handle qualifiers.
492   if (PointeeTy.hasLocalQualifiers())
493     return CreateQualifiedType(PointeeTy, Unit);
494 
495   if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
496     RecordDecl *RD = RTy->getDecl();
497     llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
498     unsigned Line = getLineNumber(RD->getLocation());
499     llvm::DIDescriptor FDContext =
500       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
501 
502     if (RD->isStruct())
503       return DBuilder.createStructType(FDContext, RD->getName(), DefUnit,
504                                        Line, 0, 0, llvm::DIType::FlagFwdDecl,
505                                        llvm::DIArray());
506     else if (RD->isUnion())
507       return DBuilder.createUnionType(FDContext, RD->getName(), DefUnit,
508                                       Line, 0, 0, llvm::DIType::FlagFwdDecl,
509                                       llvm::DIArray());
510     else {
511       assert(RD->isClass() && "Unknown RecordType!");
512       return DBuilder.createClassType(FDContext, RD->getName(), DefUnit,
513                                       Line, 0, 0, 0, llvm::DIType::FlagFwdDecl,
514                                       llvm::DIType(), llvm::DIArray());
515     }
516   }
517   return getOrCreateType(PointeeTy, Unit);
518 
519 }
520 
521 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
522                                                 const Type *Ty,
523                                                 QualType PointeeTy,
524                                                 llvm::DIFile Unit) {
525   if (Tag == llvm::dwarf::DW_TAG_reference_type)
526     return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit));
527 
528   // Bit size, align and offset of the type.
529   // Size is always the size of a pointer. We can't use getTypeSize here
530   // because that does not return the correct value for references.
531   unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
532   uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
533   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
534 
535   return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
536                                     Size, Align);
537 }
538 
539 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
540                                      llvm::DIFile Unit) {
541   if (BlockLiteralGenericSet)
542     return BlockLiteralGeneric;
543 
544   SmallVector<llvm::Value *, 8> EltTys;
545   llvm::DIType FieldTy;
546   QualType FType;
547   uint64_t FieldSize, FieldOffset;
548   unsigned FieldAlign;
549   llvm::DIArray Elements;
550   llvm::DIType EltTy, DescTy;
551 
552   FieldOffset = 0;
553   FType = CGM.getContext().UnsignedLongTy;
554   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
555   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
556 
557   Elements = DBuilder.getOrCreateArray(EltTys);
558   EltTys.clear();
559 
560   unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
561   unsigned LineNo = getLineNumber(CurLoc);
562 
563   EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
564                                     Unit, LineNo, FieldOffset, 0,
565                                     Flags, Elements);
566 
567   // Bit size, align and offset of the type.
568   uint64_t Size = CGM.getContext().getTypeSize(Ty);
569 
570   DescTy = DBuilder.createPointerType(EltTy, Size);
571 
572   FieldOffset = 0;
573   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
574   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
575   FType = CGM.getContext().IntTy;
576   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
577   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
578   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
579   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
580 
581   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
582   FieldTy = DescTy;
583   FieldSize = CGM.getContext().getTypeSize(Ty);
584   FieldAlign = CGM.getContext().getTypeAlign(Ty);
585   FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
586                                       LineNo, FieldSize, FieldAlign,
587                                       FieldOffset, 0, FieldTy);
588   EltTys.push_back(FieldTy);
589 
590   FieldOffset += FieldSize;
591   Elements = DBuilder.getOrCreateArray(EltTys);
592 
593   EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
594                                     Unit, LineNo, FieldOffset, 0,
595                                     Flags, Elements);
596 
597   BlockLiteralGenericSet = true;
598   BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
599   return BlockLiteralGeneric;
600 }
601 
602 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
603   // Typedefs are derived from some other type.  If we have a typedef of a
604   // typedef, make sure to emit the whole chain.
605   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
606   if (!Src.Verify())
607     return llvm::DIType();
608   // We don't set size information, but do specify where the typedef was
609   // declared.
610   unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
611   const TypedefNameDecl *TyDecl = Ty->getDecl();
612   llvm::DIDescriptor TypedefContext =
613     getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
614 
615   return
616     DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
617 }
618 
619 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
620                                      llvm::DIFile Unit) {
621   SmallVector<llvm::Value *, 16> EltTys;
622 
623   // Add the result type at least.
624   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
625 
626   // Set up remainder of arguments if there is a prototype.
627   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
628   if (isa<FunctionNoProtoType>(Ty))
629     EltTys.push_back(DBuilder.createUnspecifiedParameter());
630   else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
631     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
632       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
633   }
634 
635   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
636 
637   llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray);
638   return DbgTy;
639 }
640 
641 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
642                                           QualType type,
643                                           uint64_t sizeInBitsOverride,
644                                           SourceLocation loc,
645                                           AccessSpecifier AS,
646                                           uint64_t offsetInBits,
647                                           llvm::DIFile tunit,
648                                           llvm::DIDescriptor scope) {
649   llvm::DIType debugType = getOrCreateType(type, tunit);
650 
651   // Get the location for the field.
652   llvm::DIFile file = getOrCreateFile(loc);
653   unsigned line = getLineNumber(loc);
654 
655   uint64_t sizeInBits = 0;
656   unsigned alignInBits = 0;
657   if (!type->isIncompleteArrayType()) {
658     llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
659 
660     if (sizeInBitsOverride)
661       sizeInBits = sizeInBitsOverride;
662   }
663 
664   unsigned flags = 0;
665   if (AS == clang::AS_private)
666     flags |= llvm::DIDescriptor::FlagPrivate;
667   else if (AS == clang::AS_protected)
668     flags |= llvm::DIDescriptor::FlagProtected;
669 
670   return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
671                                    alignInBits, offsetInBits, flags, debugType);
672 }
673 
674 /// CollectRecordFields - A helper function to collect debug info for
675 /// record fields. This is used while creating debug info entry for a Record.
676 void CGDebugInfo::
677 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
678                     SmallVectorImpl<llvm::Value *> &elements,
679                     llvm::DIType RecordTy) {
680   unsigned fieldNo = 0;
681   const FieldDecl *LastFD = 0;
682   bool IsMsStruct = record->hasAttr<MsStructAttr>();
683 
684   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
685   for (RecordDecl::field_iterator I = record->field_begin(),
686                                   E = record->field_end();
687        I != E; ++I, ++fieldNo) {
688     FieldDecl *field = *I;
689     if (IsMsStruct) {
690       // Zero-length bitfields following non-bitfield members are ignored
691       if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
692         --fieldNo;
693         continue;
694       }
695       LastFD = field;
696     }
697 
698     StringRef name = field->getName();
699     QualType type = field->getType();
700 
701     // Ignore unnamed fields unless they're anonymous structs/unions.
702     if (name.empty() && !type->isRecordType()) {
703       LastFD = field;
704       continue;
705     }
706 
707     uint64_t SizeInBitsOverride = 0;
708     if (field->isBitField()) {
709       SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
710       assert(SizeInBitsOverride && "found named 0-width bitfield");
711     }
712 
713     llvm::DIType fieldType
714       = createFieldType(name, type, SizeInBitsOverride,
715                         field->getLocation(), field->getAccess(),
716                         layout.getFieldOffset(fieldNo), tunit, RecordTy);
717 
718     elements.push_back(fieldType);
719   }
720 }
721 
722 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
723 /// function type is not updated to include implicit "this" pointer. Use this
724 /// routine to get a method type which includes "this" pointer.
725 llvm::DIType
726 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
727                                    llvm::DIFile Unit) {
728   llvm::DIType FnTy
729     = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
730                                0),
731                       Unit);
732 
733   // Add "this" pointer.
734   llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
735   assert (Args.getNumElements() && "Invalid number of arguments!");
736 
737   SmallVector<llvm::Value *, 16> Elts;
738 
739   // First element is always return type. For 'void' functions it is NULL.
740   Elts.push_back(Args.getElement(0));
741 
742   if (!Method->isStatic()) {
743     // "this" pointer is always first argument.
744     QualType ThisPtr = Method->getThisType(CGM.getContext());
745 
746     const CXXRecordDecl *RD = Method->getParent();
747     if (isa<ClassTemplateSpecializationDecl>(RD)) {
748       // Create pointer type directly in this case.
749       const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
750       QualType PointeeTy = ThisPtrTy->getPointeeType();
751       unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
752       uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
753       uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
754       llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
755       llvm::DIType ThisPtrType =
756         DBuilder.createArtificialType
757         (DBuilder.createPointerType(PointeeType, Size, Align));
758       TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
759       Elts.push_back(ThisPtrType);
760     } else {
761       llvm::DIType ThisPtrType =
762         DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit));
763       TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
764       Elts.push_back(ThisPtrType);
765     }
766   }
767 
768   // Copy rest of the arguments.
769   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
770     Elts.push_back(Args.getElement(i));
771 
772   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
773 
774   return DBuilder.createSubroutineType(Unit, EltTypeArray);
775 }
776 
777 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
778 /// inside a function.
779 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
780   if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
781     return isFunctionLocalClass(NRD);
782   if (isa<FunctionDecl>(RD->getDeclContext()))
783     return true;
784   return false;
785 }
786 
787 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
788 /// a single member function GlobalDecl.
789 llvm::DISubprogram
790 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
791                                      llvm::DIFile Unit,
792                                      llvm::DIType RecordTy) {
793   bool IsCtorOrDtor =
794     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
795 
796   StringRef MethodName = getFunctionName(Method);
797   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
798 
799   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
800   // make sense to give a single ctor/dtor a linkage name.
801   StringRef MethodLinkageName;
802   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
803     MethodLinkageName = CGM.getMangledName(Method);
804 
805   // Get the location for the method.
806   llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
807   unsigned MethodLine = getLineNumber(Method->getLocation());
808 
809   // Collect virtual method info.
810   llvm::DIType ContainingType;
811   unsigned Virtuality = 0;
812   unsigned VIndex = 0;
813 
814   if (Method->isVirtual()) {
815     if (Method->isPure())
816       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
817     else
818       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
819 
820     // It doesn't make sense to give a virtual destructor a vtable index,
821     // since a single destructor has two entries in the vtable.
822     if (!isa<CXXDestructorDecl>(Method))
823       VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
824     ContainingType = RecordTy;
825   }
826 
827   unsigned Flags = 0;
828   if (Method->isImplicit())
829     Flags |= llvm::DIDescriptor::FlagArtificial;
830   AccessSpecifier Access = Method->getAccess();
831   if (Access == clang::AS_private)
832     Flags |= llvm::DIDescriptor::FlagPrivate;
833   else if (Access == clang::AS_protected)
834     Flags |= llvm::DIDescriptor::FlagProtected;
835   if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
836     if (CXXC->isExplicit())
837       Flags |= llvm::DIDescriptor::FlagExplicit;
838   } else if (const CXXConversionDecl *CXXC =
839              dyn_cast<CXXConversionDecl>(Method)) {
840     if (CXXC->isExplicit())
841       Flags |= llvm::DIDescriptor::FlagExplicit;
842   }
843   if (Method->hasPrototype())
844     Flags |= llvm::DIDescriptor::FlagPrototyped;
845 
846   llvm::DISubprogram SP =
847     DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
848                           MethodDefUnit, MethodLine,
849                           MethodTy, /*isLocalToUnit=*/false,
850                           /* isDefinition=*/ false,
851                           Virtuality, VIndex, ContainingType,
852                           Flags, CGM.getLangOptions().Optimize);
853 
854   SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
855 
856   return SP;
857 }
858 
859 /// CollectCXXMemberFunctions - A helper function to collect debug info for
860 /// C++ member functions.This is used while creating debug info entry for
861 /// a Record.
862 void CGDebugInfo::
863 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
864                           SmallVectorImpl<llvm::Value *> &EltTys,
865                           llvm::DIType RecordTy) {
866   for(CXXRecordDecl::method_iterator I = RD->method_begin(),
867         E = RD->method_end(); I != E; ++I) {
868     const CXXMethodDecl *Method = *I;
869 
870     if (Method->isImplicit() && !Method->isUsed())
871       continue;
872 
873     EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
874   }
875 }
876 
877 /// CollectCXXFriends - A helper function to collect debug info for
878 /// C++ base classes. This is used while creating debug info entry for
879 /// a Record.
880 void CGDebugInfo::
881 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
882                 SmallVectorImpl<llvm::Value *> &EltTys,
883                 llvm::DIType RecordTy) {
884   for (CXXRecordDecl::friend_iterator BI =  RD->friend_begin(),
885          BE = RD->friend_end(); BI != BE; ++BI) {
886     if ((*BI)->isUnsupportedFriend())
887       continue;
888     if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
889       EltTys.push_back(DBuilder.createFriend(RecordTy,
890                                              getOrCreateType(TInfo->getType(),
891                                                              Unit)));
892   }
893 }
894 
895 /// CollectCXXBases - A helper function to collect debug info for
896 /// C++ base classes. This is used while creating debug info entry for
897 /// a Record.
898 void CGDebugInfo::
899 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
900                 SmallVectorImpl<llvm::Value *> &EltTys,
901                 llvm::DIType RecordTy) {
902 
903   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
904   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
905          BE = RD->bases_end(); BI != BE; ++BI) {
906     unsigned BFlags = 0;
907     uint64_t BaseOffset;
908 
909     const CXXRecordDecl *Base =
910       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
911 
912     if (BI->isVirtual()) {
913       // virtual base offset offset is -ve. The code generator emits dwarf
914       // expression where it expects +ve number.
915       BaseOffset =
916         0 - CGM.getVTableContext()
917                .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
918       BFlags = llvm::DIDescriptor::FlagVirtual;
919     } else
920       BaseOffset = RL.getBaseClassOffsetInBits(Base);
921     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
922     // BI->isVirtual() and bits when not.
923 
924     AccessSpecifier Access = BI->getAccessSpecifier();
925     if (Access == clang::AS_private)
926       BFlags |= llvm::DIDescriptor::FlagPrivate;
927     else if (Access == clang::AS_protected)
928       BFlags |= llvm::DIDescriptor::FlagProtected;
929 
930     llvm::DIType DTy =
931       DBuilder.createInheritance(RecordTy,
932                                  getOrCreateType(BI->getType(), Unit),
933                                  BaseOffset, BFlags);
934     EltTys.push_back(DTy);
935   }
936 }
937 
938 /// CollectTemplateParams - A helper function to collect template parameters.
939 llvm::DIArray CGDebugInfo::
940 CollectTemplateParams(const TemplateParameterList *TPList,
941                       const TemplateArgumentList &TAList,
942                       llvm::DIFile Unit) {
943   SmallVector<llvm::Value *, 16> TemplateParams;
944   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
945     const TemplateArgument &TA = TAList[i];
946     const NamedDecl *ND = TPList->getParam(i);
947     if (TA.getKind() == TemplateArgument::Type) {
948       llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
949       llvm::DITemplateTypeParameter TTP =
950         DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
951       TemplateParams.push_back(TTP);
952     } else if (TA.getKind() == TemplateArgument::Integral) {
953       llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
954       llvm::DITemplateValueParameter TVP =
955         DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
956                                           TA.getAsIntegral()->getZExtValue());
957       TemplateParams.push_back(TVP);
958     }
959   }
960   return DBuilder.getOrCreateArray(TemplateParams);
961 }
962 
963 /// CollectFunctionTemplateParams - A helper function to collect debug
964 /// info for function template parameters.
965 llvm::DIArray CGDebugInfo::
966 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
967   if (FD->getTemplatedKind() ==
968       FunctionDecl::TK_FunctionTemplateSpecialization) {
969     const TemplateParameterList *TList =
970       FD->getTemplateSpecializationInfo()->getTemplate()
971       ->getTemplateParameters();
972     return
973       CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
974   }
975   return llvm::DIArray();
976 }
977 
978 /// CollectCXXTemplateParams - A helper function to collect debug info for
979 /// template parameters.
980 llvm::DIArray CGDebugInfo::
981 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
982                          llvm::DIFile Unit) {
983   llvm::PointerUnion<ClassTemplateDecl *,
984                      ClassTemplatePartialSpecializationDecl *>
985     PU = TSpecial->getSpecializedTemplateOrPartial();
986 
987   TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
988     PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
989     PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
990   const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
991   return CollectTemplateParams(TPList, TAList, Unit);
992 }
993 
994 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
995 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
996   if (VTablePtrType.isValid())
997     return VTablePtrType;
998 
999   ASTContext &Context = CGM.getContext();
1000 
1001   /* Function type */
1002   llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1003   llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1004   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1005   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1006   llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1007                                                           "__vtbl_ptr_type");
1008   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1009   return VTablePtrType;
1010 }
1011 
1012 /// getVTableName - Get vtable name for the given Class.
1013 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1014   // Otherwise construct gdb compatible name name.
1015   std::string Name = "_vptr$" + RD->getNameAsString();
1016 
1017   // Copy this name on the side and use its reference.
1018   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1019   memcpy(StrPtr, Name.data(), Name.length());
1020   return StringRef(StrPtr, Name.length());
1021 }
1022 
1023 
1024 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1025 /// debug info entry in EltTys vector.
1026 void CGDebugInfo::
1027 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1028                   SmallVectorImpl<llvm::Value *> &EltTys) {
1029   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1030 
1031   // If there is a primary base then it will hold vtable info.
1032   if (RL.getPrimaryBase())
1033     return;
1034 
1035   // If this class is not dynamic then there is not any vtable info to collect.
1036   if (!RD->isDynamicClass())
1037     return;
1038 
1039   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1040   llvm::DIType VPTR
1041     = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1042                                 0, Size, 0, 0, 0,
1043                                 getOrCreateVTablePtrType(Unit));
1044   EltTys.push_back(VPTR);
1045 }
1046 
1047 /// getOrCreateRecordType - Emit record type's standalone debug info.
1048 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1049                                                 SourceLocation Loc) {
1050   llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1051   DBuilder.retainType(T);
1052   return T;
1053 }
1054 
1055 /// CreateType - get structure or union type.
1056 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1057   RecordDecl *RD = Ty->getDecl();
1058   llvm::DIFile Unit = getOrCreateFile(RD->getLocation());
1059 
1060   // Get overall information about the record type for the debug info.
1061   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1062   unsigned Line = getLineNumber(RD->getLocation());
1063 
1064   // Records and classes and unions can all be recursive.  To handle them, we
1065   // first generate a debug descriptor for the struct as a forward declaration.
1066   // Then (if it is a definition) we go through and get debug info for all of
1067   // its members.  Finally, we create a descriptor for the complete type (which
1068   // may refer to the forward decl if the struct is recursive) and replace all
1069   // uses of the forward declaration with the final definition.
1070   llvm::DIDescriptor FDContext =
1071     getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1072 
1073   // If this is just a forward declaration, construct an appropriately
1074   // marked node and just return it.
1075   if (!RD->getDefinition()) {
1076     llvm::DIType FwdDecl =
1077       DBuilder.createStructType(FDContext, RD->getName(),
1078                                 DefUnit, Line, 0, 0,
1079                                 llvm::DIDescriptor::FlagFwdDecl,
1080                                 llvm::DIArray());
1081 
1082       return FwdDecl;
1083   }
1084 
1085   llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1086 
1087   llvm::MDNode *MN = FwdDecl;
1088   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1089   // Otherwise, insert it into the TypeCache so that recursive uses will find
1090   // it.
1091   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1092   // Push the struct on region stack.
1093   LexicalBlockStack.push_back(FwdDeclNode);
1094   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1095 
1096   // Convert all the elements.
1097   SmallVector<llvm::Value *, 16> EltTys;
1098 
1099   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1100   if (CXXDecl) {
1101     CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
1102     CollectVTableInfo(CXXDecl, Unit, EltTys);
1103   }
1104 
1105   // Collect static variables with initializers.
1106   for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
1107        I != E; ++I)
1108     if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
1109       if (const Expr *Init = V->getInit()) {
1110         Expr::EvalResult Result;
1111         if (Init->EvaluateAsRValue(Result, CGM.getContext()) &&
1112             Result.Val.isInt()) {
1113           llvm::ConstantInt *CI
1114             = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt());
1115 
1116           // Create the descriptor for static variable.
1117           llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
1118           StringRef VName = V->getName();
1119           llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
1120           // Do not use DIGlobalVariable for enums.
1121           if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
1122             DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
1123                                           getLineNumber(V->getLocation()),
1124                                           VTy, true, CI);
1125           }
1126         }
1127       }
1128     }
1129 
1130   CollectRecordFields(RD, Unit, EltTys, FwdDecl);
1131   llvm::DIArray TParamsArray;
1132   if (CXXDecl) {
1133     CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
1134     CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
1135     if (const ClassTemplateSpecializationDecl *TSpecial
1136         = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1137       TParamsArray = CollectCXXTemplateParams(TSpecial, Unit);
1138   }
1139 
1140   LexicalBlockStack.pop_back();
1141   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1142     RegionMap.find(Ty->getDecl());
1143   if (RI != RegionMap.end())
1144     RegionMap.erase(RI);
1145 
1146   llvm::DIDescriptor RDContext =
1147     getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1148   StringRef RDName = RD->getName();
1149   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1150   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1151   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1152   llvm::MDNode *RealDecl = NULL;
1153 
1154   if (RD->isUnion())
1155     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1156                                         Size, Align, 0, Elements);
1157   else if (CXXDecl) {
1158     RDName = getClassName(RD);
1159      // A class's primary base or the class itself contains the vtable.
1160     llvm::MDNode *ContainingType = NULL;
1161     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1162     if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1163       // Seek non virtual primary base root.
1164       while (1) {
1165         const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1166         const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1167         if (PBT && !BRL.isPrimaryBaseVirtual())
1168           PBase = PBT;
1169         else
1170           break;
1171       }
1172       ContainingType =
1173         getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
1174     }
1175     else if (CXXDecl->isDynamicClass())
1176       ContainingType = FwdDecl;
1177 
1178    RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1179                                        Size, Align, 0, 0, llvm::DIType(),
1180                                        Elements, ContainingType,
1181                                        TParamsArray);
1182   } else
1183     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1184                                          Size, Align, 0, Elements);
1185 
1186   // Now that we have a real decl for the struct, replace anything using the
1187   // old decl with the new one.  This will recursively update the debug info.
1188   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1189   RegionMap[RD] = llvm::WeakVH(RealDecl);
1190   return llvm::DIType(RealDecl);
1191 }
1192 
1193 /// CreateType - get objective-c object type.
1194 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1195                                      llvm::DIFile Unit) {
1196   // Ignore protocols.
1197   return getOrCreateType(Ty->getBaseType(), Unit);
1198 }
1199 
1200 /// CreateType - get objective-c interface type.
1201 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1202                                      llvm::DIFile Unit) {
1203   ObjCInterfaceDecl *ID = Ty->getDecl();
1204   if (!ID)
1205     return llvm::DIType();
1206 
1207   // Get overall information about the record type for the debug info.
1208   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1209   unsigned Line = getLineNumber(ID->getLocation());
1210   unsigned RuntimeLang = TheCU.getLanguage();
1211 
1212   // If this is just a forward declaration return a special forward-declaration
1213   // debug type since we won't be able to lay out the entire type.
1214   if (ID->isForwardDecl()) {
1215     llvm::DIType FwdDecl =
1216       DBuilder.createStructType(Unit, ID->getName(),
1217                                 DefUnit, Line, 0, 0,
1218                                 llvm::DIDescriptor::FlagFwdDecl,
1219                                 llvm::DIArray(), RuntimeLang);
1220     return FwdDecl;
1221   }
1222 
1223   // To handle a recursive interface, we first generate a debug descriptor
1224   // for the struct as a forward declaration. Then (if it is a definition)
1225   // we go through and get debug info for all of its members.  Finally, we
1226   // create a descriptor for the complete type (which may refer to the
1227   // forward decl if the struct is recursive) and replace all uses of the
1228   // forward declaration with the final definition.
1229   llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1230 
1231   llvm::MDNode *MN = FwdDecl;
1232   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1233   // Otherwise, insert it into the TypeCache so that recursive uses will find
1234   // it.
1235   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1236   // Push the struct on region stack.
1237   LexicalBlockStack.push_back(FwdDeclNode);
1238   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1239 
1240   // Convert all the elements.
1241   SmallVector<llvm::Value *, 16> EltTys;
1242 
1243   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1244   if (SClass) {
1245     llvm::DIType SClassTy =
1246       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1247     if (!SClassTy.isValid())
1248       return llvm::DIType();
1249 
1250     llvm::DIType InhTag =
1251       DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0);
1252     EltTys.push_back(InhTag);
1253   }
1254 
1255   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1256   ObjCImplementationDecl *ImpD = ID->getImplementation();
1257   unsigned FieldNo = 0;
1258   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1259        Field = Field->getNextIvar(), ++FieldNo) {
1260     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1261     if (!FieldTy.isValid())
1262       return llvm::DIType();
1263 
1264     StringRef FieldName = Field->getName();
1265 
1266     // Ignore unnamed fields.
1267     if (FieldName.empty())
1268       continue;
1269 
1270     // Get the location for the field.
1271     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1272     unsigned FieldLine = getLineNumber(Field->getLocation());
1273     QualType FType = Field->getType();
1274     uint64_t FieldSize = 0;
1275     unsigned FieldAlign = 0;
1276 
1277     if (!FType->isIncompleteArrayType()) {
1278 
1279       // Bit size, align and offset of the type.
1280       FieldSize = Field->isBitField()
1281         ? Field->getBitWidthValue(CGM.getContext())
1282         : CGM.getContext().getTypeSize(FType);
1283       FieldAlign = CGM.getContext().getTypeAlign(FType);
1284     }
1285 
1286     // We can't know the offset of our ivar in the structure if we're using
1287     // the non-fragile abi and the debugger should ignore the value anyways.
1288     // Call it the FieldNo+1 due to how debuggers use the information,
1289     // e.g. negating the value when it needs a lookup in the dynamic table.
1290     uint64_t FieldOffset = CGM.getLangOptions().ObjCNonFragileABI ? FieldNo+1
1291       : RL.getFieldOffset(FieldNo);
1292 
1293     unsigned Flags = 0;
1294     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1295       Flags = llvm::DIDescriptor::FlagProtected;
1296     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1297       Flags = llvm::DIDescriptor::FlagPrivate;
1298 
1299     StringRef PropertyName;
1300     StringRef PropertyGetter;
1301     StringRef PropertySetter;
1302     unsigned PropertyAttributes = 0;
1303     ObjCPropertyDecl *PD = NULL;
1304     if (ImpD)
1305       if (ObjCPropertyImplDecl *PImpD =
1306           ImpD->FindPropertyImplIvarDecl(Field->getIdentifier()))
1307         PD = PImpD->getPropertyDecl();
1308     if (PD) {
1309       PropertyName = PD->getName();
1310       PropertyGetter = getSelectorName(PD->getGetterName());
1311       PropertySetter = getSelectorName(PD->getSetterName());
1312       PropertyAttributes = PD->getPropertyAttributes();
1313     }
1314     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1315                                       FieldLine, FieldSize, FieldAlign,
1316                                       FieldOffset, Flags, FieldTy,
1317                                       PropertyName, PropertyGetter,
1318                                       PropertySetter, PropertyAttributes);
1319     EltTys.push_back(FieldTy);
1320   }
1321 
1322   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1323 
1324   LexicalBlockStack.pop_back();
1325   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1326     RegionMap.find(Ty->getDecl());
1327   if (RI != RegionMap.end())
1328     RegionMap.erase(RI);
1329 
1330   // Bit size, align and offset of the type.
1331   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1332   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1333 
1334   unsigned Flags = 0;
1335   if (ID->getImplementation())
1336     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1337 
1338   llvm::DIType RealDecl =
1339     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1340                                   Line, Size, Align, Flags,
1341                                   Elements, RuntimeLang);
1342 
1343   // Now that we have a real decl for the struct, replace anything using the
1344   // old decl with the new one.  This will recursively update the debug info.
1345   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1346   RegionMap[ID] = llvm::WeakVH(RealDecl);
1347 
1348   return RealDecl;
1349 }
1350 
1351 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1352   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1353   int64_t NumElems = Ty->getNumElements();
1354   int64_t LowerBound = 0;
1355   if (NumElems == 0)
1356     // If number of elements are not known then this is an unbounded array.
1357     // Use Low = 1, Hi = 0 to express such arrays.
1358     LowerBound = 1;
1359   else
1360     --NumElems;
1361 
1362   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1363   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1364 
1365   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1366   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1367 
1368   return
1369     DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1370 }
1371 
1372 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1373                                      llvm::DIFile Unit) {
1374   uint64_t Size;
1375   uint64_t Align;
1376 
1377 
1378   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1379   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1380     Size = 0;
1381     Align =
1382       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1383   } else if (Ty->isIncompleteArrayType()) {
1384     Size = 0;
1385     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1386   } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1387     Size = 0;
1388     Align = 0;
1389   } else {
1390     // Size and align of the whole array, not the element type.
1391     Size = CGM.getContext().getTypeSize(Ty);
1392     Align = CGM.getContext().getTypeAlign(Ty);
1393   }
1394 
1395   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1396   // interior arrays, do we care?  Why aren't nested arrays represented the
1397   // obvious/recursive way?
1398   SmallVector<llvm::Value *, 8> Subscripts;
1399   QualType EltTy(Ty, 0);
1400   if (Ty->isIncompleteArrayType())
1401     EltTy = Ty->getElementType();
1402   else {
1403     while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1404       int64_t UpperBound = 0;
1405       int64_t LowerBound = 0;
1406       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1407         if (CAT->getSize().getZExtValue())
1408           UpperBound = CAT->getSize().getZExtValue() - 1;
1409       } else
1410         // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1411         // arrays.
1412         LowerBound = 1;
1413 
1414       // FIXME: Verify this is right for VLAs.
1415       Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1416                                                         UpperBound));
1417       EltTy = Ty->getElementType();
1418     }
1419   }
1420 
1421   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1422 
1423   llvm::DIType DbgTy =
1424     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1425                              SubscriptArray);
1426   return DbgTy;
1427 }
1428 
1429 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1430                                      llvm::DIFile Unit) {
1431   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1432                                Ty, Ty->getPointeeType(), Unit);
1433 }
1434 
1435 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1436                                      llvm::DIFile Unit) {
1437   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1438                                Ty, Ty->getPointeeType(), Unit);
1439 }
1440 
1441 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1442                                      llvm::DIFile U) {
1443   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1444   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1445 
1446   if (!Ty->getPointeeType()->isFunctionType()) {
1447     // We have a data member pointer type.
1448     return PointerDiffDITy;
1449   }
1450 
1451   // We have a member function pointer type. Treat it as a struct with two
1452   // ptrdiff_t members.
1453   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1454 
1455   uint64_t FieldOffset = 0;
1456   llvm::Value *ElementTypes[2];
1457 
1458   // FIXME: This should probably be a function type instead.
1459   ElementTypes[0] =
1460     DBuilder.createMemberType(U, "ptr", U, 0,
1461                               Info.first, Info.second, FieldOffset, 0,
1462                               PointerDiffDITy);
1463   FieldOffset += Info.first;
1464 
1465   ElementTypes[1] =
1466     DBuilder.createMemberType(U, "ptr", U, 0,
1467                               Info.first, Info.second, FieldOffset, 0,
1468                               PointerDiffDITy);
1469 
1470   llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1471 
1472   return DBuilder.createStructType(U, StringRef("test"),
1473                                    U, 0, FieldOffset,
1474                                    0, 0, Elements);
1475 }
1476 
1477 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1478                                      llvm::DIFile U) {
1479   // Ignore the atomic wrapping
1480   // FIXME: What is the correct representation?
1481   return getOrCreateType(Ty->getValueType(), U);
1482 }
1483 
1484 /// CreateEnumType - get enumeration type.
1485 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1486   llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1487   SmallVector<llvm::Value *, 16> Enumerators;
1488 
1489   // Create DIEnumerator elements for each enumerator.
1490   for (EnumDecl::enumerator_iterator
1491          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1492        Enum != EnumEnd; ++Enum) {
1493     Enumerators.push_back(
1494       DBuilder.createEnumerator(Enum->getName(),
1495                                 Enum->getInitVal().getZExtValue()));
1496   }
1497 
1498   // Return a CompositeType for the enum itself.
1499   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1500 
1501   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1502   unsigned Line = getLineNumber(ED->getLocation());
1503   uint64_t Size = 0;
1504   uint64_t Align = 0;
1505   if (!ED->getTypeForDecl()->isIncompleteType()) {
1506     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1507     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1508   }
1509   llvm::DIDescriptor EnumContext =
1510     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1511   llvm::DIType DbgTy =
1512     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1513                                    Size, Align, EltArray);
1514   return DbgTy;
1515 }
1516 
1517 static QualType UnwrapTypeForDebugInfo(QualType T) {
1518   do {
1519     QualType LastT = T;
1520     switch (T->getTypeClass()) {
1521     default:
1522       return T;
1523     case Type::TemplateSpecialization:
1524       T = cast<TemplateSpecializationType>(T)->desugar();
1525       break;
1526     case Type::TypeOfExpr:
1527       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1528       break;
1529     case Type::TypeOf:
1530       T = cast<TypeOfType>(T)->getUnderlyingType();
1531       break;
1532     case Type::Decltype:
1533       T = cast<DecltypeType>(T)->getUnderlyingType();
1534       break;
1535     case Type::UnaryTransform:
1536       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1537       break;
1538     case Type::Attributed:
1539       T = cast<AttributedType>(T)->getEquivalentType();
1540       break;
1541     case Type::Elaborated:
1542       T = cast<ElaboratedType>(T)->getNamedType();
1543       break;
1544     case Type::Paren:
1545       T = cast<ParenType>(T)->getInnerType();
1546       break;
1547     case Type::SubstTemplateTypeParm:
1548       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1549       break;
1550     case Type::Auto:
1551       T = cast<AutoType>(T)->getDeducedType();
1552       break;
1553     }
1554 
1555     assert(T != LastT && "Type unwrapping failed to unwrap!");
1556     if (T == LastT)
1557       return T;
1558   } while (true);
1559 
1560   return T;
1561 }
1562 
1563 /// getOrCreateType - Get the type from the cache or create a new
1564 /// one if necessary.
1565 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1566   if (Ty.isNull())
1567     return llvm::DIType();
1568 
1569   // Unwrap the type as needed for debug information.
1570   Ty = UnwrapTypeForDebugInfo(Ty);
1571 
1572   // Check for existing entry.
1573   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1574     TypeCache.find(Ty.getAsOpaquePtr());
1575   if (it != TypeCache.end()) {
1576     // Verify that the debug info still exists.
1577     if (&*it->second)
1578       return llvm::DIType(cast<llvm::MDNode>(it->second));
1579   }
1580 
1581   // Otherwise create the type.
1582   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1583 
1584   // And update the type cache.
1585   TypeCache[Ty.getAsOpaquePtr()] = Res;
1586   return Res;
1587 }
1588 
1589 /// CreateTypeNode - Create a new debug type node.
1590 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1591   // Handle qualifiers, which recursively handles what they refer to.
1592   if (Ty.hasLocalQualifiers())
1593     return CreateQualifiedType(Ty, Unit);
1594 
1595   const char *Diag = 0;
1596 
1597   // Work out details of type.
1598   switch (Ty->getTypeClass()) {
1599 #define TYPE(Class, Base)
1600 #define ABSTRACT_TYPE(Class, Base)
1601 #define NON_CANONICAL_TYPE(Class, Base)
1602 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1603 #include "clang/AST/TypeNodes.def"
1604     llvm_unreachable("Dependent types cannot show up in debug information");
1605 
1606   case Type::ExtVector:
1607   case Type::Vector:
1608     return CreateType(cast<VectorType>(Ty), Unit);
1609   case Type::ObjCObjectPointer:
1610     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1611   case Type::ObjCObject:
1612     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1613   case Type::ObjCInterface:
1614     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1615   case Type::Builtin:
1616     return CreateType(cast<BuiltinType>(Ty));
1617   case Type::Complex:
1618     return CreateType(cast<ComplexType>(Ty));
1619   case Type::Pointer:
1620     return CreateType(cast<PointerType>(Ty), Unit);
1621   case Type::BlockPointer:
1622     return CreateType(cast<BlockPointerType>(Ty), Unit);
1623   case Type::Typedef:
1624     return CreateType(cast<TypedefType>(Ty), Unit);
1625   case Type::Record:
1626     return CreateType(cast<RecordType>(Ty));
1627   case Type::Enum:
1628     return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1629   case Type::FunctionProto:
1630   case Type::FunctionNoProto:
1631     return CreateType(cast<FunctionType>(Ty), Unit);
1632   case Type::ConstantArray:
1633   case Type::VariableArray:
1634   case Type::IncompleteArray:
1635     return CreateType(cast<ArrayType>(Ty), Unit);
1636 
1637   case Type::LValueReference:
1638     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1639   case Type::RValueReference:
1640     return CreateType(cast<RValueReferenceType>(Ty), Unit);
1641 
1642   case Type::MemberPointer:
1643     return CreateType(cast<MemberPointerType>(Ty), Unit);
1644 
1645   case Type::Atomic:
1646     return CreateType(cast<AtomicType>(Ty), Unit);
1647 
1648   case Type::Attributed:
1649   case Type::TemplateSpecialization:
1650   case Type::Elaborated:
1651   case Type::Paren:
1652   case Type::SubstTemplateTypeParm:
1653   case Type::TypeOfExpr:
1654   case Type::TypeOf:
1655   case Type::Decltype:
1656   case Type::UnaryTransform:
1657   case Type::Auto:
1658     llvm_unreachable("type should have been unwrapped!");
1659     return llvm::DIType();
1660   }
1661 
1662   assert(Diag && "Fall through without a diagnostic?");
1663   unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1664                                "debug information for %0 is not yet supported");
1665   CGM.getDiags().Report(DiagID)
1666     << Diag;
1667   return llvm::DIType();
1668 }
1669 
1670 /// CreateMemberType - Create new member and increase Offset by FType's size.
1671 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1672                                            StringRef Name,
1673                                            uint64_t *Offset) {
1674   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1675   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1676   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1677   llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1678                                               FieldSize, FieldAlign,
1679                                               *Offset, 0, FieldTy);
1680   *Offset += FieldSize;
1681   return Ty;
1682 }
1683 
1684 /// getFunctionDeclaration - Return debug info descriptor to describe method
1685 /// declaration for the given method definition.
1686 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1687   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1688   if (!FD) return llvm::DISubprogram();
1689 
1690   // Setup context.
1691   getContextDescriptor(cast<Decl>(D->getDeclContext()));
1692 
1693   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1694     MI = SPCache.find(FD->getCanonicalDecl());
1695   if (MI != SPCache.end()) {
1696     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1697     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1698       return SP;
1699   }
1700 
1701   for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1702          E = FD->redecls_end(); I != E; ++I) {
1703     const FunctionDecl *NextFD = *I;
1704     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1705       MI = SPCache.find(NextFD->getCanonicalDecl());
1706     if (MI != SPCache.end()) {
1707       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1708       if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1709         return SP;
1710     }
1711   }
1712   return llvm::DISubprogram();
1713 }
1714 
1715 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1716 // implicit parameter "this".
1717 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D,
1718                                                   QualType FnType,
1719                                                   llvm::DIFile F) {
1720   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1721     return getOrCreateMethodType(Method, F);
1722   if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1723     // Add "self" and "_cmd"
1724     SmallVector<llvm::Value *, 16> Elts;
1725 
1726     // First element is always return type. For 'void' functions it is NULL.
1727     Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1728     // "self" pointer is always first argument.
1729     Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1730     // "cmd" pointer is always second argument.
1731     Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1732     // Get rest of the arguments.
1733     for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
1734            PE = OMethod->param_end(); PI != PE; ++PI)
1735       Elts.push_back(getOrCreateType((*PI)->getType(), F));
1736 
1737     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1738     return DBuilder.createSubroutineType(F, EltTypeArray);
1739   }
1740   return getOrCreateType(FnType, F);
1741 }
1742 
1743 /// EmitFunctionStart - Constructs the debug code for entering a function -
1744 /// "llvm.dbg.func.start.".
1745 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1746                                     llvm::Function *Fn,
1747                                     CGBuilderTy &Builder) {
1748 
1749   StringRef Name;
1750   StringRef LinkageName;
1751 
1752   FnBeginRegionCount.push_back(LexicalBlockStack.size());
1753 
1754   const Decl *D = GD.getDecl();
1755 
1756   unsigned Flags = 0;
1757   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1758   llvm::DIDescriptor FDContext(Unit);
1759   llvm::DIArray TParamsArray;
1760   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1761     // If there is a DISubprogram for this function available then use it.
1762     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1763       FI = SPCache.find(FD->getCanonicalDecl());
1764     if (FI != SPCache.end()) {
1765       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1766       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1767         llvm::MDNode *SPN = SP;
1768         LexicalBlockStack.push_back(SPN);
1769         RegionMap[D] = llvm::WeakVH(SP);
1770         return;
1771       }
1772     }
1773     Name = getFunctionName(FD);
1774     // Use mangled name as linkage name for c/c++ functions.
1775     if (!Fn->hasInternalLinkage())
1776       LinkageName = CGM.getMangledName(GD);
1777     if (LinkageName == Name)
1778       LinkageName = StringRef();
1779     if (FD->hasPrototype())
1780       Flags |= llvm::DIDescriptor::FlagPrototyped;
1781     if (const NamespaceDecl *NSDecl =
1782         dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1783       FDContext = getOrCreateNameSpace(NSDecl);
1784     else if (const RecordDecl *RDecl =
1785              dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1786       FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1787 
1788     // Collect template parameters.
1789     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1790   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1791     Name = getObjCMethodName(OMD);
1792     Flags |= llvm::DIDescriptor::FlagPrototyped;
1793   } else {
1794     // Use llvm function name.
1795     Name = Fn->getName();
1796     Flags |= llvm::DIDescriptor::FlagPrototyped;
1797   }
1798   if (!Name.empty() && Name[0] == '\01')
1799     Name = Name.substr(1);
1800 
1801   // It is expected that CurLoc is set before using EmitFunctionStart.
1802   // Usually, CurLoc points to the left bracket location of compound
1803   // statement representing function body.
1804   unsigned LineNo = getLineNumber(CurLoc);
1805   if (D->isImplicit())
1806     Flags |= llvm::DIDescriptor::FlagArtificial;
1807   llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1808   llvm::DISubprogram SP =
1809     DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1810                             LineNo, getOrCreateFunctionType(D, FnType, Unit),
1811                             Fn->hasInternalLinkage(), true/*definition*/,
1812                             Flags, CGM.getLangOptions().Optimize, Fn,
1813                             TParamsArray, SPDecl);
1814 
1815   // Push function on region stack.
1816   llvm::MDNode *SPN = SP;
1817   LexicalBlockStack.push_back(SPN);
1818   RegionMap[D] = llvm::WeakVH(SP);
1819 }
1820 
1821 /// EmitLocation - Emit metadata to indicate a change in line/column
1822 /// information in the source file.
1823 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
1824 
1825   // Update our current location
1826   setLocation(Loc);
1827 
1828   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1829 
1830   // Don't bother if things are the same as last time.
1831   SourceManager &SM = CGM.getContext().getSourceManager();
1832   if (CurLoc == PrevLoc ||
1833       SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
1834     // New Builder may not be in sync with CGDebugInfo.
1835     if (!Builder.getCurrentDebugLocation().isUnknown())
1836       return;
1837 
1838   // Update last state.
1839   PrevLoc = CurLoc;
1840 
1841   llvm::MDNode *Scope = LexicalBlockStack.back();
1842   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1843                                                       getColumnNumber(CurLoc),
1844                                                       Scope));
1845 }
1846 
1847 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
1848 /// the stack.
1849 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
1850   llvm::DIDescriptor D =
1851     DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
1852 				llvm::DIDescriptor() :
1853 				llvm::DIDescriptor(LexicalBlockStack.back()),
1854 				getOrCreateFile(CurLoc),
1855 				getLineNumber(CurLoc),
1856 				getColumnNumber(CurLoc));
1857   llvm::MDNode *DN = D;
1858   LexicalBlockStack.push_back(DN);
1859 }
1860 
1861 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
1862 /// region - beginning of a DW_TAG_lexical_block.
1863 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
1864   // Set our current location.
1865   setLocation(Loc);
1866 
1867   // Create a new lexical block and push it on the stack.
1868   CreateLexicalBlock(Loc);
1869 
1870   // Emit a line table change for the current location inside the new scope.
1871   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
1872   					      getColumnNumber(Loc),
1873   					      LexicalBlockStack.back()));
1874 }
1875 
1876 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
1877 /// region - end of a DW_TAG_lexical_block.
1878 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
1879   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1880 
1881   // Provide an entry in the line table for the end of the block.
1882   EmitLocation(Builder, Loc);
1883 
1884   LexicalBlockStack.pop_back();
1885 }
1886 
1887 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
1888 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1889   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1890   unsigned RCount = FnBeginRegionCount.back();
1891   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
1892 
1893   // Pop all regions for this function.
1894   while (LexicalBlockStack.size() != RCount)
1895     EmitLexicalBlockEnd(Builder, CurLoc);
1896   FnBeginRegionCount.pop_back();
1897 }
1898 
1899 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1900 // See BuildByRefType.
1901 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1902                                                        uint64_t *XOffset) {
1903 
1904   SmallVector<llvm::Value *, 5> EltTys;
1905   QualType FType;
1906   uint64_t FieldSize, FieldOffset;
1907   unsigned FieldAlign;
1908 
1909   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1910   QualType Type = VD->getType();
1911 
1912   FieldOffset = 0;
1913   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1914   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1915   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1916   FType = CGM.getContext().IntTy;
1917   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1918   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1919 
1920   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
1921   if (HasCopyAndDispose) {
1922     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1923     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1924                                       &FieldOffset));
1925     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1926                                       &FieldOffset));
1927   }
1928 
1929   CharUnits Align = CGM.getContext().getDeclAlign(VD);
1930   if (Align > CGM.getContext().toCharUnitsFromBits(
1931         CGM.getContext().getTargetInfo().getPointerAlign(0))) {
1932     CharUnits FieldOffsetInBytes
1933       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
1934     CharUnits AlignedOffsetInBytes
1935       = FieldOffsetInBytes.RoundUpToAlignment(Align);
1936     CharUnits NumPaddingBytes
1937       = AlignedOffsetInBytes - FieldOffsetInBytes;
1938 
1939     if (NumPaddingBytes.isPositive()) {
1940       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
1941       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1942                                                     pad, ArrayType::Normal, 0);
1943       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1944     }
1945   }
1946 
1947   FType = Type;
1948   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1949   FieldSize = CGM.getContext().getTypeSize(FType);
1950   FieldAlign = CGM.getContext().toBits(Align);
1951 
1952   *XOffset = FieldOffset;
1953   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
1954                                       0, FieldSize, FieldAlign,
1955                                       FieldOffset, 0, FieldTy);
1956   EltTys.push_back(FieldTy);
1957   FieldOffset += FieldSize;
1958 
1959   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1960 
1961   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1962 
1963   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1964                                    Elements);
1965 }
1966 
1967 /// EmitDeclare - Emit local variable declaration debug info.
1968 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1969                               llvm::Value *Storage,
1970                               unsigned ArgNo, CGBuilderTy &Builder) {
1971   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1972 
1973   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1974   llvm::DIType Ty;
1975   uint64_t XOffset = 0;
1976   if (VD->hasAttr<BlocksAttr>())
1977     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1978   else
1979     Ty = getOrCreateType(VD->getType(), Unit);
1980 
1981   // If there is not any debug info for type then do not emit debug info
1982   // for this variable.
1983   if (!Ty)
1984     return;
1985 
1986   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
1987     // If Storage is an aggregate returned as 'sret' then let debugger know
1988     // about this.
1989     if (Arg->hasStructRetAttr())
1990       Ty = DBuilder.createReferenceType(Ty);
1991     else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
1992       // If an aggregate variable has non trivial destructor or non trivial copy
1993       // constructor than it is pass indirectly. Let debug info know about this
1994       // by using reference of the aggregate type as a argument type.
1995       if (!Record->hasTrivialCopyConstructor() ||
1996           !Record->hasTrivialDestructor())
1997         Ty = DBuilder.createReferenceType(Ty);
1998     }
1999   }
2000 
2001   // Get location information.
2002   unsigned Line = getLineNumber(VD->getLocation());
2003   unsigned Column = getColumnNumber(VD->getLocation());
2004   unsigned Flags = 0;
2005   if (VD->isImplicit())
2006     Flags |= llvm::DIDescriptor::FlagArtificial;
2007   llvm::MDNode *Scope = LexicalBlockStack.back();
2008 
2009   StringRef Name = VD->getName();
2010   if (!Name.empty()) {
2011     if (VD->hasAttr<BlocksAttr>()) {
2012       CharUnits offset = CharUnits::fromQuantity(32);
2013       SmallVector<llvm::Value *, 9> addr;
2014       llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2015       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2016       // offset of __forwarding field
2017       offset = CGM.getContext().toCharUnitsFromBits(
2018         CGM.getContext().getTargetInfo().getPointerWidth(0));
2019       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2020       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2021       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2022       // offset of x field
2023       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2024       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2025 
2026       // Create the descriptor for the variable.
2027       llvm::DIVariable D =
2028         DBuilder.createComplexVariable(Tag,
2029                                        llvm::DIDescriptor(Scope),
2030                                        VD->getName(), Unit, Line, Ty,
2031                                        addr, ArgNo);
2032 
2033       // Insert an llvm.dbg.declare into the current block.
2034       // Insert an llvm.dbg.declare into the current block.
2035       llvm::Instruction *Call =
2036         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2037       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2038       return;
2039     }
2040       // Create the descriptor for the variable.
2041     llvm::DIVariable D =
2042       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2043                                    Name, Unit, Line, Ty,
2044                                    CGM.getLangOptions().Optimize, Flags, ArgNo);
2045 
2046     // Insert an llvm.dbg.declare into the current block.
2047     llvm::Instruction *Call =
2048       DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2049     Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2050     return;
2051   }
2052 
2053   // If VD is an anonymous union then Storage represents value for
2054   // all union fields.
2055   if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2056     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2057     if (RD->isUnion()) {
2058       for (RecordDecl::field_iterator I = RD->field_begin(),
2059              E = RD->field_end();
2060            I != E; ++I) {
2061         FieldDecl *Field = *I;
2062         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2063         StringRef FieldName = Field->getName();
2064 
2065         // Ignore unnamed fields. Do not ignore unnamed records.
2066         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2067           continue;
2068 
2069         // Use VarDecl's Tag, Scope and Line number.
2070         llvm::DIVariable D =
2071           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2072                                        FieldName, Unit, Line, FieldTy,
2073                                        CGM.getLangOptions().Optimize, Flags,
2074                                        ArgNo);
2075 
2076         // Insert an llvm.dbg.declare into the current block.
2077         llvm::Instruction *Call =
2078           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2079         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2080       }
2081     }
2082   }
2083 }
2084 
2085 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2086                                             llvm::Value *Storage,
2087                                             CGBuilderTy &Builder) {
2088   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2089 }
2090 
2091 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2092   const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2093   const CGBlockInfo &blockInfo) {
2094   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2095 
2096   if (Builder.GetInsertBlock() == 0)
2097     return;
2098 
2099   bool isByRef = VD->hasAttr<BlocksAttr>();
2100 
2101   uint64_t XOffset = 0;
2102   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2103   llvm::DIType Ty;
2104   if (isByRef)
2105     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2106   else
2107     Ty = getOrCreateType(VD->getType(), Unit);
2108 
2109   // Get location information.
2110   unsigned Line = getLineNumber(VD->getLocation());
2111   unsigned Column = getColumnNumber(VD->getLocation());
2112 
2113   const llvm::TargetData &target = CGM.getTargetData();
2114 
2115   CharUnits offset = CharUnits::fromQuantity(
2116     target.getStructLayout(blockInfo.StructureType)
2117           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2118 
2119   SmallVector<llvm::Value *, 9> addr;
2120   llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2121   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2122   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2123   if (isByRef) {
2124     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2125     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2126     // offset of __forwarding field
2127     offset = CGM.getContext()
2128                 .toCharUnitsFromBits(target.getPointerSizeInBits());
2129     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2130     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2131     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2132     // offset of x field
2133     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2134     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2135   }
2136 
2137   // Create the descriptor for the variable.
2138   llvm::DIVariable D =
2139     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2140                                    llvm::DIDescriptor(LexicalBlockStack.back()),
2141                                    VD->getName(), Unit, Line, Ty, addr);
2142   // Insert an llvm.dbg.declare into the current block.
2143   llvm::Instruction *Call =
2144     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2145   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2146                                         LexicalBlockStack.back()));
2147 }
2148 
2149 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2150 /// variable declaration.
2151 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2152                                            unsigned ArgNo,
2153                                            CGBuilderTy &Builder) {
2154   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2155 }
2156 
2157 namespace {
2158   struct BlockLayoutChunk {
2159     uint64_t OffsetInBits;
2160     const BlockDecl::Capture *Capture;
2161   };
2162   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2163     return l.OffsetInBits < r.OffsetInBits;
2164   }
2165 }
2166 
2167 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2168                                                        llvm::Value *addr,
2169                                                        CGBuilderTy &Builder) {
2170   ASTContext &C = CGM.getContext();
2171   const BlockDecl *blockDecl = block.getBlockDecl();
2172 
2173   // Collect some general information about the block's location.
2174   SourceLocation loc = blockDecl->getCaretLocation();
2175   llvm::DIFile tunit = getOrCreateFile(loc);
2176   unsigned line = getLineNumber(loc);
2177   unsigned column = getColumnNumber(loc);
2178 
2179   // Build the debug-info type for the block literal.
2180   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2181 
2182   const llvm::StructLayout *blockLayout =
2183     CGM.getTargetData().getStructLayout(block.StructureType);
2184 
2185   SmallVector<llvm::Value*, 16> fields;
2186   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2187                                    blockLayout->getElementOffsetInBits(0),
2188                                    tunit, tunit));
2189   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2190                                    blockLayout->getElementOffsetInBits(1),
2191                                    tunit, tunit));
2192   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2193                                    blockLayout->getElementOffsetInBits(2),
2194                                    tunit, tunit));
2195   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2196                                    blockLayout->getElementOffsetInBits(3),
2197                                    tunit, tunit));
2198   fields.push_back(createFieldType("__descriptor",
2199                                    C.getPointerType(block.NeedsCopyDispose ?
2200                                         C.getBlockDescriptorExtendedType() :
2201                                         C.getBlockDescriptorType()),
2202                                    0, loc, AS_public,
2203                                    blockLayout->getElementOffsetInBits(4),
2204                                    tunit, tunit));
2205 
2206   // We want to sort the captures by offset, not because DWARF
2207   // requires this, but because we're paranoid about debuggers.
2208   SmallVector<BlockLayoutChunk, 8> chunks;
2209 
2210   // 'this' capture.
2211   if (blockDecl->capturesCXXThis()) {
2212     BlockLayoutChunk chunk;
2213     chunk.OffsetInBits =
2214       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2215     chunk.Capture = 0;
2216     chunks.push_back(chunk);
2217   }
2218 
2219   // Variable captures.
2220   for (BlockDecl::capture_const_iterator
2221          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2222        i != e; ++i) {
2223     const BlockDecl::Capture &capture = *i;
2224     const VarDecl *variable = capture.getVariable();
2225     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2226 
2227     // Ignore constant captures.
2228     if (captureInfo.isConstant())
2229       continue;
2230 
2231     BlockLayoutChunk chunk;
2232     chunk.OffsetInBits =
2233       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2234     chunk.Capture = &capture;
2235     chunks.push_back(chunk);
2236   }
2237 
2238   // Sort by offset.
2239   llvm::array_pod_sort(chunks.begin(), chunks.end());
2240 
2241   for (SmallVectorImpl<BlockLayoutChunk>::iterator
2242          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2243     uint64_t offsetInBits = i->OffsetInBits;
2244     const BlockDecl::Capture *capture = i->Capture;
2245 
2246     // If we have a null capture, this must be the C++ 'this' capture.
2247     if (!capture) {
2248       const CXXMethodDecl *method =
2249         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2250       QualType type = method->getThisType(C);
2251 
2252       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2253                                        offsetInBits, tunit, tunit));
2254       continue;
2255     }
2256 
2257     const VarDecl *variable = capture->getVariable();
2258     StringRef name = variable->getName();
2259 
2260     llvm::DIType fieldType;
2261     if (capture->isByRef()) {
2262       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2263 
2264       // FIXME: this creates a second copy of this type!
2265       uint64_t xoffset;
2266       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2267       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2268       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2269                                             ptrInfo.first, ptrInfo.second,
2270                                             offsetInBits, 0, fieldType);
2271     } else {
2272       fieldType = createFieldType(name, variable->getType(), 0,
2273                                   loc, AS_public, offsetInBits, tunit, tunit);
2274     }
2275     fields.push_back(fieldType);
2276   }
2277 
2278   llvm::SmallString<36> typeName;
2279   llvm::raw_svector_ostream(typeName)
2280     << "__block_literal_" << CGM.getUniqueBlockCount();
2281 
2282   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2283 
2284   llvm::DIType type =
2285     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2286                               CGM.getContext().toBits(block.BlockSize),
2287                               CGM.getContext().toBits(block.BlockAlign),
2288                               0, fieldsArray);
2289   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2290 
2291   // Get overall information about the block.
2292   unsigned flags = llvm::DIDescriptor::FlagArtificial;
2293   llvm::MDNode *scope = LexicalBlockStack.back();
2294   StringRef name = ".block_descriptor";
2295 
2296   // Create the descriptor for the parameter.
2297   llvm::DIVariable debugVar =
2298     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2299                                  llvm::DIDescriptor(scope),
2300                                  name, tunit, line, type,
2301                                  CGM.getLangOptions().Optimize, flags,
2302                                  cast<llvm::Argument>(addr)->getArgNo() + 1);
2303 
2304   // Insert an llvm.dbg.value into the current block.
2305   llvm::Instruction *declare =
2306     DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2307                                      Builder.GetInsertBlock());
2308   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2309 }
2310 
2311 /// EmitGlobalVariable - Emit information about a global variable.
2312 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2313                                      const VarDecl *D) {
2314   // Create global variable debug descriptor.
2315   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2316   unsigned LineNo = getLineNumber(D->getLocation());
2317 
2318   setLocation(D->getLocation());
2319 
2320   QualType T = D->getType();
2321   if (T->isIncompleteArrayType()) {
2322 
2323     // CodeGen turns int[] into int[1] so we'll do the same here.
2324     llvm::APSInt ConstVal(32);
2325 
2326     ConstVal = 1;
2327     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2328 
2329     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2330                                               ArrayType::Normal, 0);
2331   }
2332   StringRef DeclName = D->getName();
2333   StringRef LinkageName;
2334   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2335       && !isa<ObjCMethodDecl>(D->getDeclContext()))
2336     LinkageName = Var->getName();
2337   if (LinkageName == DeclName)
2338     LinkageName = StringRef();
2339   llvm::DIDescriptor DContext =
2340     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2341   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2342                                 Unit, LineNo, getOrCreateType(T, Unit),
2343                                 Var->hasInternalLinkage(), Var);
2344 }
2345 
2346 /// EmitGlobalVariable - Emit information about an objective-c interface.
2347 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2348                                      ObjCInterfaceDecl *ID) {
2349   // Create global variable debug descriptor.
2350   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2351   unsigned LineNo = getLineNumber(ID->getLocation());
2352 
2353   StringRef Name = ID->getName();
2354 
2355   QualType T = CGM.getContext().getObjCInterfaceType(ID);
2356   if (T->isIncompleteArrayType()) {
2357 
2358     // CodeGen turns int[] into int[1] so we'll do the same here.
2359     llvm::APSInt ConstVal(32);
2360 
2361     ConstVal = 1;
2362     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2363 
2364     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2365                                            ArrayType::Normal, 0);
2366   }
2367 
2368   DBuilder.createGlobalVariable(Name, Unit, LineNo,
2369                                 getOrCreateType(T, Unit),
2370                                 Var->hasInternalLinkage(), Var);
2371 }
2372 
2373 /// EmitGlobalVariable - Emit global variable's debug info.
2374 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2375                                      llvm::Constant *Init) {
2376   // Create the descriptor for the variable.
2377   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2378   StringRef Name = VD->getName();
2379   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2380   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2381     if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2382       Ty = CreateEnumType(ED);
2383   }
2384   // Do not use DIGlobalVariable for enums.
2385   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2386     return;
2387   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2388                                 getLineNumber(VD->getLocation()),
2389                                 Ty, true, Init);
2390 }
2391 
2392 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2393 /// namespace decl.
2394 llvm::DINameSpace
2395 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2396   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2397     NameSpaceCache.find(NSDecl);
2398   if (I != NameSpaceCache.end())
2399     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2400 
2401   unsigned LineNo = getLineNumber(NSDecl->getLocation());
2402   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2403   llvm::DIDescriptor Context =
2404     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2405   llvm::DINameSpace NS =
2406     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2407   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2408   return NS;
2409 }
2410 
2411 /// UpdateCompletedType - Update type cache because the type is now
2412 /// translated.
2413 void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) {
2414   QualType Ty = CGM.getContext().getTagDeclType(TD);
2415 
2416   // If the type exist in type cache then remove it from the cache.
2417   // There is no need to prepare debug info for the completed type
2418   // right now. It will be generated on demand lazily.
2419   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2420     TypeCache.find(Ty.getAsOpaquePtr());
2421   if (it != TypeCache.end())
2422     TypeCache.erase(it);
2423 }
2424