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