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