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