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