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