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 "CodeGenTBAA.h" 18 #include "CGCall.h" 19 #include "CGCUDARuntime.h" 20 #include "CGCXXABI.h" 21 #include "CGObjCRuntime.h" 22 #include "CGOpenCLRuntime.h" 23 #include "TargetInfo.h" 24 #include "clang/Frontend/CodeGenOptions.h" 25 #include "clang/AST/ASTContext.h" 26 #include "clang/AST/CharUnits.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/DeclCXX.h" 29 #include "clang/AST/DeclTemplate.h" 30 #include "clang/AST/Mangle.h" 31 #include "clang/AST/RecordLayout.h" 32 #include "clang/AST/RecursiveASTVisitor.h" 33 #include "clang/Basic/Builtins.h" 34 #include "clang/Basic/Diagnostic.h" 35 #include "clang/Basic/SourceManager.h" 36 #include "clang/Basic/TargetInfo.h" 37 #include "clang/Basic/ConvertUTF.h" 38 #include "llvm/CallingConv.h" 39 #include "llvm/Module.h" 40 #include "llvm/Intrinsics.h" 41 #include "llvm/LLVMContext.h" 42 #include "llvm/ADT/Triple.h" 43 #include "llvm/Target/Mangler.h" 44 #include "llvm/Target/TargetData.h" 45 #include "llvm/Support/CallSite.h" 46 #include "llvm/Support/ErrorHandling.h" 47 using namespace clang; 48 using namespace CodeGen; 49 50 static const char AnnotationSection[] = "llvm.metadata"; 51 52 static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 53 switch (CGM.getContext().getTargetInfo().getCXXABI()) { 54 case CXXABI_ARM: return *CreateARMCXXABI(CGM); 55 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 56 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 57 } 58 59 llvm_unreachable("invalid C++ ABI kind"); 60 return *CreateItaniumCXXABI(CGM); 61 } 62 63 64 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 65 llvm::Module &M, const llvm::TargetData &TD, 66 DiagnosticsEngine &diags) 67 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 68 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 69 ABI(createCXXABI(*this)), 70 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO), 71 TBAA(0), 72 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0), 73 DebugInfo(0), ARCData(0), RRData(0), CFConstantStringClassRef(0), 74 ConstantStringClassRef(0), NSConstantStringType(0), 75 VMContext(M.getContext()), 76 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 77 BlockObjectAssign(0), BlockObjectDispose(0), 78 BlockDescriptorType(0), GenericBlockLiteralType(0) { 79 if (Features.ObjC1) 80 createObjCRuntime(); 81 if (Features.OpenCL) 82 createOpenCLRuntime(); 83 if (Features.CUDA) 84 createCUDARuntime(); 85 86 // Enable TBAA unless it's suppressed. 87 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0) 88 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(), 89 ABI.getMangleContext()); 90 91 // If debug info or coverage generation is enabled, create the CGDebugInfo 92 // object. 93 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs || 94 CodeGenOpts.EmitGcovNotes) 95 DebugInfo = new CGDebugInfo(*this); 96 97 Block.GlobalUniqueCount = 0; 98 99 if (C.getLangOptions().ObjCAutoRefCount) 100 ARCData = new ARCEntrypoints(); 101 RRData = new RREntrypoints(); 102 103 // Initialize the type cache. 104 llvm::LLVMContext &LLVMContext = M.getContext(); 105 VoidTy = llvm::Type::getVoidTy(LLVMContext); 106 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 107 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 108 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 109 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 110 PointerAlignInBytes = 111 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 112 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 113 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 114 Int8PtrTy = Int8Ty->getPointerTo(0); 115 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 116 } 117 118 CodeGenModule::~CodeGenModule() { 119 delete ObjCRuntime; 120 delete OpenCLRuntime; 121 delete CUDARuntime; 122 delete TheTargetCodeGenInfo; 123 delete &ABI; 124 delete TBAA; 125 delete DebugInfo; 126 delete ARCData; 127 delete RRData; 128 } 129 130 void CodeGenModule::createObjCRuntime() { 131 if (!Features.NeXTRuntime) 132 ObjCRuntime = CreateGNUObjCRuntime(*this); 133 else 134 ObjCRuntime = CreateMacObjCRuntime(*this); 135 } 136 137 void CodeGenModule::createOpenCLRuntime() { 138 OpenCLRuntime = new CGOpenCLRuntime(*this); 139 } 140 141 void CodeGenModule::createCUDARuntime() { 142 CUDARuntime = CreateNVCUDARuntime(*this); 143 } 144 145 void CodeGenModule::Release() { 146 EmitDeferred(); 147 EmitCXXGlobalInitFunc(); 148 EmitCXXGlobalDtorFunc(); 149 if (ObjCRuntime) 150 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 151 AddGlobalCtor(ObjCInitFunction); 152 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 153 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 154 EmitGlobalAnnotations(); 155 EmitLLVMUsed(); 156 157 SimplifyPersonality(); 158 159 if (getCodeGenOpts().EmitDeclMetadata) 160 EmitDeclMetadata(); 161 162 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 163 EmitCoverageFile(); 164 165 if (DebugInfo) 166 DebugInfo->finalize(); 167 } 168 169 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 170 // Make sure that this type is translated. 171 Types.UpdateCompletedType(TD); 172 if (DebugInfo) 173 DebugInfo->UpdateCompletedType(TD); 174 } 175 176 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 177 if (!TBAA) 178 return 0; 179 return TBAA->getTBAAInfo(QTy); 180 } 181 182 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 183 llvm::MDNode *TBAAInfo) { 184 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 185 } 186 187 bool CodeGenModule::isTargetDarwin() const { 188 return getContext().getTargetInfo().getTriple().isOSDarwin(); 189 } 190 191 void CodeGenModule::Error(SourceLocation loc, StringRef error) { 192 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error); 193 getDiags().Report(Context.getFullLoc(loc), diagID); 194 } 195 196 /// ErrorUnsupported - Print out an error that codegen doesn't support the 197 /// specified stmt yet. 198 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 199 bool OmitOnError) { 200 if (OmitOnError && getDiags().hasErrorOccurred()) 201 return; 202 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 203 "cannot compile this %0 yet"); 204 std::string Msg = Type; 205 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 206 << Msg << S->getSourceRange(); 207 } 208 209 /// ErrorUnsupported - Print out an error that codegen doesn't support the 210 /// specified decl yet. 211 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 212 bool OmitOnError) { 213 if (OmitOnError && getDiags().hasErrorOccurred()) 214 return; 215 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 216 "cannot compile this %0 yet"); 217 std::string Msg = Type; 218 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 219 } 220 221 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 222 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 223 } 224 225 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 226 const NamedDecl *D) const { 227 // Internal definitions always have default visibility. 228 if (GV->hasLocalLinkage()) { 229 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 230 return; 231 } 232 233 // Set visibility for definitions. 234 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 235 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 236 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 237 } 238 239 /// Set the symbol visibility of type information (vtable and RTTI) 240 /// associated with the given type. 241 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 242 const CXXRecordDecl *RD, 243 TypeVisibilityKind TVK) const { 244 setGlobalVisibility(GV, RD); 245 246 if (!CodeGenOpts.HiddenWeakVTables) 247 return; 248 249 // We never want to drop the visibility for RTTI names. 250 if (TVK == TVK_ForRTTIName) 251 return; 252 253 // We want to drop the visibility to hidden for weak type symbols. 254 // This isn't possible if there might be unresolved references 255 // elsewhere that rely on this symbol being visible. 256 257 // This should be kept roughly in sync with setThunkVisibility 258 // in CGVTables.cpp. 259 260 // Preconditions. 261 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 262 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 263 return; 264 265 // Don't override an explicit visibility attribute. 266 if (RD->getExplicitVisibility()) 267 return; 268 269 switch (RD->getTemplateSpecializationKind()) { 270 // We have to disable the optimization if this is an EI definition 271 // because there might be EI declarations in other shared objects. 272 case TSK_ExplicitInstantiationDefinition: 273 case TSK_ExplicitInstantiationDeclaration: 274 return; 275 276 // Every use of a non-template class's type information has to emit it. 277 case TSK_Undeclared: 278 break; 279 280 // In theory, implicit instantiations can ignore the possibility of 281 // an explicit instantiation declaration because there necessarily 282 // must be an EI definition somewhere with default visibility. In 283 // practice, it's possible to have an explicit instantiation for 284 // an arbitrary template class, and linkers aren't necessarily able 285 // to deal with mixed-visibility symbols. 286 case TSK_ExplicitSpecialization: 287 case TSK_ImplicitInstantiation: 288 if (!CodeGenOpts.HiddenWeakTemplateVTables) 289 return; 290 break; 291 } 292 293 // If there's a key function, there may be translation units 294 // that don't have the key function's definition. But ignore 295 // this if we're emitting RTTI under -fno-rtti. 296 if (!(TVK != TVK_ForRTTI) || Features.RTTI) { 297 if (Context.getKeyFunction(RD)) 298 return; 299 } 300 301 // Otherwise, drop the visibility to hidden. 302 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 303 GV->setUnnamedAddr(true); 304 } 305 306 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 307 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 308 309 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 310 if (!Str.empty()) 311 return Str; 312 313 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 314 IdentifierInfo *II = ND->getIdentifier(); 315 assert(II && "Attempt to mangle unnamed decl."); 316 317 Str = II->getName(); 318 return Str; 319 } 320 321 llvm::SmallString<256> Buffer; 322 llvm::raw_svector_ostream Out(Buffer); 323 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 324 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 325 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 326 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 327 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 328 getCXXABI().getMangleContext().mangleBlock(BD, Out); 329 else 330 getCXXABI().getMangleContext().mangleName(ND, Out); 331 332 // Allocate space for the mangled name. 333 Out.flush(); 334 size_t Length = Buffer.size(); 335 char *Name = MangledNamesAllocator.Allocate<char>(Length); 336 std::copy(Buffer.begin(), Buffer.end(), Name); 337 338 Str = StringRef(Name, Length); 339 340 return Str; 341 } 342 343 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 344 const BlockDecl *BD) { 345 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 346 const Decl *D = GD.getDecl(); 347 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 348 if (D == 0) 349 MangleCtx.mangleGlobalBlock(BD, Out); 350 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 351 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 352 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 353 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 354 else 355 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 356 } 357 358 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 359 return getModule().getNamedValue(Name); 360 } 361 362 /// AddGlobalCtor - Add a function to the list that will be called before 363 /// main() runs. 364 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 365 // FIXME: Type coercion of void()* types. 366 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 367 } 368 369 /// AddGlobalDtor - Add a function to the list that will be called 370 /// when the module is unloaded. 371 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 372 // FIXME: Type coercion of void()* types. 373 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 374 } 375 376 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 377 // Ctor function type is void()*. 378 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 379 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 380 381 // Get the type of a ctor entry, { i32, void ()* }. 382 llvm::StructType *CtorStructTy = 383 llvm::StructType::get(llvm::Type::getInt32Ty(VMContext), 384 llvm::PointerType::getUnqual(CtorFTy), NULL); 385 386 // Construct the constructor and destructor arrays. 387 std::vector<llvm::Constant*> Ctors; 388 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 389 std::vector<llvm::Constant*> S; 390 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 391 I->second, false)); 392 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 393 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 394 } 395 396 if (!Ctors.empty()) { 397 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 398 new llvm::GlobalVariable(TheModule, AT, false, 399 llvm::GlobalValue::AppendingLinkage, 400 llvm::ConstantArray::get(AT, Ctors), 401 GlobalName); 402 } 403 } 404 405 llvm::GlobalValue::LinkageTypes 406 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 407 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 408 409 if (Linkage == GVA_Internal) 410 return llvm::Function::InternalLinkage; 411 412 if (D->hasAttr<DLLExportAttr>()) 413 return llvm::Function::DLLExportLinkage; 414 415 if (D->hasAttr<WeakAttr>()) 416 return llvm::Function::WeakAnyLinkage; 417 418 // In C99 mode, 'inline' functions are guaranteed to have a strong 419 // definition somewhere else, so we can use available_externally linkage. 420 if (Linkage == GVA_C99Inline) 421 return llvm::Function::AvailableExternallyLinkage; 422 423 // Note that Apple's kernel linker doesn't support symbol 424 // coalescing, so we need to avoid linkonce and weak linkages there. 425 // Normally, this means we just map to internal, but for explicit 426 // instantiations we'll map to external. 427 428 // In C++, the compiler has to emit a definition in every translation unit 429 // that references the function. We should use linkonce_odr because 430 // a) if all references in this translation unit are optimized away, we 431 // don't need to codegen it. b) if the function persists, it needs to be 432 // merged with other definitions. c) C++ has the ODR, so we know the 433 // definition is dependable. 434 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 435 return !Context.getLangOptions().AppleKext 436 ? llvm::Function::LinkOnceODRLinkage 437 : llvm::Function::InternalLinkage; 438 439 // An explicit instantiation of a template has weak linkage, since 440 // explicit instantiations can occur in multiple translation units 441 // and must all be equivalent. However, we are not allowed to 442 // throw away these explicit instantiations. 443 if (Linkage == GVA_ExplicitTemplateInstantiation) 444 return !Context.getLangOptions().AppleKext 445 ? llvm::Function::WeakODRLinkage 446 : llvm::Function::ExternalLinkage; 447 448 // Otherwise, we have strong external linkage. 449 assert(Linkage == GVA_StrongExternal); 450 return llvm::Function::ExternalLinkage; 451 } 452 453 454 /// SetFunctionDefinitionAttributes - Set attributes for a global. 455 /// 456 /// FIXME: This is currently only done for aliases and functions, but not for 457 /// variables (these details are set in EmitGlobalVarDefinition for variables). 458 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 459 llvm::GlobalValue *GV) { 460 SetCommonAttributes(D, GV); 461 } 462 463 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 464 const CGFunctionInfo &Info, 465 llvm::Function *F) { 466 unsigned CallingConv; 467 AttributeListType AttributeList; 468 ConstructAttributeList(Info, D, AttributeList, CallingConv); 469 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 470 AttributeList.size())); 471 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 472 } 473 474 /// Determines whether the language options require us to model 475 /// unwind exceptions. We treat -fexceptions as mandating this 476 /// except under the fragile ObjC ABI with only ObjC exceptions 477 /// enabled. This means, for example, that C with -fexceptions 478 /// enables this. 479 static bool hasUnwindExceptions(const LangOptions &Features) { 480 // If exceptions are completely disabled, obviously this is false. 481 if (!Features.Exceptions) return false; 482 483 // If C++ exceptions are enabled, this is true. 484 if (Features.CXXExceptions) return true; 485 486 // If ObjC exceptions are enabled, this depends on the ABI. 487 if (Features.ObjCExceptions) { 488 if (!Features.ObjCNonFragileABI) return false; 489 } 490 491 return true; 492 } 493 494 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 495 llvm::Function *F) { 496 if (CodeGenOpts.UnwindTables) 497 F->setHasUWTable(); 498 499 if (!hasUnwindExceptions(Features)) 500 F->addFnAttr(llvm::Attribute::NoUnwind); 501 502 if (D->hasAttr<NakedAttr>()) { 503 // Naked implies noinline: we should not be inlining such functions. 504 F->addFnAttr(llvm::Attribute::Naked); 505 F->addFnAttr(llvm::Attribute::NoInline); 506 } 507 508 if (D->hasAttr<NoInlineAttr>()) 509 F->addFnAttr(llvm::Attribute::NoInline); 510 511 // (noinline wins over always_inline, and we can't specify both in IR) 512 if (D->hasAttr<AlwaysInlineAttr>() && 513 !F->hasFnAttr(llvm::Attribute::NoInline)) 514 F->addFnAttr(llvm::Attribute::AlwaysInline); 515 516 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 517 F->setUnnamedAddr(true); 518 519 if (Features.getStackProtector() == LangOptions::SSPOn) 520 F->addFnAttr(llvm::Attribute::StackProtect); 521 else if (Features.getStackProtector() == LangOptions::SSPReq) 522 F->addFnAttr(llvm::Attribute::StackProtectReq); 523 524 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 525 if (alignment) 526 F->setAlignment(alignment); 527 528 // C++ ABI requires 2-byte alignment for member functions. 529 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 530 F->setAlignment(2); 531 } 532 533 void CodeGenModule::SetCommonAttributes(const Decl *D, 534 llvm::GlobalValue *GV) { 535 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 536 setGlobalVisibility(GV, ND); 537 else 538 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 539 540 if (D->hasAttr<UsedAttr>()) 541 AddUsedGlobal(GV); 542 543 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 544 GV->setSection(SA->getName()); 545 546 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 547 } 548 549 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 550 llvm::Function *F, 551 const CGFunctionInfo &FI) { 552 SetLLVMFunctionAttributes(D, FI, F); 553 SetLLVMFunctionAttributesForDefinition(D, F); 554 555 F->setLinkage(llvm::Function::InternalLinkage); 556 557 SetCommonAttributes(D, F); 558 } 559 560 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 561 llvm::Function *F, 562 bool IsIncompleteFunction) { 563 if (unsigned IID = F->getIntrinsicID()) { 564 // If this is an intrinsic function, set the function's attributes 565 // to the intrinsic's attributes. 566 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID)); 567 return; 568 } 569 570 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 571 572 if (!IsIncompleteFunction) 573 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 574 575 // Only a few attributes are set on declarations; these may later be 576 // overridden by a definition. 577 578 if (FD->hasAttr<DLLImportAttr>()) { 579 F->setLinkage(llvm::Function::DLLImportLinkage); 580 } else if (FD->hasAttr<WeakAttr>() || 581 FD->isWeakImported()) { 582 // "extern_weak" is overloaded in LLVM; we probably should have 583 // separate linkage types for this. 584 F->setLinkage(llvm::Function::ExternalWeakLinkage); 585 } else { 586 F->setLinkage(llvm::Function::ExternalLinkage); 587 588 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility(); 589 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) { 590 F->setVisibility(GetLLVMVisibility(LV.visibility())); 591 } 592 } 593 594 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 595 F->setSection(SA->getName()); 596 } 597 598 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 599 assert(!GV->isDeclaration() && 600 "Only globals with definition can force usage."); 601 LLVMUsed.push_back(GV); 602 } 603 604 void CodeGenModule::EmitLLVMUsed() { 605 // Don't create llvm.used if there is no need. 606 if (LLVMUsed.empty()) 607 return; 608 609 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 610 611 // Convert LLVMUsed to what ConstantArray needs. 612 std::vector<llvm::Constant*> UsedArray; 613 UsedArray.resize(LLVMUsed.size()); 614 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 615 UsedArray[i] = 616 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 617 i8PTy); 618 } 619 620 if (UsedArray.empty()) 621 return; 622 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 623 624 llvm::GlobalVariable *GV = 625 new llvm::GlobalVariable(getModule(), ATy, false, 626 llvm::GlobalValue::AppendingLinkage, 627 llvm::ConstantArray::get(ATy, UsedArray), 628 "llvm.used"); 629 630 GV->setSection("llvm.metadata"); 631 } 632 633 void CodeGenModule::EmitDeferred() { 634 // Emit code for any potentially referenced deferred decls. Since a 635 // previously unused static decl may become used during the generation of code 636 // for a static function, iterate until no changes are made. 637 638 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 639 if (!DeferredVTables.empty()) { 640 const CXXRecordDecl *RD = DeferredVTables.back(); 641 DeferredVTables.pop_back(); 642 getVTables().GenerateClassData(getVTableLinkage(RD), RD); 643 continue; 644 } 645 646 GlobalDecl D = DeferredDeclsToEmit.back(); 647 DeferredDeclsToEmit.pop_back(); 648 649 // Check to see if we've already emitted this. This is necessary 650 // for a couple of reasons: first, decls can end up in the 651 // deferred-decls queue multiple times, and second, decls can end 652 // up with definitions in unusual ways (e.g. by an extern inline 653 // function acquiring a strong function redefinition). Just 654 // ignore these cases. 655 // 656 // TODO: That said, looking this up multiple times is very wasteful. 657 StringRef Name = getMangledName(D); 658 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 659 assert(CGRef && "Deferred decl wasn't referenced?"); 660 661 if (!CGRef->isDeclaration()) 662 continue; 663 664 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 665 // purposes an alias counts as a definition. 666 if (isa<llvm::GlobalAlias>(CGRef)) 667 continue; 668 669 // Otherwise, emit the definition and move on to the next one. 670 EmitGlobalDefinition(D); 671 } 672 } 673 674 void CodeGenModule::EmitGlobalAnnotations() { 675 if (Annotations.empty()) 676 return; 677 678 // Create a new global variable for the ConstantStruct in the Module. 679 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 680 Annotations[0]->getType(), Annotations.size()), Annotations); 681 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 682 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 683 "llvm.global.annotations"); 684 gv->setSection(AnnotationSection); 685 } 686 687 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) { 688 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str); 689 if (i != AnnotationStrings.end()) 690 return i->second; 691 692 // Not found yet, create a new global. 693 llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true); 694 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 695 true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 696 gv->setSection(AnnotationSection); 697 gv->setUnnamedAddr(true); 698 AnnotationStrings[Str] = gv; 699 return gv; 700 } 701 702 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 703 SourceManager &SM = getContext().getSourceManager(); 704 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 705 if (PLoc.isValid()) 706 return EmitAnnotationString(PLoc.getFilename()); 707 return EmitAnnotationString(SM.getBufferName(Loc)); 708 } 709 710 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 711 SourceManager &SM = getContext().getSourceManager(); 712 PresumedLoc PLoc = SM.getPresumedLoc(L); 713 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 714 SM.getExpansionLineNumber(L); 715 return llvm::ConstantInt::get(Int32Ty, LineNo); 716 } 717 718 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 719 const AnnotateAttr *AA, 720 SourceLocation L) { 721 // Get the globals for file name, annotation, and the line number. 722 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 723 *UnitGV = EmitAnnotationUnit(L), 724 *LineNoCst = EmitAnnotationLineNo(L); 725 726 // Create the ConstantStruct for the global annotation. 727 llvm::Constant *Fields[4] = { 728 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 729 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 730 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 731 LineNoCst 732 }; 733 return llvm::ConstantStruct::getAnon(Fields); 734 } 735 736 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 737 llvm::GlobalValue *GV) { 738 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 739 // Get the struct elements for these annotations. 740 for (specific_attr_iterator<AnnotateAttr> 741 ai = D->specific_attr_begin<AnnotateAttr>(), 742 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 743 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 744 } 745 746 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 747 // Never defer when EmitAllDecls is specified. 748 if (Features.EmitAllDecls) 749 return false; 750 751 return !getContext().DeclMustBeEmitted(Global); 752 } 753 754 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 755 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 756 assert(AA && "No alias?"); 757 758 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 759 760 // See if there is already something with the target's name in the module. 761 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 762 763 llvm::Constant *Aliasee; 764 if (isa<llvm::FunctionType>(DeclTy)) 765 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 766 /*ForVTable=*/false); 767 else 768 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 769 llvm::PointerType::getUnqual(DeclTy), 0); 770 if (!Entry) { 771 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 772 F->setLinkage(llvm::Function::ExternalWeakLinkage); 773 WeakRefReferences.insert(F); 774 } 775 776 return Aliasee; 777 } 778 779 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 780 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 781 782 // Weak references don't produce any output by themselves. 783 if (Global->hasAttr<WeakRefAttr>()) 784 return; 785 786 // If this is an alias definition (which otherwise looks like a declaration) 787 // emit it now. 788 if (Global->hasAttr<AliasAttr>()) 789 return EmitAliasDefinition(GD); 790 791 // If this is CUDA, be selective about which declarations we emit. 792 if (Features.CUDA) { 793 if (CodeGenOpts.CUDAIsDevice) { 794 if (!Global->hasAttr<CUDADeviceAttr>() && 795 !Global->hasAttr<CUDAGlobalAttr>() && 796 !Global->hasAttr<CUDAConstantAttr>() && 797 !Global->hasAttr<CUDASharedAttr>()) 798 return; 799 } else { 800 if (!Global->hasAttr<CUDAHostAttr>() && ( 801 Global->hasAttr<CUDADeviceAttr>() || 802 Global->hasAttr<CUDAConstantAttr>() || 803 Global->hasAttr<CUDASharedAttr>())) 804 return; 805 } 806 } 807 808 // Ignore declarations, they will be emitted on their first use. 809 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 810 // Forward declarations are emitted lazily on first use. 811 if (!FD->doesThisDeclarationHaveABody()) { 812 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 813 return; 814 815 const FunctionDecl *InlineDefinition = 0; 816 FD->getBody(InlineDefinition); 817 818 StringRef MangledName = getMangledName(GD); 819 llvm::StringMap<GlobalDecl>::iterator DDI = 820 DeferredDecls.find(MangledName); 821 if (DDI != DeferredDecls.end()) 822 DeferredDecls.erase(DDI); 823 EmitGlobalDefinition(InlineDefinition); 824 return; 825 } 826 } else { 827 const VarDecl *VD = cast<VarDecl>(Global); 828 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 829 830 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 831 return; 832 } 833 834 // Defer code generation when possible if this is a static definition, inline 835 // function etc. These we only want to emit if they are used. 836 if (!MayDeferGeneration(Global)) { 837 // Emit the definition if it can't be deferred. 838 EmitGlobalDefinition(GD); 839 return; 840 } 841 842 // If we're deferring emission of a C++ variable with an 843 // initializer, remember the order in which it appeared in the file. 844 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) && 845 cast<VarDecl>(Global)->hasInit()) { 846 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 847 CXXGlobalInits.push_back(0); 848 } 849 850 // If the value has already been used, add it directly to the 851 // DeferredDeclsToEmit list. 852 StringRef MangledName = getMangledName(GD); 853 if (GetGlobalValue(MangledName)) 854 DeferredDeclsToEmit.push_back(GD); 855 else { 856 // Otherwise, remember that we saw a deferred decl with this name. The 857 // first use of the mangled name will cause it to move into 858 // DeferredDeclsToEmit. 859 DeferredDecls[MangledName] = GD; 860 } 861 } 862 863 namespace { 864 struct FunctionIsDirectlyRecursive : 865 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 866 const StringRef Name; 867 const Builtin::Context &BI; 868 bool Result; 869 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 870 Name(N), BI(C), Result(false) { 871 } 872 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 873 874 bool TraverseCallExpr(CallExpr *E) { 875 const FunctionDecl *FD = E->getDirectCallee(); 876 if (!FD) 877 return true; 878 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 879 if (Attr && Name == Attr->getLabel()) { 880 Result = true; 881 return false; 882 } 883 unsigned BuiltinID = FD->getBuiltinID(); 884 if (!BuiltinID) 885 return true; 886 const char *BuiltinName = BI.GetName(BuiltinID) + strlen("__builtin_"); 887 if (Name == BuiltinName) { 888 Result = true; 889 return false; 890 } 891 return true; 892 } 893 }; 894 } 895 896 // isTriviallyRecursive - Check if this function calls another 897 // decl that, because of the asm attribute or the other decl being a builtin, 898 // ends up pointing to itself. 899 bool 900 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 901 StringRef Name; 902 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 903 // asm labels are a special king of mangling we have to support. 904 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 905 if (!Attr) 906 return false; 907 Name = Attr->getLabel(); 908 } else { 909 Name = FD->getName(); 910 } 911 912 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 913 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 914 return Walker.Result; 915 } 916 917 bool 918 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) { 919 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage) 920 return true; 921 if (CodeGenOpts.OptimizationLevel == 0 && 922 !F->hasAttr<AlwaysInlineAttr>()) 923 return false; 924 // PR9614. Avoid cases where the source code is lying to us. An available 925 // externally function should have an equivalent function somewhere else, 926 // but a function that calls itself is clearly not equivalent to the real 927 // implementation. 928 // This happens in glibc's btowc and in some configure checks. 929 return !isTriviallyRecursive(F); 930 } 931 932 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 933 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 934 935 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 936 Context.getSourceManager(), 937 "Generating code for declaration"); 938 939 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 940 // At -O0, don't generate IR for functions with available_externally 941 // linkage. 942 if (!shouldEmitFunction(Function)) 943 return; 944 945 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 946 // Make sure to emit the definition(s) before we emit the thunks. 947 // This is necessary for the generation of certain thunks. 948 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 949 EmitCXXConstructor(CD, GD.getCtorType()); 950 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 951 EmitCXXDestructor(DD, GD.getDtorType()); 952 else 953 EmitGlobalFunctionDefinition(GD); 954 955 if (Method->isVirtual()) 956 getVTables().EmitThunks(GD); 957 958 return; 959 } 960 961 return EmitGlobalFunctionDefinition(GD); 962 } 963 964 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 965 return EmitGlobalVarDefinition(VD); 966 967 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 968 } 969 970 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 971 /// module, create and return an llvm Function with the specified type. If there 972 /// is something in the module with the specified name, return it potentially 973 /// bitcasted to the right type. 974 /// 975 /// If D is non-null, it specifies a decl that correspond to this. This is used 976 /// to set the attributes on the function when it is first created. 977 llvm::Constant * 978 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 979 llvm::Type *Ty, 980 GlobalDecl D, bool ForVTable, 981 llvm::Attributes ExtraAttrs) { 982 // Lookup the entry, lazily creating it if necessary. 983 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 984 if (Entry) { 985 if (WeakRefReferences.count(Entry)) { 986 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 987 if (FD && !FD->hasAttr<WeakAttr>()) 988 Entry->setLinkage(llvm::Function::ExternalLinkage); 989 990 WeakRefReferences.erase(Entry); 991 } 992 993 if (Entry->getType()->getElementType() == Ty) 994 return Entry; 995 996 // Make sure the result is of the correct type. 997 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 998 } 999 1000 // This function doesn't have a complete type (for example, the return 1001 // type is an incomplete struct). Use a fake type instead, and make 1002 // sure not to try to set attributes. 1003 bool IsIncompleteFunction = false; 1004 1005 llvm::FunctionType *FTy; 1006 if (isa<llvm::FunctionType>(Ty)) { 1007 FTy = cast<llvm::FunctionType>(Ty); 1008 } else { 1009 FTy = llvm::FunctionType::get(VoidTy, false); 1010 IsIncompleteFunction = true; 1011 } 1012 1013 llvm::Function *F = llvm::Function::Create(FTy, 1014 llvm::Function::ExternalLinkage, 1015 MangledName, &getModule()); 1016 assert(F->getName() == MangledName && "name was uniqued!"); 1017 if (D.getDecl()) 1018 SetFunctionAttributes(D, F, IsIncompleteFunction); 1019 if (ExtraAttrs != llvm::Attribute::None) 1020 F->addFnAttr(ExtraAttrs); 1021 1022 // This is the first use or definition of a mangled name. If there is a 1023 // deferred decl with this name, remember that we need to emit it at the end 1024 // of the file. 1025 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1026 if (DDI != DeferredDecls.end()) { 1027 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1028 // list, and remove it from DeferredDecls (since we don't need it anymore). 1029 DeferredDeclsToEmit.push_back(DDI->second); 1030 DeferredDecls.erase(DDI); 1031 1032 // Otherwise, there are cases we have to worry about where we're 1033 // using a declaration for which we must emit a definition but where 1034 // we might not find a top-level definition: 1035 // - member functions defined inline in their classes 1036 // - friend functions defined inline in some class 1037 // - special member functions with implicit definitions 1038 // If we ever change our AST traversal to walk into class methods, 1039 // this will be unnecessary. 1040 // 1041 // We also don't emit a definition for a function if it's going to be an entry 1042 // in a vtable, unless it's already marked as used. 1043 } else if (getLangOptions().CPlusPlus && D.getDecl()) { 1044 // Look for a declaration that's lexically in a record. 1045 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl()); 1046 do { 1047 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1048 if (FD->isImplicit() && !ForVTable) { 1049 assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 1050 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 1051 break; 1052 } else if (FD->doesThisDeclarationHaveABody()) { 1053 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 1054 break; 1055 } 1056 } 1057 FD = FD->getPreviousDeclaration(); 1058 } while (FD); 1059 } 1060 1061 // Make sure the result is of the requested type. 1062 if (!IsIncompleteFunction) { 1063 assert(F->getType()->getElementType() == Ty); 1064 return F; 1065 } 1066 1067 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1068 return llvm::ConstantExpr::getBitCast(F, PTy); 1069 } 1070 1071 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1072 /// non-null, then this function will use the specified type if it has to 1073 /// create it (this occurs when we see a definition of the function). 1074 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1075 llvm::Type *Ty, 1076 bool ForVTable) { 1077 // If there was no specific requested type, just convert it now. 1078 if (!Ty) 1079 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1080 1081 StringRef MangledName = getMangledName(GD); 1082 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 1083 } 1084 1085 /// CreateRuntimeFunction - Create a new runtime function with the specified 1086 /// type and name. 1087 llvm::Constant * 1088 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1089 StringRef Name, 1090 llvm::Attributes ExtraAttrs) { 1091 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1092 ExtraAttrs); 1093 } 1094 1095 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D, 1096 bool ConstantInit) { 1097 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 1098 return false; 1099 1100 if (Context.getLangOptions().CPlusPlus) { 1101 if (const RecordType *Record 1102 = Context.getBaseElementType(D->getType())->getAs<RecordType>()) 1103 return ConstantInit && 1104 cast<CXXRecordDecl>(Record->getDecl())->isPOD() && 1105 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields(); 1106 } 1107 1108 return true; 1109 } 1110 1111 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1112 /// create and return an llvm GlobalVariable with the specified type. If there 1113 /// is something in the module with the specified name, return it potentially 1114 /// bitcasted to the right type. 1115 /// 1116 /// If D is non-null, it specifies a decl that correspond to this. This is used 1117 /// to set the attributes on the global when it is first created. 1118 llvm::Constant * 1119 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1120 llvm::PointerType *Ty, 1121 const VarDecl *D, 1122 bool UnnamedAddr) { 1123 // Lookup the entry, lazily creating it if necessary. 1124 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1125 if (Entry) { 1126 if (WeakRefReferences.count(Entry)) { 1127 if (D && !D->hasAttr<WeakAttr>()) 1128 Entry->setLinkage(llvm::Function::ExternalLinkage); 1129 1130 WeakRefReferences.erase(Entry); 1131 } 1132 1133 if (UnnamedAddr) 1134 Entry->setUnnamedAddr(true); 1135 1136 if (Entry->getType() == Ty) 1137 return Entry; 1138 1139 // Make sure the result is of the correct type. 1140 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1141 } 1142 1143 // This is the first use or definition of a mangled name. If there is a 1144 // deferred decl with this name, remember that we need to emit it at the end 1145 // of the file. 1146 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1147 if (DDI != DeferredDecls.end()) { 1148 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1149 // list, and remove it from DeferredDecls (since we don't need it anymore). 1150 DeferredDeclsToEmit.push_back(DDI->second); 1151 DeferredDecls.erase(DDI); 1152 } 1153 1154 llvm::GlobalVariable *GV = 1155 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1156 llvm::GlobalValue::ExternalLinkage, 1157 0, MangledName, 0, 1158 false, Ty->getAddressSpace()); 1159 1160 // Handle things which are present even on external declarations. 1161 if (D) { 1162 // FIXME: This code is overly simple and should be merged with other global 1163 // handling. 1164 GV->setConstant(DeclIsConstantGlobal(Context, D, false)); 1165 1166 // Set linkage and visibility in case we never see a definition. 1167 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 1168 if (LV.linkage() != ExternalLinkage) { 1169 // Don't set internal linkage on declarations. 1170 } else { 1171 if (D->hasAttr<DLLImportAttr>()) 1172 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 1173 else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 1174 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1175 1176 // Set visibility on a declaration only if it's explicit. 1177 if (LV.visibilityExplicit()) 1178 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 1179 } 1180 1181 GV->setThreadLocal(D->isThreadSpecified()); 1182 } 1183 1184 return GV; 1185 } 1186 1187 1188 llvm::GlobalVariable * 1189 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1190 llvm::Type *Ty, 1191 llvm::GlobalValue::LinkageTypes Linkage) { 1192 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1193 llvm::GlobalVariable *OldGV = 0; 1194 1195 1196 if (GV) { 1197 // Check if the variable has the right type. 1198 if (GV->getType()->getElementType() == Ty) 1199 return GV; 1200 1201 // Because C++ name mangling, the only way we can end up with an already 1202 // existing global with the same name is if it has been declared extern "C". 1203 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1204 OldGV = GV; 1205 } 1206 1207 // Create a new variable. 1208 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1209 Linkage, 0, Name); 1210 1211 if (OldGV) { 1212 // Replace occurrences of the old variable if needed. 1213 GV->takeName(OldGV); 1214 1215 if (!OldGV->use_empty()) { 1216 llvm::Constant *NewPtrForOldDecl = 1217 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1218 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1219 } 1220 1221 OldGV->eraseFromParent(); 1222 } 1223 1224 return GV; 1225 } 1226 1227 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1228 /// given global variable. If Ty is non-null and if the global doesn't exist, 1229 /// then it will be greated with the specified type instead of whatever the 1230 /// normal requested type would be. 1231 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1232 llvm::Type *Ty) { 1233 assert(D->hasGlobalStorage() && "Not a global variable"); 1234 QualType ASTTy = D->getType(); 1235 if (Ty == 0) 1236 Ty = getTypes().ConvertTypeForMem(ASTTy); 1237 1238 llvm::PointerType *PTy = 1239 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1240 1241 StringRef MangledName = getMangledName(D); 1242 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1243 } 1244 1245 /// CreateRuntimeVariable - Create a new runtime global variable with the 1246 /// specified type and name. 1247 llvm::Constant * 1248 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1249 StringRef Name) { 1250 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1251 true); 1252 } 1253 1254 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1255 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1256 1257 if (MayDeferGeneration(D)) { 1258 // If we have not seen a reference to this variable yet, place it 1259 // into the deferred declarations table to be emitted if needed 1260 // later. 1261 StringRef MangledName = getMangledName(D); 1262 if (!GetGlobalValue(MangledName)) { 1263 DeferredDecls[MangledName] = D; 1264 return; 1265 } 1266 } 1267 1268 // The tentative definition is the only definition. 1269 EmitGlobalVarDefinition(D); 1270 } 1271 1272 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1273 if (DefinitionRequired) 1274 getVTables().GenerateClassData(getVTableLinkage(Class), Class); 1275 } 1276 1277 llvm::GlobalVariable::LinkageTypes 1278 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1279 if (RD->getLinkage() != ExternalLinkage) 1280 return llvm::GlobalVariable::InternalLinkage; 1281 1282 if (const CXXMethodDecl *KeyFunction 1283 = RD->getASTContext().getKeyFunction(RD)) { 1284 // If this class has a key function, use that to determine the linkage of 1285 // the vtable. 1286 const FunctionDecl *Def = 0; 1287 if (KeyFunction->hasBody(Def)) 1288 KeyFunction = cast<CXXMethodDecl>(Def); 1289 1290 switch (KeyFunction->getTemplateSpecializationKind()) { 1291 case TSK_Undeclared: 1292 case TSK_ExplicitSpecialization: 1293 // When compiling with optimizations turned on, we emit all vtables, 1294 // even if the key function is not defined in the current translation 1295 // unit. If this is the case, use available_externally linkage. 1296 if (!Def && CodeGenOpts.OptimizationLevel) 1297 return llvm::GlobalVariable::AvailableExternallyLinkage; 1298 1299 if (KeyFunction->isInlined()) 1300 return !Context.getLangOptions().AppleKext ? 1301 llvm::GlobalVariable::LinkOnceODRLinkage : 1302 llvm::Function::InternalLinkage; 1303 1304 return llvm::GlobalVariable::ExternalLinkage; 1305 1306 case TSK_ImplicitInstantiation: 1307 return !Context.getLangOptions().AppleKext ? 1308 llvm::GlobalVariable::LinkOnceODRLinkage : 1309 llvm::Function::InternalLinkage; 1310 1311 case TSK_ExplicitInstantiationDefinition: 1312 return !Context.getLangOptions().AppleKext ? 1313 llvm::GlobalVariable::WeakODRLinkage : 1314 llvm::Function::InternalLinkage; 1315 1316 case TSK_ExplicitInstantiationDeclaration: 1317 // FIXME: Use available_externally linkage. However, this currently 1318 // breaks LLVM's build due to undefined symbols. 1319 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1320 return !Context.getLangOptions().AppleKext ? 1321 llvm::GlobalVariable::LinkOnceODRLinkage : 1322 llvm::Function::InternalLinkage; 1323 } 1324 } 1325 1326 if (Context.getLangOptions().AppleKext) 1327 return llvm::Function::InternalLinkage; 1328 1329 switch (RD->getTemplateSpecializationKind()) { 1330 case TSK_Undeclared: 1331 case TSK_ExplicitSpecialization: 1332 case TSK_ImplicitInstantiation: 1333 // FIXME: Use available_externally linkage. However, this currently 1334 // breaks LLVM's build due to undefined symbols. 1335 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1336 case TSK_ExplicitInstantiationDeclaration: 1337 return llvm::GlobalVariable::LinkOnceODRLinkage; 1338 1339 case TSK_ExplicitInstantiationDefinition: 1340 return llvm::GlobalVariable::WeakODRLinkage; 1341 } 1342 1343 // Silence GCC warning. 1344 return llvm::GlobalVariable::LinkOnceODRLinkage; 1345 } 1346 1347 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1348 return Context.toCharUnitsFromBits( 1349 TheTargetData.getTypeStoreSizeInBits(Ty)); 1350 } 1351 1352 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1353 llvm::Constant *Init = 0; 1354 QualType ASTTy = D->getType(); 1355 bool NonConstInit = false; 1356 1357 const Expr *InitExpr = D->getAnyInitializer(); 1358 1359 if (!InitExpr) { 1360 // This is a tentative definition; tentative definitions are 1361 // implicitly initialized with { 0 }. 1362 // 1363 // Note that tentative definitions are only emitted at the end of 1364 // a translation unit, so they should never have incomplete 1365 // type. In addition, EmitTentativeDefinition makes sure that we 1366 // never attempt to emit a tentative definition if a real one 1367 // exists. A use may still exists, however, so we still may need 1368 // to do a RAUW. 1369 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1370 Init = EmitNullConstant(D->getType()); 1371 } else { 1372 Init = EmitConstantExpr(InitExpr, D->getType()); 1373 if (!Init) { 1374 QualType T = InitExpr->getType(); 1375 if (D->getType()->isReferenceType()) 1376 T = D->getType(); 1377 1378 if (getLangOptions().CPlusPlus) { 1379 Init = EmitNullConstant(T); 1380 NonConstInit = true; 1381 } else { 1382 ErrorUnsupported(D, "static initializer"); 1383 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1384 } 1385 } else { 1386 // We don't need an initializer, so remove the entry for the delayed 1387 // initializer position (just in case this entry was delayed). 1388 if (getLangOptions().CPlusPlus) 1389 DelayedCXXInitPosition.erase(D); 1390 } 1391 } 1392 1393 llvm::Type* InitType = Init->getType(); 1394 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1395 1396 // Strip off a bitcast if we got one back. 1397 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1398 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1399 // all zero index gep. 1400 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1401 Entry = CE->getOperand(0); 1402 } 1403 1404 // Entry is now either a Function or GlobalVariable. 1405 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1406 1407 // We have a definition after a declaration with the wrong type. 1408 // We must make a new GlobalVariable* and update everything that used OldGV 1409 // (a declaration or tentative definition) with the new GlobalVariable* 1410 // (which will be a definition). 1411 // 1412 // This happens if there is a prototype for a global (e.g. 1413 // "extern int x[];") and then a definition of a different type (e.g. 1414 // "int x[10];"). This also happens when an initializer has a different type 1415 // from the type of the global (this happens with unions). 1416 if (GV == 0 || 1417 GV->getType()->getElementType() != InitType || 1418 GV->getType()->getAddressSpace() != 1419 getContext().getTargetAddressSpace(ASTTy)) { 1420 1421 // Move the old entry aside so that we'll create a new one. 1422 Entry->setName(StringRef()); 1423 1424 // Make a new global with the correct type, this is now guaranteed to work. 1425 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1426 1427 // Replace all uses of the old global with the new global 1428 llvm::Constant *NewPtrForOldDecl = 1429 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1430 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1431 1432 // Erase the old global, since it is no longer used. 1433 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1434 } 1435 1436 if (D->hasAttr<AnnotateAttr>()) 1437 AddGlobalAnnotations(D, GV); 1438 1439 GV->setInitializer(Init); 1440 1441 // If it is safe to mark the global 'constant', do so now. 1442 GV->setConstant(false); 1443 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true)) 1444 GV->setConstant(true); 1445 1446 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1447 1448 // Set the llvm linkage type as appropriate. 1449 llvm::GlobalValue::LinkageTypes Linkage = 1450 GetLLVMLinkageVarDefinition(D, GV); 1451 GV->setLinkage(Linkage); 1452 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1453 // common vars aren't constant even if declared const. 1454 GV->setConstant(false); 1455 1456 SetCommonAttributes(D, GV); 1457 1458 // Emit the initializer function if necessary. 1459 if (NonConstInit) 1460 EmitCXXGlobalVarDeclInitFunc(D, GV); 1461 1462 // Emit global variable debug information. 1463 if (CGDebugInfo *DI = getModuleDebugInfo()) 1464 DI->EmitGlobalVariable(GV, D); 1465 } 1466 1467 llvm::GlobalValue::LinkageTypes 1468 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 1469 llvm::GlobalVariable *GV) { 1470 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1471 if (Linkage == GVA_Internal) 1472 return llvm::Function::InternalLinkage; 1473 else if (D->hasAttr<DLLImportAttr>()) 1474 return llvm::Function::DLLImportLinkage; 1475 else if (D->hasAttr<DLLExportAttr>()) 1476 return llvm::Function::DLLExportLinkage; 1477 else if (D->hasAttr<WeakAttr>()) { 1478 if (GV->isConstant()) 1479 return llvm::GlobalVariable::WeakODRLinkage; 1480 else 1481 return llvm::GlobalVariable::WeakAnyLinkage; 1482 } else if (Linkage == GVA_TemplateInstantiation || 1483 Linkage == GVA_ExplicitTemplateInstantiation) 1484 return llvm::GlobalVariable::WeakODRLinkage; 1485 else if (!getLangOptions().CPlusPlus && 1486 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1487 D->getAttr<CommonAttr>()) && 1488 !D->hasExternalStorage() && !D->getInit() && 1489 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() && 1490 !D->getAttr<WeakImportAttr>()) { 1491 // Thread local vars aren't considered common linkage. 1492 return llvm::GlobalVariable::CommonLinkage; 1493 } 1494 return llvm::GlobalVariable::ExternalLinkage; 1495 } 1496 1497 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1498 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1499 /// existing call uses of the old function in the module, this adjusts them to 1500 /// call the new function directly. 1501 /// 1502 /// This is not just a cleanup: the always_inline pass requires direct calls to 1503 /// functions to be able to inline them. If there is a bitcast in the way, it 1504 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1505 /// run at -O0. 1506 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1507 llvm::Function *NewFn) { 1508 // If we're redefining a global as a function, don't transform it. 1509 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1510 if (OldFn == 0) return; 1511 1512 llvm::Type *NewRetTy = NewFn->getReturnType(); 1513 SmallVector<llvm::Value*, 4> ArgList; 1514 1515 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1516 UI != E; ) { 1517 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1518 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1519 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1520 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1521 llvm::CallSite CS(CI); 1522 if (!CI || !CS.isCallee(I)) continue; 1523 1524 // If the return types don't match exactly, and if the call isn't dead, then 1525 // we can't transform this call. 1526 if (CI->getType() != NewRetTy && !CI->use_empty()) 1527 continue; 1528 1529 // Get the attribute list. 1530 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec; 1531 llvm::AttrListPtr AttrList = CI->getAttributes(); 1532 1533 // Get any return attributes. 1534 llvm::Attributes RAttrs = AttrList.getRetAttributes(); 1535 1536 // Add the return attributes. 1537 if (RAttrs) 1538 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs)); 1539 1540 // If the function was passed too few arguments, don't transform. If extra 1541 // arguments were passed, we silently drop them. If any of the types 1542 // mismatch, we don't transform. 1543 unsigned ArgNo = 0; 1544 bool DontTransform = false; 1545 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1546 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1547 if (CS.arg_size() == ArgNo || 1548 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1549 DontTransform = true; 1550 break; 1551 } 1552 1553 // Add any parameter attributes. 1554 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1)) 1555 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs)); 1556 } 1557 if (DontTransform) 1558 continue; 1559 1560 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes()) 1561 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs)); 1562 1563 // Okay, we can transform this. Create the new call instruction and copy 1564 // over the required information. 1565 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1566 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI); 1567 ArgList.clear(); 1568 if (!NewCall->getType()->isVoidTy()) 1569 NewCall->takeName(CI); 1570 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(), 1571 AttrVec.end())); 1572 NewCall->setCallingConv(CI->getCallingConv()); 1573 1574 // Finally, remove the old call, replacing any uses with the new one. 1575 if (!CI->use_empty()) 1576 CI->replaceAllUsesWith(NewCall); 1577 1578 // Copy debug location attached to CI. 1579 if (!CI->getDebugLoc().isUnknown()) 1580 NewCall->setDebugLoc(CI->getDebugLoc()); 1581 CI->eraseFromParent(); 1582 } 1583 } 1584 1585 1586 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1587 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1588 1589 // Compute the function info and LLVM type. 1590 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD); 1591 bool variadic = false; 1592 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>()) 1593 variadic = fpt->isVariadic(); 1594 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic); 1595 1596 // Get or create the prototype for the function. 1597 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1598 1599 // Strip off a bitcast if we got one back. 1600 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1601 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1602 Entry = CE->getOperand(0); 1603 } 1604 1605 1606 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1607 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1608 1609 // If the types mismatch then we have to rewrite the definition. 1610 assert(OldFn->isDeclaration() && 1611 "Shouldn't replace non-declaration"); 1612 1613 // F is the Function* for the one with the wrong type, we must make a new 1614 // Function* and update everything that used F (a declaration) with the new 1615 // Function* (which will be a definition). 1616 // 1617 // This happens if there is a prototype for a function 1618 // (e.g. "int f()") and then a definition of a different type 1619 // (e.g. "int f(int x)"). Move the old function aside so that it 1620 // doesn't interfere with GetAddrOfFunction. 1621 OldFn->setName(StringRef()); 1622 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1623 1624 // If this is an implementation of a function without a prototype, try to 1625 // replace any existing uses of the function (which may be calls) with uses 1626 // of the new function 1627 if (D->getType()->isFunctionNoProtoType()) { 1628 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1629 OldFn->removeDeadConstantUsers(); 1630 } 1631 1632 // Replace uses of F with the Function we will endow with a body. 1633 if (!Entry->use_empty()) { 1634 llvm::Constant *NewPtrForOldDecl = 1635 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1636 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1637 } 1638 1639 // Ok, delete the old function now, which is dead. 1640 OldFn->eraseFromParent(); 1641 1642 Entry = NewFn; 1643 } 1644 1645 // We need to set linkage and visibility on the function before 1646 // generating code for it because various parts of IR generation 1647 // want to propagate this information down (e.g. to local static 1648 // declarations). 1649 llvm::Function *Fn = cast<llvm::Function>(Entry); 1650 setFunctionLinkage(D, Fn); 1651 1652 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 1653 setGlobalVisibility(Fn, D); 1654 1655 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 1656 1657 SetFunctionDefinitionAttributes(D, Fn); 1658 SetLLVMFunctionAttributesForDefinition(D, Fn); 1659 1660 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1661 AddGlobalCtor(Fn, CA->getPriority()); 1662 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1663 AddGlobalDtor(Fn, DA->getPriority()); 1664 if (D->hasAttr<AnnotateAttr>()) 1665 AddGlobalAnnotations(D, Fn); 1666 } 1667 1668 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1669 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1670 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1671 assert(AA && "Not an alias?"); 1672 1673 StringRef MangledName = getMangledName(GD); 1674 1675 // If there is a definition in the module, then it wins over the alias. 1676 // This is dubious, but allow it to be safe. Just ignore the alias. 1677 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1678 if (Entry && !Entry->isDeclaration()) 1679 return; 1680 1681 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1682 1683 // Create a reference to the named value. This ensures that it is emitted 1684 // if a deferred decl. 1685 llvm::Constant *Aliasee; 1686 if (isa<llvm::FunctionType>(DeclTy)) 1687 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 1688 /*ForVTable=*/false); 1689 else 1690 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1691 llvm::PointerType::getUnqual(DeclTy), 0); 1692 1693 // Create the new alias itself, but don't set a name yet. 1694 llvm::GlobalValue *GA = 1695 new llvm::GlobalAlias(Aliasee->getType(), 1696 llvm::Function::ExternalLinkage, 1697 "", Aliasee, &getModule()); 1698 1699 if (Entry) { 1700 assert(Entry->isDeclaration()); 1701 1702 // If there is a declaration in the module, then we had an extern followed 1703 // by the alias, as in: 1704 // extern int test6(); 1705 // ... 1706 // int test6() __attribute__((alias("test7"))); 1707 // 1708 // Remove it and replace uses of it with the alias. 1709 GA->takeName(Entry); 1710 1711 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1712 Entry->getType())); 1713 Entry->eraseFromParent(); 1714 } else { 1715 GA->setName(MangledName); 1716 } 1717 1718 // Set attributes which are particular to an alias; this is a 1719 // specialization of the attributes which may be set on a global 1720 // variable/function. 1721 if (D->hasAttr<DLLExportAttr>()) { 1722 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1723 // The dllexport attribute is ignored for undefined symbols. 1724 if (FD->hasBody()) 1725 GA->setLinkage(llvm::Function::DLLExportLinkage); 1726 } else { 1727 GA->setLinkage(llvm::Function::DLLExportLinkage); 1728 } 1729 } else if (D->hasAttr<WeakAttr>() || 1730 D->hasAttr<WeakRefAttr>() || 1731 D->isWeakImported()) { 1732 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1733 } 1734 1735 SetCommonAttributes(D, GA); 1736 } 1737 1738 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 1739 ArrayRef<llvm::Type*> Tys) { 1740 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 1741 Tys); 1742 } 1743 1744 static llvm::StringMapEntry<llvm::Constant*> & 1745 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1746 const StringLiteral *Literal, 1747 bool TargetIsLSB, 1748 bool &IsUTF16, 1749 unsigned &StringLength) { 1750 StringRef String = Literal->getString(); 1751 unsigned NumBytes = String.size(); 1752 1753 // Check for simple case. 1754 if (!Literal->containsNonAsciiOrNull()) { 1755 StringLength = NumBytes; 1756 return Map.GetOrCreateValue(String); 1757 } 1758 1759 // Otherwise, convert the UTF8 literals into a byte string. 1760 SmallVector<UTF16, 128> ToBuf(NumBytes); 1761 const UTF8 *FromPtr = (UTF8 *)String.data(); 1762 UTF16 *ToPtr = &ToBuf[0]; 1763 1764 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1765 &ToPtr, ToPtr + NumBytes, 1766 strictConversion); 1767 1768 // ConvertUTF8toUTF16 returns the length in ToPtr. 1769 StringLength = ToPtr - &ToBuf[0]; 1770 1771 // Render the UTF-16 string into a byte array and convert to the target byte 1772 // order. 1773 // 1774 // FIXME: This isn't something we should need to do here. 1775 llvm::SmallString<128> AsBytes; 1776 AsBytes.reserve(StringLength * 2); 1777 for (unsigned i = 0; i != StringLength; ++i) { 1778 unsigned short Val = ToBuf[i]; 1779 if (TargetIsLSB) { 1780 AsBytes.push_back(Val & 0xFF); 1781 AsBytes.push_back(Val >> 8); 1782 } else { 1783 AsBytes.push_back(Val >> 8); 1784 AsBytes.push_back(Val & 0xFF); 1785 } 1786 } 1787 // Append one extra null character, the second is automatically added by our 1788 // caller. 1789 AsBytes.push_back(0); 1790 1791 IsUTF16 = true; 1792 return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size())); 1793 } 1794 1795 static llvm::StringMapEntry<llvm::Constant*> & 1796 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1797 const StringLiteral *Literal, 1798 unsigned &StringLength) 1799 { 1800 StringRef String = Literal->getString(); 1801 StringLength = String.size(); 1802 return Map.GetOrCreateValue(String); 1803 } 1804 1805 llvm::Constant * 1806 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1807 unsigned StringLength = 0; 1808 bool isUTF16 = false; 1809 llvm::StringMapEntry<llvm::Constant*> &Entry = 1810 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1811 getTargetData().isLittleEndian(), 1812 isUTF16, StringLength); 1813 1814 if (llvm::Constant *C = Entry.getValue()) 1815 return C; 1816 1817 llvm::Constant *Zero = 1818 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1819 llvm::Constant *Zeros[] = { Zero, Zero }; 1820 1821 // If we don't already have it, get __CFConstantStringClassReference. 1822 if (!CFConstantStringClassRef) { 1823 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1824 Ty = llvm::ArrayType::get(Ty, 0); 1825 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1826 "__CFConstantStringClassReference"); 1827 // Decay array -> ptr 1828 CFConstantStringClassRef = 1829 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1830 } 1831 1832 QualType CFTy = getContext().getCFConstantStringType(); 1833 1834 llvm::StructType *STy = 1835 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1836 1837 llvm::Constant *Fields[4]; 1838 1839 // Class pointer. 1840 Fields[0] = CFConstantStringClassRef; 1841 1842 // Flags. 1843 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1844 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1845 llvm::ConstantInt::get(Ty, 0x07C8); 1846 1847 // String pointer. 1848 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1849 1850 llvm::GlobalValue::LinkageTypes Linkage; 1851 bool isConstant; 1852 if (isUTF16) { 1853 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1854 Linkage = llvm::GlobalValue::InternalLinkage; 1855 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1856 // does make plain ascii ones writable. 1857 isConstant = true; 1858 } else { 1859 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 1860 // when using private linkage. It is not clear if this is a bug in ld 1861 // or a reasonable new restriction. 1862 Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 1863 isConstant = !Features.WritableStrings; 1864 } 1865 1866 llvm::GlobalVariable *GV = 1867 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1868 ".str"); 1869 GV->setUnnamedAddr(true); 1870 if (isUTF16) { 1871 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1872 GV->setAlignment(Align.getQuantity()); 1873 } else { 1874 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 1875 GV->setAlignment(Align.getQuantity()); 1876 } 1877 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1878 1879 // String length. 1880 Ty = getTypes().ConvertType(getContext().LongTy); 1881 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1882 1883 // The struct. 1884 C = llvm::ConstantStruct::get(STy, Fields); 1885 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1886 llvm::GlobalVariable::PrivateLinkage, C, 1887 "_unnamed_cfstring_"); 1888 if (const char *Sect = getContext().getTargetInfo().getCFStringSection()) 1889 GV->setSection(Sect); 1890 Entry.setValue(GV); 1891 1892 return GV; 1893 } 1894 1895 static RecordDecl * 1896 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 1897 DeclContext *DC, IdentifierInfo *Id) { 1898 SourceLocation Loc; 1899 if (Ctx.getLangOptions().CPlusPlus) 1900 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 1901 else 1902 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 1903 } 1904 1905 llvm::Constant * 1906 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 1907 unsigned StringLength = 0; 1908 llvm::StringMapEntry<llvm::Constant*> &Entry = 1909 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 1910 1911 if (llvm::Constant *C = Entry.getValue()) 1912 return C; 1913 1914 llvm::Constant *Zero = 1915 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1916 llvm::Constant *Zeros[] = { Zero, Zero }; 1917 1918 // If we don't already have it, get _NSConstantStringClassReference. 1919 if (!ConstantStringClassRef) { 1920 std::string StringClass(getLangOptions().ObjCConstantStringClass); 1921 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1922 llvm::Constant *GV; 1923 if (Features.ObjCNonFragileABI) { 1924 std::string str = 1925 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 1926 : "OBJC_CLASS_$_" + StringClass; 1927 GV = getObjCRuntime().GetClassGlobal(str); 1928 // Make sure the result is of the correct type. 1929 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1930 ConstantStringClassRef = 1931 llvm::ConstantExpr::getBitCast(GV, PTy); 1932 } else { 1933 std::string str = 1934 StringClass.empty() ? "_NSConstantStringClassReference" 1935 : "_" + StringClass + "ClassReference"; 1936 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 1937 GV = CreateRuntimeVariable(PTy, str); 1938 // Decay array -> ptr 1939 ConstantStringClassRef = 1940 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1941 } 1942 } 1943 1944 if (!NSConstantStringType) { 1945 // Construct the type for a constant NSString. 1946 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 1947 Context.getTranslationUnitDecl(), 1948 &Context.Idents.get("__builtin_NSString")); 1949 D->startDefinition(); 1950 1951 QualType FieldTypes[3]; 1952 1953 // const int *isa; 1954 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 1955 // const char *str; 1956 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 1957 // unsigned int length; 1958 FieldTypes[2] = Context.UnsignedIntTy; 1959 1960 // Create fields 1961 for (unsigned i = 0; i < 3; ++i) { 1962 FieldDecl *Field = FieldDecl::Create(Context, D, 1963 SourceLocation(), 1964 SourceLocation(), 0, 1965 FieldTypes[i], /*TInfo=*/0, 1966 /*BitWidth=*/0, 1967 /*Mutable=*/false, 1968 /*HasInit=*/false); 1969 Field->setAccess(AS_public); 1970 D->addDecl(Field); 1971 } 1972 1973 D->completeDefinition(); 1974 QualType NSTy = Context.getTagDeclType(D); 1975 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 1976 } 1977 1978 llvm::Constant *Fields[3]; 1979 1980 // Class pointer. 1981 Fields[0] = ConstantStringClassRef; 1982 1983 // String pointer. 1984 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1985 1986 llvm::GlobalValue::LinkageTypes Linkage; 1987 bool isConstant; 1988 Linkage = llvm::GlobalValue::PrivateLinkage; 1989 isConstant = !Features.WritableStrings; 1990 1991 llvm::GlobalVariable *GV = 1992 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1993 ".str"); 1994 GV->setUnnamedAddr(true); 1995 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 1996 GV->setAlignment(Align.getQuantity()); 1997 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1998 1999 // String length. 2000 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2001 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2002 2003 // The struct. 2004 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2005 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2006 llvm::GlobalVariable::PrivateLinkage, C, 2007 "_unnamed_nsstring_"); 2008 // FIXME. Fix section. 2009 if (const char *Sect = 2010 Features.ObjCNonFragileABI 2011 ? getContext().getTargetInfo().getNSStringNonFragileABISection() 2012 : getContext().getTargetInfo().getNSStringSection()) 2013 GV->setSection(Sect); 2014 Entry.setValue(GV); 2015 2016 return GV; 2017 } 2018 2019 QualType CodeGenModule::getObjCFastEnumerationStateType() { 2020 if (ObjCFastEnumerationStateType.isNull()) { 2021 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2022 Context.getTranslationUnitDecl(), 2023 &Context.Idents.get("__objcFastEnumerationState")); 2024 D->startDefinition(); 2025 2026 QualType FieldTypes[] = { 2027 Context.UnsignedLongTy, 2028 Context.getPointerType(Context.getObjCIdType()), 2029 Context.getPointerType(Context.UnsignedLongTy), 2030 Context.getConstantArrayType(Context.UnsignedLongTy, 2031 llvm::APInt(32, 5), ArrayType::Normal, 0) 2032 }; 2033 2034 for (size_t i = 0; i < 4; ++i) { 2035 FieldDecl *Field = FieldDecl::Create(Context, 2036 D, 2037 SourceLocation(), 2038 SourceLocation(), 0, 2039 FieldTypes[i], /*TInfo=*/0, 2040 /*BitWidth=*/0, 2041 /*Mutable=*/false, 2042 /*HasInit=*/false); 2043 Field->setAccess(AS_public); 2044 D->addDecl(Field); 2045 } 2046 2047 D->completeDefinition(); 2048 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2049 } 2050 2051 return ObjCFastEnumerationStateType; 2052 } 2053 2054 /// GetStringForStringLiteral - Return the appropriate bytes for a 2055 /// string literal, properly padded to match the literal type. 2056 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 2057 assert((E->isAscii() || E->isUTF8()) 2058 && "Use GetConstantArrayFromStringLiteral for wide strings"); 2059 const ASTContext &Context = getContext(); 2060 const ConstantArrayType *CAT = 2061 Context.getAsConstantArrayType(E->getType()); 2062 assert(CAT && "String isn't pointer or array!"); 2063 2064 // Resize the string to the right size. 2065 uint64_t RealLen = CAT->getSize().getZExtValue(); 2066 2067 std::string Str = E->getString().str(); 2068 Str.resize(RealLen, '\0'); 2069 2070 return Str; 2071 } 2072 2073 llvm::Constant * 2074 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2075 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2076 2077 // Don't emit it as the address of the string, emit the string data itself 2078 // as an inline array. 2079 if (E->getCharByteWidth()==1) { 2080 return llvm::ConstantArray::get(VMContext, 2081 GetStringForStringLiteral(E), false); 2082 } else { 2083 llvm::ArrayType *AType = 2084 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2085 llvm::Type *ElemTy = AType->getElementType(); 2086 unsigned NumElements = AType->getNumElements(); 2087 std::vector<llvm::Constant*> Elts; 2088 Elts.reserve(NumElements); 2089 2090 for(unsigned i=0;i<E->getLength();++i) { 2091 unsigned value = E->getCodeUnit(i); 2092 llvm::Constant *C = llvm::ConstantInt::get(ElemTy,value,false); 2093 Elts.push_back(C); 2094 } 2095 for(unsigned i=E->getLength();i<NumElements;++i) { 2096 llvm::Constant *C = llvm::ConstantInt::get(ElemTy,0,false); 2097 Elts.push_back(C); 2098 } 2099 2100 return llvm::ConstantArray::get(AType, Elts); 2101 } 2102 2103 } 2104 2105 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2106 /// constant array for the given string literal. 2107 llvm::Constant * 2108 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2109 // FIXME: This can be more efficient. 2110 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 2111 CharUnits Align = getContext().getTypeAlignInChars(S->getType()); 2112 if (S->isAscii() || S->isUTF8()) { 2113 return GetAddrOfConstantString(GetStringForStringLiteral(S), 2114 /* GlobalName */ 0, 2115 Align.getQuantity()); 2116 } 2117 2118 // FIXME: the following does not memoize wide strings 2119 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2120 llvm::GlobalVariable *GV = 2121 new llvm::GlobalVariable(getModule(),C->getType(), 2122 !Features.WritableStrings, 2123 llvm::GlobalValue::PrivateLinkage, 2124 C,".str"); 2125 GV->setAlignment(Align.getQuantity()); 2126 GV->setUnnamedAddr(true); 2127 2128 return GV; 2129 } 2130 2131 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2132 /// array for the given ObjCEncodeExpr node. 2133 llvm::Constant * 2134 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2135 std::string Str; 2136 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2137 2138 return GetAddrOfConstantCString(Str); 2139 } 2140 2141 2142 /// GenerateWritableString -- Creates storage for a string literal. 2143 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2144 bool constant, 2145 CodeGenModule &CGM, 2146 const char *GlobalName, 2147 unsigned Alignment) { 2148 // Create Constant for this string literal. Don't add a '\0'. 2149 llvm::Constant *C = 2150 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 2151 2152 // Create a global variable for this string 2153 llvm::GlobalVariable *GV = 2154 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 2155 llvm::GlobalValue::PrivateLinkage, 2156 C, GlobalName); 2157 GV->setAlignment(Alignment); 2158 GV->setUnnamedAddr(true); 2159 return GV; 2160 } 2161 2162 /// GetAddrOfConstantString - Returns a pointer to a character array 2163 /// containing the literal. This contents are exactly that of the 2164 /// given string, i.e. it will not be null terminated automatically; 2165 /// see GetAddrOfConstantCString. Note that whether the result is 2166 /// actually a pointer to an LLVM constant depends on 2167 /// Feature.WriteableStrings. 2168 /// 2169 /// The result has pointer to array type. 2170 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2171 const char *GlobalName, 2172 unsigned Alignment) { 2173 bool IsConstant = !Features.WritableStrings; 2174 2175 // Get the default prefix if a name wasn't specified. 2176 if (!GlobalName) 2177 GlobalName = ".str"; 2178 2179 // Don't share any string literals if strings aren't constant. 2180 if (!IsConstant) 2181 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2182 2183 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2184 ConstantStringMap.GetOrCreateValue(Str); 2185 2186 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2187 if (Alignment > GV->getAlignment()) { 2188 GV->setAlignment(Alignment); 2189 } 2190 return GV; 2191 } 2192 2193 // Create a global variable for this. 2194 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment); 2195 Entry.setValue(GV); 2196 return GV; 2197 } 2198 2199 /// GetAddrOfConstantCString - Returns a pointer to a character 2200 /// array containing the literal and a terminating '\0' 2201 /// character. The result has pointer to array type. 2202 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2203 const char *GlobalName, 2204 unsigned Alignment) { 2205 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2206 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2207 } 2208 2209 /// EmitObjCPropertyImplementations - Emit information for synthesized 2210 /// properties for an implementation. 2211 void CodeGenModule::EmitObjCPropertyImplementations(const 2212 ObjCImplementationDecl *D) { 2213 for (ObjCImplementationDecl::propimpl_iterator 2214 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2215 ObjCPropertyImplDecl *PID = *i; 2216 2217 // Dynamic is just for type-checking. 2218 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2219 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2220 2221 // Determine which methods need to be implemented, some may have 2222 // been overridden. Note that ::isSynthesized is not the method 2223 // we want, that just indicates if the decl came from a 2224 // property. What we want to know is if the method is defined in 2225 // this implementation. 2226 if (!D->getInstanceMethod(PD->getGetterName())) 2227 CodeGenFunction(*this).GenerateObjCGetter( 2228 const_cast<ObjCImplementationDecl *>(D), PID); 2229 if (!PD->isReadOnly() && 2230 !D->getInstanceMethod(PD->getSetterName())) 2231 CodeGenFunction(*this).GenerateObjCSetter( 2232 const_cast<ObjCImplementationDecl *>(D), PID); 2233 } 2234 } 2235 } 2236 2237 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2238 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2239 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2240 ivar; ivar = ivar->getNextIvar()) 2241 if (ivar->getType().isDestructedType()) 2242 return true; 2243 2244 return false; 2245 } 2246 2247 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2248 /// for an implementation. 2249 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2250 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2251 if (needsDestructMethod(D)) { 2252 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2253 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2254 ObjCMethodDecl *DTORMethod = 2255 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2256 cxxSelector, getContext().VoidTy, 0, D, 2257 /*isInstance=*/true, /*isVariadic=*/false, 2258 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true, 2259 /*isDefined=*/false, ObjCMethodDecl::Required); 2260 D->addInstanceMethod(DTORMethod); 2261 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2262 D->setHasCXXStructors(true); 2263 } 2264 2265 // If the implementation doesn't have any ivar initializers, we don't need 2266 // a .cxx_construct. 2267 if (D->getNumIvarInitializers() == 0) 2268 return; 2269 2270 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2271 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2272 // The constructor returns 'self'. 2273 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2274 D->getLocation(), 2275 D->getLocation(), 2276 cxxSelector, 2277 getContext().getObjCIdType(), 0, 2278 D, /*isInstance=*/true, 2279 /*isVariadic=*/false, 2280 /*isSynthesized=*/true, 2281 /*isImplicitlyDeclared=*/true, 2282 /*isDefined=*/false, 2283 ObjCMethodDecl::Required); 2284 D->addInstanceMethod(CTORMethod); 2285 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2286 D->setHasCXXStructors(true); 2287 } 2288 2289 /// EmitNamespace - Emit all declarations in a namespace. 2290 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2291 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2292 I != E; ++I) 2293 EmitTopLevelDecl(*I); 2294 } 2295 2296 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2297 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2298 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2299 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2300 ErrorUnsupported(LSD, "linkage spec"); 2301 return; 2302 } 2303 2304 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2305 I != E; ++I) 2306 EmitTopLevelDecl(*I); 2307 } 2308 2309 /// EmitTopLevelDecl - Emit code for a single top level declaration. 2310 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 2311 // If an error has occurred, stop code generation, but continue 2312 // parsing and semantic analysis (to ensure all warnings and errors 2313 // are emitted). 2314 if (Diags.hasErrorOccurred()) 2315 return; 2316 2317 // Ignore dependent declarations. 2318 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2319 return; 2320 2321 switch (D->getKind()) { 2322 case Decl::CXXConversion: 2323 case Decl::CXXMethod: 2324 case Decl::Function: 2325 // Skip function templates 2326 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2327 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2328 return; 2329 2330 EmitGlobal(cast<FunctionDecl>(D)); 2331 break; 2332 2333 case Decl::Var: 2334 EmitGlobal(cast<VarDecl>(D)); 2335 break; 2336 2337 // Indirect fields from global anonymous structs and unions can be 2338 // ignored; only the actual variable requires IR gen support. 2339 case Decl::IndirectField: 2340 break; 2341 2342 // C++ Decls 2343 case Decl::Namespace: 2344 EmitNamespace(cast<NamespaceDecl>(D)); 2345 break; 2346 // No code generation needed. 2347 case Decl::UsingShadow: 2348 case Decl::Using: 2349 case Decl::UsingDirective: 2350 case Decl::ClassTemplate: 2351 case Decl::FunctionTemplate: 2352 case Decl::TypeAliasTemplate: 2353 case Decl::NamespaceAlias: 2354 case Decl::Block: 2355 case Decl::Import: 2356 break; 2357 case Decl::CXXConstructor: 2358 // Skip function templates 2359 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2360 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2361 return; 2362 2363 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2364 break; 2365 case Decl::CXXDestructor: 2366 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 2367 return; 2368 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2369 break; 2370 2371 case Decl::StaticAssert: 2372 // Nothing to do. 2373 break; 2374 2375 // Objective-C Decls 2376 2377 // Forward declarations, no (immediate) code generation. 2378 case Decl::ObjCForwardProtocol: 2379 case Decl::ObjCInterface: 2380 break; 2381 2382 case Decl::ObjCCategory: { 2383 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 2384 if (CD->IsClassExtension() && CD->hasSynthBitfield()) 2385 Context.ResetObjCLayout(CD->getClassInterface()); 2386 break; 2387 } 2388 2389 case Decl::ObjCProtocol: 2390 ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 2391 break; 2392 2393 case Decl::ObjCCategoryImpl: 2394 // Categories have properties but don't support synthesize so we 2395 // can ignore them here. 2396 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2397 break; 2398 2399 case Decl::ObjCImplementation: { 2400 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2401 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield()) 2402 Context.ResetObjCLayout(OMD->getClassInterface()); 2403 EmitObjCPropertyImplementations(OMD); 2404 EmitObjCIvarInitializations(OMD); 2405 ObjCRuntime->GenerateClass(OMD); 2406 break; 2407 } 2408 case Decl::ObjCMethod: { 2409 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2410 // If this is not a prototype, emit the body. 2411 if (OMD->getBody()) 2412 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2413 break; 2414 } 2415 case Decl::ObjCCompatibleAlias: 2416 // compatibility-alias is a directive and has no code gen. 2417 break; 2418 2419 case Decl::LinkageSpec: 2420 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2421 break; 2422 2423 case Decl::FileScopeAsm: { 2424 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2425 StringRef AsmString = AD->getAsmString()->getString(); 2426 2427 const std::string &S = getModule().getModuleInlineAsm(); 2428 if (S.empty()) 2429 getModule().setModuleInlineAsm(AsmString); 2430 else if (*--S.end() == '\n') 2431 getModule().setModuleInlineAsm(S + AsmString.str()); 2432 else 2433 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2434 break; 2435 } 2436 2437 default: 2438 // Make sure we handled everything we should, every other kind is a 2439 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2440 // function. Need to recode Decl::Kind to do that easily. 2441 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2442 } 2443 } 2444 2445 /// Turns the given pointer into a constant. 2446 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2447 const void *Ptr) { 2448 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2449 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2450 return llvm::ConstantInt::get(i64, PtrInt); 2451 } 2452 2453 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2454 llvm::NamedMDNode *&GlobalMetadata, 2455 GlobalDecl D, 2456 llvm::GlobalValue *Addr) { 2457 if (!GlobalMetadata) 2458 GlobalMetadata = 2459 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2460 2461 // TODO: should we report variant information for ctors/dtors? 2462 llvm::Value *Ops[] = { 2463 Addr, 2464 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2465 }; 2466 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2467 } 2468 2469 /// Emits metadata nodes associating all the global values in the 2470 /// current module with the Decls they came from. This is useful for 2471 /// projects using IR gen as a subroutine. 2472 /// 2473 /// Since there's currently no way to associate an MDNode directly 2474 /// with an llvm::GlobalValue, we create a global named metadata 2475 /// with the name 'clang.global.decl.ptrs'. 2476 void CodeGenModule::EmitDeclMetadata() { 2477 llvm::NamedMDNode *GlobalMetadata = 0; 2478 2479 // StaticLocalDeclMap 2480 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 2481 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2482 I != E; ++I) { 2483 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2484 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2485 } 2486 } 2487 2488 /// Emits metadata nodes for all the local variables in the current 2489 /// function. 2490 void CodeGenFunction::EmitDeclMetadata() { 2491 if (LocalDeclMap.empty()) return; 2492 2493 llvm::LLVMContext &Context = getLLVMContext(); 2494 2495 // Find the unique metadata ID for this name. 2496 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2497 2498 llvm::NamedMDNode *GlobalMetadata = 0; 2499 2500 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2501 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2502 const Decl *D = I->first; 2503 llvm::Value *Addr = I->second; 2504 2505 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2506 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2507 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 2508 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2509 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2510 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2511 } 2512 } 2513 } 2514 2515 void CodeGenModule::EmitCoverageFile() { 2516 if (!getCodeGenOpts().CoverageFile.empty()) { 2517 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 2518 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 2519 llvm::LLVMContext &Ctx = TheModule.getContext(); 2520 llvm::MDString *CoverageFile = 2521 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 2522 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 2523 llvm::MDNode *CU = CUNode->getOperand(i); 2524 llvm::Value *node[] = { CoverageFile, CU }; 2525 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 2526 GCov->addOperand(N); 2527 } 2528 } 2529 } 2530 } 2531