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