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