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