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