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