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