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