zcov: / lib/CodeGen/CodeGenModule.cpp


Files: 1 Branches Taken: 86.6% 538 / 621
Generated: 2010-02-10 01:31 Branches Executed: 93.9% 583 / 621
Line Coverage: 93.6% 722 / 771


Programs: 1 Runs 2897


       1                 : //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs 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 per-module state used while generating code.
      11                 : //
      12                 : //===----------------------------------------------------------------------===//
      13                 : 
      14                 : #include "CodeGenModule.h"
      15                 : #include "CGDebugInfo.h"
      16                 : #include "CodeGenFunction.h"
      17                 : #include "CGCall.h"
      18                 : #include "CGObjCRuntime.h"
      19                 : #include "Mangle.h"
      20                 : #include "TargetInfo.h"
      21                 : #include "clang/CodeGen/CodeGenOptions.h"
      22                 : #include "clang/AST/ASTContext.h"
      23                 : #include "clang/AST/CharUnits.h"
      24                 : #include "clang/AST/DeclObjC.h"
      25                 : #include "clang/AST/DeclCXX.h"
      26                 : #include "clang/AST/RecordLayout.h"
      27                 : #include "clang/Basic/Builtins.h"
      28                 : #include "clang/Basic/Diagnostic.h"
      29                 : #include "clang/Basic/SourceManager.h"
      30                 : #include "clang/Basic/TargetInfo.h"
      31                 : #include "clang/Basic/ConvertUTF.h"
      32                 : #include "llvm/CallingConv.h"
      33                 : #include "llvm/Module.h"
      34                 : #include "llvm/Intrinsics.h"
      35                 : #include "llvm/LLVMContext.h"
      36                 : #include "llvm/Target/TargetData.h"
      37                 : #include "llvm/Support/ErrorHandling.h"
      38                 : using namespace clang;
      39                 : using namespace CodeGen;
      40                 : 
      41                 : 
      42                 : CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
      43                 :                              llvm::Module &M, const llvm::TargetData &TD,
      44              625:                              Diagnostic &diags)
      45                 :   : BlockModule(C, M, TD, Types, *this), Context(C),
      46                 :     Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
      47                 :     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
      48                 :     Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
      49                 :     MangleCtx(C), VtableInfo(*this), Runtime(0),
      50                 :     MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0),
      51              625:     VMContext(M.getContext()) {
      52                 : 
                      488: branch 0 taken
                      137: branch 1 taken
                      137: branch 2 taken
                      137: branch 3 taken
      53              625:   if (!Features.ObjC1)
      54              488:     Runtime = 0;
                        7: branch 0 taken
                      130: branch 1 taken
                      130: branch 2 taken
                      130: branch 3 taken
      55              137:   else if (!Features.NeXTRuntime)
      56                7:     Runtime = CreateGNUObjCRuntime(*this);
                       20: branch 0 taken
                      110: branch 1 taken
                      110: branch 2 taken
                      110: branch 3 taken
      57              130:   else if (Features.ObjCNonFragileABI)
      58               20:     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
      59                 :   else
      60              110:     Runtime = CreateMacObjCRuntime(*this);
      61                 : 
      62                 :   // If debug info generation is enabled, create the CGDebugInfo object.
                       39: branch 0 taken
                      586: branch 1 taken
                       39: branch 4 taken
                       39: branch 5 taken
      63              625:   DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
      64              625: }
      65                 : 
      66              599: CodeGenModule::~CodeGenModule() {
                      135: branch 0 taken
                      464: branch 1 taken
                      135: branch 3 taken
                      135: branch 4 taken
      67              599:   delete Runtime;
                       36: branch 0 taken
                      563: branch 1 taken
                       36: branch 4 taken
                       36: branch 5 taken
      68              599:   delete DebugInfo;
      69              599: }
      70                 : 
      71                0: void CodeGenModule::createObjCRuntime() {
                        0: branch 0 not taken
                        0: branch 1 not taken
      72                0:   if (!Features.NeXTRuntime)
      73                0:     Runtime = CreateGNUObjCRuntime(*this);
                        0: branch 0 not taken
                        0: branch 1 not taken
      74                0:   else if (Features.ObjCNonFragileABI)
      75                0:     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
      76                 :   else
      77                0:     Runtime = CreateMacObjCRuntime(*this);
      78                0: }
      79                 : 
      80              622: void CodeGenModule::Release() {
      81              622:   EmitDeferred();
      82              622:   EmitCXXGlobalInitFunc();
                      136: branch 0 taken
                      486: branch 1 taken
      83              622:   if (Runtime)
                        7: branch 1 taken
                      129: branch 2 taken
      84              136:     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
      85                7:       AddGlobalCtor(ObjCInitFunction);
      86              622:   EmitCtorList(GlobalCtors, "llvm.global_ctors");
      87              622:   EmitCtorList(GlobalDtors, "llvm.global_dtors");
      88              622:   EmitAnnotations();
      89              622:   EmitLLVMUsed();
      90              622: }
      91                 : 
      92                 : /// ErrorUnsupported - Print out an error that codegen doesn't support the
      93                 : /// specified stmt yet.
      94                 : void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
      95                0:                                      bool OmitOnError) {
                        0: branch 0 not taken
                        0: branch 1 not taken
                        0: branch 4 not taken
                        0: branch 5 not taken
                        0: branch 6 not taken
                        0: branch 7 not taken
      96                0:   if (OmitOnError && getDiags().hasErrorOccurred())
      97                0:     return;
      98                 :   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
      99                0:                                                "cannot compile this %0 yet");
     100                0:   std::string Msg = Type;
     101                 :   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
     102                0:     << Msg << S->getSourceRange();
     103                 : }
     104                 : 
     105                 : /// ErrorUnsupported - Print out an error that codegen doesn't support the
     106                 : /// specified decl yet.
     107                 : void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
     108                0:                                      bool OmitOnError) {
                        0: branch 0 not taken
                        0: branch 1 not taken
                        0: branch 4 not taken
                        0: branch 5 not taken
                        0: branch 6 not taken
                        0: branch 7 not taken
     109                0:   if (OmitOnError && getDiags().hasErrorOccurred())
     110                0:     return;
     111                 :   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
     112                0:                                                "cannot compile this %0 yet");
     113                0:   std::string Msg = Type;
     114                0:   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
     115                 : }
     116                 : 
     117                 : LangOptions::VisibilityMode
     118             9167: CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
                      627: branch 1 taken
                     8540: branch 2 taken
     119             9167:   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
                        1: branch 1 taken
                      626: branch 2 taken
     120              627:     if (VD->getStorageClass() == VarDecl::PrivateExtern)
     121                1:       return LangOptions::Hidden;
     122                 : 
                       13: branch 1 taken
                     9153: branch 2 taken
     123             9166:   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
                        0: branch 1 not taken
                        3: branch 2 taken
                        9: branch 3 taken
                        1: branch 4 taken
     124               13:     switch (attr->getVisibility()) {
     125                0:     default: assert(0 && "Unknown visibility!");
     126                 :     case VisibilityAttr::DefaultVisibility:
     127                3:       return LangOptions::Default;
     128                 :     case VisibilityAttr::HiddenVisibility:
     129                9:       return LangOptions::Hidden;
     130                 :     case VisibilityAttr::ProtectedVisibility:
     131                1:       return LangOptions::Protected;
     132                 :     }
     133                 :   }
     134                 : 
     135                 :   // This decl should have the same visibility as its parent.
                     5197: branch 1 taken
                     3956: branch 2 taken
     136             9153:   if (const DeclContext *DC = D->getDeclContext()) 
     137             5197:     return getDeclVisibilityMode(cast<Decl>(DC));
     138                 : 
     139             3956:   return getLangOptions().getVisibilityMode();
     140                 : }
     141                 : 
     142                 : void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
     143             3983:                                         const Decl *D) const {
     144                 :   // Internal definitions always have default visibility.
                      615: branch 1 taken
                     3368: branch 2 taken
     145             3983:   if (GV->hasLocalLinkage()) {
     146              615:     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
     147              615:     return;
     148                 :   }
     149                 : 
                        0: branch 1 not taken
                     3351: branch 2 taken
                       13: branch 3 taken
                        4: branch 4 taken
     150             3368:   switch (getDeclVisibilityMode(D)) {
     151                0:   default: assert(0 && "Unknown visibility!");
     152                 :   case LangOptions::Default:
     153             3351:     return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
     154                 :   case LangOptions::Hidden:
     155               13:     return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
     156                 :   case LangOptions::Protected:
     157                4:     return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
     158                 :   }
     159                 : }
     160                 : 
     161             5551: const char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
     162             5551:   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
     163                 : 
                      474: branch 1 taken
                     5077: branch 2 taken
     164             5551:   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
     165              474:     return getMangledCXXCtorName(D, GD.getCtorType());
                      130: branch 1 taken
                     4947: branch 2 taken
     166             5077:   if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
     167              130:     return getMangledCXXDtorName(D, GD.getDtorType());
     168                 : 
     169             4947:   return getMangledName(ND);
     170                 : }
     171                 : 
     172                 : /// \brief Retrieves the mangled name for the given declaration.
     173                 : ///
     174                 : /// If the given declaration requires a mangled name, returns an
     175                 : /// const char* containing the mangled name.  Otherwise, returns
     176                 : /// the unmangled name.
     177                 : ///
     178             6675: const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
                     3342: branch 2 taken
                     3333: branch 3 taken
     179             6675:   if (!getMangleContext().shouldMangleDeclName(ND)) {
                     3342: branch 1 taken
                        0: branch 2 not taken
     180             3342:     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
     181             3342:     return ND->getNameAsCString();
     182                 :   }
     183                 : 
     184             3333:   llvm::SmallString<256> Name;
     185             3333:   getMangleContext().mangleName(ND, Name);
     186             3333:   Name += '\0';
     187             3333:   return UniqueMangledName(Name.begin(), Name.end());
     188                 : }
     189                 : 
     190                 : const char *CodeGenModule::UniqueMangledName(const char *NameStart,
     191             5771:                                              const char *NameEnd) {
                        0: branch 0 not taken
                     5771: branch 1 taken
     192             5771:   assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
     193                 : 
     194             5771:   return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
     195                 : }
     196                 : 
     197                 : /// AddGlobalCtor - Add a function to the list that will be called before
     198                 : /// main() runs.
     199               48: void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
     200                 :   // FIXME: Type coercion of void()* types.
     201               48:   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
     202               48: }
     203                 : 
     204                 : /// AddGlobalDtor - Add a function to the list that will be called
     205                 : /// when the module is unloaded.
     206                2: void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
     207                 :   // FIXME: Type coercion of void()* types.
     208                2:   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
     209                2: }
     210                 : 
     211             1244: void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
     212                 :   // Ctor function type is void()*.
     213                 :   llvm::FunctionType* CtorFTy =
     214                 :     llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
     215                 :                             std::vector<const llvm::Type*>(),
     216             1244:                             false);
     217             1244:   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
     218                 : 
     219                 :   // Get the type of a ctor entry, { i32, void ()* }.
     220                 :   llvm::StructType* CtorStructTy =
     221                 :     llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
     222             1244:                           llvm::PointerType::getUnqual(CtorFTy), NULL);
     223                 : 
     224                 :   // Construct the constructor and destructor arrays.
     225             1244:   std::vector<llvm::Constant*> Ctors;
                       50: branch 5 taken
                     1244: branch 6 taken
     226             1294:   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
     227               50:     std::vector<llvm::Constant*> S;
     228                 :     S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
     229               50:                 I->second, false));
     230               50:     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
     231               50:     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
     232                 :   }
     233                 : 
                       48: branch 1 taken
                     1196: branch 2 taken
     234             1244:   if (!Ctors.empty()) {
     235               48:     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
     236                 :     new llvm::GlobalVariable(TheModule, AT, false,
     237                 :                              llvm::GlobalValue::AppendingLinkage,
     238                 :                              llvm::ConstantArray::get(AT, Ctors),
     239               48:                              GlobalName);
     240             1244:   }
     241             1244: }
     242                 : 
     243              622: void CodeGenModule::EmitAnnotations() {
                      621: branch 1 taken
                        1: branch 2 taken
     244              622:   if (Annotations.empty())
     245              621:     return;
     246                 : 
     247                 :   // Create a new global variable for the ConstantStruct in the Module.
     248                 :   llvm::Constant *Array =
     249                 :   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
     250                 :                                                 Annotations.size()),
     251                1:                            Annotations);
     252                 :   llvm::GlobalValue *gv =
     253                 :   new llvm::GlobalVariable(TheModule, Array->getType(), false,
     254                 :                            llvm::GlobalValue::AppendingLinkage, Array,
     255                1:                            "llvm.global.annotations");
     256                1:   gv->setSection("llvm.metadata");
     257                 : }
     258                 : 
     259                 : static CodeGenModule::GVALinkage
     260                 : GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
     261             6059:                       const LangOptions &Features) {
     262             6059:   CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
     263                 : 
     264             6059:   Linkage L = FD->getLinkage();
                     5763: branch 0 taken
                      296: branch 1 taken
                     3013: branch 3 taken
                     2750: branch 4 taken
                        0: branch 8 not taken
                     3013: branch 9 taken
                        0: branch 10 not taken
                     6059: branch 11 taken
     265             6059:   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
     266                 :       FD->getType()->getLinkage() == UniqueExternalLinkage)
     267                0:     L = UniqueExternalLinkage;
     268                 :   
                      296: branch 0 taken
                     5763: branch 1 taken
                        0: branch 2 not taken
     269             6059:   switch (L) {
     270                 :   case NoLinkage:
     271                 :   case InternalLinkage:
     272                 :   case UniqueExternalLinkage:
     273              296:     return CodeGenModule::GVA_Internal;
     274                 :     
     275                 :   case ExternalLinkage:
                     5447: branch 1 taken
                      102: branch 2 taken
                      214: branch 3 taken
                        0: branch 4 not taken
     276             5763:     switch (FD->getTemplateSpecializationKind()) {
     277                 :     case TSK_Undeclared:
     278                 :     case TSK_ExplicitSpecialization:
     279             5447:       External = CodeGenModule::GVA_StrongExternal;
     280             5447:       break;
     281                 : 
     282                 :     case TSK_ExplicitInstantiationDefinition:
     283                 :       // FIXME: explicit instantiation definitions should use weak linkage
     284              102:       return CodeGenModule::GVA_StrongExternal;
     285                 : 
     286                 :     case TSK_ExplicitInstantiationDeclaration:
     287                 :     case TSK_ImplicitInstantiation:
     288              214:       External = CodeGenModule::GVA_TemplateInstantiation;
     289                 :       break;
     290                 :     }
     291                 :   }
     292                 : 
                     4156: branch 1 taken
                     1505: branch 2 taken
     293             5661:   if (!FD->isInlined())
     294             4156:     return External;
     295                 :     
                     1404: branch 0 taken
                      101: branch 1 taken
                       12: branch 3 taken
                     1392: branch 4 taken
                      113: branch 5 taken
                     1392: branch 6 taken
     296             1505:   if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
     297                 :     // GNU or C99 inline semantics. Determine whether this symbol should be
     298                 :     // externally visible.
                       71: branch 1 taken
                       42: branch 2 taken
     299              113:     if (FD->isInlineDefinitionExternallyVisible())
     300               71:       return External;
     301                 : 
     302                 :     // C99 inline semantics, where the symbol is not externally visible.
     303               42:     return CodeGenModule::GVA_C99Inline;
     304                 :   }
     305                 : 
     306                 :   // C++0x [temp.explicit]p9:
     307                 :   //   [ Note: The intent is that an inline function that is the subject of 
     308                 :   //   an explicit instantiation declaration will still be implicitly 
     309                 :   //   instantiated when used so that the body can be considered for 
     310                 :   //   inlining, but that no out-of-line copy of the inline function would be
     311                 :   //   generated in the translation unit. -- end note ]
                        8: branch 1 taken
                     1384: branch 2 taken
     312             1392:   if (FD->getTemplateSpecializationKind() 
     313                 :                                        == TSK_ExplicitInstantiationDeclaration)
     314                8:     return CodeGenModule::GVA_C99Inline;
     315                 :   
     316             1384:   return CodeGenModule::GVA_CXXInline;
     317                 : }
     318                 : 
     319                 : /// SetFunctionDefinitionAttributes - Set attributes for a global.
     320                 : ///
     321                 : /// FIXME: This is currently only done for aliases and functions, but not for
     322                 : /// variables (these details are set in EmitGlobalVarDefinition for variables).
     323                 : void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
     324             2451:                                                     llvm::GlobalValue *GV) {
     325             2451:   GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
     326                 : 
                      115: branch 0 taken
                     2336: branch 1 taken
     327             2451:   if (Linkage == GVA_Internal) {
     328              115:     GV->setLinkage(llvm::Function::InternalLinkage);
                        1: branch 1 taken
                     2335: branch 2 taken
     329             2336:   } else if (D->hasAttr<DLLExportAttr>()) {
     330                1:     GV->setLinkage(llvm::Function::DLLExportLinkage);
                        4: branch 1 taken
                     2331: branch 2 taken
     331             2335:   } else if (D->hasAttr<WeakAttr>()) {
     332                4:     GV->setLinkage(llvm::Function::WeakAnyLinkage);
                       19: branch 0 taken
                     2312: branch 1 taken
     333             2331:   } else if (Linkage == GVA_C99Inline) {
     334                 :     // In C99 mode, 'inline' functions are guaranteed to have a strong
     335                 :     // definition somewhere else, so we can use available_externally linkage.
     336               19:     GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
                     1491: branch 0 taken
                      821: branch 1 taken
                       32: branch 2 taken
                     1459: branch 3 taken
     337             3165:   } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
     338                 :     // In C++, the compiler has to emit a definition in every translation unit
     339                 :     // that references the function.  We should use linkonce_odr because
     340                 :     // a) if all references in this translation unit are optimized away, we
     341                 :     // don't need to codegen it.  b) if the function persists, it needs to be
     342                 :     // merged with other definitions. c) C++ has the ODR, so we know the
     343                 :     // definition is dependable.
     344              853:     GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
     345                 :   } else {
                        0: branch 0 not taken
                     1459: branch 1 taken
     346             1459:     assert(Linkage == GVA_StrongExternal);
     347                 :     // Otherwise, we have strong external linkage.
     348             1459:     GV->setLinkage(llvm::Function::ExternalLinkage);
     349                 :   }
     350                 : 
     351             2451:   SetCommonAttributes(D, GV);
     352             2451: }
     353                 : 
     354                 : void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
     355                 :                                               const CGFunctionInfo &Info,
     356             3310:                                               llvm::Function *F) {
     357                 :   unsigned CallingConv;
     358             3310:   AttributeListType AttributeList;
     359             3310:   ConstructAttributeList(Info, D, AttributeList, CallingConv);
     360                 :   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
     361             3310:                                           AttributeList.size()));
     362             3310:   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
     363             3310: }
     364                 : 
     365                 : void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
     366             2777:                                                            llvm::Function *F) {
                     2747: branch 0 taken
                       30: branch 1 taken
                     2657: branch 2 taken
                       90: branch 3 taken
     367             2777:   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
     368             2657:     F->addFnAttr(llvm::Attribute::NoUnwind);
     369                 : 
                       13: branch 1 taken
                     2764: branch 2 taken
     370             2777:   if (D->hasAttr<AlwaysInlineAttr>())
     371               13:     F->addFnAttr(llvm::Attribute::AlwaysInline);
     372                 : 
                        6: branch 1 taken
                     2771: branch 2 taken
     373             2777:   if (D->hasAttr<NoInlineAttr>())
     374                6:     F->addFnAttr(llvm::Attribute::NoInline);
     375                 : 
                        2: branch 1 taken
                     2775: branch 2 taken
     376             2777:   if (Features.getStackProtectorMode() == LangOptions::SSPOn)
     377                2:     F->addFnAttr(llvm::Attribute::StackProtect);
                        1: branch 1 taken
                     2774: branch 2 taken
     378             2775:   else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
     379                1:     F->addFnAttr(llvm::Attribute::StackProtectReq);
     380                 :   
                        4: branch 1 taken
                     2773: branch 2 taken
     381             2777:   if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
     382                4:     unsigned width = Context.Target.getCharWidth();
     383                4:     F->setAlignment(AA->getAlignment() / width);
                        0: branch 1 not taken
                        4: branch 2 taken
     384                8:     while ((AA = AA->getNext<AlignedAttr>()))
     385                0:       F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
     386                 :   }
     387                 :   // C++ ABI requires 2-byte alignment for member functions.
                     2774: branch 1 taken
                        3: branch 2 taken
                      982: branch 4 taken
                     1792: branch 5 taken
                      982: branch 6 taken
                     1795: branch 7 taken
     388             2777:   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
     389              982:     F->setAlignment(2);
     390             2777: }
     391                 : 
     392                 : void CodeGenModule::SetCommonAttributes(const Decl *D,
     393             3481:                                         llvm::GlobalValue *GV) {
     394             3481:   setGlobalVisibility(GV, D);
     395                 : 
                        7: branch 1 taken
                     3474: branch 2 taken
     396             3481:   if (D->hasAttr<UsedAttr>())
     397                7:     AddUsedGlobal(GV);
     398                 : 
                        9: branch 1 taken
                     3472: branch 2 taken
     399             3481:   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
     400                9:     GV->setSection(SA->getName());
     401                 : 
     402             3481:   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
     403             3481: }
     404                 : 
     405                 : void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
     406                 :                                                   llvm::Function *F,
     407              326:                                                   const CGFunctionInfo &FI) {
     408              326:   SetLLVMFunctionAttributes(D, FI, F);
     409              326:   SetLLVMFunctionAttributesForDefinition(D, F);
     410                 : 
     411              326:   F->setLinkage(llvm::Function::InternalLinkage);
     412                 : 
     413              326:   SetCommonAttributes(D, F);
     414              326: }
     415                 : 
     416                 : void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
     417                 :                                           llvm::Function *F,
     418             2990:                                           bool IsIncompleteFunction) {
     419             2990:   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
     420                 : 
                     2984: branch 0 taken
                        6: branch 1 taken
     421             2990:   if (!IsIncompleteFunction)
     422             2984:     SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
     423                 : 
     424                 :   // Only a few attributes are set on declarations; these may later be
     425                 :   // overridden by a definition.
     426                 : 
                        1: branch 1 taken
                     2989: branch 2 taken
     427             2990:   if (FD->hasAttr<DLLImportAttr>()) {
     428                1:     F->setLinkage(llvm::Function::DLLImportLinkage);
                     2982: branch 1 taken
                        7: branch 2 taken
                        2: branch 4 taken
                     2980: branch 5 taken
                        9: branch 6 taken
                     2980: branch 7 taken
     429             2989:   } else if (FD->hasAttr<WeakAttr>() ||
     430                 :              FD->hasAttr<WeakImportAttr>()) {
     431                 :     // "extern_weak" is overloaded in LLVM; we probably should have
     432                 :     // separate linkage types for this.
     433                9:     F->setLinkage(llvm::Function::ExternalWeakLinkage);
     434                 :   } else {
     435             2980:     F->setLinkage(llvm::Function::ExternalLinkage);
     436                 :   }
     437                 : 
                        2: branch 1 taken
                     2988: branch 2 taken
     438             2990:   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
     439                2:     F->setSection(SA->getName());
     440             2990: }
     441                 : 
     442             2418: void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
     443                 :   assert(!GV->isDeclaration() &&
                     2418: branch 1 taken
                        0: branch 2 not taken
     444             2418:          "Only globals with definition can force usage.");
     445             2418:   LLVMUsed.push_back(GV);
     446             2418: }
     447                 : 
     448              622: void CodeGenModule::EmitLLVMUsed() {
     449                 :   // Don't create llvm.used if there is no need.
                      491: branch 1 taken
                      131: branch 2 taken
     450              622:   if (LLVMUsed.empty())
     451              491:     return;
     452                 : 
     453              131:   const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
     454                 : 
     455                 :   // Convert LLVMUsed to what ConstantArray needs.
     456              131:   std::vector<llvm::Constant*> UsedArray;
     457              131:   UsedArray.resize(LLVMUsed.size());
                     2417: branch 1 taken
                      131: branch 2 taken
     458             2548:   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
     459                 :     UsedArray[i] =
     460                 :      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
     461             2417:                                       i8PTy);
     462                 :   }
     463                 : 
                        0: branch 1 not taken
                      131: branch 2 taken
     464              131:   if (UsedArray.empty())
     465                0:     return;
     466              131:   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
     467                 : 
     468                 :   llvm::GlobalVariable *GV =
     469                 :     new llvm::GlobalVariable(getModule(), ATy, false,
     470                 :                              llvm::GlobalValue::AppendingLinkage,
     471                 :                              llvm::ConstantArray::get(ATy, UsedArray),
     472              131:                              "llvm.used");
     473                 : 
                      131: branch 3 taken
                        0: branch 4 not taken
     474              131:   GV->setSection("llvm.metadata");
     475                 : }
     476                 : 
     477              622: void CodeGenModule::EmitDeferred() {
     478                 :   // Emit code for any potentially referenced deferred decls.  Since a
     479                 :   // previously unused static decl may become used during the generation of code
     480                 :   // for a static function, iterate until no  changes are made.
                     1016: branch 1 taken
                      622: branch 2 taken
     481             2260:   while (!DeferredDeclsToEmit.empty()) {
     482             1016:     GlobalDecl D = DeferredDeclsToEmit.back();
     483             1016:     DeferredDeclsToEmit.pop_back();
     484                 : 
     485                 :     // The mangled name for the decl must have been emitted in GlobalDeclMap.
     486                 :     // Look it up to see if it was defined with a stronger definition (e.g. an
     487                 :     // extern inline function with a strong function redefinition).  If so,
     488                 :     // just ignore the deferred decl.
     489             1016:     llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
                        0: branch 0 not taken
                     1016: branch 1 taken
     490             1016:     assert(CGRef && "Deferred decl wasn't referenced?");
     491                 : 
                       14: branch 1 taken
                     1002: branch 2 taken
     492             1016:     if (!CGRef->isDeclaration())
     493               14:       continue;
     494                 : 
     495                 :     // Otherwise, emit the definition and move on to the next one.
     496             1002:     EmitGlobalDefinition(D);
     497                 :   }
     498              622: }
     499                 : 
     500                 : /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
     501                 : /// annotation information for a given GlobalValue.  The annotation struct is
     502                 : /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
     503                 : /// GlobalValue being annotated.  The second field is the constant string
     504                 : /// created from the AnnotateAttr's annotation.  The third field is a constant
     505                 : /// string containing the name of the translation unit.  The fourth field is
     506                 : /// the line number in the file of the annotated value declaration.
     507                 : ///
     508                 : /// FIXME: this does not unique the annotation string constants, as llvm-gcc
     509                 : ///        appears to.
     510                 : ///
     511                 : llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
     512                 :                                                 const AnnotateAttr *AA,
     513                2:                                                 unsigned LineNo) {
     514                2:   llvm::Module *M = &getModule();
     515                 : 
     516                 :   // get [N x i8] constants for the annotation string, and the filename string
     517                 :   // which are the 2nd and 3rd elements of the global annotation structure.
     518                2:   const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
     519                 :   llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
     520                2:                                                   AA->getAnnotation(), true);
     521                 :   llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
     522                 :                                                   M->getModuleIdentifier(),
     523                2:                                                   true);
     524                 : 
     525                 :   // Get the two global values corresponding to the ConstantArrays we just
     526                 :   // created to hold the bytes of the strings.
     527                 :   llvm::GlobalValue *annoGV =
     528                 :     new llvm::GlobalVariable(*M, anno->getType(), false,
     529                 :                              llvm::GlobalValue::PrivateLinkage, anno,
     530                2:                              GV->getName());
     531                 :   // translation unit name string, emitted into the llvm.metadata section.
     532                 :   llvm::GlobalValue *unitGV =
     533                 :     new llvm::GlobalVariable(*M, unit->getType(), false,
     534                 :                              llvm::GlobalValue::PrivateLinkage, unit,
     535                2:                              ".str");
     536                 : 
     537                 :   // Create the ConstantStruct for the global annotation.
     538                 :   llvm::Constant *Fields[4] = {
     539                 :     llvm::ConstantExpr::getBitCast(GV, SBP),
     540                 :     llvm::ConstantExpr::getBitCast(annoGV, SBP),
     541                 :     llvm::ConstantExpr::getBitCast(unitGV, SBP),
     542                 :     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
     543                2:   };
     544                2:   return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
     545                 : }
     546                 : 
     547             4382: bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
     548                 :   // Never defer when EmitAllDecls is specified or the decl has
     549                 :   // attribute used.
                     4380: branch 0 taken
                        2: branch 1 taken
                        8: branch 3 taken
                     4372: branch 4 taken
                       10: branch 5 taken
                     4372: branch 6 taken
     550             4382:   if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
     551               10:     return false;
     552                 : 
                     3687: branch 1 taken
                      685: branch 2 taken
     553             4372:   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
     554                 :     // Constructors and destructors should never be deferred.
                     3683: branch 1 taken
                        4: branch 2 taken
                        4: branch 4 taken
                     3679: branch 5 taken
                        8: branch 6 taken
                     3679: branch 7 taken
     555             3687:     if (FD->hasAttr<ConstructorAttr>() ||
     556                 :         FD->hasAttr<DestructorAttr>())
     557                8:       return false;
     558                 : 
     559                 :     // The key function for a class must never be deferred.
                      810: branch 1 taken
                     2869: branch 2 taken
     560             3679:     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
     561              810:       const CXXRecordDecl *RD = MD->getParent();
                      238: branch 1 taken
                      572: branch 2 taken
                      132: branch 4 taken
                      106: branch 5 taken
                      132: branch 6 taken
                      678: branch 7 taken
     562              810:       if (MD->isOutOfLine() && RD->isDynamicClass()) {
     563              132:         const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
                      102: branch 0 taken
                       30: branch 1 taken
                       71: branch 4 taken
                       31: branch 5 taken
                       71: branch 6 taken
                       61: branch 7 taken
     564              132:         if (KeyFunction && 
     565                 :             KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
     566               71:           return false;
     567                 :       }
     568                 :     }
     569                 : 
     570             3608:     GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
     571                 : 
     572                 :     // static, static inline, always_inline, and extern inline functions can
     573                 :     // always be deferred.  Normal inline functions can be deferred in C99/C++.
                     3427: branch 0 taken
                      181: branch 1 taken
                     3396: branch 2 taken
                       31: branch 3 taken
                     2833: branch 4 taken
                      563: branch 5 taken
                       30: branch 6 taken
                     2803: branch 7 taken
     574             3608:     if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
     575                 :         Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
     576              805:       return true;
     577             2803:     return false;
     578                 :   }
     579                 : 
     580              685:   const VarDecl *VD = cast<VarDecl>(Global);
                      685: branch 1 taken
                        0: branch 2 not taken
     581              685:   assert(VD->isFileVarDecl() && "Invalid decl");
     582                 : 
     583                 :   // We never want to defer structs that have non-trivial constructors or 
     584                 :   // destructors.
     585                 :   
     586                 :   // FIXME: Handle references.
                      188: branch 3 taken
                      497: branch 4 taken
     587              685:   if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
                      112: branch 2 taken
                       76: branch 3 taken
     588              188:     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
                       26: branch 1 taken
                       86: branch 2 taken
                        1: branch 4 taken
                       25: branch 5 taken
                       87: branch 6 taken
                       25: branch 7 taken
     589              112:       if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
     590               87:         return false;
     591                 :     }
     592                 :   }
     593                 :       
     594                 :   // Static data may be deferred, but out-of-line static data members
     595                 :   // cannot be.
     596              598:   Linkage L = VD->getLinkage();
                      543: branch 0 taken
                       55: branch 1 taken
                      125: branch 4 taken
                      418: branch 5 taken
                        3: branch 9 taken
                      122: branch 10 taken
                        3: branch 11 taken
                      595: branch 12 taken
     597              598:   if (L == ExternalLinkage && getContext().getLangOptions().CPlusPlus &&
     598                 :       VD->getType()->getLinkage() == UniqueExternalLinkage)
     599                3:     L = UniqueExternalLinkage;
     600                 : 
                       58: branch 0 taken
                      540: branch 1 taken
     601              598:   switch (L) {
     602                 :   case NoLinkage:
     603                 :   case InternalLinkage:
     604                 :   case UniqueExternalLinkage:
     605                 :     // Initializer has side effects?
                       32: branch 1 taken
                       26: branch 2 taken
                       18: branch 5 taken
                       14: branch 6 taken
                       18: branch 7 taken
                       40: branch 8 taken
     606               58:     if (VD->getInit() && VD->getInit()->HasSideEffects(Context))
     607               18:       return false;
                        0: branch 1 not taken
                       40: branch 2 taken
                        0: branch 4 not taken
                        0: branch 5 not taken
     608               40:     return !(VD->isStaticDataMember() && VD->isOutOfLine());
     609                 : 
     610                 :   case ExternalLinkage:
     611                 :     break;
     612                 :   }
     613                 : 
     614              540:   return false;
     615                 : }
     616                 : 
     617             3277: void CodeGenModule::EmitGlobal(GlobalDecl GD) {
     618             3277:   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
     619                 : 
     620                 :   // If this is an alias definition (which otherwise looks like a declaration)
     621                 :   // emit it now.
                       27: branch 1 taken
                     3250: branch 2 taken
     622             3277:   if (Global->hasAttr<AliasAttr>())
     623               27:     return EmitAliasDefinition(Global);
     624                 : 
     625                 :   // Ignore declarations, they will be emitted on their first use.
                     2506: branch 1 taken
                      744: branch 2 taken
     626             3250:   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
     627                 :     // Forward declarations are emitted lazily on first use.
                      722: branch 1 taken
                     1784: branch 2 taken
     628             2506:     if (!FD->isThisDeclarationADefinition())
     629              722:       return;
     630                 :   } else {
     631              744:     const VarDecl *VD = cast<VarDecl>(Global);
                      744: branch 1 taken
                        0: branch 2 not taken
     632              744:     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
     633                 : 
                      309: branch 1 taken
                      435: branch 2 taken
     634              744:     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
     635              309:       return;
     636                 :   }
     637                 : 
     638                 :   // Defer code generation when possible if this is a static definition, inline
     639                 :   // function etc.  These we only want to emit if they are used.
                      339: branch 1 taken
                     1880: branch 2 taken
     640             2219:   if (MayDeferGeneration(Global)) {
     641                 :     // If the value has already been used, add it directly to the
     642                 :     // DeferredDeclsToEmit list.
     643              339:     const char *MangledName = getMangledName(GD);
                       78: branch 1 taken
                      261: branch 2 taken
     644              339:     if (GlobalDeclMap.count(MangledName))
     645               78:       DeferredDeclsToEmit.push_back(GD);
     646                 :     else {
     647                 :       // Otherwise, remember that we saw a deferred decl with this name.  The
     648                 :       // first use of the mangled name will cause it to move into
     649                 :       // DeferredDeclsToEmit.
     650              261:       DeferredDecls[MangledName] = GD;
     651                 :     }
     652              339:     return;
     653                 :   }
     654                 : 
     655                 :   // Otherwise emit the definition.
     656             1880:   EmitGlobalDefinition(GD);
     657                 : }
     658                 : 
     659             2882: void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
     660             2882:   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
     661                 : 
     662                 :   PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(), 
     663                 :                                  Context.getSourceManager(),
     664             2882:                                  "Generating code for declaration");
     665                 :   
                      984: branch 1 taken
                     1898: branch 2 taken
     666             2882:   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
     667              984:     getVtableInfo().MaybeEmitVtable(GD);
                      317: branch 1 taken
                      667: branch 2 taken
                       68: branch 4 taken
                      249: branch 5 taken
                       30: branch 7 taken
                       38: branch 8 taken
                       20: branch 10 taken
                       10: branch 11 taken
                       58: branch 12 taken
                      926: branch 13 taken
     668              984:     if (MD->isVirtual() && MD->isOutOfLine() &&
     669                 :         (!isa<CXXDestructorDecl>(D) || GD.getDtorType() != Dtor_Base)) {
                       20: branch 1 taken
                       38: branch 2 taken
     670               58:       if (isa<CXXDestructorDecl>(D)) {
     671                 :         GlobalDecl CanonGD(cast<CXXDestructorDecl>(D->getCanonicalDecl()),
     672               20:                            GD.getDtorType());
     673               20:         BuildThunksForVirtual(CanonGD);
     674                 :       } else {
     675               38:         BuildThunksForVirtual(MD->getCanonicalDecl());
     676                 :       }
     677                 :     }
     678                 :   }
     679                 :   
                      476: branch 1 taken
                     2406: branch 2 taken
     680             2882:   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
     681              476:     EmitCXXConstructor(CD, GD.getCtorType());
                      105: branch 1 taken
                     2301: branch 2 taken
     682             2406:   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
     683              105:     EmitCXXDestructor(DD, GD.getDtorType());
                     1870: branch 1 taken
                      431: branch 2 taken
     684             2301:   else if (isa<FunctionDecl>(D))
     685             1870:     EmitGlobalFunctionDefinition(GD);
                      431: branch 1 taken
                        0: branch 2 not taken
     686              431:   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
     687              431:     EmitGlobalVarDefinition(VD);
     688                 :   else {
     689                0:     assert(0 && "Invalid argument to EmitGlobalDefinition()");
     690             2882:   }
     691             2882: }
     692                 : 
     693                 : /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
     694                 : /// module, create and return an llvm Function with the specified type. If there
     695                 : /// is something in the module with the specified name, return it potentially
     696                 : /// bitcasted to the right type.
     697                 : ///
     698                 : /// If D is non-null, it specifies a decl that correspond to this.  This is used
     699                 : /// to set the attributes on the function when it is first created.
     700                 : llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
     701                 :                                                        const llvm::Type *Ty,
     702             7102:                                                        GlobalDecl D) {
     703                 :   // Lookup the entry, lazily creating it if necessary.
     704             7102:   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
                     3797: branch 0 taken
                     3305: branch 1 taken
     705             7102:   if (Entry) {
                     3739: branch 2 taken
                       58: branch 3 taken
     706             3797:     if (Entry->getType()->getElementType() == Ty)
     707             3739:       return Entry;
     708                 : 
     709                 :     // Make sure the result is of the correct type.
     710               58:     const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
     711               58:     return llvm::ConstantExpr::getBitCast(Entry, PTy);
     712                 :   }
     713                 : 
     714                 :   // This function doesn't have a complete type (for example, the return
     715                 :   // type is an incomplete struct). Use a fake type instead, and make
     716                 :   // sure not to try to set attributes.
     717             3305:   bool IsIncompleteFunction = false;
                        6: branch 1 taken
                     3299: branch 2 taken
     718             3305:   if (!isa<llvm::FunctionType>(Ty)) {
     719                 :     Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
     720                6:                                  std::vector<const llvm::Type*>(), false);
     721                6:     IsIncompleteFunction = true;
     722                 :   }
     723                 :   llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
     724                 :                                              llvm::Function::ExternalLinkage,
     725             3305:                                              "", &getModule());
     726             3305:   F->setName(MangledName);
                     2990: branch 1 taken
                      315: branch 2 taken
     727             3305:   if (D.getDecl())
     728             2990:     SetFunctionAttributes(D, F, IsIncompleteFunction);
     729             3305:   Entry = F;
     730                 : 
     731                 :   // This is the first use or definition of a mangled name.  If there is a
     732                 :   // deferred decl with this name, remember that we need to emit it at the end
     733                 :   // of the file.
     734                 :   llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
     735             3305:     DeferredDecls.find(MangledName);
                      127: branch 3 taken
                     3178: branch 4 taken
     736             3305:   if (DDI != DeferredDecls.end()) {
     737                 :     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
     738                 :     // list, and remove it from DeferredDecls (since we don't need it anymore).
     739              127:     DeferredDeclsToEmit.push_back(DDI->second);
     740              127:     DeferredDecls.erase(DDI);
                     2865: branch 2 taken
                      313: branch 3 taken
     741             3178:   } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
     742                 :     // If this the first reference to a C++ inline function in a class, queue up
     743                 :     // the deferred function body for emission.  These are not seen as
     744                 :     // top-level declarations.
                     1907: branch 1 taken
                      958: branch 2 taken
                      493: branch 4 taken
                     1414: branch 5 taken
                      493: branch 6 taken
                     2372: branch 7 taken
     745             2865:     if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
     746              493:       DeferredDeclsToEmit.push_back(D);
     747                 :     // A called constructor which has no definition or declaration need be
     748                 :     // synthesized.
                      381: branch 1 taken
                     1991: branch 2 taken
     749             2372:     else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
                      272: branch 1 taken
                      109: branch 2 taken
     750              381:       if (CD->isImplicit())
     751              272:         DeferredDeclsToEmit.push_back(D);
                      107: branch 1 taken
                     1884: branch 2 taken
     752             1991:     } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
                       17: branch 1 taken
                       90: branch 2 taken
     753              107:       if (DD->isImplicit())
     754               17:         DeferredDeclsToEmit.push_back(D);
                      228: branch 1 taken
                     1656: branch 2 taken
     755             1884:     } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
                       11: branch 1 taken
                      217: branch 2 taken
                        8: branch 4 taken
                        3: branch 5 taken
                        8: branch 6 taken
                      220: branch 7 taken
     756              228:       if (MD->isCopyAssignment() && MD->isImplicit())
     757                8:         DeferredDeclsToEmit.push_back(D);
     758                 :     }
     759                 :   }
     760                 : 
     761             3305:   return F;
     762                 : }
     763                 : 
     764                 : /// GetAddrOfFunction - Return the address of the given function.  If Ty is
     765                 : /// non-null, then this function will use the specified type if it has to
     766                 : /// create it (this occurs when we see a definition of the function).
     767                 : llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
     768             4146:                                                  const llvm::Type *Ty) {
     769                 :   // If there was no specific requested type, just convert it now.
                      899: branch 0 taken
                     3247: branch 1 taken
     770             4146:   if (!Ty)
     771              899:     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
     772             4146:   return GetOrCreateLLVMFunction(getMangledName(GD), Ty, GD);
     773                 : }
     774                 : 
     775                 : /// CreateRuntimeFunction - Create a new runtime function with the specified
     776                 : /// type and name.
     777                 : llvm::Constant *
     778                 : CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
     779              683:                                      const char *Name) {
     780                 :   // Convert Name to be a uniqued string from the IdentifierInfo table.
     781              683:   Name = getContext().Idents.get(Name).getNameStart();
     782              683:   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
     783                 : }
     784                 : 
     785             1301: static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
                     1272: branch 2 taken
                       29: branch 3 taken
                     1257: branch 7 taken
                       15: branch 8 taken
                     1257: branch 9 taken
                       44: branch 10 taken
     786             1301:   if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
     787             1257:     return false;
                       25: branch 1 taken
                       19: branch 2 taken
                        1: branch 7 taken
                       24: branch 8 taken
                        1: branch 9 taken
                       43: branch 10 taken
     788               44:   if (Context.getLangOptions().CPlusPlus &&
     789                 :       Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
     790                 :     // FIXME: We should do something fancier here!
     791                1:     return false;
     792                 :   }
     793               43:   return true;
     794                 : }
     795                 : 
     796                 : /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
     797                 : /// create and return an llvm GlobalVariable with the specified type.  If there
     798                 : /// is something in the module with the specified name, return it potentially
     799                 : /// bitcasted to the right type.
     800                 : ///
     801                 : /// If D is non-null, it specifies a decl that correspond to this.  This is used
     802                 : /// to set the attributes on the global when it is first created.
     803                 : llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
     804                 :                                                      const llvm::PointerType*Ty,
     805             1596:                                                      const VarDecl *D) {
     806                 :   // Lookup the entry, lazily creating it if necessary.
     807             1596:   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
                      824: branch 0 taken
                      772: branch 1 taken
     808             1596:   if (Entry) {
                      813: branch 1 taken
                       11: branch 2 taken
     809              824:     if (Entry->getType() == Ty)
     810              813:       return Entry;
     811                 : 
     812                 :     // Make sure the result is of the correct type.
     813               11:     return llvm::ConstantExpr::getBitCast(Entry, Ty);
     814                 :   }
     815                 : 
     816                 :   // This is the first use or definition of a mangled name.  If there is a
     817                 :   // deferred decl with this name, remember that we need to emit it at the end
     818                 :   // of the file.
     819                 :   llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
     820              772:     DeferredDecls.find(MangledName);
                       23: branch 3 taken
                      749: branch 4 taken
     821              772:   if (DDI != DeferredDecls.end()) {
     822                 :     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
     823                 :     // list, and remove it from DeferredDecls (since we don't need it anymore).
     824               23:     DeferredDeclsToEmit.push_back(DDI->second);
     825               23:     DeferredDecls.erase(DDI);
     826                 :   }
     827                 : 
     828                 :   llvm::GlobalVariable *GV =
     829                 :     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
     830                 :                              llvm::GlobalValue::ExternalLinkage,
     831                 :                              0, "", 0,
     832              772:                              false, Ty->getAddressSpace());
     833              772:   GV->setName(MangledName);
     834                 : 
     835                 :   // Handle things which are present even on external declarations.
                      729: branch 0 taken
                       43: branch 1 taken
     836              772:   if (D) {
     837                 :     // FIXME: This code is overly simple and should be merged with other global
     838                 :     // handling.
     839              729:     GV->setConstant(DeclIsConstantGlobal(Context, D));
     840                 : 
     841                 :     // FIXME: Merge with other attribute handling code.
                        2: branch 1 taken
                      727: branch 2 taken
     842              729:     if (D->getStorageClass() == VarDecl::PrivateExtern)
     843                2:       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
     844                 : 
                      721: branch 1 taken
                        8: branch 2 taken
                        2: branch 4 taken
                      719: branch 5 taken
                       10: branch 6 taken
                      719: branch 7 taken
     845              729:     if (D->hasAttr<WeakAttr>() ||
     846                 :         D->hasAttr<WeakImportAttr>())
     847               10:       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
     848                 : 
     849              729:     GV->setThreadLocal(D->isThreadSpecified());
     850                 :   }
     851                 : 
     852              772:   return Entry = GV;
     853                 : }
     854                 : 
     855                 : 
     856                 : /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
     857                 : /// given global variable.  If Ty is non-null and if the global doesn't exist,
     858                 : /// then it will be greated with the specified type instead of whatever the
     859                 : /// normal requested type would be.
     860                 : llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
     861             1540:                                                   const llvm::Type *Ty) {
                     1540: branch 1 taken
                        0: branch 2 not taken
     862             1540:   assert(D->hasGlobalStorage() && "Not a global variable");
     863             1540:   QualType ASTTy = D->getType();
                      849: branch 0 taken
                      691: branch 1 taken
     864             1540:   if (Ty == 0)
     865              849:     Ty = getTypes().ConvertTypeForMem(ASTTy);
     866                 : 
     867                 :   const llvm::PointerType *PTy =
     868             1540:     llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
     869             1540:   return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
     870                 : }
     871                 : 
     872                 : /// CreateRuntimeVariable - Create a new runtime global variable with the
     873                 : /// specified type and name.
     874                 : llvm::Constant *
     875                 : CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
     876               54:                                      const char *Name) {
     877                 :   // Convert Name to be a uniqued string from the IdentifierInfo table.
     878               54:   Name = getContext().Idents.get(Name).getNameStart();
     879               54:   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
     880                 : }
     881                 : 
     882              256: void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
                      256: branch 1 taken
                        0: branch 2 not taken
     883              256:   assert(!D->getInit() && "Cannot emit definite definitions here!");
     884                 : 
                       13: branch 1 taken
                      243: branch 2 taken
     885              256:   if (MayDeferGeneration(D)) {
     886                 :     // If we have not seen a reference to this variable yet, place it
     887                 :     // into the deferred declarations table to be emitted if needed
     888                 :     // later.
     889               13:     const char *MangledName = getMangledName(D);
                        4: branch 1 taken
                        9: branch 2 taken
     890               13:     if (GlobalDeclMap.count(MangledName) == 0) {
     891                4:       DeferredDecls[MangledName] = D;
     892                4:       return;
     893                 :     }
     894                 :   }
     895                 : 
     896                 :   // The tentative definition is the only definition.
     897              252:   EmitGlobalVarDefinition(D);
     898                 : }
     899                 : 
     900                 : llvm::GlobalVariable::LinkageTypes 
     901              704: CodeGenModule::getVtableLinkage(const CXXRecordDecl *RD) {
                      701: branch 1 taken
                        3: branch 2 taken
                        7: branch 4 taken
                      694: branch 5 taken
                       10: branch 6 taken
                      694: branch 7 taken
     902              704:   if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
     903               10:     return llvm::GlobalVariable::InternalLinkage;
     904                 : 
                       97: branch 0 taken
                      597: branch 1 taken
     905              694:   if (const CXXMethodDecl *KeyFunction
     906              694:                                     = RD->getASTContext().getKeyFunction(RD)) {
     907                 :     // If this class has a key function, use that to determine the linkage of
     908                 :     // the vtable.
     909               97:     const FunctionDecl *Def = 0;
                       96: branch 1 taken
                        1: branch 2 taken
     910               97:     if (KeyFunction->getBody(Def))
     911               96:       KeyFunction = cast<CXXMethodDecl>(Def);
     912                 :     
                       89: branch 1 taken
                        8: branch 2 taken
                        0: branch 3 not taken
                        0: branch 4 not taken
     913               97:     switch (KeyFunction->getTemplateSpecializationKind()) {
     914                 :       case TSK_Undeclared:
     915                 :       case TSK_ExplicitSpecialization:
                        5: branch 1 taken
                       84: branch 2 taken
     916               89:         if (KeyFunction->isInlined())
     917                5:           return llvm::GlobalVariable::WeakODRLinkage;
     918                 :         
     919               84:         return llvm::GlobalVariable::ExternalLinkage;
     920                 :         
     921                 :       case TSK_ImplicitInstantiation:
     922                 :       case TSK_ExplicitInstantiationDefinition:
     923                8:         return llvm::GlobalVariable::WeakODRLinkage;
     924                 :         
     925                 :       case TSK_ExplicitInstantiationDeclaration:
     926                 :         // FIXME: Use available_externally linkage. However, this currently
     927                 :         // breaks LLVM's build due to undefined symbols.
     928                 :         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
     929                0:         return llvm::GlobalVariable::WeakODRLinkage;
     930                 :     }
     931                 :   }
     932                 :   
                      594: branch 1 taken
                        3: branch 2 taken
                        0: branch 3 not taken
     933              597:   switch (RD->getTemplateSpecializationKind()) {
     934                 :   case TSK_Undeclared:
     935                 :   case TSK_ExplicitSpecialization:
     936                 :   case TSK_ImplicitInstantiation:
     937                 :   case TSK_ExplicitInstantiationDefinition:
     938              594:     return llvm::GlobalVariable::WeakODRLinkage;
     939                 :     
     940                 :   case TSK_ExplicitInstantiationDeclaration:
     941                 :     // FIXME: Use available_externally linkage. However, this currently
     942                 :     // breaks LLVM's build due to undefined symbols.
     943                 :     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
     944                3:     return llvm::GlobalVariable::WeakODRLinkage;
     945                 :   }
     946                 :   
     947                 :   // Silence GCC warning.
     948                0:   return llvm::GlobalVariable::WeakODRLinkage;
     949                 : }
     950                 : 
     951                 : static CodeGenModule::GVALinkage
     952              683: GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
     953                 :   // If this is a static data member, compute the kind of template
     954                 :   // specialization. Otherwise, this variable is not part of a
     955                 :   // template.
     956              683:   TemplateSpecializationKind TSK = TSK_Undeclared;
                        7: branch 1 taken
                      676: branch 2 taken
     957              683:   if (VD->isStaticDataMember())
     958                7:     TSK = VD->getTemplateSpecializationKind();
     959                 : 
     960              683:   Linkage L = VD->getLinkage();
                      628: branch 0 taken
                       55: branch 1 taken
                      208: branch 3 taken
                      420: branch 4 taken
                        3: branch 8 taken
                      205: branch 9 taken
                        3: branch 10 taken
                      680: branch 11 taken
     961              683:   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
     962                 :       VD->getType()->getLinkage() == UniqueExternalLinkage)
     963                3:     L = UniqueExternalLinkage;
     964                 : 
                       58: branch 0 taken
                      625: branch 1 taken
                        0: branch 2 not taken
     965              683:   switch (L) {
     966                 :   case NoLinkage:
     967                 :   case InternalLinkage:
     968                 :   case UniqueExternalLinkage:
     969               58:     return CodeGenModule::GVA_Internal;
     970                 : 
     971                 :   case ExternalLinkage:
                      623: branch 0 taken
                        0: branch 1 not taken
                        2: branch 2 taken
                        0: branch 3 not taken
     972              625:     switch (TSK) {
     973                 :     case TSK_Undeclared:
     974                 :     case TSK_ExplicitSpecialization:
     975                 : 
     976                 :       // FIXME: ExplicitInstantiationDefinition should be weak!
     977                 :     case TSK_ExplicitInstantiationDefinition:
     978              623:       return CodeGenModule::GVA_StrongExternal;
     979                 :       
     980                 :     case TSK_ExplicitInstantiationDeclaration:
     981                0:       llvm_unreachable("Variable should not be instantiated");
     982                 :       // Fall through to treat this like any other instantiation.
     983                 :         
     984                 :     case TSK_ImplicitInstantiation:
     985                2:       return CodeGenModule::GVA_TemplateInstantiation;      
     986                 :     }
     987                 :   }
     988                 : 
     989                0:   return CodeGenModule::GVA_StrongExternal;
     990                 : }
     991                 : 
     992               62: CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
     993                 :     return CharUnits::fromQuantity(
     994               62:       TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
     995                 : }
     996                 : 
     997              683: void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
     998              683:   llvm::Constant *Init = 0;
     999              683:   QualType ASTTy = D->getType();
    1000              683:   bool NonConstInit = false;
    1001                 : 
    1002              683:   const Expr *InitExpr = D->getAnyInitializer();
    1003                 :   
                      305: branch 0 taken
                      378: branch 1 taken
    1004              683:   if (!InitExpr) {
    1005                 :     // This is a tentative definition; tentative definitions are
    1006                 :     // implicitly initialized with { 0 }.
    1007                 :     //
    1008                 :     // Note that tentative definitions are only emitted at the end of
    1009                 :     // a translation unit, so they should never have incomplete
    1010                 :     // type. In addition, EmitTentativeDefinition makes sure that we
    1011                 :     // never attempt to emit a tentative definition if a real one
    1012                 :     // exists. A use may still exists, however, so we still may need
    1013                 :     // to do a RAUW.
                      305: branch 2 taken
                        0: branch 3 not taken
    1014              305:     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
    1015              305:     Init = EmitNullConstant(D->getType());
    1016                 :   } else {
    1017              378:     Init = EmitConstantExpr(InitExpr, D->getType());
    1018                 : 
                      111: branch 0 taken
                      267: branch 1 taken
    1019              378:     if (!Init) {
    1020              111:       QualType T = InitExpr->getType();
                      111: branch 1 taken
                        0: branch 2 not taken
    1021              111:       if (getLangOptions().CPlusPlus) {
    1022              111:         EmitCXXGlobalVarDeclInitFunc(D);
    1023              111:         Init = EmitNullConstant(T);
    1024              111:         NonConstInit = true;
    1025                 :       } else {
    1026                0:         ErrorUnsupported(D, "static initializer");
    1027                0:         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
    1028                 :       }
    1029                 :     }
    1030                 :   }
    1031                 : 
    1032              683:   const llvm::Type* InitType = Init->getType();
    1033              683:   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
    1034                 : 
    1035                 :   // Strip off a bitcast if we got one back.
                        8: branch 1 taken
                      675: branch 2 taken
    1036              683:   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
    1037                 :     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
    1038                 :            // all zero index gep.
                        0: branch 1 not taken
                        8: branch 2 taken
                        0: branch 4 not taken
                        0: branch 5 not taken
    1039                8:            CE->getOpcode() == llvm::Instruction::GetElementPtr);
    1040                8:     Entry = CE->getOperand(0);
    1041                 :   }
    1042                 : 
    1043                 :   // Entry is now either a Function or GlobalVariable.
    1044              683:   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
    1045                 : 
    1046                 :   // We have a definition after a declaration with the wrong type.
    1047                 :   // We must make a new GlobalVariable* and update everything that used OldGV
    1048                 :   // (a declaration or tentative definition) with the new GlobalVariable*
    1049                 :   // (which will be a definition).
    1050                 :   //
    1051                 :   // This happens if there is a prototype for a global (e.g.
    1052                 :   // "extern int x[];") and then a definition of a different type (e.g.
    1053                 :   // "int x[10];"). This also happens when an initializer has a different type
    1054                 :   // from the type of the global (this happens with unions).
                      681: branch 0 taken
                        2: branch 1 taken
                      675: branch 4 taken
                        6: branch 5 taken
                        0: branch 9 not taken
                      675: branch 10 taken
                        8: branch 11 taken
                      675: branch 12 taken
    1055              683:   if (GV == 0 ||
    1056                 :       GV->getType()->getElementType() != InitType ||
    1057                 :       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
    1058                 : 
    1059                 :     // Remove the old entry from GlobalDeclMap so that we'll create a new one.
    1060                8:     GlobalDeclMap.erase(getMangledName(D));
    1061                 : 
    1062                 :     // Make a new global with the correct type, this is now guaranteed to work.
    1063                8:     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
    1064                8:     GV->takeName(cast<llvm::GlobalValue>(Entry));
    1065                 : 
    1066                 :     // Replace all uses of the old global with the new global
    1067                 :     llvm::Constant *NewPtrForOldDecl =
    1068                8:         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
    1069                8:     Entry->replaceAllUsesWith(NewPtrForOldDecl);
    1070                 : 
    1071                 :     // Erase the old global, since it is no longer used.
    1072                8:     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
    1073                 :   }
    1074                 : 
                        1: branch 1 taken
                      682: branch 2 taken
    1075              683:   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
    1076                1:     SourceManager &SM = Context.getSourceManager();
    1077                 :     AddAnnotation(EmitAnnotateAttr(GV, AA,
    1078                1:                               SM.getInstantiationLineNumber(D->getLocation())));
    1079                 :   }
    1080                 : 
    1081              683:   GV->setInitializer(Init);
    1082                 : 
    1083                 :   // If it is safe to mark the global 'constant', do so now.
    1084              683:   GV->setConstant(false);
                      572: branch 0 taken
                      111: branch 1 taken
                       18: branch 3 taken
                      554: branch 4 taken
                       18: branch 5 taken
                      665: branch 6 taken
    1085              683:   if (!NonConstInit && DeclIsConstantGlobal(Context, D))
    1086               18:     GV->setConstant(true);
    1087                 : 
    1088              683:   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
    1089                 : 
    1090                 :   // Set the llvm linkage type as appropriate.
    1091              683:   GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
                       58: branch 0 taken
                      625: branch 1 taken
    1092              683:   if (Linkage == GVA_Internal)
    1093               58:     GV->setLinkage(llvm::Function::InternalLinkage);
                        0: branch 1 not taken
                      625: branch 2 taken
    1094              625:   else if (D->hasAttr<DLLImportAttr>())
    1095                0:     GV->setLinkage(llvm::Function::DLLImportLinkage);
                        0: branch 1 not taken
                      625: branch 2 taken
    1096              625:   else if (D->hasAttr<DLLExportAttr>())
    1097                0:     GV->setLinkage(llvm::Function::DLLExportLinkage);
                        7: branch 1 taken
                      618: branch 2 taken
    1098              625:   else if (D->hasAttr<WeakAttr>()) {
                        1: branch 1 taken
                        6: branch 2 taken
    1099                7:     if (GV->isConstant())
    1100                1:       GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
    1101                 :     else
    1102                6:       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
                        2: branch 0 taken
                      616: branch 1 taken
    1103              618:   } else if (Linkage == GVA_TemplateInstantiation)
    1104                2:     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);   
                      413: branch 1 taken
                      203: branch 2 taken
                      412: branch 3 taken
                        1: branch 4 taken
                      411: branch 6 taken
                        1: branch 7 taken
                      235: branch 9 taken
                      176: branch 10 taken
                      233: branch 12 taken
                        2: branch 13 taken
                      233: branch 14 taken
                      383: branch 15 taken
    1105              616:   else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
    1106                 :            !D->hasExternalStorage() && !D->getInit() &&
    1107                 :            !D->getAttr<SectionAttr>()) {
    1108              233:     GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
    1109                 :     // common vars aren't constant even if declared const.
    1110              233:     GV->setConstant(false);
    1111                 :   } else
    1112              383:     GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
    1113                 : 
    1114              683:   SetCommonAttributes(D, GV);
    1115                 : 
    1116                 :   // Emit global variable debug information.
                       22: branch 1 taken
                      661: branch 2 taken
    1117              683:   if (CGDebugInfo *DI = getDebugInfo()) {
    1118               22:     DI->setLocation(D->getLocation());
    1119               22:     DI->EmitGlobalVariable(GV, D);
    1120                 :   }
    1121              683: }
    1122                 : 
    1123                 : /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
    1124                 : /// implement a function with no prototype, e.g. "int foo() {}".  If there are
    1125                 : /// existing call uses of the old function in the module, this adjusts them to
    1126                 : /// call the new function directly.
    1127                 : ///
    1128                 : /// This is not just a cleanup: the always_inline pass requires direct calls to
    1129                 : /// functions to be able to inline them.  If there is a bitcast in the way, it
    1130                 : /// won't inline them.  Instcombine normally deletes these calls, but it isn't
    1131                 : /// run at -O0.
    1132                 : static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
    1133               18:                                                       llvm::Function *NewFn) {
    1134                 :   // If we're redefining a global as a function, don't transform it.
    1135               18:   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
                       17: branch 0 taken
                        1: branch 1 taken
    1136               18:   if (OldFn == 0) return;
    1137                 : 
    1138               17:   const llvm::Type *NewRetTy = NewFn->getReturnType();
    1139               17:   llvm::SmallVector<llvm::Value*, 4> ArgList;
    1140                 : 
                       34: branch 3 taken
                       17: branch 4 taken
    1141               68:   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
    1142                 :        UI != E; ) {
    1143                 :     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
    1144               34:     unsigned OpNo = UI.getOperandNo();
    1145               34:     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
                       14: branch 0 taken
                       20: branch 1 taken
                        1: branch 2 taken
                       13: branch 3 taken
    1146               34:     if (!CI || OpNo != 0) continue;
    1147                 : 
    1148                 :     // If the return types don't match exactly, and if the call isn't dead, then
    1149                 :     // we can't transform this call.
                        1: branch 1 taken
                       12: branch 2 taken
                        0: branch 4 not taken
                        1: branch 5 taken
                        0: branch 6 not taken
                       13: branch 7 taken
    1150               13:     if (CI->getType() != NewRetTy && !CI->use_empty())
    1151                0:       continue;
    1152                 : 
    1153                 :     // If the function was passed too few arguments, don't transform.  If extra
    1154                 :     // arguments were passed, we silently drop them.  If any of the types
    1155                 :     // mismatch, we don't transform.
    1156               13:     unsigned ArgNo = 0;
    1157               13:     bool DontTransform = false;
                        1: branch 3 taken
                       13: branch 4 taken
    1158               27:     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
    1159               13:          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
                        1: branch 1 taken
                        0: branch 2 not taken
                        0: branch 7 not taken
                        1: branch 8 taken
                        0: branch 9 not taken
                        1: branch 10 taken
    1160                1:       if (CI->getNumOperands()-1 == ArgNo ||
    1161                 :           CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
    1162                0:         DontTransform = true;
    1163                0:         break;
    1164                 :       }
    1165                 :     }
                        0: branch 0 not taken
                       13: branch 1 taken
    1166               13:     if (DontTransform)
    1167                0:       continue;
    1168                 : 
    1169                 :     // Okay, we can transform this.  Create the new call instruction and copy
    1170                 :     // over the required information.
    1171               13:     ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
    1172                 :     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
    1173               13:                                                      ArgList.end(), "", CI);
    1174               13:     ArgList.clear();
                        8: branch 2 taken
                        5: branch 3 taken
    1175               13:     if (!NewCall->getType()->isVoidTy())
    1176                8:       NewCall->takeName(CI);
    1177               13:     NewCall->setAttributes(CI->getAttributes());
    1178               13:     NewCall->setCallingConv(CI->getCallingConv());
    1179                 : 
    1180                 :     // Finally, remove the old call, replacing any uses with the new one.
                        6: branch 1 taken
                        7: branch 2 taken
    1181               13:     if (!CI->use_empty())
    1182                6:       CI->replaceAllUsesWith(NewCall);
    1183                 : 
    1184                 :     // Copy any custom metadata attached with CI.
                        0: branch 1 not taken
                       13: branch 2 taken
    1185               13:     if (llvm::MDNode *DbgNode = CI->getMetadata("dbg"))
    1186                0:       NewCall->setMetadata("dbg", DbgNode);
    1187               13:     CI->eraseFromParent();
    1188               17:   }
    1189                 : }
    1190                 : 
    1191                 : 
    1192             1870: void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
    1193                 :   const llvm::FunctionType *Ty;
    1194             1870:   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
    1195                 : 
                      403: branch 1 taken
                     1467: branch 2 taken
    1196             1870:   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
    1197              403:     bool isVariadic = D->getType()->getAs<FunctionProtoType>()->isVariadic();
    1198                 : 
    1199              403:     Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
    1200                 :   } else {
    1201             1467:     Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
    1202                 : 
    1203                 :     // As a special case, make sure that definitions of K&R function
    1204                 :     // "type foo()" aren't declared as varargs (which forces the backend
    1205                 :     // to do unnecessary work).
                      362: branch 3 taken
                     1105: branch 4 taken
    1206             1467:     if (D->getType()->isFunctionNoProtoType()) {
                      362: branch 1 taken
                        0: branch 2 not taken
    1207              362:       assert(Ty->isVarArg() && "Didn't lower type as expected");
    1208                 :       // Due to stret, the lowered function could have arguments.
    1209                 :       // Just create the same type as was lowered by ConvertType
    1210                 :       // but strip off the varargs bit.
    1211              362:       std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
    1212              362:       Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
    1213                 :     }
    1214                 :   }
    1215                 : 
    1216                 :   // Get or create the prototype for the function.
    1217             1870:   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
    1218                 : 
    1219                 :   // Strip off a bitcast if we got one back.
                       21: branch 1 taken
                     1849: branch 2 taken
    1220             1870:   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
                        0: branch 1 not taken
                       21: branch 2 taken
    1221               21:     assert(CE->getOpcode() == llvm::Instruction::BitCast);
    1222               21:     Entry = CE->getOperand(0);
    1223                 :   }
    1224                 : 
    1225                 : 
                       21: branch 3 taken
                     1849: branch 4 taken
    1226             1870:   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
    1227               21:     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
    1228                 : 
    1229                 :     // If the types mismatch then we have to rewrite the definition.
    1230                 :     assert(OldFn->isDeclaration() &&
                       21: branch 1 taken
                        0: branch 2 not taken
    1231               21:            "Shouldn't replace non-declaration");
    1232                 : 
    1233                 :     // F is the Function* for the one with the wrong type, we must make a new
    1234                 :     // Function* and update everything that used F (a declaration) with the new
    1235                 :     // Function* (which will be a definition).
    1236                 :     //
    1237                 :     // This happens if there is a prototype for a function
    1238                 :     // (e.g. "int f()") and then a definition of a different type
    1239                 :     // (e.g. "int f(int x)").  Start by making a new function of the
    1240                 :     // correct type, RAUW, then steal the name.
    1241               21:     GlobalDeclMap.erase(getMangledName(D));
    1242               21:     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
    1243               21:     NewFn->takeName(OldFn);
    1244                 : 
    1245                 :     // If this is an implementation of a function without a prototype, try to
    1246                 :     // replace any existing uses of the function (which may be calls) with uses
    1247                 :     // of the new function
                       18: branch 3 taken
                        3: branch 4 taken
    1248               21:     if (D->getType()->isFunctionNoProtoType()) {
    1249               18:       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
    1250               18:       OldFn->removeDeadConstantUsers();
    1251                 :     }
    1252                 : 
    1253                 :     // Replace uses of F with the Function we will endow with a body.
                        8: branch 1 taken
                       13: branch 2 taken
    1254               21:     if (!Entry->use_empty()) {
    1255                 :       llvm::Constant *NewPtrForOldDecl =
    1256                8:         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
    1257                8:       Entry->replaceAllUsesWith(NewPtrForOldDecl);
    1258                 :     }
    1259                 : 
    1260                 :     // Ok, delete the old function now, which is dead.
    1261               21:     OldFn->eraseFromParent();
    1262                 : 
    1263               21:     Entry = NewFn;
    1264                 :   }
    1265                 : 
    1266             1870:   llvm::Function *Fn = cast<llvm::Function>(Entry);
    1267                 : 
    1268             1870:   CodeGenFunction(*this).GenerateCode(D, Fn);
    1269                 : 
    1270             1870:   SetFunctionDefinitionAttributes(D, Fn);
    1271             1870:   SetLLVMFunctionAttributesForDefinition(D, Fn);
    1272                 : 
                        2: branch 1 taken
                     1868: branch 2 taken
    1273             1870:   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
    1274                2:     AddGlobalCtor(Fn, CA->getPriority());
                        2: branch 1 taken
                     1868: branch 2 taken
    1275             1870:   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
    1276                2:     AddGlobalDtor(Fn, DA->getPriority());
    1277             1870: }
    1278                 : 
    1279               27: void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
    1280               27:   const AliasAttr *AA = D->getAttr<AliasAttr>();
                        0: branch 0 not taken
                       27: branch 1 taken
    1281               27:   assert(AA && "Not an alias?");
    1282                 : 
    1283               27:   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
    1284                 : 
    1285                 :   // Unique the name through the identifier table.
    1286               27:   const char *AliaseeName = AA->getAliasee().c_str();
    1287               27:   AliaseeName = getContext().Idents.get(AliaseeName).getNameStart();
    1288                 : 
    1289                 :   // Create a reference to the named value.  This ensures that it is emitted
    1290                 :   // if a deferred decl.
    1291                 :   llvm::Constant *Aliasee;
                       25: branch 1 taken
                        2: branch 2 taken
    1292               27:   if (isa<llvm::FunctionType>(DeclTy))
    1293               25:     Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
    1294                 :   else
    1295                 :     Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
    1296                2:                                     llvm::PointerType::getUnqual(DeclTy), 0);
    1297                 : 
    1298                 :   // Create the new alias itself, but don't set a name yet.
    1299                 :   llvm::GlobalValue *GA =
    1300                 :     new llvm::GlobalAlias(Aliasee->getType(),
    1301                 :                           llvm::Function::ExternalLinkage,
    1302               27:                           "", Aliasee, &getModule());
    1303                 : 
    1304                 :   // See if there is already something with the alias' name in the module.
    1305               27:   const char *MangledName = getMangledName(D);
    1306               27:   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
    1307                 : 
                        7: branch 0 taken
                       20: branch 1 taken
                        6: branch 3 taken
                        1: branch 4 taken
                        6: branch 5 taken
                       21: branch 6 taken
    1308               27:   if (Entry && !Entry->isDeclaration()) {
    1309                 :     // If there is a definition in the module, then it wins over the alias.
    1310                 :     // This is dubious, but allow it to be safe.  Just ignore the alias.
    1311                6:     GA->eraseFromParent();
    1312                6:     return;
    1313                 :   }
    1314                 : 
                        1: branch 0 taken
                       20: branch 1 taken
    1315               21:   if (Entry) {
    1316                 :     // If there is a declaration in the module, then we had an extern followed
    1317                 :     // by the alias, as in:
    1318                 :     //   extern int test6();
    1319                 :     //   ...
    1320                 :     //   int test6() __attribute__((alias("test7")));
    1321                 :     //
    1322                 :     // Remove it and replace uses of it with the alias.
    1323                 : 
    1324                 :     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
    1325                1:                                                           Entry->getType()));
    1326                1:     Entry->eraseFromParent();
    1327                 :   }
    1328                 : 
    1329                 :   // Now we know that there is no conflict, set the name.
    1330               21:   Entry = GA;
    1331               21:   GA->setName(MangledName);
    1332                 : 
    1333                 :   // Set attributes which are particular to an alias; this is a
    1334                 :   // specialization of the attributes which may be set on a global
    1335                 :   // variable/function.
                        0: branch 1 not taken
                       21: branch 2 taken
    1336               21:   if (D->hasAttr<DLLExportAttr>()) {
                        0: branch 1 not taken
                        0: branch 2 not taken
    1337                0:     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    1338                 :       // The dllexport attribute is ignored for undefined symbols.
                        0: branch 1 not taken
                        0: branch 2 not taken
    1339                0:       if (FD->getBody())
    1340                0:         GA->setLinkage(llvm::Function::DLLExportLinkage);
    1341                 :     } else {
    1342                0:       GA->setLinkage(llvm::Function::DLLExportLinkage);
    1343                 :     }
                        7: branch 1 taken
                       14: branch 2 taken
                        0: branch 4 not taken
                        7: branch 5 taken
                       14: branch 6 taken
                        7: branch 7 taken
    1344               21:   } else if (D->hasAttr<WeakAttr>() ||
    1345                 :              D->hasAttr<WeakImportAttr>()) {
    1346               14:     GA->setLinkage(llvm::Function::WeakAnyLinkage);
    1347                 :   }
    1348                 : 
    1349               21:   SetCommonAttributes(D, GA);
    1350                 : }
    1351                 : 
    1352                 : /// getBuiltinLibFunction - Given a builtin id for a function like
    1353                 : /// "__builtin_fabsf", return a Function* for "fabsf".
    1354                 : llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
    1355              414:                                                   unsigned BuiltinID) {
    1356                 :   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
    1357                 :           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
                      388: branch 1 taken
                       26: branch 2 taken
                      388: branch 4 taken
                        0: branch 5 not taken
    1358              414:          "isn't a lib fn");
    1359                 : 
    1360                 :   // Get the name, skip over the __builtin_ prefix (if necessary).
    1361              414:   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
                       26: branch 1 taken
                      388: branch 2 taken
    1362              414:   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
    1363               26:     Name += 10;
    1364                 : 
    1365                 :   const llvm::FunctionType *Ty =
    1366              414:     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
    1367                 : 
    1368                 :   // Unique the name through the identifier table.
    1369              414:   Name = getContext().Idents.get(Name).getNameStart();
    1370              414:   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
    1371                 : }
    1372                 : 
    1373                 : llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
    1374              478:                                             unsigned NumTys) {
    1375                 :   return llvm::Intrinsic::getDeclaration(&getModule(),
    1376              478:                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
    1377                 : }
    1378                 : 
    1379              251: llvm::Function *CodeGenModule::getMemCpyFn() {
                      179: branch 0 taken
                       72: branch 1 taken
    1380              251:   if (MemCpyFn) return MemCpyFn;
    1381               72:   const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
    1382               72:   return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
    1383                 : }
    1384                 : 
    1385                1: llvm::Function *CodeGenModule::getMemMoveFn() {
                        0: branch 0 not taken
                        1: branch 1 taken
    1386                1:   if (MemMoveFn) return MemMoveFn;
    1387                1:   const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
    1388                1:   return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
    1389                 : }
    1390                 : 
    1391               40: llvm::Function *CodeGenModule::getMemSetFn() {
                       14: branch 0 taken
                       26: branch 1 taken
    1392               40:   if (MemSetFn) return MemSetFn;
    1393               26:   const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
    1394               26:   return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
    1395                 : }
    1396                 : 
    1397                 : static llvm::StringMapEntry<llvm::Constant*> &
    1398                 : GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
    1399                 :                          const StringLiteral *Literal,
    1400                 :                          bool TargetIsLSB,
    1401                 :                          bool &IsUTF16,
    1402               79:                          unsigned &StringLength) {
    1403               79:   unsigned NumBytes = Literal->getByteLength();
    1404                 : 
    1405                 :   // Check for simple case.
                       75: branch 1 taken
                        4: branch 2 taken
    1406               79:   if (!Literal->containsNonAsciiOrNull()) {
    1407               75:     StringLength = NumBytes;
    1408                 :     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
    1409               75:                                                 StringLength));
    1410                 :   }
    1411                 : 
    1412                 :   // Otherwise, convert the UTF8 literals into a byte string.
    1413                4:   llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
    1414                4:   const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
    1415                4:   UTF16 *ToPtr = &ToBuf[0];
    1416                 : 
    1417                 :   ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
    1418                 :                                                &ToPtr, ToPtr + NumBytes,
    1419                4:                                                strictConversion);
    1420                 : 
    1421                 :   // Check for conversion failure.
                        0: branch 0 not taken
                        4: branch 1 taken
    1422                4:   if (Result != conversionOK) {
    1423                 :     // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
    1424                 :     // this duplicate code.
                        0: branch 0 not taken
                        0: branch 1 not taken
    1425                0:     assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
    1426                0:     StringLength = NumBytes;
    1427                 :     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
    1428                0:                                                 StringLength));
    1429                 :   }
    1430                 : 
    1431                 :   // ConvertUTF8toUTF16 returns the length in ToPtr.
    1432                4:   StringLength = ToPtr - &ToBuf[0];
    1433                 : 
    1434                 :   // Render the UTF-16 string into a byte array and convert to the target byte
    1435                 :   // order.
    1436                 :   //
    1437                 :   // FIXME: This isn't something we should need to do here.
    1438                4:   llvm::SmallString<128> AsBytes;
    1439                4:   AsBytes.reserve(StringLength * 2);
                       44: branch 0 taken
                        4: branch 1 taken
    1440               48:   for (unsigned i = 0; i != StringLength; ++i) {
    1441               44:     unsigned short Val = ToBuf[i];
                       22: branch 0 taken
                       22: branch 1 taken
    1442               44:     if (TargetIsLSB) {
    1443               22:       AsBytes.push_back(Val & 0xFF);
    1444               22:       AsBytes.push_back(Val >> 8);
    1445                 :     } else {
    1446               22:       AsBytes.push_back(Val >> 8);
    1447               22:       AsBytes.push_back(Val & 0xFF);
    1448                 :     }
    1449                 :   }
    1450                 :   // Append one extra null character, the second is automatically added by our
    1451                 :   // caller.
    1452                4:   AsBytes.push_back(0);
    1453                 : 
    1454                4:   IsUTF16 = true;
    1455                4:   return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
    1456                 : }
    1457                 : 
    1458                 : llvm::Constant *
    1459               79: CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
    1460               79:   unsigned StringLength = 0;
    1461               79:   bool isUTF16 = false;
    1462                 :   llvm::StringMapEntry<llvm::Constant*> &Entry =
    1463                 :     GetConstantCFStringEntry(CFConstantStringMap, Literal,
    1464                 :                              getTargetData().isLittleEndian(),
    1465               79:                              isUTF16, StringLength);
    1466                 : 
                        0: branch 1 not taken
                       79: branch 2 taken
    1467               79:   if (llvm::Constant *C = Entry.getValue())
    1468                0:     return C;
    1469                 : 
    1470                 :   llvm::Constant *Zero =
    1471               79:       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
    1472               79:   llvm::Constant *Zeros[] = { Zero, Zero };
    1473                 : 
    1474                 :   // If we don't already have it, get __CFConstantStringClassReference.
                        7: branch 0 taken
                       72: branch 1 taken
    1475               79:   if (!CFConstantStringClassRef) {
    1476                7:     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
    1477                7:     Ty = llvm::ArrayType::get(Ty, 0);
    1478                 :     llvm::Constant *GV = CreateRuntimeVariable(Ty,
    1479                7:                                            "__CFConstantStringClassReference");
    1480                 :     // Decay array -> ptr
    1481                 :     CFConstantStringClassRef =
    1482                7:       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
    1483                 :   }
    1484                 : 
    1485               79:   QualType CFTy = getContext().getCFConstantStringType();
    1486                 : 
    1487                 :   const llvm::StructType *STy =
    1488               79:     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
    1489                 : 
    1490               79:   std::vector<llvm::Constant*> Fields(4);
    1491                 : 
    1492                 :   // Class pointer.
    1493               79:   Fields[0] = CFConstantStringClassRef;
    1494                 : 
    1495                 :   // Flags.
    1496               79:   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
    1497                 :   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
                        4: branch 1 taken
                       75: branch 2 taken
    1498               79:     llvm::ConstantInt::get(Ty, 0x07C8);
    1499                 : 
    1500                 :   // String pointer.
    1501               79:   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
    1502                 : 
    1503                 :   llvm::GlobalValue::LinkageTypes Linkage;
    1504                 :   bool isConstant;
                        4: branch 0 taken
                       75: branch 1 taken
    1505               79:   if (isUTF16) {
    1506                 :     // FIXME: why do utf strings get "_" labels instead of "L" labels?
    1507                4:     Linkage = llvm::GlobalValue::InternalLinkage;
    1508                 :     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
    1509                 :     // does make plain ascii ones writable.
    1510                4:     isConstant = true;
    1511                 :   } else {
    1512               75:     Linkage = llvm::GlobalValue::PrivateLinkage;
    1513               75:     isConstant = !Features.WritableStrings;
    1514                 :   }
    1515                 :   
    1516                 :   llvm::GlobalVariable *GV =
    1517                 :     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
    1518               79:                              ".str");
                        4: branch 0 taken
                       75: branch 1 taken
    1519               79:   if (isUTF16) {
    1520                4:     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
    1521                4:     GV->setAlignment(Align.getQuantity());
    1522                 :   }
    1523               79:   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
    1524                 : 
    1525                 :   // String length.
    1526               79:   Ty = getTypes().ConvertType(getContext().LongTy);
    1527               79:   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
    1528                 : 
    1529                 :   // The struct.
    1530               79:   C = llvm::ConstantStruct::get(STy, Fields);
    1531                 :   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
    1532                 :                                 llvm::GlobalVariable::PrivateLinkage, C,
    1533               79:                                 "_unnamed_cfstring_");
                       79: branch 2 taken
                        0: branch 3 not taken
    1534               79:   if (const char *Sect = getContext().Target.getCFStringSection())
    1535               79:     GV->setSection(Sect);
    1536               79:   Entry.setValue(GV);
    1537                 : 
    1538               79:   return GV;
    1539                 : }
    1540                 : 
    1541                 : /// GetStringForStringLiteral - Return the appropriate bytes for a
    1542                 : /// string literal, properly padded to match the literal type.
    1543              637: std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
    1544              637:   const char *StrData = E->getStrData();
    1545              637:   unsigned Len = E->getByteLength();
    1546                 : 
    1547                 :   const ConstantArrayType *CAT =
    1548              637:     getContext().getAsConstantArrayType(E->getType());
                        0: branch 0 not taken
                      637: branch 1 taken
    1549              637:   assert(CAT && "String isn't pointer or array!");
    1550                 : 
    1551                 :   // Resize the string to the right size.
    1552              637:   std::string Str(StrData, StrData+Len);
    1553              637:   uint64_t RealLen = CAT->getSize().getZExtValue();
    1554                 : 
                        1: branch 1 taken
                      636: branch 2 taken
    1555              637:   if (E->isWide())
    1556                1:     RealLen *= getContext().Target.getWCharWidth()/8;
    1557                 : 
    1558              637:   Str.resize(RealLen, '\0');
    1559                 : 
    1560                 :   return Str;
    1561                 : }
    1562                 : 
    1563                 : /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
    1564                 : /// constant array for the given string literal.
    1565                 : llvm::Constant *
    1566              618: CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
    1567                 :   // FIXME: This can be more efficient.
    1568                 :   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
    1569              618:   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
                        1: branch 1 taken
                      617: branch 2 taken
    1570              618:   if (S->isWide()) {
    1571                 :     llvm::Type *DestTy =
    1572                1:         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
    1573                1:     C = llvm::ConstantExpr::getBitCast(C, DestTy);
    1574                 :   }
    1575              618:   return C;
    1576                 : }
    1577                 : 
    1578                 : /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
    1579                 : /// array for the given ObjCEncodeExpr node.
    1580                 : llvm::Constant *
    1581               19: CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
    1582               19:   std::string Str;
    1583               19:   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
    1584                 : 
    1585               19:   return GetAddrOfConstantCString(Str);
    1586                 : }
    1587                 : 
    1588                 : 
    1589                 : /// GenerateWritableString -- Creates storage for a string literal.
    1590                 : static llvm::Constant *GenerateStringLiteral(const std::string &str,
    1591                 :                                              bool constant,
    1592                 :                                              CodeGenModule &CGM,
    1593              539:                                              const char *GlobalName) {
    1594                 :   // Create Constant for this string literal. Don't add a '\0'.
    1595                 :   llvm::Constant *C =
    1596              539:       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
    1597                 : 
    1598                 :   // Create a global variable for this string
    1599                 :   return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
    1600                 :                                   llvm::GlobalValue::PrivateLinkage,
    1601              539:                                   C, GlobalName);
    1602                 : }
    1603                 : 
    1604                 : /// GetAddrOfConstantString - Returns a pointer to a character array
    1605                 : /// containing the literal. This contents are exactly that of the
    1606                 : /// given string, i.e. it will not be null terminated automatically;
    1607                 : /// see GetAddrOfConstantCString. Note that whether the result is
    1608                 : /// actually a pointer to an LLVM constant depends on
    1609                 : /// Feature.WriteableStrings.
    1610                 : ///
    1611                 : /// The result has pointer to array type.
    1612                 : llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
    1613              882:                                                        const char *GlobalName) {
    1614              882:   bool IsConstant = !Features.WritableStrings;
    1615                 : 
    1616                 :   // Get the default prefix if a name wasn't specified.
                      637: branch 0 taken
                      245: branch 1 taken
    1617              882:   if (!GlobalName)
    1618              637:     GlobalName = ".str";
    1619                 : 
    1620                 :   // Don't share any string literals if strings aren't constant.
                        2: branch 0 taken
                      880: branch 1 taken
    1621              882:   if (!IsConstant)
    1622                2:     return GenerateStringLiteral(str, false, *this, GlobalName);
    1623                 : 
    1624                 :   llvm::StringMapEntry<llvm::Constant *> &Entry =
    1625              880:     ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
    1626                 : 
                      343: branch 1 taken
                      537: branch 2 taken
    1627              880:   if (Entry.getValue())
    1628              343:     return Entry.getValue();
    1629                 : 
    1630                 :   // Create a global variable for this.
    1631              537:   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
    1632              537:   Entry.setValue(C);
    1633              537:   return C;
    1634                 : }
    1635                 : 
    1636                 : /// GetAddrOfConstantCString - Returns a pointer to a character
    1637                 : /// array containing the literal and a terminating '\-'
    1638                 : /// character. The result has pointer to array type.
    1639                 : llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
    1640              264:                                                         const char *GlobalName){
    1641              264:   return GetAddrOfConstantString(str + '\0', GlobalName);
    1642                 : }
    1643                 : 
    1644                 : /// EmitObjCPropertyImplementations - Emit information for synthesized
    1645                 : /// properties for an implementation.
    1646                 : void CodeGenModule::EmitObjCPropertyImplementations(const
    1647              158:                                                     ObjCImplementationDecl *D) {
                       84: branch 2 taken
                      158: branch 3 taken
    1648              242:   for (ObjCImplementationDecl::propimpl_iterator
    1649              158:          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
    1650               84:     ObjCPropertyImplDecl *PID = *i;
    1651                 : 
    1652                 :     // Dynamic is just for type-checking.
                       60: branch 1 taken
                       24: branch 2 taken
    1653               84:     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
    1654               60:       ObjCPropertyDecl *PD = PID->getPropertyDecl();
    1655                 : 
    1656                 :       // Determine which methods need to be implemented, some may have
    1657                 :       // been overridden. Note that ::isSynthesized is not the method
    1658                 :       // we want, that just indicates if the decl came from a
    1659                 :       // property. What we want to know is if the method is defined in
    1660                 :       // this implementation.
                       59: branch 2 taken
                        1: branch 3 taken
    1661               60:       if (!D->getInstanceMethod(PD->getGetterName()))
    1662                 :         CodeGenFunction(*this).GenerateObjCGetter(
    1663               59:                                  const_cast<ObjCImplementationDecl *>(D), PID);
                       59: branch 1 taken
                        1: branch 2 taken
                       57: branch 5 taken
                        2: branch 6 taken
                       57: branch 7 taken
                        3: branch 8 taken
    1664               60:       if (!PD->isReadOnly() &&
    1665                 :           !D->getInstanceMethod(PD->getSetterName()))
    1666                 :         CodeGenFunction(*this).GenerateObjCSetter(
    1667               57:                                  const_cast<ObjCImplementationDecl *>(D), PID);
    1668                 :     }
    1669                 :   }
    1670              158: }
    1671                 : 
    1672                 : /// EmitNamespace - Emit all declarations in a namespace.
    1673               96: void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
                      280: branch 4 taken
                       96: branch 5 taken
    1674              376:   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
    1675                 :        I != E; ++I)
    1676              280:     EmitTopLevelDecl(*I);
    1677               96: }
    1678                 : 
    1679                 : // EmitLinkageSpec - Emit all declarations in a linkage spec.
    1680               64: void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
                        2: branch 1 taken
                       62: branch 2 taken
                        0: branch 4 not taken
                        2: branch 5 taken
                        0: branch 6 not taken
                       64: branch 7 taken
    1681               64:   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
    1682                 :       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
    1683                0:     ErrorUnsupported(LSD, "linkage spec");
    1684                0:     return;
    1685                 :   }
    1686                 : 
                      338: branch 4 taken
                       64: branch 5 taken
    1687              402:   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
    1688                 :        I != E; ++I)
    1689              338:     EmitTopLevelDecl(*I);
    1690                 : }
    1691                 : 
    1692                 : /// EmitTopLevelDecl - Emit code for a single top level declaration.
    1693             6760: void CodeGenModule::EmitTopLevelDecl(Decl *D) {
    1694                 :   // If an error has occurred, stop code generation, but continue
    1695                 :   // parsing and semantic analysis (to ensure all warnings and errors
    1696                 :   // are emitted).
                     6751: branch 1 taken
                        9: branch 2 taken
    1697             6760:   if (Diags.hasErrorOccurred())
    1698                9:     return;
    1699                 : 
    1700                 :   // Ignore dependent declarations.
                     6751: branch 1 taken
                        0: branch 2 not taken
                       11: branch 5 taken
                     6740: branch 6 taken
                       11: branch 7 taken
                     6740: branch 8 taken
    1701             6751:   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
    1702               11:     return;
    1703                 : 
                     2411: branch 1 taken
                      746: branch 2 taken
                       96: branch 3 taken
                       53: branch 4 taken
                       40: branch 5 taken
                       27: branch 6 taken
                        5: branch 7 taken
                      292: branch 8 taken
                       32: branch 9 taken
                       21: branch 10 taken
                      158: branch 11 taken
                      175: branch 12 taken
                        1: branch 13 taken
                       64: branch 14 taken
                        6: branch 15 taken
                     2613: branch 16 taken
    1704             6740:   switch (D->getKind()) {
    1705                 :   case Decl::CXXConversion:
    1706                 :   case Decl::CXXMethod:
    1707                 :   case Decl::Function:
    1708                 :     // Skip function templates
                       22: branch 2 taken
                     2389: branch 3 taken
    1709             2411:     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
    1710               22:       return;
    1711                 : 
    1712             2389:     EmitGlobal(cast<FunctionDecl>(D));
    1713             2389:     break;
    1714                 :       
    1715                 :   case Decl::Var:
    1716              746:     EmitGlobal(cast<VarDecl>(D));
    1717              746:     break;
    1718                 : 
    1719                 :   // C++ Decls
    1720                 :   case Decl::Namespace:
    1721               96:     EmitNamespace(cast<NamespaceDecl>(D));
    1722               96:     break;
    1723                 :     // No code generation needed.
    1724                 :   case Decl::UsingShadow:
    1725                 :   case Decl::Using:
    1726                 :   case Decl::UsingDirective:
    1727                 :   case Decl::ClassTemplate:
    1728                 :   case Decl::FunctionTemplate:
    1729                 :   case Decl::NamespaceAlias:
    1730               53:     break;
    1731                 :   case Decl::CXXConstructor:
    1732                 :     // Skip function templates
                        2: branch 2 taken
                       38: branch 3 taken
    1733               40:     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
    1734                2:       return;
    1735                 :       
    1736               38:     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
    1737               38:     break;
    1738                 :   case Decl::CXXDestructor:
    1739               27:     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
    1740               27:     break;
    1741                 : 
    1742                 :   case Decl::StaticAssert:
    1743                 :     // Nothing to do.
    1744                5:     break;
    1745                 : 
    1746                 :   // Objective-C Decls
    1747                 : 
    1748                 :   // Forward declarations, no (immediate) code generation.
    1749                 :   case Decl::ObjCClass:
    1750                 :   case Decl::ObjCForwardProtocol:
    1751                 :   case Decl::ObjCCategory:
    1752                 :   case Decl::ObjCInterface:
    1753              292:     break;
    1754                 : 
    1755                 :   case Decl::ObjCProtocol:
    1756               32:     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
    1757               32:     break;
    1758                 : 
    1759                 :   case Decl::ObjCCategoryImpl:
    1760                 :     // Categories have properties but don't support synthesize so we
    1761                 :     // can ignore them here.
    1762               21:     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
    1763               21:     break;
    1764                 : 
    1765                 :   case Decl::ObjCImplementation: {
    1766              158:     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
    1767              158:     EmitObjCPropertyImplementations(OMD);
    1768              158:     Runtime->GenerateClass(OMD);
    1769              158:     break;
    1770                 :   }
    1771                 :   case Decl::ObjCMethod: {
    1772              175:     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
    1773                 :     // If this is not a prototype, emit the body.
                      175: branch 1 taken
                        0: branch 2 not taken
    1774              175:     if (OMD->getBody())
    1775              175:       CodeGenFunction(*this).GenerateObjCMethod(OMD);
    1776              175:     break;
    1777                 :   }
    1778                 :   case Decl::ObjCCompatibleAlias:
    1779                 :     // compatibility-alias is a directive and has no code gen.
    1780                1:     break;
    1781                 : 
    1782                 :   case Decl::LinkageSpec:
    1783               64:     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
    1784               64:     break;
    1785                 : 
    1786                 :   case Decl::FileScopeAsm: {
    1787                6:     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
    1788                6:     llvm::StringRef AsmString = AD->getAsmString()->getString();
    1789                 : 
    1790                6:     const std::string &S = getModule().getModuleInlineAsm();
                        6: branch 1 taken
                        0: branch 2 not taken
    1791                6:     if (S.empty())
    1792                6:       getModule().setModuleInlineAsm(AsmString);
    1793                 :     else
    1794                0:       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
    1795                6:     break;
    1796                 :   }
    1797                 : 
    1798                 :   default:
    1799                 :     // Make sure we handled everything we should, every other kind is a
    1800                 :     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
    1801                 :     // function. Need to recode Decl::Kind to do that easily.
                     2613: branch 1 taken
                        0: branch 2 not taken
    1802             2613:     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
    1803                 :   }
    1804                 : }

Generated: 2010-02-10 01:31 by zcov