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 std::pair<StaticExternCMap::iterator, bool> R = 1736 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 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 (!R.second) 1741 R.first->second = 0; 1742 else 1743 StaticExternCIdents.push_back(D->getIdentifier()); 1744 } 1745 1746 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1747 llvm::Constant *Init = 0; 1748 QualType ASTTy = D->getType(); 1749 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1750 bool NeedsGlobalCtor = false; 1751 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1752 1753 const VarDecl *InitDecl; 1754 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1755 1756 if (!InitExpr) { 1757 // This is a tentative definition; tentative definitions are 1758 // implicitly initialized with { 0 }. 1759 // 1760 // Note that tentative definitions are only emitted at the end of 1761 // a translation unit, so they should never have incomplete 1762 // type. In addition, EmitTentativeDefinition makes sure that we 1763 // never attempt to emit a tentative definition if a real one 1764 // exists. A use may still exists, however, so we still may need 1765 // to do a RAUW. 1766 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1767 Init = EmitNullConstant(D->getType()); 1768 } else { 1769 // If this is a std::initializer_list, emit the special initializer. 1770 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr); 1771 // An empty init list will perform zero-initialization, which happens 1772 // to be exactly what we want. 1773 // FIXME: It does so in a global constructor, which is *not* what we 1774 // want. 1775 1776 if (!Init) { 1777 initializedGlobalDecl = GlobalDecl(D); 1778 Init = EmitConstantInit(*InitDecl); 1779 } 1780 if (!Init) { 1781 QualType T = InitExpr->getType(); 1782 if (D->getType()->isReferenceType()) 1783 T = D->getType(); 1784 1785 if (getLangOpts().CPlusPlus) { 1786 Init = EmitNullConstant(T); 1787 NeedsGlobalCtor = true; 1788 } else { 1789 ErrorUnsupported(D, "static initializer"); 1790 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1791 } 1792 } else { 1793 // We don't need an initializer, so remove the entry for the delayed 1794 // initializer position (just in case this entry was delayed) if we 1795 // also don't need to register a destructor. 1796 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1797 DelayedCXXInitPosition.erase(D); 1798 } 1799 } 1800 1801 llvm::Type* InitType = Init->getType(); 1802 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1803 1804 // Strip off a bitcast if we got one back. 1805 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1806 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1807 // all zero index gep. 1808 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1809 Entry = CE->getOperand(0); 1810 } 1811 1812 // Entry is now either a Function or GlobalVariable. 1813 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1814 1815 // We have a definition after a declaration with the wrong type. 1816 // We must make a new GlobalVariable* and update everything that used OldGV 1817 // (a declaration or tentative definition) with the new GlobalVariable* 1818 // (which will be a definition). 1819 // 1820 // This happens if there is a prototype for a global (e.g. 1821 // "extern int x[];") and then a definition of a different type (e.g. 1822 // "int x[10];"). This also happens when an initializer has a different type 1823 // from the type of the global (this happens with unions). 1824 if (GV == 0 || 1825 GV->getType()->getElementType() != InitType || 1826 GV->getType()->getAddressSpace() != 1827 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1828 1829 // Move the old entry aside so that we'll create a new one. 1830 Entry->setName(StringRef()); 1831 1832 // Make a new global with the correct type, this is now guaranteed to work. 1833 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1834 1835 // Replace all uses of the old global with the new global 1836 llvm::Constant *NewPtrForOldDecl = 1837 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1838 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1839 1840 // Erase the old global, since it is no longer used. 1841 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1842 } 1843 1844 MaybeHandleStaticInExternC(D, GV); 1845 1846 if (D->hasAttr<AnnotateAttr>()) 1847 AddGlobalAnnotations(D, GV); 1848 1849 GV->setInitializer(Init); 1850 1851 // If it is safe to mark the global 'constant', do so now. 1852 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1853 isTypeConstant(D->getType(), true)); 1854 1855 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1856 1857 // Set the llvm linkage type as appropriate. 1858 llvm::GlobalValue::LinkageTypes Linkage = 1859 GetLLVMLinkageVarDefinition(D, GV); 1860 GV->setLinkage(Linkage); 1861 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1862 // common vars aren't constant even if declared const. 1863 GV->setConstant(false); 1864 1865 SetCommonAttributes(D, GV); 1866 1867 // Emit the initializer function if necessary. 1868 if (NeedsGlobalCtor || NeedsGlobalDtor) 1869 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1870 1871 // If we are compiling with ASan, add metadata indicating dynamically 1872 // initialized globals. 1873 if (SanOpts.Address && NeedsGlobalCtor) { 1874 llvm::Module &M = getModule(); 1875 1876 llvm::NamedMDNode *DynamicInitializers = 1877 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals"); 1878 llvm::Value *GlobalToAdd[] = { GV }; 1879 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd); 1880 DynamicInitializers->addOperand(ThisGlobal); 1881 } 1882 1883 // Emit global variable debug information. 1884 if (CGDebugInfo *DI = getModuleDebugInfo()) 1885 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1886 DI->EmitGlobalVariable(GV, D); 1887 } 1888 1889 llvm::GlobalValue::LinkageTypes 1890 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 1891 llvm::GlobalVariable *GV) { 1892 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1893 if (Linkage == GVA_Internal) 1894 return llvm::Function::InternalLinkage; 1895 else if (D->hasAttr<DLLImportAttr>()) 1896 return llvm::Function::DLLImportLinkage; 1897 else if (D->hasAttr<DLLExportAttr>()) 1898 return llvm::Function::DLLExportLinkage; 1899 else if (D->hasAttr<WeakAttr>()) { 1900 if (GV->isConstant()) 1901 return llvm::GlobalVariable::WeakODRLinkage; 1902 else 1903 return llvm::GlobalVariable::WeakAnyLinkage; 1904 } else if (Linkage == GVA_TemplateInstantiation || 1905 Linkage == GVA_ExplicitTemplateInstantiation) 1906 return llvm::GlobalVariable::WeakODRLinkage; 1907 else if (!getLangOpts().CPlusPlus && 1908 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1909 D->getAttr<CommonAttr>()) && 1910 !D->hasExternalStorage() && !D->getInit() && 1911 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() && 1912 !D->getAttr<WeakImportAttr>()) { 1913 // Thread local vars aren't considered common linkage. 1914 return llvm::GlobalVariable::CommonLinkage; 1915 } 1916 return llvm::GlobalVariable::ExternalLinkage; 1917 } 1918 1919 /// Replace the uses of a function that was declared with a non-proto type. 1920 /// We want to silently drop extra arguments from call sites 1921 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 1922 llvm::Function *newFn) { 1923 // Fast path. 1924 if (old->use_empty()) return; 1925 1926 llvm::Type *newRetTy = newFn->getReturnType(); 1927 SmallVector<llvm::Value*, 4> newArgs; 1928 1929 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 1930 ui != ue; ) { 1931 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 1932 llvm::User *user = *use; 1933 1934 // Recognize and replace uses of bitcasts. Most calls to 1935 // unprototyped functions will use bitcasts. 1936 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 1937 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 1938 replaceUsesOfNonProtoConstant(bitcast, newFn); 1939 continue; 1940 } 1941 1942 // Recognize calls to the function. 1943 llvm::CallSite callSite(user); 1944 if (!callSite) continue; 1945 if (!callSite.isCallee(use)) continue; 1946 1947 // If the return types don't match exactly, then we can't 1948 // transform this call unless it's dead. 1949 if (callSite->getType() != newRetTy && !callSite->use_empty()) 1950 continue; 1951 1952 // Get the call site's attribute list. 1953 SmallVector<llvm::AttributeSet, 8> newAttrs; 1954 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 1955 1956 // Collect any return attributes from the call. 1957 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 1958 newAttrs.push_back( 1959 llvm::AttributeSet::get(newFn->getContext(), 1960 oldAttrs.getRetAttributes())); 1961 1962 // If the function was passed too few arguments, don't transform. 1963 unsigned newNumArgs = newFn->arg_size(); 1964 if (callSite.arg_size() < newNumArgs) continue; 1965 1966 // If extra arguments were passed, we silently drop them. 1967 // If any of the types mismatch, we don't transform. 1968 unsigned argNo = 0; 1969 bool dontTransform = false; 1970 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 1971 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 1972 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 1973 dontTransform = true; 1974 break; 1975 } 1976 1977 // Add any parameter attributes. 1978 if (oldAttrs.hasAttributes(argNo + 1)) 1979 newAttrs. 1980 push_back(llvm:: 1981 AttributeSet::get(newFn->getContext(), 1982 oldAttrs.getParamAttributes(argNo + 1))); 1983 } 1984 if (dontTransform) 1985 continue; 1986 1987 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 1988 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 1989 oldAttrs.getFnAttributes())); 1990 1991 // Okay, we can transform this. Create the new call instruction and copy 1992 // over the required information. 1993 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 1994 1995 llvm::CallSite newCall; 1996 if (callSite.isCall()) { 1997 newCall = llvm::CallInst::Create(newFn, newArgs, "", 1998 callSite.getInstruction()); 1999 } else { 2000 llvm::InvokeInst *oldInvoke = 2001 cast<llvm::InvokeInst>(callSite.getInstruction()); 2002 newCall = llvm::InvokeInst::Create(newFn, 2003 oldInvoke->getNormalDest(), 2004 oldInvoke->getUnwindDest(), 2005 newArgs, "", 2006 callSite.getInstruction()); 2007 } 2008 newArgs.clear(); // for the next iteration 2009 2010 if (!newCall->getType()->isVoidTy()) 2011 newCall->takeName(callSite.getInstruction()); 2012 newCall.setAttributes( 2013 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2014 newCall.setCallingConv(callSite.getCallingConv()); 2015 2016 // Finally, remove the old call, replacing any uses with the new one. 2017 if (!callSite->use_empty()) 2018 callSite->replaceAllUsesWith(newCall.getInstruction()); 2019 2020 // Copy debug location attached to CI. 2021 if (!callSite->getDebugLoc().isUnknown()) 2022 newCall->setDebugLoc(callSite->getDebugLoc()); 2023 callSite->eraseFromParent(); 2024 } 2025 } 2026 2027 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2028 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2029 /// existing call uses of the old function in the module, this adjusts them to 2030 /// call the new function directly. 2031 /// 2032 /// This is not just a cleanup: the always_inline pass requires direct calls to 2033 /// functions to be able to inline them. If there is a bitcast in the way, it 2034 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2035 /// run at -O0. 2036 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2037 llvm::Function *NewFn) { 2038 // If we're redefining a global as a function, don't transform it. 2039 if (!isa<llvm::Function>(Old)) return; 2040 2041 replaceUsesOfNonProtoConstant(Old, NewFn); 2042 } 2043 2044 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2045 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2046 // If we have a definition, this might be a deferred decl. If the 2047 // instantiation is explicit, make sure we emit it at the end. 2048 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2049 GetAddrOfGlobalVar(VD); 2050 2051 EmitTopLevelDecl(VD); 2052 } 2053 2054 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 2055 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 2056 2057 // Compute the function info and LLVM type. 2058 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2059 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2060 2061 // Get or create the prototype for the function. 2062 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 2063 2064 // Strip off a bitcast if we got one back. 2065 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2066 assert(CE->getOpcode() == llvm::Instruction::BitCast); 2067 Entry = CE->getOperand(0); 2068 } 2069 2070 2071 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 2072 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 2073 2074 // If the types mismatch then we have to rewrite the definition. 2075 assert(OldFn->isDeclaration() && 2076 "Shouldn't replace non-declaration"); 2077 2078 // F is the Function* for the one with the wrong type, we must make a new 2079 // Function* and update everything that used F (a declaration) with the new 2080 // Function* (which will be a definition). 2081 // 2082 // This happens if there is a prototype for a function 2083 // (e.g. "int f()") and then a definition of a different type 2084 // (e.g. "int f(int x)"). Move the old function aside so that it 2085 // doesn't interfere with GetAddrOfFunction. 2086 OldFn->setName(StringRef()); 2087 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2088 2089 // This might be an implementation of a function without a 2090 // prototype, in which case, try to do special replacement of 2091 // calls which match the new prototype. The really key thing here 2092 // is that we also potentially drop arguments from the call site 2093 // so as to make a direct call, which makes the inliner happier 2094 // and suppresses a number of optimizer warnings (!) about 2095 // dropping arguments. 2096 if (!OldFn->use_empty()) { 2097 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 2098 OldFn->removeDeadConstantUsers(); 2099 } 2100 2101 // Replace uses of F with the Function we will endow with a body. 2102 if (!Entry->use_empty()) { 2103 llvm::Constant *NewPtrForOldDecl = 2104 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 2105 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2106 } 2107 2108 // Ok, delete the old function now, which is dead. 2109 OldFn->eraseFromParent(); 2110 2111 Entry = NewFn; 2112 } 2113 2114 // We need to set linkage and visibility on the function before 2115 // generating code for it because various parts of IR generation 2116 // want to propagate this information down (e.g. to local static 2117 // declarations). 2118 llvm::Function *Fn = cast<llvm::Function>(Entry); 2119 setFunctionLinkage(D, Fn); 2120 2121 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 2122 setGlobalVisibility(Fn, D); 2123 2124 MaybeHandleStaticInExternC(D, Fn); 2125 2126 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2127 2128 SetFunctionDefinitionAttributes(D, Fn); 2129 SetLLVMFunctionAttributesForDefinition(D, Fn); 2130 2131 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2132 AddGlobalCtor(Fn, CA->getPriority()); 2133 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2134 AddGlobalDtor(Fn, DA->getPriority()); 2135 if (D->hasAttr<AnnotateAttr>()) 2136 AddGlobalAnnotations(D, Fn); 2137 } 2138 2139 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2140 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 2141 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2142 assert(AA && "Not an alias?"); 2143 2144 StringRef MangledName = getMangledName(GD); 2145 2146 // If there is a definition in the module, then it wins over the alias. 2147 // This is dubious, but allow it to be safe. Just ignore the alias. 2148 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2149 if (Entry && !Entry->isDeclaration()) 2150 return; 2151 2152 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2153 2154 // Create a reference to the named value. This ensures that it is emitted 2155 // if a deferred decl. 2156 llvm::Constant *Aliasee; 2157 if (isa<llvm::FunctionType>(DeclTy)) 2158 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2159 /*ForVTable=*/false); 2160 else 2161 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2162 llvm::PointerType::getUnqual(DeclTy), 0); 2163 2164 // Create the new alias itself, but don't set a name yet. 2165 llvm::GlobalValue *GA = 2166 new llvm::GlobalAlias(Aliasee->getType(), 2167 llvm::Function::ExternalLinkage, 2168 "", Aliasee, &getModule()); 2169 2170 if (Entry) { 2171 assert(Entry->isDeclaration()); 2172 2173 // If there is a declaration in the module, then we had an extern followed 2174 // by the alias, as in: 2175 // extern int test6(); 2176 // ... 2177 // int test6() __attribute__((alias("test7"))); 2178 // 2179 // Remove it and replace uses of it with the alias. 2180 GA->takeName(Entry); 2181 2182 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2183 Entry->getType())); 2184 Entry->eraseFromParent(); 2185 } else { 2186 GA->setName(MangledName); 2187 } 2188 2189 // Set attributes which are particular to an alias; this is a 2190 // specialization of the attributes which may be set on a global 2191 // variable/function. 2192 if (D->hasAttr<DLLExportAttr>()) { 2193 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2194 // The dllexport attribute is ignored for undefined symbols. 2195 if (FD->hasBody()) 2196 GA->setLinkage(llvm::Function::DLLExportLinkage); 2197 } else { 2198 GA->setLinkage(llvm::Function::DLLExportLinkage); 2199 } 2200 } else if (D->hasAttr<WeakAttr>() || 2201 D->hasAttr<WeakRefAttr>() || 2202 D->isWeakImported()) { 2203 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2204 } 2205 2206 SetCommonAttributes(D, GA); 2207 } 2208 2209 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2210 ArrayRef<llvm::Type*> Tys) { 2211 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2212 Tys); 2213 } 2214 2215 static llvm::StringMapEntry<llvm::Constant*> & 2216 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2217 const StringLiteral *Literal, 2218 bool TargetIsLSB, 2219 bool &IsUTF16, 2220 unsigned &StringLength) { 2221 StringRef String = Literal->getString(); 2222 unsigned NumBytes = String.size(); 2223 2224 // Check for simple case. 2225 if (!Literal->containsNonAsciiOrNull()) { 2226 StringLength = NumBytes; 2227 return Map.GetOrCreateValue(String); 2228 } 2229 2230 // Otherwise, convert the UTF8 literals into a string of shorts. 2231 IsUTF16 = true; 2232 2233 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2234 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2235 UTF16 *ToPtr = &ToBuf[0]; 2236 2237 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2238 &ToPtr, ToPtr + NumBytes, 2239 strictConversion); 2240 2241 // ConvertUTF8toUTF16 returns the length in ToPtr. 2242 StringLength = ToPtr - &ToBuf[0]; 2243 2244 // Add an explicit null. 2245 *ToPtr = 0; 2246 return Map. 2247 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2248 (StringLength + 1) * 2)); 2249 } 2250 2251 static llvm::StringMapEntry<llvm::Constant*> & 2252 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2253 const StringLiteral *Literal, 2254 unsigned &StringLength) { 2255 StringRef String = Literal->getString(); 2256 StringLength = String.size(); 2257 return Map.GetOrCreateValue(String); 2258 } 2259 2260 llvm::Constant * 2261 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2262 unsigned StringLength = 0; 2263 bool isUTF16 = false; 2264 llvm::StringMapEntry<llvm::Constant*> &Entry = 2265 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2266 getDataLayout().isLittleEndian(), 2267 isUTF16, StringLength); 2268 2269 if (llvm::Constant *C = Entry.getValue()) 2270 return C; 2271 2272 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2273 llvm::Constant *Zeros[] = { Zero, Zero }; 2274 2275 // If we don't already have it, get __CFConstantStringClassReference. 2276 if (!CFConstantStringClassRef) { 2277 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2278 Ty = llvm::ArrayType::get(Ty, 0); 2279 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2280 "__CFConstantStringClassReference"); 2281 // Decay array -> ptr 2282 CFConstantStringClassRef = 2283 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2284 } 2285 2286 QualType CFTy = getContext().getCFConstantStringType(); 2287 2288 llvm::StructType *STy = 2289 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2290 2291 llvm::Constant *Fields[4]; 2292 2293 // Class pointer. 2294 Fields[0] = CFConstantStringClassRef; 2295 2296 // Flags. 2297 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2298 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2299 llvm::ConstantInt::get(Ty, 0x07C8); 2300 2301 // String pointer. 2302 llvm::Constant *C = 0; 2303 if (isUTF16) { 2304 ArrayRef<uint16_t> Arr = 2305 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>( 2306 const_cast<char *>(Entry.getKey().data())), 2307 Entry.getKey().size() / 2); 2308 C = llvm::ConstantDataArray::get(VMContext, Arr); 2309 } else { 2310 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2311 } 2312 2313 llvm::GlobalValue::LinkageTypes Linkage; 2314 if (isUTF16) 2315 // FIXME: why do utf strings get "_" labels instead of "L" labels? 2316 Linkage = llvm::GlobalValue::InternalLinkage; 2317 else 2318 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 2319 // when using private linkage. It is not clear if this is a bug in ld 2320 // or a reasonable new restriction. 2321 Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 2322 2323 // Note: -fwritable-strings doesn't make the backing store strings of 2324 // CFStrings writable. (See <rdar://problem/10657500>) 2325 llvm::GlobalVariable *GV = 2326 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2327 Linkage, C, ".str"); 2328 GV->setUnnamedAddr(true); 2329 if (isUTF16) { 2330 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2331 GV->setAlignment(Align.getQuantity()); 2332 } else { 2333 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2334 GV->setAlignment(Align.getQuantity()); 2335 } 2336 2337 // String. 2338 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2339 2340 if (isUTF16) 2341 // Cast the UTF16 string to the correct type. 2342 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2343 2344 // String length. 2345 Ty = getTypes().ConvertType(getContext().LongTy); 2346 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2347 2348 // The struct. 2349 C = llvm::ConstantStruct::get(STy, Fields); 2350 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2351 llvm::GlobalVariable::PrivateLinkage, C, 2352 "_unnamed_cfstring_"); 2353 if (const char *Sect = getContext().getTargetInfo().getCFStringSection()) 2354 GV->setSection(Sect); 2355 Entry.setValue(GV); 2356 2357 return GV; 2358 } 2359 2360 static RecordDecl * 2361 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 2362 DeclContext *DC, IdentifierInfo *Id) { 2363 SourceLocation Loc; 2364 if (Ctx.getLangOpts().CPlusPlus) 2365 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2366 else 2367 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2368 } 2369 2370 llvm::Constant * 2371 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2372 unsigned StringLength = 0; 2373 llvm::StringMapEntry<llvm::Constant*> &Entry = 2374 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2375 2376 if (llvm::Constant *C = Entry.getValue()) 2377 return C; 2378 2379 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2380 llvm::Constant *Zeros[] = { Zero, Zero }; 2381 2382 // If we don't already have it, get _NSConstantStringClassReference. 2383 if (!ConstantStringClassRef) { 2384 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2385 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2386 llvm::Constant *GV; 2387 if (LangOpts.ObjCRuntime.isNonFragile()) { 2388 std::string str = 2389 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2390 : "OBJC_CLASS_$_" + StringClass; 2391 GV = getObjCRuntime().GetClassGlobal(str); 2392 // Make sure the result is of the correct type. 2393 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2394 ConstantStringClassRef = 2395 llvm::ConstantExpr::getBitCast(GV, PTy); 2396 } else { 2397 std::string str = 2398 StringClass.empty() ? "_NSConstantStringClassReference" 2399 : "_" + StringClass + "ClassReference"; 2400 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2401 GV = CreateRuntimeVariable(PTy, str); 2402 // Decay array -> ptr 2403 ConstantStringClassRef = 2404 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2405 } 2406 } 2407 2408 if (!NSConstantStringType) { 2409 // Construct the type for a constant NSString. 2410 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2411 Context.getTranslationUnitDecl(), 2412 &Context.Idents.get("__builtin_NSString")); 2413 D->startDefinition(); 2414 2415 QualType FieldTypes[3]; 2416 2417 // const int *isa; 2418 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2419 // const char *str; 2420 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2421 // unsigned int length; 2422 FieldTypes[2] = Context.UnsignedIntTy; 2423 2424 // Create fields 2425 for (unsigned i = 0; i < 3; ++i) { 2426 FieldDecl *Field = FieldDecl::Create(Context, D, 2427 SourceLocation(), 2428 SourceLocation(), 0, 2429 FieldTypes[i], /*TInfo=*/0, 2430 /*BitWidth=*/0, 2431 /*Mutable=*/false, 2432 ICIS_NoInit); 2433 Field->setAccess(AS_public); 2434 D->addDecl(Field); 2435 } 2436 2437 D->completeDefinition(); 2438 QualType NSTy = Context.getTagDeclType(D); 2439 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2440 } 2441 2442 llvm::Constant *Fields[3]; 2443 2444 // Class pointer. 2445 Fields[0] = ConstantStringClassRef; 2446 2447 // String pointer. 2448 llvm::Constant *C = 2449 llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2450 2451 llvm::GlobalValue::LinkageTypes Linkage; 2452 bool isConstant; 2453 Linkage = llvm::GlobalValue::PrivateLinkage; 2454 isConstant = !LangOpts.WritableStrings; 2455 2456 llvm::GlobalVariable *GV = 2457 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 2458 ".str"); 2459 GV->setUnnamedAddr(true); 2460 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2461 GV->setAlignment(Align.getQuantity()); 2462 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2463 2464 // String length. 2465 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2466 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2467 2468 // The struct. 2469 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2470 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2471 llvm::GlobalVariable::PrivateLinkage, C, 2472 "_unnamed_nsstring_"); 2473 // FIXME. Fix section. 2474 if (const char *Sect = 2475 LangOpts.ObjCRuntime.isNonFragile() 2476 ? getContext().getTargetInfo().getNSStringNonFragileABISection() 2477 : getContext().getTargetInfo().getNSStringSection()) 2478 GV->setSection(Sect); 2479 Entry.setValue(GV); 2480 2481 return GV; 2482 } 2483 2484 QualType CodeGenModule::getObjCFastEnumerationStateType() { 2485 if (ObjCFastEnumerationStateType.isNull()) { 2486 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2487 Context.getTranslationUnitDecl(), 2488 &Context.Idents.get("__objcFastEnumerationState")); 2489 D->startDefinition(); 2490 2491 QualType FieldTypes[] = { 2492 Context.UnsignedLongTy, 2493 Context.getPointerType(Context.getObjCIdType()), 2494 Context.getPointerType(Context.UnsignedLongTy), 2495 Context.getConstantArrayType(Context.UnsignedLongTy, 2496 llvm::APInt(32, 5), ArrayType::Normal, 0) 2497 }; 2498 2499 for (size_t i = 0; i < 4; ++i) { 2500 FieldDecl *Field = FieldDecl::Create(Context, 2501 D, 2502 SourceLocation(), 2503 SourceLocation(), 0, 2504 FieldTypes[i], /*TInfo=*/0, 2505 /*BitWidth=*/0, 2506 /*Mutable=*/false, 2507 ICIS_NoInit); 2508 Field->setAccess(AS_public); 2509 D->addDecl(Field); 2510 } 2511 2512 D->completeDefinition(); 2513 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2514 } 2515 2516 return ObjCFastEnumerationStateType; 2517 } 2518 2519 llvm::Constant * 2520 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2521 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2522 2523 // Don't emit it as the address of the string, emit the string data itself 2524 // as an inline array. 2525 if (E->getCharByteWidth() == 1) { 2526 SmallString<64> Str(E->getString()); 2527 2528 // Resize the string to the right size, which is indicated by its type. 2529 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2530 Str.resize(CAT->getSize().getZExtValue()); 2531 return llvm::ConstantDataArray::getString(VMContext, Str, false); 2532 } 2533 2534 llvm::ArrayType *AType = 2535 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2536 llvm::Type *ElemTy = AType->getElementType(); 2537 unsigned NumElements = AType->getNumElements(); 2538 2539 // Wide strings have either 2-byte or 4-byte elements. 2540 if (ElemTy->getPrimitiveSizeInBits() == 16) { 2541 SmallVector<uint16_t, 32> Elements; 2542 Elements.reserve(NumElements); 2543 2544 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2545 Elements.push_back(E->getCodeUnit(i)); 2546 Elements.resize(NumElements); 2547 return llvm::ConstantDataArray::get(VMContext, Elements); 2548 } 2549 2550 assert(ElemTy->getPrimitiveSizeInBits() == 32); 2551 SmallVector<uint32_t, 32> Elements; 2552 Elements.reserve(NumElements); 2553 2554 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2555 Elements.push_back(E->getCodeUnit(i)); 2556 Elements.resize(NumElements); 2557 return llvm::ConstantDataArray::get(VMContext, Elements); 2558 } 2559 2560 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2561 /// constant array for the given string literal. 2562 llvm::Constant * 2563 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2564 CharUnits Align = getContext().getTypeAlignInChars(S->getType()); 2565 if (S->isAscii() || S->isUTF8()) { 2566 SmallString<64> Str(S->getString()); 2567 2568 // Resize the string to the right size, which is indicated by its type. 2569 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); 2570 Str.resize(CAT->getSize().getZExtValue()); 2571 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity()); 2572 } 2573 2574 // FIXME: the following does not memoize wide strings. 2575 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2576 llvm::GlobalVariable *GV = 2577 new llvm::GlobalVariable(getModule(),C->getType(), 2578 !LangOpts.WritableStrings, 2579 llvm::GlobalValue::PrivateLinkage, 2580 C,".str"); 2581 2582 GV->setAlignment(Align.getQuantity()); 2583 GV->setUnnamedAddr(true); 2584 return GV; 2585 } 2586 2587 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2588 /// array for the given ObjCEncodeExpr node. 2589 llvm::Constant * 2590 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2591 std::string Str; 2592 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2593 2594 return GetAddrOfConstantCString(Str); 2595 } 2596 2597 2598 /// GenerateWritableString -- Creates storage for a string literal. 2599 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2600 bool constant, 2601 CodeGenModule &CGM, 2602 const char *GlobalName, 2603 unsigned Alignment) { 2604 // Create Constant for this string literal. Don't add a '\0'. 2605 llvm::Constant *C = 2606 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 2607 2608 // Create a global variable for this string 2609 llvm::GlobalVariable *GV = 2610 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 2611 llvm::GlobalValue::PrivateLinkage, 2612 C, GlobalName); 2613 GV->setAlignment(Alignment); 2614 GV->setUnnamedAddr(true); 2615 return GV; 2616 } 2617 2618 /// GetAddrOfConstantString - Returns a pointer to a character array 2619 /// containing the literal. This contents are exactly that of the 2620 /// given string, i.e. it will not be null terminated automatically; 2621 /// see GetAddrOfConstantCString. Note that whether the result is 2622 /// actually a pointer to an LLVM constant depends on 2623 /// Feature.WriteableStrings. 2624 /// 2625 /// The result has pointer to array type. 2626 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2627 const char *GlobalName, 2628 unsigned Alignment) { 2629 // Get the default prefix if a name wasn't specified. 2630 if (!GlobalName) 2631 GlobalName = ".str"; 2632 2633 // Don't share any string literals if strings aren't constant. 2634 if (LangOpts.WritableStrings) 2635 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2636 2637 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2638 ConstantStringMap.GetOrCreateValue(Str); 2639 2640 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2641 if (Alignment > GV->getAlignment()) { 2642 GV->setAlignment(Alignment); 2643 } 2644 return GV; 2645 } 2646 2647 // Create a global variable for this. 2648 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 2649 Alignment); 2650 Entry.setValue(GV); 2651 return GV; 2652 } 2653 2654 /// GetAddrOfConstantCString - Returns a pointer to a character 2655 /// array containing the literal and a terminating '\0' 2656 /// character. The result has pointer to array type. 2657 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2658 const char *GlobalName, 2659 unsigned Alignment) { 2660 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2661 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2662 } 2663 2664 /// EmitObjCPropertyImplementations - Emit information for synthesized 2665 /// properties for an implementation. 2666 void CodeGenModule::EmitObjCPropertyImplementations(const 2667 ObjCImplementationDecl *D) { 2668 for (ObjCImplementationDecl::propimpl_iterator 2669 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2670 ObjCPropertyImplDecl *PID = *i; 2671 2672 // Dynamic is just for type-checking. 2673 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2674 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2675 2676 // Determine which methods need to be implemented, some may have 2677 // been overridden. Note that ::isPropertyAccessor is not the method 2678 // we want, that just indicates if the decl came from a 2679 // property. What we want to know is if the method is defined in 2680 // this implementation. 2681 if (!D->getInstanceMethod(PD->getGetterName())) 2682 CodeGenFunction(*this).GenerateObjCGetter( 2683 const_cast<ObjCImplementationDecl *>(D), PID); 2684 if (!PD->isReadOnly() && 2685 !D->getInstanceMethod(PD->getSetterName())) 2686 CodeGenFunction(*this).GenerateObjCSetter( 2687 const_cast<ObjCImplementationDecl *>(D), PID); 2688 } 2689 } 2690 } 2691 2692 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2693 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2694 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2695 ivar; ivar = ivar->getNextIvar()) 2696 if (ivar->getType().isDestructedType()) 2697 return true; 2698 2699 return false; 2700 } 2701 2702 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2703 /// for an implementation. 2704 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2705 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2706 if (needsDestructMethod(D)) { 2707 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2708 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2709 ObjCMethodDecl *DTORMethod = 2710 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2711 cxxSelector, getContext().VoidTy, 0, D, 2712 /*isInstance=*/true, /*isVariadic=*/false, 2713 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2714 /*isDefined=*/false, ObjCMethodDecl::Required); 2715 D->addInstanceMethod(DTORMethod); 2716 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2717 D->setHasDestructors(true); 2718 } 2719 2720 // If the implementation doesn't have any ivar initializers, we don't need 2721 // a .cxx_construct. 2722 if (D->getNumIvarInitializers() == 0) 2723 return; 2724 2725 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2726 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2727 // The constructor returns 'self'. 2728 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2729 D->getLocation(), 2730 D->getLocation(), 2731 cxxSelector, 2732 getContext().getObjCIdType(), 0, 2733 D, /*isInstance=*/true, 2734 /*isVariadic=*/false, 2735 /*isPropertyAccessor=*/true, 2736 /*isImplicitlyDeclared=*/true, 2737 /*isDefined=*/false, 2738 ObjCMethodDecl::Required); 2739 D->addInstanceMethod(CTORMethod); 2740 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2741 D->setHasNonZeroConstructors(true); 2742 } 2743 2744 /// EmitNamespace - Emit all declarations in a namespace. 2745 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2746 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2747 I != E; ++I) 2748 EmitTopLevelDecl(*I); 2749 } 2750 2751 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2752 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2753 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2754 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2755 ErrorUnsupported(LSD, "linkage spec"); 2756 return; 2757 } 2758 2759 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2760 I != E; ++I) { 2761 // Meta-data for ObjC class includes references to implemented methods. 2762 // Generate class's method definitions first. 2763 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) { 2764 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(), 2765 MEnd = OID->meth_end(); 2766 M != MEnd; ++M) 2767 EmitTopLevelDecl(*M); 2768 } 2769 EmitTopLevelDecl(*I); 2770 } 2771 } 2772 2773 /// EmitTopLevelDecl - Emit code for a single top level declaration. 2774 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 2775 // If an error has occurred, stop code generation, but continue 2776 // parsing and semantic analysis (to ensure all warnings and errors 2777 // are emitted). 2778 if (Diags.hasErrorOccurred()) 2779 return; 2780 2781 // Ignore dependent declarations. 2782 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2783 return; 2784 2785 switch (D->getKind()) { 2786 case Decl::CXXConversion: 2787 case Decl::CXXMethod: 2788 case Decl::Function: 2789 // Skip function templates 2790 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2791 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2792 return; 2793 2794 EmitGlobal(cast<FunctionDecl>(D)); 2795 break; 2796 2797 case Decl::Var: 2798 EmitGlobal(cast<VarDecl>(D)); 2799 break; 2800 2801 // Indirect fields from global anonymous structs and unions can be 2802 // ignored; only the actual variable requires IR gen support. 2803 case Decl::IndirectField: 2804 break; 2805 2806 // C++ Decls 2807 case Decl::Namespace: 2808 EmitNamespace(cast<NamespaceDecl>(D)); 2809 break; 2810 // No code generation needed. 2811 case Decl::UsingShadow: 2812 case Decl::Using: 2813 case Decl::UsingDirective: 2814 case Decl::ClassTemplate: 2815 case Decl::FunctionTemplate: 2816 case Decl::TypeAliasTemplate: 2817 case Decl::NamespaceAlias: 2818 case Decl::Block: 2819 case Decl::Empty: 2820 break; 2821 case Decl::CXXConstructor: 2822 // Skip function templates 2823 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2824 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2825 return; 2826 2827 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2828 break; 2829 case Decl::CXXDestructor: 2830 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 2831 return; 2832 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2833 break; 2834 2835 case Decl::StaticAssert: 2836 // Nothing to do. 2837 break; 2838 2839 // Objective-C Decls 2840 2841 // Forward declarations, no (immediate) code generation. 2842 case Decl::ObjCInterface: 2843 case Decl::ObjCCategory: 2844 break; 2845 2846 case Decl::ObjCProtocol: { 2847 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D); 2848 if (Proto->isThisDeclarationADefinition()) 2849 ObjCRuntime->GenerateProtocol(Proto); 2850 break; 2851 } 2852 2853 case Decl::ObjCCategoryImpl: 2854 // Categories have properties but don't support synthesize so we 2855 // can ignore them here. 2856 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2857 break; 2858 2859 case Decl::ObjCImplementation: { 2860 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2861 EmitObjCPropertyImplementations(OMD); 2862 EmitObjCIvarInitializations(OMD); 2863 ObjCRuntime->GenerateClass(OMD); 2864 // Emit global variable debug information. 2865 if (CGDebugInfo *DI = getModuleDebugInfo()) 2866 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2867 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 2868 OMD->getClassInterface()), OMD->getLocation()); 2869 break; 2870 } 2871 case Decl::ObjCMethod: { 2872 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2873 // If this is not a prototype, emit the body. 2874 if (OMD->getBody()) 2875 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2876 break; 2877 } 2878 case Decl::ObjCCompatibleAlias: 2879 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 2880 break; 2881 2882 case Decl::LinkageSpec: 2883 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2884 break; 2885 2886 case Decl::FileScopeAsm: { 2887 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2888 StringRef AsmString = AD->getAsmString()->getString(); 2889 2890 const std::string &S = getModule().getModuleInlineAsm(); 2891 if (S.empty()) 2892 getModule().setModuleInlineAsm(AsmString); 2893 else if (S.end()[-1] == '\n') 2894 getModule().setModuleInlineAsm(S + AsmString.str()); 2895 else 2896 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2897 break; 2898 } 2899 2900 case Decl::Import: { 2901 ImportDecl *Import = cast<ImportDecl>(D); 2902 2903 // Ignore import declarations that come from imported modules. 2904 if (clang::Module *Owner = Import->getOwningModule()) { 2905 if (getLangOpts().CurrentModule.empty() || 2906 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 2907 break; 2908 } 2909 2910 ImportedModules.insert(Import->getImportedModule()); 2911 break; 2912 } 2913 2914 default: 2915 // Make sure we handled everything we should, every other kind is a 2916 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2917 // function. Need to recode Decl::Kind to do that easily. 2918 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2919 } 2920 } 2921 2922 /// Turns the given pointer into a constant. 2923 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2924 const void *Ptr) { 2925 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2926 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2927 return llvm::ConstantInt::get(i64, PtrInt); 2928 } 2929 2930 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2931 llvm::NamedMDNode *&GlobalMetadata, 2932 GlobalDecl D, 2933 llvm::GlobalValue *Addr) { 2934 if (!GlobalMetadata) 2935 GlobalMetadata = 2936 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2937 2938 // TODO: should we report variant information for ctors/dtors? 2939 llvm::Value *Ops[] = { 2940 Addr, 2941 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2942 }; 2943 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2944 } 2945 2946 /// For each function which is declared within an extern "C" region and marked 2947 /// as 'used', but has internal linkage, create an alias from the unmangled 2948 /// name to the mangled name if possible. People expect to be able to refer 2949 /// to such functions with an unmangled name from inline assembly within the 2950 /// same translation unit. 2951 void CodeGenModule::EmitStaticExternCAliases() { 2952 for (unsigned I = 0, N = StaticExternCIdents.size(); I != N; ++I) { 2953 IdentifierInfo *Name = StaticExternCIdents[I]; 2954 llvm::GlobalValue *Val = StaticExternCValues[Name]; 2955 if (Val && !getModule().getNamedValue(Name->getName())) 2956 AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(), 2957 Name->getName(), Val, &getModule())); 2958 } 2959 } 2960 2961 /// Emits metadata nodes associating all the global values in the 2962 /// current module with the Decls they came from. This is useful for 2963 /// projects using IR gen as a subroutine. 2964 /// 2965 /// Since there's currently no way to associate an MDNode directly 2966 /// with an llvm::GlobalValue, we create a global named metadata 2967 /// with the name 'clang.global.decl.ptrs'. 2968 void CodeGenModule::EmitDeclMetadata() { 2969 llvm::NamedMDNode *GlobalMetadata = 0; 2970 2971 // StaticLocalDeclMap 2972 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 2973 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2974 I != E; ++I) { 2975 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2976 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2977 } 2978 } 2979 2980 /// Emits metadata nodes for all the local variables in the current 2981 /// function. 2982 void CodeGenFunction::EmitDeclMetadata() { 2983 if (LocalDeclMap.empty()) return; 2984 2985 llvm::LLVMContext &Context = getLLVMContext(); 2986 2987 // Find the unique metadata ID for this name. 2988 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2989 2990 llvm::NamedMDNode *GlobalMetadata = 0; 2991 2992 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2993 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2994 const Decl *D = I->first; 2995 llvm::Value *Addr = I->second; 2996 2997 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2998 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2999 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 3000 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3001 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3002 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3003 } 3004 } 3005 } 3006 3007 void CodeGenModule::EmitCoverageFile() { 3008 if (!getCodeGenOpts().CoverageFile.empty()) { 3009 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3010 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3011 llvm::LLVMContext &Ctx = TheModule.getContext(); 3012 llvm::MDString *CoverageFile = 3013 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3014 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3015 llvm::MDNode *CU = CUNode->getOperand(i); 3016 llvm::Value *node[] = { CoverageFile, CU }; 3017 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 3018 GCov->addOperand(N); 3019 } 3020 } 3021 } 3022 } 3023 3024 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid, 3025 QualType GuidType) { 3026 // Sema has checked that all uuid strings are of the form 3027 // "12345678-1234-1234-1234-1234567890ab". 3028 assert(Uuid.size() == 36); 3029 const char *Uuidstr = Uuid.data(); 3030 for (int i = 0; i < 36; ++i) { 3031 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-'); 3032 else assert(isHexDigit(Uuidstr[i])); 3033 } 3034 3035 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16); 3036 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16); 3037 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16); 3038 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3039 3040 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4); 3041 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0)); 3042 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1)); 3043 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2)); 3044 APValue& Arr = InitStruct.getStructField(3); 3045 Arr = APValue(APValue::UninitArray(), 8, 8); 3046 for (int t = 0; t < 8; ++t) 3047 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt( 3048 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16))); 3049 3050 return EmitConstantValue(InitStruct, GuidType); 3051 } 3052