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