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