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