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