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