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 "CGDebugInfo.h" 16 #include "CodeGenFunction.h" 17 #include "CodeGenTBAA.h" 18 #include "CGCall.h" 19 #include "CGCXXABI.h" 20 #include "CGObjCRuntime.h" 21 #include "TargetInfo.h" 22 #include "clang/Frontend/CodeGenOptions.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/CharUnits.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/DeclTemplate.h" 28 #include "clang/AST/Mangle.h" 29 #include "clang/AST/RecordLayout.h" 30 #include "clang/Basic/Diagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Basic/ConvertUTF.h" 34 #include "llvm/CallingConv.h" 35 #include "llvm/Module.h" 36 #include "llvm/Intrinsics.h" 37 #include "llvm/LLVMContext.h" 38 #include "llvm/ADT/Triple.h" 39 #include "llvm/Target/Mangler.h" 40 #include "llvm/Target/TargetData.h" 41 #include "llvm/Support/CallSite.h" 42 #include "llvm/Support/ErrorHandling.h" 43 using namespace clang; 44 using namespace CodeGen; 45 46 static const char AnnotationSection[] = "llvm.metadata"; 47 48 static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 49 switch (CGM.getContext().getTargetInfo().getCXXABI()) { 50 case CXXABI_ARM: return *CreateARMCXXABI(CGM); 51 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 52 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 53 } 54 55 llvm_unreachable("invalid C++ ABI kind"); 56 return *CreateItaniumCXXABI(CGM); 57 } 58 59 60 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 61 llvm::Module &M, const llvm::TargetData &TD, 62 Diagnostic &diags) 63 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 64 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 65 ABI(createCXXABI(*this)), 66 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO), 67 TBAA(0), 68 VTables(*this), ObjCRuntime(0), DebugInfo(0), ARCData(0), RRData(0), 69 CFConstantStringClassRef(0), ConstantStringClassRef(0), 70 NSConstantStringType(0), 71 VMContext(M.getContext()), 72 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 73 BlockObjectAssign(0), BlockObjectDispose(0), 74 BlockDescriptorType(0), GenericBlockLiteralType(0) { 75 if (Features.ObjC1) 76 createObjCRuntime(); 77 78 // Enable TBAA unless it's suppressed. 79 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0) 80 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(), 81 ABI.getMangleContext()); 82 83 // If debug info or coverage generation is enabled, create the CGDebugInfo 84 // object. 85 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs || 86 CodeGenOpts.EmitGcovNotes) 87 DebugInfo = new CGDebugInfo(*this); 88 89 Block.GlobalUniqueCount = 0; 90 91 if (C.getLangOptions().ObjCAutoRefCount) 92 ARCData = new ARCEntrypoints(); 93 RRData = new RREntrypoints(); 94 95 // Initialize the type cache. 96 llvm::LLVMContext &LLVMContext = M.getContext(); 97 VoidTy = llvm::Type::getVoidTy(LLVMContext); 98 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 101 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 102 PointerAlignInBytes = 103 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 104 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 105 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 106 Int8PtrTy = Int8Ty->getPointerTo(0); 107 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 108 } 109 110 CodeGenModule::~CodeGenModule() { 111 delete ObjCRuntime; 112 delete &ABI; 113 delete TBAA; 114 delete DebugInfo; 115 delete ARCData; 116 delete RRData; 117 } 118 119 void CodeGenModule::createObjCRuntime() { 120 if (!Features.NeXTRuntime) 121 ObjCRuntime = CreateGNUObjCRuntime(*this); 122 else 123 ObjCRuntime = CreateMacObjCRuntime(*this); 124 } 125 126 void CodeGenModule::Release() { 127 EmitDeferred(); 128 EmitCXXGlobalInitFunc(); 129 EmitCXXGlobalDtorFunc(); 130 if (ObjCRuntime) 131 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 132 AddGlobalCtor(ObjCInitFunction); 133 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 134 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 135 EmitGlobalAnnotations(); 136 EmitLLVMUsed(); 137 138 SimplifyPersonality(); 139 140 if (getCodeGenOpts().EmitDeclMetadata) 141 EmitDeclMetadata(); 142 143 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 144 EmitCoverageFile(); 145 146 if (DebugInfo) 147 DebugInfo->finalize(); 148 } 149 150 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 151 // Make sure that this type is translated. 152 Types.UpdateCompletedType(TD); 153 if (DebugInfo) 154 DebugInfo->UpdateCompletedType(TD); 155 } 156 157 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 158 if (!TBAA) 159 return 0; 160 return TBAA->getTBAAInfo(QTy); 161 } 162 163 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 164 llvm::MDNode *TBAAInfo) { 165 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 166 } 167 168 bool CodeGenModule::isTargetDarwin() const { 169 return getContext().getTargetInfo().getTriple().isOSDarwin(); 170 } 171 172 void CodeGenModule::Error(SourceLocation loc, StringRef error) { 173 unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error); 174 getDiags().Report(Context.getFullLoc(loc), diagID); 175 } 176 177 /// ErrorUnsupported - Print out an error that codegen doesn't support the 178 /// specified stmt yet. 179 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 180 bool OmitOnError) { 181 if (OmitOnError && getDiags().hasErrorOccurred()) 182 return; 183 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 184 "cannot compile this %0 yet"); 185 std::string Msg = Type; 186 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 187 << Msg << S->getSourceRange(); 188 } 189 190 /// ErrorUnsupported - Print out an error that codegen doesn't support the 191 /// specified decl yet. 192 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 193 bool OmitOnError) { 194 if (OmitOnError && getDiags().hasErrorOccurred()) 195 return; 196 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 197 "cannot compile this %0 yet"); 198 std::string Msg = Type; 199 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 200 } 201 202 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 203 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 204 } 205 206 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 207 const NamedDecl *D) const { 208 // Internal definitions always have default visibility. 209 if (GV->hasLocalLinkage()) { 210 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 211 return; 212 } 213 214 // Set visibility for definitions. 215 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 216 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 217 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 218 } 219 220 /// Set the symbol visibility of type information (vtable and RTTI) 221 /// associated with the given type. 222 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 223 const CXXRecordDecl *RD, 224 TypeVisibilityKind TVK) const { 225 setGlobalVisibility(GV, RD); 226 227 if (!CodeGenOpts.HiddenWeakVTables) 228 return; 229 230 // We never want to drop the visibility for RTTI names. 231 if (TVK == TVK_ForRTTIName) 232 return; 233 234 // We want to drop the visibility to hidden for weak type symbols. 235 // This isn't possible if there might be unresolved references 236 // elsewhere that rely on this symbol being visible. 237 238 // This should be kept roughly in sync with setThunkVisibility 239 // in CGVTables.cpp. 240 241 // Preconditions. 242 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 243 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 244 return; 245 246 // Don't override an explicit visibility attribute. 247 if (RD->getExplicitVisibility()) 248 return; 249 250 switch (RD->getTemplateSpecializationKind()) { 251 // We have to disable the optimization if this is an EI definition 252 // because there might be EI declarations in other shared objects. 253 case TSK_ExplicitInstantiationDefinition: 254 case TSK_ExplicitInstantiationDeclaration: 255 return; 256 257 // Every use of a non-template class's type information has to emit it. 258 case TSK_Undeclared: 259 break; 260 261 // In theory, implicit instantiations can ignore the possibility of 262 // an explicit instantiation declaration because there necessarily 263 // must be an EI definition somewhere with default visibility. In 264 // practice, it's possible to have an explicit instantiation for 265 // an arbitrary template class, and linkers aren't necessarily able 266 // to deal with mixed-visibility symbols. 267 case TSK_ExplicitSpecialization: 268 case TSK_ImplicitInstantiation: 269 if (!CodeGenOpts.HiddenWeakTemplateVTables) 270 return; 271 break; 272 } 273 274 // If there's a key function, there may be translation units 275 // that don't have the key function's definition. But ignore 276 // this if we're emitting RTTI under -fno-rtti. 277 if (!(TVK != TVK_ForRTTI) || Features.RTTI) { 278 if (Context.getKeyFunction(RD)) 279 return; 280 } 281 282 // Otherwise, drop the visibility to hidden. 283 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 284 GV->setUnnamedAddr(true); 285 } 286 287 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 288 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 289 290 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 291 if (!Str.empty()) 292 return Str; 293 294 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 295 IdentifierInfo *II = ND->getIdentifier(); 296 assert(II && "Attempt to mangle unnamed decl."); 297 298 Str = II->getName(); 299 return Str; 300 } 301 302 llvm::SmallString<256> Buffer; 303 llvm::raw_svector_ostream Out(Buffer); 304 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 305 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 306 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 307 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 308 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 309 getCXXABI().getMangleContext().mangleBlock(BD, Out); 310 else 311 getCXXABI().getMangleContext().mangleName(ND, Out); 312 313 // Allocate space for the mangled name. 314 Out.flush(); 315 size_t Length = Buffer.size(); 316 char *Name = MangledNamesAllocator.Allocate<char>(Length); 317 std::copy(Buffer.begin(), Buffer.end(), Name); 318 319 Str = StringRef(Name, Length); 320 321 return Str; 322 } 323 324 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 325 const BlockDecl *BD) { 326 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 327 const Decl *D = GD.getDecl(); 328 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 329 if (D == 0) 330 MangleCtx.mangleGlobalBlock(BD, Out); 331 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 332 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 333 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 334 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 335 else 336 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 337 } 338 339 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 340 return getModule().getNamedValue(Name); 341 } 342 343 /// AddGlobalCtor - Add a function to the list that will be called before 344 /// main() runs. 345 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 346 // FIXME: Type coercion of void()* types. 347 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 348 } 349 350 /// AddGlobalDtor - Add a function to the list that will be called 351 /// when the module is unloaded. 352 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 353 // FIXME: Type coercion of void()* types. 354 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 355 } 356 357 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 358 // Ctor function type is void()*. 359 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 360 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 361 362 // Get the type of a ctor entry, { i32, void ()* }. 363 llvm::StructType *CtorStructTy = 364 llvm::StructType::get(llvm::Type::getInt32Ty(VMContext), 365 llvm::PointerType::getUnqual(CtorFTy), NULL); 366 367 // Construct the constructor and destructor arrays. 368 std::vector<llvm::Constant*> Ctors; 369 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 370 std::vector<llvm::Constant*> S; 371 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 372 I->second, false)); 373 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 374 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 375 } 376 377 if (!Ctors.empty()) { 378 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 379 new llvm::GlobalVariable(TheModule, AT, false, 380 llvm::GlobalValue::AppendingLinkage, 381 llvm::ConstantArray::get(AT, Ctors), 382 GlobalName); 383 } 384 } 385 386 llvm::GlobalValue::LinkageTypes 387 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 388 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 389 390 if (Linkage == GVA_Internal) 391 return llvm::Function::InternalLinkage; 392 393 if (D->hasAttr<DLLExportAttr>()) 394 return llvm::Function::DLLExportLinkage; 395 396 if (D->hasAttr<WeakAttr>()) 397 return llvm::Function::WeakAnyLinkage; 398 399 // In C99 mode, 'inline' functions are guaranteed to have a strong 400 // definition somewhere else, so we can use available_externally linkage. 401 if (Linkage == GVA_C99Inline) 402 return llvm::Function::AvailableExternallyLinkage; 403 404 // In C++, the compiler has to emit a definition in every translation unit 405 // that references the function. We should use linkonce_odr because 406 // a) if all references in this translation unit are optimized away, we 407 // don't need to codegen it. b) if the function persists, it needs to be 408 // merged with other definitions. c) C++ has the ODR, so we know the 409 // definition is dependable. 410 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 411 return !Context.getLangOptions().AppleKext 412 ? llvm::Function::LinkOnceODRLinkage 413 : llvm::Function::InternalLinkage; 414 415 // An explicit instantiation of a template has weak linkage, since 416 // explicit instantiations can occur in multiple translation units 417 // and must all be equivalent. However, we are not allowed to 418 // throw away these explicit instantiations. 419 if (Linkage == GVA_ExplicitTemplateInstantiation) 420 return !Context.getLangOptions().AppleKext 421 ? llvm::Function::WeakODRLinkage 422 : llvm::Function::InternalLinkage; 423 424 // Otherwise, we have strong external linkage. 425 assert(Linkage == GVA_StrongExternal); 426 return llvm::Function::ExternalLinkage; 427 } 428 429 430 /// SetFunctionDefinitionAttributes - Set attributes for a global. 431 /// 432 /// FIXME: This is currently only done for aliases and functions, but not for 433 /// variables (these details are set in EmitGlobalVarDefinition for variables). 434 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 435 llvm::GlobalValue *GV) { 436 SetCommonAttributes(D, GV); 437 } 438 439 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 440 const CGFunctionInfo &Info, 441 llvm::Function *F) { 442 unsigned CallingConv; 443 AttributeListType AttributeList; 444 ConstructAttributeList(Info, D, AttributeList, CallingConv); 445 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 446 AttributeList.size())); 447 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 448 } 449 450 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 451 llvm::Function *F) { 452 if (CodeGenOpts.UnwindTables) 453 F->setHasUWTable(); 454 455 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 456 F->addFnAttr(llvm::Attribute::NoUnwind); 457 458 if (D->hasAttr<NakedAttr>()) { 459 // Naked implies noinline: we should not be inlining such functions. 460 F->addFnAttr(llvm::Attribute::Naked); 461 F->addFnAttr(llvm::Attribute::NoInline); 462 } 463 464 if (D->hasAttr<NoInlineAttr>()) 465 F->addFnAttr(llvm::Attribute::NoInline); 466 467 // (noinline wins over always_inline, and we can't specify both in IR) 468 if (D->hasAttr<AlwaysInlineAttr>() && 469 !F->hasFnAttr(llvm::Attribute::NoInline)) 470 F->addFnAttr(llvm::Attribute::AlwaysInline); 471 472 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 473 F->setUnnamedAddr(true); 474 475 if (Features.getStackProtector() == LangOptions::SSPOn) 476 F->addFnAttr(llvm::Attribute::StackProtect); 477 else if (Features.getStackProtector() == LangOptions::SSPReq) 478 F->addFnAttr(llvm::Attribute::StackProtectReq); 479 480 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 481 if (alignment) 482 F->setAlignment(alignment); 483 484 // C++ ABI requires 2-byte alignment for member functions. 485 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 486 F->setAlignment(2); 487 } 488 489 void CodeGenModule::SetCommonAttributes(const Decl *D, 490 llvm::GlobalValue *GV) { 491 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 492 setGlobalVisibility(GV, ND); 493 else 494 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 495 496 if (D->hasAttr<UsedAttr>()) 497 AddUsedGlobal(GV); 498 499 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 500 GV->setSection(SA->getName()); 501 502 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 503 } 504 505 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 506 llvm::Function *F, 507 const CGFunctionInfo &FI) { 508 SetLLVMFunctionAttributes(D, FI, F); 509 SetLLVMFunctionAttributesForDefinition(D, F); 510 511 F->setLinkage(llvm::Function::InternalLinkage); 512 513 SetCommonAttributes(D, F); 514 } 515 516 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 517 llvm::Function *F, 518 bool IsIncompleteFunction) { 519 if (unsigned IID = F->getIntrinsicID()) { 520 // If this is an intrinsic function, set the function's attributes 521 // to the intrinsic's attributes. 522 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID)); 523 return; 524 } 525 526 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 527 528 if (!IsIncompleteFunction) 529 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 530 531 // Only a few attributes are set on declarations; these may later be 532 // overridden by a definition. 533 534 if (FD->hasAttr<DLLImportAttr>()) { 535 F->setLinkage(llvm::Function::DLLImportLinkage); 536 } else if (FD->hasAttr<WeakAttr>() || 537 FD->isWeakImported()) { 538 // "extern_weak" is overloaded in LLVM; we probably should have 539 // separate linkage types for this. 540 F->setLinkage(llvm::Function::ExternalWeakLinkage); 541 } else { 542 F->setLinkage(llvm::Function::ExternalLinkage); 543 544 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility(); 545 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) { 546 F->setVisibility(GetLLVMVisibility(LV.visibility())); 547 } 548 } 549 550 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 551 F->setSection(SA->getName()); 552 } 553 554 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 555 assert(!GV->isDeclaration() && 556 "Only globals with definition can force usage."); 557 LLVMUsed.push_back(GV); 558 } 559 560 void CodeGenModule::EmitLLVMUsed() { 561 // Don't create llvm.used if there is no need. 562 if (LLVMUsed.empty()) 563 return; 564 565 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 566 567 // Convert LLVMUsed to what ConstantArray needs. 568 std::vector<llvm::Constant*> UsedArray; 569 UsedArray.resize(LLVMUsed.size()); 570 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 571 UsedArray[i] = 572 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 573 i8PTy); 574 } 575 576 if (UsedArray.empty()) 577 return; 578 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 579 580 llvm::GlobalVariable *GV = 581 new llvm::GlobalVariable(getModule(), ATy, false, 582 llvm::GlobalValue::AppendingLinkage, 583 llvm::ConstantArray::get(ATy, UsedArray), 584 "llvm.used"); 585 586 GV->setSection("llvm.metadata"); 587 } 588 589 void CodeGenModule::EmitDeferred() { 590 // Emit code for any potentially referenced deferred decls. Since a 591 // previously unused static decl may become used during the generation of code 592 // for a static function, iterate until no changes are made. 593 594 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 595 if (!DeferredVTables.empty()) { 596 const CXXRecordDecl *RD = DeferredVTables.back(); 597 DeferredVTables.pop_back(); 598 getVTables().GenerateClassData(getVTableLinkage(RD), RD); 599 continue; 600 } 601 602 GlobalDecl D = DeferredDeclsToEmit.back(); 603 DeferredDeclsToEmit.pop_back(); 604 605 // Check to see if we've already emitted this. This is necessary 606 // for a couple of reasons: first, decls can end up in the 607 // deferred-decls queue multiple times, and second, decls can end 608 // up with definitions in unusual ways (e.g. by an extern inline 609 // function acquiring a strong function redefinition). Just 610 // ignore these cases. 611 // 612 // TODO: That said, looking this up multiple times is very wasteful. 613 StringRef Name = getMangledName(D); 614 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 615 assert(CGRef && "Deferred decl wasn't referenced?"); 616 617 if (!CGRef->isDeclaration()) 618 continue; 619 620 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 621 // purposes an alias counts as a definition. 622 if (isa<llvm::GlobalAlias>(CGRef)) 623 continue; 624 625 // Otherwise, emit the definition and move on to the next one. 626 EmitGlobalDefinition(D); 627 } 628 } 629 630 void CodeGenModule::EmitGlobalAnnotations() { 631 if (Annotations.empty()) 632 return; 633 634 // Create a new global variable for the ConstantStruct in the Module. 635 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 636 Annotations[0]->getType(), Annotations.size()), Annotations); 637 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 638 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 639 "llvm.global.annotations"); 640 gv->setSection(AnnotationSection); 641 } 642 643 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) { 644 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str); 645 if (i != AnnotationStrings.end()) 646 return i->second; 647 648 // Not found yet, create a new global. 649 llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true); 650 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 651 true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 652 gv->setSection(AnnotationSection); 653 gv->setUnnamedAddr(true); 654 AnnotationStrings[Str] = gv; 655 return gv; 656 } 657 658 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 659 SourceManager &SM = getContext().getSourceManager(); 660 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 661 if (PLoc.isValid()) 662 return EmitAnnotationString(PLoc.getFilename()); 663 return EmitAnnotationString(SM.getBufferName(Loc)); 664 } 665 666 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 667 SourceManager &SM = getContext().getSourceManager(); 668 PresumedLoc PLoc = SM.getPresumedLoc(L); 669 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 670 SM.getExpansionLineNumber(L); 671 return llvm::ConstantInt::get(Int32Ty, LineNo); 672 } 673 674 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 675 const AnnotateAttr *AA, 676 SourceLocation L) { 677 // Get the globals for file name, annotation, and the line number. 678 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 679 *UnitGV = EmitAnnotationUnit(L), 680 *LineNoCst = EmitAnnotationLineNo(L); 681 682 // Create the ConstantStruct for the global annotation. 683 llvm::Constant *Fields[4] = { 684 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 685 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 686 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 687 LineNoCst 688 }; 689 return llvm::ConstantStruct::getAnon(Fields); 690 } 691 692 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 693 llvm::GlobalValue *GV) { 694 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 695 // Get the struct elements for these annotations. 696 for (specific_attr_iterator<AnnotateAttr> 697 ai = D->specific_attr_begin<AnnotateAttr>(), 698 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 699 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 700 } 701 702 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 703 // Never defer when EmitAllDecls is specified. 704 if (Features.EmitAllDecls) 705 return false; 706 707 return !getContext().DeclMustBeEmitted(Global); 708 } 709 710 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 711 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 712 assert(AA && "No alias?"); 713 714 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 715 716 // See if there is already something with the target's name in the module. 717 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 718 719 llvm::Constant *Aliasee; 720 if (isa<llvm::FunctionType>(DeclTy)) 721 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 722 /*ForVTable=*/false); 723 else 724 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 725 llvm::PointerType::getUnqual(DeclTy), 0); 726 if (!Entry) { 727 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 728 F->setLinkage(llvm::Function::ExternalWeakLinkage); 729 WeakRefReferences.insert(F); 730 } 731 732 return Aliasee; 733 } 734 735 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 736 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 737 738 // Weak references don't produce any output by themselves. 739 if (Global->hasAttr<WeakRefAttr>()) 740 return; 741 742 // If this is an alias definition (which otherwise looks like a declaration) 743 // emit it now. 744 if (Global->hasAttr<AliasAttr>()) 745 return EmitAliasDefinition(GD); 746 747 // Ignore declarations, they will be emitted on their first use. 748 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 749 // Forward declarations are emitted lazily on first use. 750 if (!FD->doesThisDeclarationHaveABody()) { 751 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 752 return; 753 754 const FunctionDecl *InlineDefinition = 0; 755 FD->getBody(InlineDefinition); 756 757 StringRef MangledName = getMangledName(GD); 758 llvm::StringMap<GlobalDecl>::iterator DDI = 759 DeferredDecls.find(MangledName); 760 if (DDI != DeferredDecls.end()) 761 DeferredDecls.erase(DDI); 762 EmitGlobalDefinition(InlineDefinition); 763 return; 764 } 765 } else { 766 const VarDecl *VD = cast<VarDecl>(Global); 767 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 768 769 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 770 return; 771 } 772 773 // Defer code generation when possible if this is a static definition, inline 774 // function etc. These we only want to emit if they are used. 775 if (!MayDeferGeneration(Global)) { 776 // Emit the definition if it can't be deferred. 777 EmitGlobalDefinition(GD); 778 return; 779 } 780 781 // If we're deferring emission of a C++ variable with an 782 // initializer, remember the order in which it appeared in the file. 783 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) && 784 cast<VarDecl>(Global)->hasInit()) { 785 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 786 CXXGlobalInits.push_back(0); 787 } 788 789 // If the value has already been used, add it directly to the 790 // DeferredDeclsToEmit list. 791 StringRef MangledName = getMangledName(GD); 792 if (GetGlobalValue(MangledName)) 793 DeferredDeclsToEmit.push_back(GD); 794 else { 795 // Otherwise, remember that we saw a deferred decl with this name. The 796 // first use of the mangled name will cause it to move into 797 // DeferredDeclsToEmit. 798 DeferredDecls[MangledName] = GD; 799 } 800 } 801 802 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 803 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 804 805 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 806 Context.getSourceManager(), 807 "Generating code for declaration"); 808 809 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 810 // At -O0, don't generate IR for functions with available_externally 811 // linkage. 812 if (CodeGenOpts.OptimizationLevel == 0 && 813 !Function->hasAttr<AlwaysInlineAttr>() && 814 getFunctionLinkage(Function) 815 == llvm::Function::AvailableExternallyLinkage) 816 return; 817 818 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 819 // Make sure to emit the definition(s) before we emit the thunks. 820 // This is necessary for the generation of certain thunks. 821 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 822 EmitCXXConstructor(CD, GD.getCtorType()); 823 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 824 EmitCXXDestructor(DD, GD.getDtorType()); 825 else 826 EmitGlobalFunctionDefinition(GD); 827 828 if (Method->isVirtual()) 829 getVTables().EmitThunks(GD); 830 831 return; 832 } 833 834 return EmitGlobalFunctionDefinition(GD); 835 } 836 837 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 838 return EmitGlobalVarDefinition(VD); 839 840 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 841 } 842 843 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 844 /// module, create and return an llvm Function with the specified type. If there 845 /// is something in the module with the specified name, return it potentially 846 /// bitcasted to the right type. 847 /// 848 /// If D is non-null, it specifies a decl that correspond to this. This is used 849 /// to set the attributes on the function when it is first created. 850 llvm::Constant * 851 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 852 llvm::Type *Ty, 853 GlobalDecl D, bool ForVTable, 854 llvm::Attributes ExtraAttrs) { 855 // Lookup the entry, lazily creating it if necessary. 856 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 857 if (Entry) { 858 if (WeakRefReferences.count(Entry)) { 859 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 860 if (FD && !FD->hasAttr<WeakAttr>()) 861 Entry->setLinkage(llvm::Function::ExternalLinkage); 862 863 WeakRefReferences.erase(Entry); 864 } 865 866 if (Entry->getType()->getElementType() == Ty) 867 return Entry; 868 869 // Make sure the result is of the correct type. 870 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 871 } 872 873 // This function doesn't have a complete type (for example, the return 874 // type is an incomplete struct). Use a fake type instead, and make 875 // sure not to try to set attributes. 876 bool IsIncompleteFunction = false; 877 878 llvm::FunctionType *FTy; 879 if (isa<llvm::FunctionType>(Ty)) { 880 FTy = cast<llvm::FunctionType>(Ty); 881 } else { 882 FTy = llvm::FunctionType::get(VoidTy, false); 883 IsIncompleteFunction = true; 884 } 885 886 llvm::Function *F = llvm::Function::Create(FTy, 887 llvm::Function::ExternalLinkage, 888 MangledName, &getModule()); 889 assert(F->getName() == MangledName && "name was uniqued!"); 890 if (D.getDecl()) 891 SetFunctionAttributes(D, F, IsIncompleteFunction); 892 if (ExtraAttrs != llvm::Attribute::None) 893 F->addFnAttr(ExtraAttrs); 894 895 // This is the first use or definition of a mangled name. If there is a 896 // deferred decl with this name, remember that we need to emit it at the end 897 // of the file. 898 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 899 if (DDI != DeferredDecls.end()) { 900 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 901 // list, and remove it from DeferredDecls (since we don't need it anymore). 902 DeferredDeclsToEmit.push_back(DDI->second); 903 DeferredDecls.erase(DDI); 904 905 // Otherwise, there are cases we have to worry about where we're 906 // using a declaration for which we must emit a definition but where 907 // we might not find a top-level definition: 908 // - member functions defined inline in their classes 909 // - friend functions defined inline in some class 910 // - special member functions with implicit definitions 911 // If we ever change our AST traversal to walk into class methods, 912 // this will be unnecessary. 913 // 914 // We also don't emit a definition for a function if it's going to be an entry 915 // in a vtable, unless it's already marked as used. 916 } else if (getLangOptions().CPlusPlus && D.getDecl()) { 917 // Look for a declaration that's lexically in a record. 918 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl()); 919 do { 920 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 921 if (FD->isImplicit() && !ForVTable) { 922 assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 923 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 924 break; 925 } else if (FD->doesThisDeclarationHaveABody()) { 926 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 927 break; 928 } 929 } 930 FD = FD->getPreviousDeclaration(); 931 } while (FD); 932 } 933 934 // Make sure the result is of the requested type. 935 if (!IsIncompleteFunction) { 936 assert(F->getType()->getElementType() == Ty); 937 return F; 938 } 939 940 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 941 return llvm::ConstantExpr::getBitCast(F, PTy); 942 } 943 944 /// GetAddrOfFunction - Return the address of the given function. If Ty is 945 /// non-null, then this function will use the specified type if it has to 946 /// create it (this occurs when we see a definition of the function). 947 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 948 llvm::Type *Ty, 949 bool ForVTable) { 950 // If there was no specific requested type, just convert it now. 951 if (!Ty) 952 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 953 954 StringRef MangledName = getMangledName(GD); 955 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 956 } 957 958 /// CreateRuntimeFunction - Create a new runtime function with the specified 959 /// type and name. 960 llvm::Constant * 961 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 962 StringRef Name, 963 llvm::Attributes ExtraAttrs) { 964 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 965 ExtraAttrs); 966 } 967 968 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D, 969 bool ConstantInit) { 970 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 971 return false; 972 973 if (Context.getLangOptions().CPlusPlus) { 974 if (const RecordType *Record 975 = Context.getBaseElementType(D->getType())->getAs<RecordType>()) 976 return ConstantInit && 977 cast<CXXRecordDecl>(Record->getDecl())->isPOD() && 978 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields(); 979 } 980 981 return true; 982 } 983 984 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 985 /// create and return an llvm GlobalVariable with the specified type. If there 986 /// is something in the module with the specified name, return it potentially 987 /// bitcasted to the right type. 988 /// 989 /// If D is non-null, it specifies a decl that correspond to this. This is used 990 /// to set the attributes on the global when it is first created. 991 llvm::Constant * 992 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 993 llvm::PointerType *Ty, 994 const VarDecl *D, 995 bool UnnamedAddr) { 996 // Lookup the entry, lazily creating it if necessary. 997 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 998 if (Entry) { 999 if (WeakRefReferences.count(Entry)) { 1000 if (D && !D->hasAttr<WeakAttr>()) 1001 Entry->setLinkage(llvm::Function::ExternalLinkage); 1002 1003 WeakRefReferences.erase(Entry); 1004 } 1005 1006 if (UnnamedAddr) 1007 Entry->setUnnamedAddr(true); 1008 1009 if (Entry->getType() == Ty) 1010 return Entry; 1011 1012 // Make sure the result is of the correct type. 1013 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1014 } 1015 1016 // This is the first use or definition of a mangled name. If there is a 1017 // deferred decl with this name, remember that we need to emit it at the end 1018 // of the file. 1019 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1020 if (DDI != DeferredDecls.end()) { 1021 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1022 // list, and remove it from DeferredDecls (since we don't need it anymore). 1023 DeferredDeclsToEmit.push_back(DDI->second); 1024 DeferredDecls.erase(DDI); 1025 } 1026 1027 llvm::GlobalVariable *GV = 1028 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1029 llvm::GlobalValue::ExternalLinkage, 1030 0, MangledName, 0, 1031 false, Ty->getAddressSpace()); 1032 1033 // Handle things which are present even on external declarations. 1034 if (D) { 1035 // FIXME: This code is overly simple and should be merged with other global 1036 // handling. 1037 GV->setConstant(DeclIsConstantGlobal(Context, D, false)); 1038 1039 // Set linkage and visibility in case we never see a definition. 1040 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 1041 if (LV.linkage() != ExternalLinkage) { 1042 // Don't set internal linkage on declarations. 1043 } else { 1044 if (D->hasAttr<DLLImportAttr>()) 1045 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 1046 else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 1047 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1048 1049 // Set visibility on a declaration only if it's explicit. 1050 if (LV.visibilityExplicit()) 1051 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 1052 } 1053 1054 GV->setThreadLocal(D->isThreadSpecified()); 1055 } 1056 1057 return GV; 1058 } 1059 1060 1061 llvm::GlobalVariable * 1062 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1063 llvm::Type *Ty, 1064 llvm::GlobalValue::LinkageTypes Linkage) { 1065 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1066 llvm::GlobalVariable *OldGV = 0; 1067 1068 1069 if (GV) { 1070 // Check if the variable has the right type. 1071 if (GV->getType()->getElementType() == Ty) 1072 return GV; 1073 1074 // Because C++ name mangling, the only way we can end up with an already 1075 // existing global with the same name is if it has been declared extern "C". 1076 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1077 OldGV = GV; 1078 } 1079 1080 // Create a new variable. 1081 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1082 Linkage, 0, Name); 1083 1084 if (OldGV) { 1085 // Replace occurrences of the old variable if needed. 1086 GV->takeName(OldGV); 1087 1088 if (!OldGV->use_empty()) { 1089 llvm::Constant *NewPtrForOldDecl = 1090 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1091 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1092 } 1093 1094 OldGV->eraseFromParent(); 1095 } 1096 1097 return GV; 1098 } 1099 1100 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1101 /// given global variable. If Ty is non-null and if the global doesn't exist, 1102 /// then it will be greated with the specified type instead of whatever the 1103 /// normal requested type would be. 1104 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1105 llvm::Type *Ty) { 1106 assert(D->hasGlobalStorage() && "Not a global variable"); 1107 QualType ASTTy = D->getType(); 1108 if (Ty == 0) 1109 Ty = getTypes().ConvertTypeForMem(ASTTy); 1110 1111 llvm::PointerType *PTy = 1112 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1113 1114 StringRef MangledName = getMangledName(D); 1115 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1116 } 1117 1118 /// CreateRuntimeVariable - Create a new runtime global variable with the 1119 /// specified type and name. 1120 llvm::Constant * 1121 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1122 StringRef Name) { 1123 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1124 true); 1125 } 1126 1127 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1128 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1129 1130 if (MayDeferGeneration(D)) { 1131 // If we have not seen a reference to this variable yet, place it 1132 // into the deferred declarations table to be emitted if needed 1133 // later. 1134 StringRef MangledName = getMangledName(D); 1135 if (!GetGlobalValue(MangledName)) { 1136 DeferredDecls[MangledName] = D; 1137 return; 1138 } 1139 } 1140 1141 // The tentative definition is the only definition. 1142 EmitGlobalVarDefinition(D); 1143 } 1144 1145 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1146 if (DefinitionRequired) 1147 getVTables().GenerateClassData(getVTableLinkage(Class), Class); 1148 } 1149 1150 llvm::GlobalVariable::LinkageTypes 1151 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1152 if (RD->getLinkage() != ExternalLinkage) 1153 return llvm::GlobalVariable::InternalLinkage; 1154 1155 if (const CXXMethodDecl *KeyFunction 1156 = RD->getASTContext().getKeyFunction(RD)) { 1157 // If this class has a key function, use that to determine the linkage of 1158 // the vtable. 1159 const FunctionDecl *Def = 0; 1160 if (KeyFunction->hasBody(Def)) 1161 KeyFunction = cast<CXXMethodDecl>(Def); 1162 1163 switch (KeyFunction->getTemplateSpecializationKind()) { 1164 case TSK_Undeclared: 1165 case TSK_ExplicitSpecialization: 1166 // When compiling with optimizations turned on, we emit all vtables, 1167 // even if the key function is not defined in the current translation 1168 // unit. If this is the case, use available_externally linkage. 1169 if (!Def && CodeGenOpts.OptimizationLevel) 1170 return llvm::GlobalVariable::AvailableExternallyLinkage; 1171 1172 if (KeyFunction->isInlined()) 1173 return !Context.getLangOptions().AppleKext ? 1174 llvm::GlobalVariable::LinkOnceODRLinkage : 1175 llvm::Function::InternalLinkage; 1176 1177 return llvm::GlobalVariable::ExternalLinkage; 1178 1179 case TSK_ImplicitInstantiation: 1180 return !Context.getLangOptions().AppleKext ? 1181 llvm::GlobalVariable::LinkOnceODRLinkage : 1182 llvm::Function::InternalLinkage; 1183 1184 case TSK_ExplicitInstantiationDefinition: 1185 return !Context.getLangOptions().AppleKext ? 1186 llvm::GlobalVariable::WeakODRLinkage : 1187 llvm::Function::InternalLinkage; 1188 1189 case TSK_ExplicitInstantiationDeclaration: 1190 // FIXME: Use available_externally linkage. However, this currently 1191 // breaks LLVM's build due to undefined symbols. 1192 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1193 return !Context.getLangOptions().AppleKext ? 1194 llvm::GlobalVariable::LinkOnceODRLinkage : 1195 llvm::Function::InternalLinkage; 1196 } 1197 } 1198 1199 if (Context.getLangOptions().AppleKext) 1200 return llvm::Function::InternalLinkage; 1201 1202 switch (RD->getTemplateSpecializationKind()) { 1203 case TSK_Undeclared: 1204 case TSK_ExplicitSpecialization: 1205 case TSK_ImplicitInstantiation: 1206 // FIXME: Use available_externally linkage. However, this currently 1207 // breaks LLVM's build due to undefined symbols. 1208 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1209 case TSK_ExplicitInstantiationDeclaration: 1210 return llvm::GlobalVariable::LinkOnceODRLinkage; 1211 1212 case TSK_ExplicitInstantiationDefinition: 1213 return llvm::GlobalVariable::WeakODRLinkage; 1214 } 1215 1216 // Silence GCC warning. 1217 return llvm::GlobalVariable::LinkOnceODRLinkage; 1218 } 1219 1220 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1221 return Context.toCharUnitsFromBits( 1222 TheTargetData.getTypeStoreSizeInBits(Ty)); 1223 } 1224 1225 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1226 llvm::Constant *Init = 0; 1227 QualType ASTTy = D->getType(); 1228 bool NonConstInit = false; 1229 1230 const Expr *InitExpr = D->getAnyInitializer(); 1231 1232 if (!InitExpr) { 1233 // This is a tentative definition; tentative definitions are 1234 // implicitly initialized with { 0 }. 1235 // 1236 // Note that tentative definitions are only emitted at the end of 1237 // a translation unit, so they should never have incomplete 1238 // type. In addition, EmitTentativeDefinition makes sure that we 1239 // never attempt to emit a tentative definition if a real one 1240 // exists. A use may still exists, however, so we still may need 1241 // to do a RAUW. 1242 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1243 Init = EmitNullConstant(D->getType()); 1244 } else { 1245 Init = EmitConstantExpr(InitExpr, D->getType()); 1246 if (!Init) { 1247 QualType T = InitExpr->getType(); 1248 if (D->getType()->isReferenceType()) 1249 T = D->getType(); 1250 1251 if (getLangOptions().CPlusPlus) { 1252 Init = EmitNullConstant(T); 1253 NonConstInit = true; 1254 } else { 1255 ErrorUnsupported(D, "static initializer"); 1256 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1257 } 1258 } else { 1259 // We don't need an initializer, so remove the entry for the delayed 1260 // initializer position (just in case this entry was delayed). 1261 if (getLangOptions().CPlusPlus) 1262 DelayedCXXInitPosition.erase(D); 1263 } 1264 } 1265 1266 llvm::Type* InitType = Init->getType(); 1267 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1268 1269 // Strip off a bitcast if we got one back. 1270 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1271 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1272 // all zero index gep. 1273 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1274 Entry = CE->getOperand(0); 1275 } 1276 1277 // Entry is now either a Function or GlobalVariable. 1278 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1279 1280 // We have a definition after a declaration with the wrong type. 1281 // We must make a new GlobalVariable* and update everything that used OldGV 1282 // (a declaration or tentative definition) with the new GlobalVariable* 1283 // (which will be a definition). 1284 // 1285 // This happens if there is a prototype for a global (e.g. 1286 // "extern int x[];") and then a definition of a different type (e.g. 1287 // "int x[10];"). This also happens when an initializer has a different type 1288 // from the type of the global (this happens with unions). 1289 if (GV == 0 || 1290 GV->getType()->getElementType() != InitType || 1291 GV->getType()->getAddressSpace() != 1292 getContext().getTargetAddressSpace(ASTTy)) { 1293 1294 // Move the old entry aside so that we'll create a new one. 1295 Entry->setName(StringRef()); 1296 1297 // Make a new global with the correct type, this is now guaranteed to work. 1298 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1299 1300 // Replace all uses of the old global with the new global 1301 llvm::Constant *NewPtrForOldDecl = 1302 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1303 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1304 1305 // Erase the old global, since it is no longer used. 1306 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1307 } 1308 1309 if (D->hasAttr<AnnotateAttr>()) 1310 AddGlobalAnnotations(D, GV); 1311 1312 GV->setInitializer(Init); 1313 1314 // If it is safe to mark the global 'constant', do so now. 1315 GV->setConstant(false); 1316 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true)) 1317 GV->setConstant(true); 1318 1319 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1320 1321 // Set the llvm linkage type as appropriate. 1322 llvm::GlobalValue::LinkageTypes Linkage = 1323 GetLLVMLinkageVarDefinition(D, GV); 1324 GV->setLinkage(Linkage); 1325 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1326 // common vars aren't constant even if declared const. 1327 GV->setConstant(false); 1328 1329 SetCommonAttributes(D, GV); 1330 1331 // Emit the initializer function if necessary. 1332 if (NonConstInit) 1333 EmitCXXGlobalVarDeclInitFunc(D, GV); 1334 1335 // Emit global variable debug information. 1336 if (CGDebugInfo *DI = getModuleDebugInfo()) { 1337 DI->setLocation(D->getLocation()); 1338 DI->EmitGlobalVariable(GV, D); 1339 } 1340 } 1341 1342 llvm::GlobalValue::LinkageTypes 1343 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 1344 llvm::GlobalVariable *GV) { 1345 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1346 if (Linkage == GVA_Internal) 1347 return llvm::Function::InternalLinkage; 1348 else if (D->hasAttr<DLLImportAttr>()) 1349 return llvm::Function::DLLImportLinkage; 1350 else if (D->hasAttr<DLLExportAttr>()) 1351 return llvm::Function::DLLExportLinkage; 1352 else if (D->hasAttr<WeakAttr>()) { 1353 if (GV->isConstant()) 1354 return llvm::GlobalVariable::WeakODRLinkage; 1355 else 1356 return llvm::GlobalVariable::WeakAnyLinkage; 1357 } else if (Linkage == GVA_TemplateInstantiation || 1358 Linkage == GVA_ExplicitTemplateInstantiation) 1359 return llvm::GlobalVariable::WeakODRLinkage; 1360 else if (!getLangOptions().CPlusPlus && 1361 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1362 D->getAttr<CommonAttr>()) && 1363 !D->hasExternalStorage() && !D->getInit() && 1364 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() && 1365 !D->getAttr<WeakImportAttr>()) { 1366 // Thread local vars aren't considered common linkage. 1367 return llvm::GlobalVariable::CommonLinkage; 1368 } 1369 return llvm::GlobalVariable::ExternalLinkage; 1370 } 1371 1372 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1373 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1374 /// existing call uses of the old function in the module, this adjusts them to 1375 /// call the new function directly. 1376 /// 1377 /// This is not just a cleanup: the always_inline pass requires direct calls to 1378 /// functions to be able to inline them. If there is a bitcast in the way, it 1379 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1380 /// run at -O0. 1381 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1382 llvm::Function *NewFn) { 1383 // If we're redefining a global as a function, don't transform it. 1384 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1385 if (OldFn == 0) return; 1386 1387 llvm::Type *NewRetTy = NewFn->getReturnType(); 1388 SmallVector<llvm::Value*, 4> ArgList; 1389 1390 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1391 UI != E; ) { 1392 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1393 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1394 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1395 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1396 llvm::CallSite CS(CI); 1397 if (!CI || !CS.isCallee(I)) continue; 1398 1399 // If the return types don't match exactly, and if the call isn't dead, then 1400 // we can't transform this call. 1401 if (CI->getType() != NewRetTy && !CI->use_empty()) 1402 continue; 1403 1404 // Get the attribute list. 1405 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec; 1406 llvm::AttrListPtr AttrList = CI->getAttributes(); 1407 1408 // Get any return attributes. 1409 llvm::Attributes RAttrs = AttrList.getRetAttributes(); 1410 1411 // Add the return attributes. 1412 if (RAttrs) 1413 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs)); 1414 1415 // If the function was passed too few arguments, don't transform. If extra 1416 // arguments were passed, we silently drop them. If any of the types 1417 // mismatch, we don't transform. 1418 unsigned ArgNo = 0; 1419 bool DontTransform = false; 1420 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1421 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1422 if (CS.arg_size() == ArgNo || 1423 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1424 DontTransform = true; 1425 break; 1426 } 1427 1428 // Add any parameter attributes. 1429 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1)) 1430 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs)); 1431 } 1432 if (DontTransform) 1433 continue; 1434 1435 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes()) 1436 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs)); 1437 1438 // Okay, we can transform this. Create the new call instruction and copy 1439 // over the required information. 1440 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1441 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI); 1442 ArgList.clear(); 1443 if (!NewCall->getType()->isVoidTy()) 1444 NewCall->takeName(CI); 1445 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(), 1446 AttrVec.end())); 1447 NewCall->setCallingConv(CI->getCallingConv()); 1448 1449 // Finally, remove the old call, replacing any uses with the new one. 1450 if (!CI->use_empty()) 1451 CI->replaceAllUsesWith(NewCall); 1452 1453 // Copy debug location attached to CI. 1454 if (!CI->getDebugLoc().isUnknown()) 1455 NewCall->setDebugLoc(CI->getDebugLoc()); 1456 CI->eraseFromParent(); 1457 } 1458 } 1459 1460 1461 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1462 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1463 1464 // Compute the function info and LLVM type. 1465 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD); 1466 bool variadic = false; 1467 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>()) 1468 variadic = fpt->isVariadic(); 1469 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic); 1470 1471 // Get or create the prototype for the function. 1472 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1473 1474 // Strip off a bitcast if we got one back. 1475 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1476 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1477 Entry = CE->getOperand(0); 1478 } 1479 1480 1481 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1482 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1483 1484 // If the types mismatch then we have to rewrite the definition. 1485 assert(OldFn->isDeclaration() && 1486 "Shouldn't replace non-declaration"); 1487 1488 // F is the Function* for the one with the wrong type, we must make a new 1489 // Function* and update everything that used F (a declaration) with the new 1490 // Function* (which will be a definition). 1491 // 1492 // This happens if there is a prototype for a function 1493 // (e.g. "int f()") and then a definition of a different type 1494 // (e.g. "int f(int x)"). Move the old function aside so that it 1495 // doesn't interfere with GetAddrOfFunction. 1496 OldFn->setName(StringRef()); 1497 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1498 1499 // If this is an implementation of a function without a prototype, try to 1500 // replace any existing uses of the function (which may be calls) with uses 1501 // of the new function 1502 if (D->getType()->isFunctionNoProtoType()) { 1503 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1504 OldFn->removeDeadConstantUsers(); 1505 } 1506 1507 // Replace uses of F with the Function we will endow with a body. 1508 if (!Entry->use_empty()) { 1509 llvm::Constant *NewPtrForOldDecl = 1510 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1511 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1512 } 1513 1514 // Ok, delete the old function now, which is dead. 1515 OldFn->eraseFromParent(); 1516 1517 Entry = NewFn; 1518 } 1519 1520 // We need to set linkage and visibility on the function before 1521 // generating code for it because various parts of IR generation 1522 // want to propagate this information down (e.g. to local static 1523 // declarations). 1524 llvm::Function *Fn = cast<llvm::Function>(Entry); 1525 setFunctionLinkage(D, Fn); 1526 1527 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 1528 setGlobalVisibility(Fn, D); 1529 1530 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 1531 1532 SetFunctionDefinitionAttributes(D, Fn); 1533 SetLLVMFunctionAttributesForDefinition(D, Fn); 1534 1535 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1536 AddGlobalCtor(Fn, CA->getPriority()); 1537 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1538 AddGlobalDtor(Fn, DA->getPriority()); 1539 if (D->hasAttr<AnnotateAttr>()) 1540 AddGlobalAnnotations(D, Fn); 1541 } 1542 1543 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1544 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1545 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1546 assert(AA && "Not an alias?"); 1547 1548 StringRef MangledName = getMangledName(GD); 1549 1550 // If there is a definition in the module, then it wins over the alias. 1551 // This is dubious, but allow it to be safe. Just ignore the alias. 1552 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1553 if (Entry && !Entry->isDeclaration()) 1554 return; 1555 1556 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1557 1558 // Create a reference to the named value. This ensures that it is emitted 1559 // if a deferred decl. 1560 llvm::Constant *Aliasee; 1561 if (isa<llvm::FunctionType>(DeclTy)) 1562 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 1563 /*ForVTable=*/false); 1564 else 1565 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1566 llvm::PointerType::getUnqual(DeclTy), 0); 1567 1568 // Create the new alias itself, but don't set a name yet. 1569 llvm::GlobalValue *GA = 1570 new llvm::GlobalAlias(Aliasee->getType(), 1571 llvm::Function::ExternalLinkage, 1572 "", Aliasee, &getModule()); 1573 1574 if (Entry) { 1575 assert(Entry->isDeclaration()); 1576 1577 // If there is a declaration in the module, then we had an extern followed 1578 // by the alias, as in: 1579 // extern int test6(); 1580 // ... 1581 // int test6() __attribute__((alias("test7"))); 1582 // 1583 // Remove it and replace uses of it with the alias. 1584 GA->takeName(Entry); 1585 1586 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1587 Entry->getType())); 1588 Entry->eraseFromParent(); 1589 } else { 1590 GA->setName(MangledName); 1591 } 1592 1593 // Set attributes which are particular to an alias; this is a 1594 // specialization of the attributes which may be set on a global 1595 // variable/function. 1596 if (D->hasAttr<DLLExportAttr>()) { 1597 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1598 // The dllexport attribute is ignored for undefined symbols. 1599 if (FD->hasBody()) 1600 GA->setLinkage(llvm::Function::DLLExportLinkage); 1601 } else { 1602 GA->setLinkage(llvm::Function::DLLExportLinkage); 1603 } 1604 } else if (D->hasAttr<WeakAttr>() || 1605 D->hasAttr<WeakRefAttr>() || 1606 D->isWeakImported()) { 1607 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1608 } 1609 1610 SetCommonAttributes(D, GA); 1611 } 1612 1613 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 1614 ArrayRef<llvm::Type*> Tys) { 1615 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 1616 Tys); 1617 } 1618 1619 static llvm::StringMapEntry<llvm::Constant*> & 1620 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1621 const StringLiteral *Literal, 1622 bool TargetIsLSB, 1623 bool &IsUTF16, 1624 unsigned &StringLength) { 1625 StringRef String = Literal->getString(); 1626 unsigned NumBytes = String.size(); 1627 1628 // Check for simple case. 1629 if (!Literal->containsNonAsciiOrNull()) { 1630 StringLength = NumBytes; 1631 return Map.GetOrCreateValue(String); 1632 } 1633 1634 // Otherwise, convert the UTF8 literals into a byte string. 1635 SmallVector<UTF16, 128> ToBuf(NumBytes); 1636 const UTF8 *FromPtr = (UTF8 *)String.data(); 1637 UTF16 *ToPtr = &ToBuf[0]; 1638 1639 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1640 &ToPtr, ToPtr + NumBytes, 1641 strictConversion); 1642 1643 // ConvertUTF8toUTF16 returns the length in ToPtr. 1644 StringLength = ToPtr - &ToBuf[0]; 1645 1646 // Render the UTF-16 string into a byte array and convert to the target byte 1647 // order. 1648 // 1649 // FIXME: This isn't something we should need to do here. 1650 llvm::SmallString<128> AsBytes; 1651 AsBytes.reserve(StringLength * 2); 1652 for (unsigned i = 0; i != StringLength; ++i) { 1653 unsigned short Val = ToBuf[i]; 1654 if (TargetIsLSB) { 1655 AsBytes.push_back(Val & 0xFF); 1656 AsBytes.push_back(Val >> 8); 1657 } else { 1658 AsBytes.push_back(Val >> 8); 1659 AsBytes.push_back(Val & 0xFF); 1660 } 1661 } 1662 // Append one extra null character, the second is automatically added by our 1663 // caller. 1664 AsBytes.push_back(0); 1665 1666 IsUTF16 = true; 1667 return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size())); 1668 } 1669 1670 static llvm::StringMapEntry<llvm::Constant*> & 1671 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1672 const StringLiteral *Literal, 1673 unsigned &StringLength) 1674 { 1675 StringRef String = Literal->getString(); 1676 StringLength = String.size(); 1677 return Map.GetOrCreateValue(String); 1678 } 1679 1680 llvm::Constant * 1681 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1682 unsigned StringLength = 0; 1683 bool isUTF16 = false; 1684 llvm::StringMapEntry<llvm::Constant*> &Entry = 1685 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1686 getTargetData().isLittleEndian(), 1687 isUTF16, StringLength); 1688 1689 if (llvm::Constant *C = Entry.getValue()) 1690 return C; 1691 1692 llvm::Constant *Zero = 1693 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1694 llvm::Constant *Zeros[] = { Zero, Zero }; 1695 1696 // If we don't already have it, get __CFConstantStringClassReference. 1697 if (!CFConstantStringClassRef) { 1698 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1699 Ty = llvm::ArrayType::get(Ty, 0); 1700 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1701 "__CFConstantStringClassReference"); 1702 // Decay array -> ptr 1703 CFConstantStringClassRef = 1704 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1705 } 1706 1707 QualType CFTy = getContext().getCFConstantStringType(); 1708 1709 llvm::StructType *STy = 1710 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1711 1712 std::vector<llvm::Constant*> Fields(4); 1713 1714 // Class pointer. 1715 Fields[0] = CFConstantStringClassRef; 1716 1717 // Flags. 1718 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1719 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1720 llvm::ConstantInt::get(Ty, 0x07C8); 1721 1722 // String pointer. 1723 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1724 1725 llvm::GlobalValue::LinkageTypes Linkage; 1726 bool isConstant; 1727 if (isUTF16) { 1728 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1729 Linkage = llvm::GlobalValue::InternalLinkage; 1730 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1731 // does make plain ascii ones writable. 1732 isConstant = true; 1733 } else { 1734 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 1735 // when using private linkage. It is not clear if this is a bug in ld 1736 // or a reasonable new restriction. 1737 Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 1738 isConstant = !Features.WritableStrings; 1739 } 1740 1741 llvm::GlobalVariable *GV = 1742 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1743 ".str"); 1744 GV->setUnnamedAddr(true); 1745 if (isUTF16) { 1746 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1747 GV->setAlignment(Align.getQuantity()); 1748 } else { 1749 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 1750 GV->setAlignment(Align.getQuantity()); 1751 } 1752 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1753 1754 // String length. 1755 Ty = getTypes().ConvertType(getContext().LongTy); 1756 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1757 1758 // The struct. 1759 C = llvm::ConstantStruct::get(STy, Fields); 1760 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1761 llvm::GlobalVariable::PrivateLinkage, C, 1762 "_unnamed_cfstring_"); 1763 if (const char *Sect = getContext().getTargetInfo().getCFStringSection()) 1764 GV->setSection(Sect); 1765 Entry.setValue(GV); 1766 1767 return GV; 1768 } 1769 1770 static RecordDecl * 1771 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 1772 DeclContext *DC, IdentifierInfo *Id) { 1773 SourceLocation Loc; 1774 if (Ctx.getLangOptions().CPlusPlus) 1775 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 1776 else 1777 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 1778 } 1779 1780 llvm::Constant * 1781 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 1782 unsigned StringLength = 0; 1783 llvm::StringMapEntry<llvm::Constant*> &Entry = 1784 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 1785 1786 if (llvm::Constant *C = Entry.getValue()) 1787 return C; 1788 1789 llvm::Constant *Zero = 1790 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1791 llvm::Constant *Zeros[] = { Zero, Zero }; 1792 1793 // If we don't already have it, get _NSConstantStringClassReference. 1794 if (!ConstantStringClassRef) { 1795 std::string StringClass(getLangOptions().ObjCConstantStringClass); 1796 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1797 llvm::Constant *GV; 1798 if (Features.ObjCNonFragileABI) { 1799 std::string str = 1800 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 1801 : "OBJC_CLASS_$_" + StringClass; 1802 GV = getObjCRuntime().GetClassGlobal(str); 1803 // Make sure the result is of the correct type. 1804 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1805 ConstantStringClassRef = 1806 llvm::ConstantExpr::getBitCast(GV, PTy); 1807 } else { 1808 std::string str = 1809 StringClass.empty() ? "_NSConstantStringClassReference" 1810 : "_" + StringClass + "ClassReference"; 1811 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 1812 GV = CreateRuntimeVariable(PTy, str); 1813 // Decay array -> ptr 1814 ConstantStringClassRef = 1815 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1816 } 1817 } 1818 1819 if (!NSConstantStringType) { 1820 // Construct the type for a constant NSString. 1821 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 1822 Context.getTranslationUnitDecl(), 1823 &Context.Idents.get("__builtin_NSString")); 1824 D->startDefinition(); 1825 1826 QualType FieldTypes[3]; 1827 1828 // const int *isa; 1829 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 1830 // const char *str; 1831 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 1832 // unsigned int length; 1833 FieldTypes[2] = Context.UnsignedIntTy; 1834 1835 // Create fields 1836 for (unsigned i = 0; i < 3; ++i) { 1837 FieldDecl *Field = FieldDecl::Create(Context, D, 1838 SourceLocation(), 1839 SourceLocation(), 0, 1840 FieldTypes[i], /*TInfo=*/0, 1841 /*BitWidth=*/0, 1842 /*Mutable=*/false, 1843 /*HasInit=*/false); 1844 Field->setAccess(AS_public); 1845 D->addDecl(Field); 1846 } 1847 1848 D->completeDefinition(); 1849 QualType NSTy = Context.getTagDeclType(D); 1850 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 1851 } 1852 1853 std::vector<llvm::Constant*> Fields(3); 1854 1855 // Class pointer. 1856 Fields[0] = ConstantStringClassRef; 1857 1858 // String pointer. 1859 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1860 1861 llvm::GlobalValue::LinkageTypes Linkage; 1862 bool isConstant; 1863 Linkage = llvm::GlobalValue::PrivateLinkage; 1864 isConstant = !Features.WritableStrings; 1865 1866 llvm::GlobalVariable *GV = 1867 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1868 ".str"); 1869 GV->setUnnamedAddr(true); 1870 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 1871 GV->setAlignment(Align.getQuantity()); 1872 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1873 1874 // String length. 1875 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1876 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 1877 1878 // The struct. 1879 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 1880 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1881 llvm::GlobalVariable::PrivateLinkage, C, 1882 "_unnamed_nsstring_"); 1883 // FIXME. Fix section. 1884 if (const char *Sect = 1885 Features.ObjCNonFragileABI 1886 ? getContext().getTargetInfo().getNSStringNonFragileABISection() 1887 : getContext().getTargetInfo().getNSStringSection()) 1888 GV->setSection(Sect); 1889 Entry.setValue(GV); 1890 1891 return GV; 1892 } 1893 1894 QualType CodeGenModule::getObjCFastEnumerationStateType() { 1895 if (ObjCFastEnumerationStateType.isNull()) { 1896 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 1897 Context.getTranslationUnitDecl(), 1898 &Context.Idents.get("__objcFastEnumerationState")); 1899 D->startDefinition(); 1900 1901 QualType FieldTypes[] = { 1902 Context.UnsignedLongTy, 1903 Context.getPointerType(Context.getObjCIdType()), 1904 Context.getPointerType(Context.UnsignedLongTy), 1905 Context.getConstantArrayType(Context.UnsignedLongTy, 1906 llvm::APInt(32, 5), ArrayType::Normal, 0) 1907 }; 1908 1909 for (size_t i = 0; i < 4; ++i) { 1910 FieldDecl *Field = FieldDecl::Create(Context, 1911 D, 1912 SourceLocation(), 1913 SourceLocation(), 0, 1914 FieldTypes[i], /*TInfo=*/0, 1915 /*BitWidth=*/0, 1916 /*Mutable=*/false, 1917 /*HasInit=*/false); 1918 Field->setAccess(AS_public); 1919 D->addDecl(Field); 1920 } 1921 1922 D->completeDefinition(); 1923 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 1924 } 1925 1926 return ObjCFastEnumerationStateType; 1927 } 1928 1929 /// GetStringForStringLiteral - Return the appropriate bytes for a 1930 /// string literal, properly padded to match the literal type. 1931 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1932 const ASTContext &Context = getContext(); 1933 const ConstantArrayType *CAT = 1934 Context.getAsConstantArrayType(E->getType()); 1935 assert(CAT && "String isn't pointer or array!"); 1936 1937 // Resize the string to the right size. 1938 uint64_t RealLen = CAT->getSize().getZExtValue(); 1939 1940 switch (E->getKind()) { 1941 case StringLiteral::Ascii: 1942 case StringLiteral::UTF8: 1943 break; 1944 case StringLiteral::Wide: 1945 RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth(); 1946 break; 1947 case StringLiteral::UTF16: 1948 RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth(); 1949 break; 1950 case StringLiteral::UTF32: 1951 RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth(); 1952 break; 1953 } 1954 1955 std::string Str = E->getString().str(); 1956 Str.resize(RealLen, '\0'); 1957 1958 return Str; 1959 } 1960 1961 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1962 /// constant array for the given string literal. 1963 llvm::Constant * 1964 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1965 // FIXME: This can be more efficient. 1966 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1967 CharUnits Align = getContext().getTypeAlignInChars(S->getType()); 1968 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S), 1969 /* GlobalName */ 0, 1970 Align.getQuantity()); 1971 if (S->isWide() || S->isUTF16() || S->isUTF32()) { 1972 llvm::Type *DestTy = 1973 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1974 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1975 } 1976 return C; 1977 } 1978 1979 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1980 /// array for the given ObjCEncodeExpr node. 1981 llvm::Constant * 1982 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1983 std::string Str; 1984 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1985 1986 return GetAddrOfConstantCString(Str); 1987 } 1988 1989 1990 /// GenerateWritableString -- Creates storage for a string literal. 1991 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 1992 bool constant, 1993 CodeGenModule &CGM, 1994 const char *GlobalName, 1995 unsigned Alignment) { 1996 // Create Constant for this string literal. Don't add a '\0'. 1997 llvm::Constant *C = 1998 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1999 2000 // Create a global variable for this string 2001 llvm::GlobalVariable *GV = 2002 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 2003 llvm::GlobalValue::PrivateLinkage, 2004 C, GlobalName); 2005 GV->setAlignment(Alignment); 2006 GV->setUnnamedAddr(true); 2007 return GV; 2008 } 2009 2010 /// GetAddrOfConstantString - Returns a pointer to a character array 2011 /// containing the literal. This contents are exactly that of the 2012 /// given string, i.e. it will not be null terminated automatically; 2013 /// see GetAddrOfConstantCString. Note that whether the result is 2014 /// actually a pointer to an LLVM constant depends on 2015 /// Feature.WriteableStrings. 2016 /// 2017 /// The result has pointer to array type. 2018 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2019 const char *GlobalName, 2020 unsigned Alignment) { 2021 bool IsConstant = !Features.WritableStrings; 2022 2023 // Get the default prefix if a name wasn't specified. 2024 if (!GlobalName) 2025 GlobalName = ".str"; 2026 2027 // Don't share any string literals if strings aren't constant. 2028 if (!IsConstant) 2029 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2030 2031 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2032 ConstantStringMap.GetOrCreateValue(Str); 2033 2034 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2035 if (Alignment > GV->getAlignment()) { 2036 GV->setAlignment(Alignment); 2037 } 2038 return GV; 2039 } 2040 2041 // Create a global variable for this. 2042 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment); 2043 Entry.setValue(GV); 2044 return GV; 2045 } 2046 2047 /// GetAddrOfConstantCString - Returns a pointer to a character 2048 /// array containing the literal and a terminating '\0' 2049 /// character. The result has pointer to array type. 2050 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2051 const char *GlobalName, 2052 unsigned Alignment) { 2053 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2054 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2055 } 2056 2057 /// EmitObjCPropertyImplementations - Emit information for synthesized 2058 /// properties for an implementation. 2059 void CodeGenModule::EmitObjCPropertyImplementations(const 2060 ObjCImplementationDecl *D) { 2061 for (ObjCImplementationDecl::propimpl_iterator 2062 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2063 ObjCPropertyImplDecl *PID = *i; 2064 2065 // Dynamic is just for type-checking. 2066 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2067 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2068 2069 // Determine which methods need to be implemented, some may have 2070 // been overridden. Note that ::isSynthesized is not the method 2071 // we want, that just indicates if the decl came from a 2072 // property. What we want to know is if the method is defined in 2073 // this implementation. 2074 if (!D->getInstanceMethod(PD->getGetterName())) 2075 CodeGenFunction(*this).GenerateObjCGetter( 2076 const_cast<ObjCImplementationDecl *>(D), PID); 2077 if (!PD->isReadOnly() && 2078 !D->getInstanceMethod(PD->getSetterName())) 2079 CodeGenFunction(*this).GenerateObjCSetter( 2080 const_cast<ObjCImplementationDecl *>(D), PID); 2081 } 2082 } 2083 } 2084 2085 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2086 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2087 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2088 ivar; ivar = ivar->getNextIvar()) 2089 if (ivar->getType().isDestructedType()) 2090 return true; 2091 2092 return false; 2093 } 2094 2095 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2096 /// for an implementation. 2097 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2098 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2099 if (needsDestructMethod(D)) { 2100 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2101 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2102 ObjCMethodDecl *DTORMethod = 2103 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2104 cxxSelector, getContext().VoidTy, 0, D, 2105 /*isInstance=*/true, /*isVariadic=*/false, 2106 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true, 2107 /*isDefined=*/false, ObjCMethodDecl::Required); 2108 D->addInstanceMethod(DTORMethod); 2109 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2110 D->setHasCXXStructors(true); 2111 } 2112 2113 // If the implementation doesn't have any ivar initializers, we don't need 2114 // a .cxx_construct. 2115 if (D->getNumIvarInitializers() == 0) 2116 return; 2117 2118 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2119 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2120 // The constructor returns 'self'. 2121 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2122 D->getLocation(), 2123 D->getLocation(), cxxSelector, 2124 getContext().getObjCIdType(), 0, 2125 D, /*isInstance=*/true, 2126 /*isVariadic=*/false, 2127 /*isSynthesized=*/true, 2128 /*isImplicitlyDeclared=*/true, 2129 /*isDefined=*/false, 2130 ObjCMethodDecl::Required); 2131 D->addInstanceMethod(CTORMethod); 2132 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2133 D->setHasCXXStructors(true); 2134 } 2135 2136 /// EmitNamespace - Emit all declarations in a namespace. 2137 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2138 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2139 I != E; ++I) 2140 EmitTopLevelDecl(*I); 2141 } 2142 2143 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2144 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2145 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2146 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2147 ErrorUnsupported(LSD, "linkage spec"); 2148 return; 2149 } 2150 2151 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2152 I != E; ++I) 2153 EmitTopLevelDecl(*I); 2154 } 2155 2156 /// EmitTopLevelDecl - Emit code for a single top level declaration. 2157 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 2158 // If an error has occurred, stop code generation, but continue 2159 // parsing and semantic analysis (to ensure all warnings and errors 2160 // are emitted). 2161 if (Diags.hasErrorOccurred()) 2162 return; 2163 2164 // Ignore dependent declarations. 2165 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2166 return; 2167 2168 switch (D->getKind()) { 2169 case Decl::CXXConversion: 2170 case Decl::CXXMethod: 2171 case Decl::Function: 2172 // Skip function templates 2173 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2174 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2175 return; 2176 2177 EmitGlobal(cast<FunctionDecl>(D)); 2178 break; 2179 2180 case Decl::Var: 2181 EmitGlobal(cast<VarDecl>(D)); 2182 break; 2183 2184 // Indirect fields from global anonymous structs and unions can be 2185 // ignored; only the actual variable requires IR gen support. 2186 case Decl::IndirectField: 2187 break; 2188 2189 // C++ Decls 2190 case Decl::Namespace: 2191 EmitNamespace(cast<NamespaceDecl>(D)); 2192 break; 2193 // No code generation needed. 2194 case Decl::UsingShadow: 2195 case Decl::Using: 2196 case Decl::UsingDirective: 2197 case Decl::ClassTemplate: 2198 case Decl::FunctionTemplate: 2199 case Decl::TypeAliasTemplate: 2200 case Decl::NamespaceAlias: 2201 case Decl::Block: 2202 break; 2203 case Decl::CXXConstructor: 2204 // Skip function templates 2205 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2206 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2207 return; 2208 2209 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2210 break; 2211 case Decl::CXXDestructor: 2212 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 2213 return; 2214 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2215 break; 2216 2217 case Decl::StaticAssert: 2218 // Nothing to do. 2219 break; 2220 2221 // Objective-C Decls 2222 2223 // Forward declarations, no (immediate) code generation. 2224 case Decl::ObjCClass: 2225 case Decl::ObjCForwardProtocol: 2226 case Decl::ObjCInterface: 2227 break; 2228 2229 case Decl::ObjCCategory: { 2230 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 2231 if (CD->IsClassExtension() && CD->hasSynthBitfield()) 2232 Context.ResetObjCLayout(CD->getClassInterface()); 2233 break; 2234 } 2235 2236 case Decl::ObjCProtocol: 2237 ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 2238 break; 2239 2240 case Decl::ObjCCategoryImpl: 2241 // Categories have properties but don't support synthesize so we 2242 // can ignore them here. 2243 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2244 break; 2245 2246 case Decl::ObjCImplementation: { 2247 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2248 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield()) 2249 Context.ResetObjCLayout(OMD->getClassInterface()); 2250 EmitObjCPropertyImplementations(OMD); 2251 EmitObjCIvarInitializations(OMD); 2252 ObjCRuntime->GenerateClass(OMD); 2253 break; 2254 } 2255 case Decl::ObjCMethod: { 2256 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2257 // If this is not a prototype, emit the body. 2258 if (OMD->getBody()) 2259 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2260 break; 2261 } 2262 case Decl::ObjCCompatibleAlias: 2263 // compatibility-alias is a directive and has no code gen. 2264 break; 2265 2266 case Decl::LinkageSpec: 2267 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2268 break; 2269 2270 case Decl::FileScopeAsm: { 2271 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2272 StringRef AsmString = AD->getAsmString()->getString(); 2273 2274 const std::string &S = getModule().getModuleInlineAsm(); 2275 if (S.empty()) 2276 getModule().setModuleInlineAsm(AsmString); 2277 else if (*--S.end() == '\n') 2278 getModule().setModuleInlineAsm(S + AsmString.str()); 2279 else 2280 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2281 break; 2282 } 2283 2284 default: 2285 // Make sure we handled everything we should, every other kind is a 2286 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2287 // function. Need to recode Decl::Kind to do that easily. 2288 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2289 } 2290 } 2291 2292 /// Turns the given pointer into a constant. 2293 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2294 const void *Ptr) { 2295 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2296 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2297 return llvm::ConstantInt::get(i64, PtrInt); 2298 } 2299 2300 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2301 llvm::NamedMDNode *&GlobalMetadata, 2302 GlobalDecl D, 2303 llvm::GlobalValue *Addr) { 2304 if (!GlobalMetadata) 2305 GlobalMetadata = 2306 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2307 2308 // TODO: should we report variant information for ctors/dtors? 2309 llvm::Value *Ops[] = { 2310 Addr, 2311 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2312 }; 2313 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2314 } 2315 2316 /// Emits metadata nodes associating all the global values in the 2317 /// current module with the Decls they came from. This is useful for 2318 /// projects using IR gen as a subroutine. 2319 /// 2320 /// Since there's currently no way to associate an MDNode directly 2321 /// with an llvm::GlobalValue, we create a global named metadata 2322 /// with the name 'clang.global.decl.ptrs'. 2323 void CodeGenModule::EmitDeclMetadata() { 2324 llvm::NamedMDNode *GlobalMetadata = 0; 2325 2326 // StaticLocalDeclMap 2327 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 2328 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2329 I != E; ++I) { 2330 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2331 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2332 } 2333 } 2334 2335 /// Emits metadata nodes for all the local variables in the current 2336 /// function. 2337 void CodeGenFunction::EmitDeclMetadata() { 2338 if (LocalDeclMap.empty()) return; 2339 2340 llvm::LLVMContext &Context = getLLVMContext(); 2341 2342 // Find the unique metadata ID for this name. 2343 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2344 2345 llvm::NamedMDNode *GlobalMetadata = 0; 2346 2347 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2348 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2349 const Decl *D = I->first; 2350 llvm::Value *Addr = I->second; 2351 2352 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2353 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2354 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 2355 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2356 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2357 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2358 } 2359 } 2360 } 2361 2362 void CodeGenModule::EmitCoverageFile() { 2363 if (!getCodeGenOpts().CoverageFile.empty()) { 2364 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 2365 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 2366 llvm::LLVMContext &Ctx = TheModule.getContext(); 2367 llvm::MDString *CoverageFile = 2368 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 2369 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 2370 llvm::MDNode *CU = CUNode->getOperand(i); 2371 llvm::Value *node[] = { CoverageFile, CU }; 2372 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 2373 GCov->addOperand(N); 2374 } 2375 } 2376 } 2377 } 2378