CodeGenModule.cpp revision d3a344c55b89bad933c04ac59650f7afb95423e9
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 "CGCall.h" 18#include "CGObjCRuntime.h" 19#include "Mangle.h" 20#include "TargetInfo.h" 21#include "clang/CodeGen/CodeGenOptions.h" 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/CharUnits.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/DeclCXX.h" 26#include "clang/AST/RecordLayout.h" 27#include "clang/Basic/Builtins.h" 28#include "clang/Basic/Diagnostic.h" 29#include "clang/Basic/SourceManager.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Basic/ConvertUTF.h" 32#include "llvm/CallingConv.h" 33#include "llvm/Module.h" 34#include "llvm/Intrinsics.h" 35#include "llvm/LLVMContext.h" 36#include "llvm/ADT/Triple.h" 37#include "llvm/Target/TargetData.h" 38#include "llvm/Support/ErrorHandling.h" 39using namespace clang; 40using namespace CodeGen; 41 42 43CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 44 llvm::Module &M, const llvm::TargetData &TD, 45 Diagnostic &diags) 46 : BlockModule(C, M, TD, Types, *this), Context(C), 47 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 48 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 49 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()), 50 MangleCtx(C), VtableInfo(*this), Runtime(0), 51 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0), 52 VMContext(M.getContext()) { 53 54 if (!Features.ObjC1) 55 Runtime = 0; 56 else if (!Features.NeXTRuntime) 57 Runtime = CreateGNUObjCRuntime(*this); 58 else if (Features.ObjCNonFragileABI) 59 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 60 else 61 Runtime = CreateMacObjCRuntime(*this); 62 63 // If debug info generation is enabled, create the CGDebugInfo object. 64 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0; 65} 66 67CodeGenModule::~CodeGenModule() { 68 delete Runtime; 69 delete DebugInfo; 70} 71 72void CodeGenModule::createObjCRuntime() { 73 if (!Features.NeXTRuntime) 74 Runtime = CreateGNUObjCRuntime(*this); 75 else if (Features.ObjCNonFragileABI) 76 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 77 else 78 Runtime = CreateMacObjCRuntime(*this); 79} 80 81void CodeGenModule::Release() { 82 EmitDeferred(); 83 EmitCXXGlobalInitFunc(); 84 if (Runtime) 85 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 86 AddGlobalCtor(ObjCInitFunction); 87 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 88 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 89 EmitAnnotations(); 90 EmitLLVMUsed(); 91} 92 93bool CodeGenModule::isTargetDarwin() const { 94 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin; 95} 96 97/// ErrorUnsupported - Print out an error that codegen doesn't support the 98/// specified stmt yet. 99void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 100 bool OmitOnError) { 101 if (OmitOnError && getDiags().hasErrorOccurred()) 102 return; 103 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 104 "cannot compile this %0 yet"); 105 std::string Msg = Type; 106 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 107 << Msg << S->getSourceRange(); 108} 109 110/// ErrorUnsupported - Print out an error that codegen doesn't support the 111/// specified decl yet. 112void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 113 bool OmitOnError) { 114 if (OmitOnError && getDiags().hasErrorOccurred()) 115 return; 116 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 117 "cannot compile this %0 yet"); 118 std::string Msg = Type; 119 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 120} 121 122LangOptions::VisibilityMode 123CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 124 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 125 if (VD->getStorageClass() == VarDecl::PrivateExtern) 126 return LangOptions::Hidden; 127 128 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 129 switch (attr->getVisibility()) { 130 default: assert(0 && "Unknown visibility!"); 131 case VisibilityAttr::DefaultVisibility: 132 return LangOptions::Default; 133 case VisibilityAttr::HiddenVisibility: 134 return LangOptions::Hidden; 135 case VisibilityAttr::ProtectedVisibility: 136 return LangOptions::Protected; 137 } 138 } 139 140 // This decl should have the same visibility as its parent. 141 if (const DeclContext *DC = D->getDeclContext()) 142 return getDeclVisibilityMode(cast<Decl>(DC)); 143 144 return getLangOptions().getVisibilityMode(); 145} 146 147void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 148 const Decl *D) const { 149 // Internal definitions always have default visibility. 150 if (GV->hasLocalLinkage()) { 151 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 152 return; 153 } 154 155 switch (getDeclVisibilityMode(D)) { 156 default: assert(0 && "Unknown visibility!"); 157 case LangOptions::Default: 158 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 159 case LangOptions::Hidden: 160 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 161 case LangOptions::Protected: 162 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 163 } 164} 165 166const char *CodeGenModule::getMangledName(const GlobalDecl &GD) { 167 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 168 169 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 170 return getMangledCXXCtorName(D, GD.getCtorType()); 171 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 172 return getMangledCXXDtorName(D, GD.getDtorType()); 173 174 return getMangledName(ND); 175} 176 177/// \brief Retrieves the mangled name for the given declaration. 178/// 179/// If the given declaration requires a mangled name, returns an 180/// const char* containing the mangled name. Otherwise, returns 181/// the unmangled name. 182/// 183const char *CodeGenModule::getMangledName(const NamedDecl *ND) { 184 if (!getMangleContext().shouldMangleDeclName(ND)) { 185 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 186 return ND->getNameAsCString(); 187 } 188 189 llvm::SmallString<256> Name; 190 getMangleContext().mangleName(ND, Name); 191 Name += '\0'; 192 return UniqueMangledName(Name.begin(), Name.end()); 193} 194 195const char *CodeGenModule::UniqueMangledName(const char *NameStart, 196 const char *NameEnd) { 197 assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!"); 198 199 return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData(); 200} 201 202/// AddGlobalCtor - Add a function to the list that will be called before 203/// main() runs. 204void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 205 // FIXME: Type coercion of void()* types. 206 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 207} 208 209/// AddGlobalDtor - Add a function to the list that will be called 210/// when the module is unloaded. 211void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 212 // FIXME: Type coercion of void()* types. 213 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 214} 215 216void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 217 // Ctor function type is void()*. 218 llvm::FunctionType* CtorFTy = 219 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 220 std::vector<const llvm::Type*>(), 221 false); 222 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 223 224 // Get the type of a ctor entry, { i32, void ()* }. 225 llvm::StructType* CtorStructTy = 226 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 227 llvm::PointerType::getUnqual(CtorFTy), NULL); 228 229 // Construct the constructor and destructor arrays. 230 std::vector<llvm::Constant*> Ctors; 231 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 232 std::vector<llvm::Constant*> S; 233 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 234 I->second, false)); 235 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 236 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 237 } 238 239 if (!Ctors.empty()) { 240 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 241 new llvm::GlobalVariable(TheModule, AT, false, 242 llvm::GlobalValue::AppendingLinkage, 243 llvm::ConstantArray::get(AT, Ctors), 244 GlobalName); 245 } 246} 247 248void CodeGenModule::EmitAnnotations() { 249 if (Annotations.empty()) 250 return; 251 252 // Create a new global variable for the ConstantStruct in the Module. 253 llvm::Constant *Array = 254 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 255 Annotations.size()), 256 Annotations); 257 llvm::GlobalValue *gv = 258 new llvm::GlobalVariable(TheModule, Array->getType(), false, 259 llvm::GlobalValue::AppendingLinkage, Array, 260 "llvm.global.annotations"); 261 gv->setSection("llvm.metadata"); 262} 263 264static CodeGenModule::GVALinkage 265GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, 266 const LangOptions &Features) { 267 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; 268 269 Linkage L = FD->getLinkage(); 270 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 271 FD->getType()->getLinkage() == UniqueExternalLinkage) 272 L = UniqueExternalLinkage; 273 274 switch (L) { 275 case NoLinkage: 276 case InternalLinkage: 277 case UniqueExternalLinkage: 278 return CodeGenModule::GVA_Internal; 279 280 case ExternalLinkage: 281 switch (FD->getTemplateSpecializationKind()) { 282 case TSK_Undeclared: 283 case TSK_ExplicitSpecialization: 284 External = CodeGenModule::GVA_StrongExternal; 285 break; 286 287 case TSK_ExplicitInstantiationDefinition: 288 // FIXME: explicit instantiation definitions should use weak linkage 289 return CodeGenModule::GVA_StrongExternal; 290 291 case TSK_ExplicitInstantiationDeclaration: 292 case TSK_ImplicitInstantiation: 293 External = CodeGenModule::GVA_TemplateInstantiation; 294 break; 295 } 296 } 297 298 if (!FD->isInlined()) 299 return External; 300 301 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 302 // GNU or C99 inline semantics. Determine whether this symbol should be 303 // externally visible. 304 if (FD->isInlineDefinitionExternallyVisible()) 305 return External; 306 307 // C99 inline semantics, where the symbol is not externally visible. 308 return CodeGenModule::GVA_C99Inline; 309 } 310 311 // C++0x [temp.explicit]p9: 312 // [ Note: The intent is that an inline function that is the subject of 313 // an explicit instantiation declaration will still be implicitly 314 // instantiated when used so that the body can be considered for 315 // inlining, but that no out-of-line copy of the inline function would be 316 // generated in the translation unit. -- end note ] 317 if (FD->getTemplateSpecializationKind() 318 == TSK_ExplicitInstantiationDeclaration) 319 return CodeGenModule::GVA_C99Inline; 320 321 return CodeGenModule::GVA_CXXInline; 322} 323 324llvm::GlobalValue::LinkageTypes 325CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 326 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features); 327 328 if (Linkage == GVA_Internal) { 329 return llvm::Function::InternalLinkage; 330 } else if (D->hasAttr<DLLExportAttr>()) { 331 return llvm::Function::DLLExportLinkage; 332 } else if (D->hasAttr<WeakAttr>()) { 333 return llvm::Function::WeakAnyLinkage; 334 } else if (Linkage == GVA_C99Inline) { 335 // In C99 mode, 'inline' functions are guaranteed to have a strong 336 // definition somewhere else, so we can use available_externally linkage. 337 return llvm::Function::AvailableExternallyLinkage; 338 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) { 339 // In C++, the compiler has to emit a definition in every translation unit 340 // that references the function. We should use linkonce_odr because 341 // a) if all references in this translation unit are optimized away, we 342 // don't need to codegen it. b) if the function persists, it needs to be 343 // merged with other definitions. c) C++ has the ODR, so we know the 344 // definition is dependable. 345 return llvm::Function::LinkOnceODRLinkage; 346 } else { 347 assert(Linkage == GVA_StrongExternal); 348 // Otherwise, we have strong external linkage. 349 return llvm::Function::ExternalLinkage; 350 } 351} 352 353 354/// SetFunctionDefinitionAttributes - Set attributes for a global. 355/// 356/// FIXME: This is currently only done for aliases and functions, but not for 357/// variables (these details are set in EmitGlobalVarDefinition for variables). 358void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 359 llvm::GlobalValue *GV) { 360 GV->setLinkage(getFunctionLinkage(D)); 361 SetCommonAttributes(D, GV); 362} 363 364void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 365 const CGFunctionInfo &Info, 366 llvm::Function *F) { 367 unsigned CallingConv; 368 AttributeListType AttributeList; 369 ConstructAttributeList(Info, D, AttributeList, CallingConv); 370 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 371 AttributeList.size())); 372 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 373} 374 375void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 376 llvm::Function *F) { 377 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 378 F->addFnAttr(llvm::Attribute::NoUnwind); 379 380 if (D->hasAttr<AlwaysInlineAttr>()) 381 F->addFnAttr(llvm::Attribute::AlwaysInline); 382 383 if (D->hasAttr<NoInlineAttr>()) 384 F->addFnAttr(llvm::Attribute::NoInline); 385 386 if (Features.getStackProtectorMode() == LangOptions::SSPOn) 387 F->addFnAttr(llvm::Attribute::StackProtect); 388 else if (Features.getStackProtectorMode() == LangOptions::SSPReq) 389 F->addFnAttr(llvm::Attribute::StackProtectReq); 390 391 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) { 392 unsigned width = Context.Target.getCharWidth(); 393 F->setAlignment(AA->getAlignment() / width); 394 while ((AA = AA->getNext<AlignedAttr>())) 395 F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width)); 396 } 397 // C++ ABI requires 2-byte alignment for member functions. 398 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 399 F->setAlignment(2); 400} 401 402void CodeGenModule::SetCommonAttributes(const Decl *D, 403 llvm::GlobalValue *GV) { 404 setGlobalVisibility(GV, D); 405 406 if (D->hasAttr<UsedAttr>()) 407 AddUsedGlobal(GV); 408 409 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 410 GV->setSection(SA->getName()); 411 412 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 413} 414 415void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 416 llvm::Function *F, 417 const CGFunctionInfo &FI) { 418 SetLLVMFunctionAttributes(D, FI, F); 419 SetLLVMFunctionAttributesForDefinition(D, F); 420 421 F->setLinkage(llvm::Function::InternalLinkage); 422 423 SetCommonAttributes(D, F); 424} 425 426void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 427 llvm::Function *F, 428 bool IsIncompleteFunction) { 429 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 430 431 if (!IsIncompleteFunction) 432 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 433 434 // Only a few attributes are set on declarations; these may later be 435 // overridden by a definition. 436 437 if (FD->hasAttr<DLLImportAttr>()) { 438 F->setLinkage(llvm::Function::DLLImportLinkage); 439 } else if (FD->hasAttr<WeakAttr>() || 440 FD->hasAttr<WeakImportAttr>()) { 441 // "extern_weak" is overloaded in LLVM; we probably should have 442 // separate linkage types for this. 443 F->setLinkage(llvm::Function::ExternalWeakLinkage); 444 } else { 445 F->setLinkage(llvm::Function::ExternalLinkage); 446 } 447 448 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 449 F->setSection(SA->getName()); 450} 451 452void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 453 assert(!GV->isDeclaration() && 454 "Only globals with definition can force usage."); 455 LLVMUsed.push_back(GV); 456} 457 458void CodeGenModule::EmitLLVMUsed() { 459 // Don't create llvm.used if there is no need. 460 if (LLVMUsed.empty()) 461 return; 462 463 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 464 465 // Convert LLVMUsed to what ConstantArray needs. 466 std::vector<llvm::Constant*> UsedArray; 467 UsedArray.resize(LLVMUsed.size()); 468 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 469 UsedArray[i] = 470 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 471 i8PTy); 472 } 473 474 if (UsedArray.empty()) 475 return; 476 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 477 478 llvm::GlobalVariable *GV = 479 new llvm::GlobalVariable(getModule(), ATy, false, 480 llvm::GlobalValue::AppendingLinkage, 481 llvm::ConstantArray::get(ATy, UsedArray), 482 "llvm.used"); 483 484 GV->setSection("llvm.metadata"); 485} 486 487void CodeGenModule::EmitDeferred() { 488 // Emit code for any potentially referenced deferred decls. Since a 489 // previously unused static decl may become used during the generation of code 490 // for a static function, iterate until no changes are made. 491 while (!DeferredDeclsToEmit.empty()) { 492 GlobalDecl D = DeferredDeclsToEmit.back(); 493 DeferredDeclsToEmit.pop_back(); 494 495 // The mangled name for the decl must have been emitted in GlobalDeclMap. 496 // Look it up to see if it was defined with a stronger definition (e.g. an 497 // extern inline function with a strong function redefinition). If so, 498 // just ignore the deferred decl. 499 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)]; 500 assert(CGRef && "Deferred decl wasn't referenced?"); 501 502 if (!CGRef->isDeclaration()) 503 continue; 504 505 // Otherwise, emit the definition and move on to the next one. 506 EmitGlobalDefinition(D); 507 } 508} 509 510/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 511/// annotation information for a given GlobalValue. The annotation struct is 512/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 513/// GlobalValue being annotated. The second field is the constant string 514/// created from the AnnotateAttr's annotation. The third field is a constant 515/// string containing the name of the translation unit. The fourth field is 516/// the line number in the file of the annotated value declaration. 517/// 518/// FIXME: this does not unique the annotation string constants, as llvm-gcc 519/// appears to. 520/// 521llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 522 const AnnotateAttr *AA, 523 unsigned LineNo) { 524 llvm::Module *M = &getModule(); 525 526 // get [N x i8] constants for the annotation string, and the filename string 527 // which are the 2nd and 3rd elements of the global annotation structure. 528 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 529 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 530 AA->getAnnotation(), true); 531 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 532 M->getModuleIdentifier(), 533 true); 534 535 // Get the two global values corresponding to the ConstantArrays we just 536 // created to hold the bytes of the strings. 537 llvm::GlobalValue *annoGV = 538 new llvm::GlobalVariable(*M, anno->getType(), false, 539 llvm::GlobalValue::PrivateLinkage, anno, 540 GV->getName()); 541 // translation unit name string, emitted into the llvm.metadata section. 542 llvm::GlobalValue *unitGV = 543 new llvm::GlobalVariable(*M, unit->getType(), false, 544 llvm::GlobalValue::PrivateLinkage, unit, 545 ".str"); 546 547 // Create the ConstantStruct for the global annotation. 548 llvm::Constant *Fields[4] = { 549 llvm::ConstantExpr::getBitCast(GV, SBP), 550 llvm::ConstantExpr::getBitCast(annoGV, SBP), 551 llvm::ConstantExpr::getBitCast(unitGV, SBP), 552 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 553 }; 554 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 555} 556 557bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 558 // Never defer when EmitAllDecls is specified or the decl has 559 // attribute used. 560 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>()) 561 return false; 562 563 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 564 // Constructors and destructors should never be deferred. 565 if (FD->hasAttr<ConstructorAttr>() || 566 FD->hasAttr<DestructorAttr>()) 567 return false; 568 569 // The key function for a class must never be deferred. 570 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) { 571 const CXXRecordDecl *RD = MD->getParent(); 572 if (MD->isOutOfLine() && RD->isDynamicClass()) { 573 const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD); 574 if (KeyFunction && 575 KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl()) 576 return false; 577 } 578 } 579 580 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features); 581 582 // static, static inline, always_inline, and extern inline functions can 583 // always be deferred. Normal inline functions can be deferred in C99/C++. 584 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 585 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 586 return true; 587 return false; 588 } 589 590 const VarDecl *VD = cast<VarDecl>(Global); 591 assert(VD->isFileVarDecl() && "Invalid decl"); 592 593 // We never want to defer structs that have non-trivial constructors or 594 // destructors. 595 596 // FIXME: Handle references. 597 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 598 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 599 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()) 600 return false; 601 } 602 } 603 604 // Static data may be deferred, but out-of-line static data members 605 // cannot be. 606 Linkage L = VD->getLinkage(); 607 if (L == ExternalLinkage && getContext().getLangOptions().CPlusPlus && 608 VD->getType()->getLinkage() == UniqueExternalLinkage) 609 L = UniqueExternalLinkage; 610 611 switch (L) { 612 case NoLinkage: 613 case InternalLinkage: 614 case UniqueExternalLinkage: 615 // Initializer has side effects? 616 if (VD->getInit() && VD->getInit()->HasSideEffects(Context)) 617 return false; 618 return !(VD->isStaticDataMember() && VD->isOutOfLine()); 619 620 case ExternalLinkage: 621 break; 622 } 623 624 return false; 625} 626 627llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 628 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 629 assert(AA && "No alias?"); 630 631 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 632 633 // Unique the name through the identifier table. 634 const char *AliaseeName = 635 getContext().Idents.get(AA->getAliasee()).getNameStart(); 636 637 // See if there is already something with the target's name in the module. 638 llvm::GlobalValue *Entry = GlobalDeclMap[AliaseeName]; 639 640 llvm::Constant *Aliasee; 641 if (isa<llvm::FunctionType>(DeclTy)) 642 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl()); 643 else 644 Aliasee = GetOrCreateLLVMGlobal(AliaseeName, 645 llvm::PointerType::getUnqual(DeclTy), 0); 646 if (!Entry) { 647 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 648 F->setLinkage(llvm::Function::ExternalWeakLinkage); 649 WeakRefReferences.insert(F); 650 } 651 652 return Aliasee; 653} 654 655void CodeGenModule::EmitGlobal(GlobalDecl GD) { 656 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 657 658 // Weak references don't produce any output by themselves. 659 if (Global->hasAttr<WeakRefAttr>()) 660 return; 661 662 // If this is an alias definition (which otherwise looks like a declaration) 663 // emit it now. 664 if (Global->hasAttr<AliasAttr>()) 665 return EmitAliasDefinition(Global); 666 667 // Ignore declarations, they will be emitted on their first use. 668 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 669 // Forward declarations are emitted lazily on first use. 670 if (!FD->isThisDeclarationADefinition()) 671 return; 672 } else { 673 const VarDecl *VD = cast<VarDecl>(Global); 674 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 675 676 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 677 return; 678 } 679 680 // Defer code generation when possible if this is a static definition, inline 681 // function etc. These we only want to emit if they are used. 682 if (MayDeferGeneration(Global)) { 683 // If the value has already been used, add it directly to the 684 // DeferredDeclsToEmit list. 685 const char *MangledName = getMangledName(GD); 686 if (GlobalDeclMap.count(MangledName)) 687 DeferredDeclsToEmit.push_back(GD); 688 else { 689 // Otherwise, remember that we saw a deferred decl with this name. The 690 // first use of the mangled name will cause it to move into 691 // DeferredDeclsToEmit. 692 DeferredDecls[MangledName] = GD; 693 } 694 return; 695 } 696 697 // Otherwise emit the definition. 698 EmitGlobalDefinition(GD); 699} 700 701void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 702 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 703 704 PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(), 705 Context.getSourceManager(), 706 "Generating code for declaration"); 707 708 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 709 getVtableInfo().MaybeEmitVtable(GD); 710 if (MD->isVirtual() && MD->isOutOfLine() && 711 (!isa<CXXDestructorDecl>(D) || GD.getDtorType() != Dtor_Base)) { 712 if (isa<CXXDestructorDecl>(D)) { 713 GlobalDecl CanonGD(cast<CXXDestructorDecl>(D->getCanonicalDecl()), 714 GD.getDtorType()); 715 BuildThunksForVirtual(CanonGD); 716 } else { 717 BuildThunksForVirtual(MD->getCanonicalDecl()); 718 } 719 } 720 } 721 722 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 723 EmitCXXConstructor(CD, GD.getCtorType()); 724 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 725 EmitCXXDestructor(DD, GD.getDtorType()); 726 else if (isa<FunctionDecl>(D)) 727 EmitGlobalFunctionDefinition(GD); 728 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 729 EmitGlobalVarDefinition(VD); 730 else { 731 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 732 } 733} 734 735/// GetOrCreateLLVMFunction - If the specified mangled name is not in the 736/// module, create and return an llvm Function with the specified type. If there 737/// is something in the module with the specified name, return it potentially 738/// bitcasted to the right type. 739/// 740/// If D is non-null, it specifies a decl that correspond to this. This is used 741/// to set the attributes on the function when it is first created. 742llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, 743 const llvm::Type *Ty, 744 GlobalDecl D) { 745 // Lookup the entry, lazily creating it if necessary. 746 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 747 if (Entry) { 748 if (WeakRefReferences.count(Entry)) { 749 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 750 if (FD && !FD->hasAttr<WeakAttr>()) 751 Entry->setLinkage(llvm::Function::ExternalLinkage); 752 753 WeakRefReferences.erase(Entry); 754 } 755 756 if (Entry->getType()->getElementType() == Ty) 757 return Entry; 758 759 // Make sure the result is of the correct type. 760 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 761 return llvm::ConstantExpr::getBitCast(Entry, PTy); 762 } 763 764 // This function doesn't have a complete type (for example, the return 765 // type is an incomplete struct). Use a fake type instead, and make 766 // sure not to try to set attributes. 767 bool IsIncompleteFunction = false; 768 if (!isa<llvm::FunctionType>(Ty)) { 769 Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 770 std::vector<const llvm::Type*>(), false); 771 IsIncompleteFunction = true; 772 } 773 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 774 llvm::Function::ExternalLinkage, 775 "", &getModule()); 776 F->setName(MangledName); 777 if (D.getDecl()) 778 SetFunctionAttributes(D, F, IsIncompleteFunction); 779 Entry = F; 780 781 // This is the first use or definition of a mangled name. If there is a 782 // deferred decl with this name, remember that we need to emit it at the end 783 // of the file. 784 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 785 DeferredDecls.find(MangledName); 786 if (DDI != DeferredDecls.end()) { 787 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 788 // list, and remove it from DeferredDecls (since we don't need it anymore). 789 DeferredDeclsToEmit.push_back(DDI->second); 790 DeferredDecls.erase(DDI); 791 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 792 // If this the first reference to a C++ inline function in a class, queue up 793 // the deferred function body for emission. These are not seen as 794 // top-level declarations. 795 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 796 DeferredDeclsToEmit.push_back(D); 797 // A called constructor which has no definition or declaration need be 798 // synthesized. 799 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 800 if (CD->isImplicit()) { 801 assert(CD->isUsed() && "Sema doesn't consider constructor as used."); 802 DeferredDeclsToEmit.push_back(D); 803 } 804 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 805 if (DD->isImplicit()) { 806 assert(DD->isUsed() && "Sema doesn't consider destructor as used."); 807 DeferredDeclsToEmit.push_back(D); 808 } 809 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 810 if (MD->isCopyAssignment() && MD->isImplicit()) { 811 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used."); 812 DeferredDeclsToEmit.push_back(D); 813 } 814 } 815 } 816 817 return F; 818} 819 820/// GetAddrOfFunction - Return the address of the given function. If Ty is 821/// non-null, then this function will use the specified type if it has to 822/// create it (this occurs when we see a definition of the function). 823llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 824 const llvm::Type *Ty) { 825 // If there was no specific requested type, just convert it now. 826 if (!Ty) 827 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 828 return GetOrCreateLLVMFunction(getMangledName(GD), Ty, GD); 829} 830 831/// CreateRuntimeFunction - Create a new runtime function with the specified 832/// type and name. 833llvm::Constant * 834CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 835 const char *Name) { 836 // Convert Name to be a uniqued string from the IdentifierInfo table. 837 Name = getContext().Idents.get(Name).getNameStart(); 838 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 839} 840 841static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) { 842 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 843 return false; 844 if (Context.getLangOptions().CPlusPlus && 845 Context.getBaseElementType(D->getType())->getAs<RecordType>()) { 846 // FIXME: We should do something fancier here! 847 return false; 848 } 849 return true; 850} 851 852/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 853/// create and return an llvm GlobalVariable with the specified type. If there 854/// is something in the module with the specified name, return it potentially 855/// bitcasted to the right type. 856/// 857/// If D is non-null, it specifies a decl that correspond to this. This is used 858/// to set the attributes on the global when it is first created. 859llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, 860 const llvm::PointerType*Ty, 861 const VarDecl *D) { 862 // Lookup the entry, lazily creating it if necessary. 863 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 864 if (Entry) { 865 if (WeakRefReferences.count(Entry)) { 866 if (D && !D->hasAttr<WeakAttr>()) 867 Entry->setLinkage(llvm::Function::ExternalLinkage); 868 869 WeakRefReferences.erase(Entry); 870 } 871 872 if (Entry->getType() == Ty) 873 return Entry; 874 875 // Make sure the result is of the correct type. 876 return llvm::ConstantExpr::getBitCast(Entry, Ty); 877 } 878 879 // This is the first use or definition of a mangled name. If there is a 880 // deferred decl with this name, remember that we need to emit it at the end 881 // of the file. 882 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 883 DeferredDecls.find(MangledName); 884 if (DDI != DeferredDecls.end()) { 885 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 886 // list, and remove it from DeferredDecls (since we don't need it anymore). 887 DeferredDeclsToEmit.push_back(DDI->second); 888 DeferredDecls.erase(DDI); 889 } 890 891 llvm::GlobalVariable *GV = 892 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 893 llvm::GlobalValue::ExternalLinkage, 894 0, "", 0, 895 false, Ty->getAddressSpace()); 896 GV->setName(MangledName); 897 898 // Handle things which are present even on external declarations. 899 if (D) { 900 // FIXME: This code is overly simple and should be merged with other global 901 // handling. 902 GV->setConstant(DeclIsConstantGlobal(Context, D)); 903 904 // FIXME: Merge with other attribute handling code. 905 if (D->getStorageClass() == VarDecl::PrivateExtern) 906 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 907 908 if (D->hasAttr<WeakAttr>() || 909 D->hasAttr<WeakImportAttr>()) 910 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 911 912 GV->setThreadLocal(D->isThreadSpecified()); 913 } 914 915 return Entry = GV; 916} 917 918 919/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 920/// given global variable. If Ty is non-null and if the global doesn't exist, 921/// then it will be greated with the specified type instead of whatever the 922/// normal requested type would be. 923llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 924 const llvm::Type *Ty) { 925 assert(D->hasGlobalStorage() && "Not a global variable"); 926 QualType ASTTy = D->getType(); 927 if (Ty == 0) 928 Ty = getTypes().ConvertTypeForMem(ASTTy); 929 930 const llvm::PointerType *PTy = 931 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 932 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D); 933} 934 935/// CreateRuntimeVariable - Create a new runtime global variable with the 936/// specified type and name. 937llvm::Constant * 938CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 939 const char *Name) { 940 // Convert Name to be a uniqued string from the IdentifierInfo table. 941 Name = getContext().Idents.get(Name).getNameStart(); 942 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 943} 944 945void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 946 assert(!D->getInit() && "Cannot emit definite definitions here!"); 947 948 if (MayDeferGeneration(D)) { 949 // If we have not seen a reference to this variable yet, place it 950 // into the deferred declarations table to be emitted if needed 951 // later. 952 const char *MangledName = getMangledName(D); 953 if (GlobalDeclMap.count(MangledName) == 0) { 954 DeferredDecls[MangledName] = D; 955 return; 956 } 957 } 958 959 // The tentative definition is the only definition. 960 EmitGlobalVarDefinition(D); 961} 962 963llvm::GlobalVariable::LinkageTypes 964CodeGenModule::getVtableLinkage(const CXXRecordDecl *RD) { 965 if (RD->isInAnonymousNamespace() || !RD->hasLinkage()) 966 return llvm::GlobalVariable::InternalLinkage; 967 968 if (const CXXMethodDecl *KeyFunction 969 = RD->getASTContext().getKeyFunction(RD)) { 970 // If this class has a key function, use that to determine the linkage of 971 // the vtable. 972 const FunctionDecl *Def = 0; 973 if (KeyFunction->getBody(Def)) 974 KeyFunction = cast<CXXMethodDecl>(Def); 975 976 switch (KeyFunction->getTemplateSpecializationKind()) { 977 case TSK_Undeclared: 978 case TSK_ExplicitSpecialization: 979 if (KeyFunction->isInlined()) 980 return llvm::GlobalVariable::WeakODRLinkage; 981 982 return llvm::GlobalVariable::ExternalLinkage; 983 984 case TSK_ImplicitInstantiation: 985 case TSK_ExplicitInstantiationDefinition: 986 return llvm::GlobalVariable::WeakODRLinkage; 987 988 case TSK_ExplicitInstantiationDeclaration: 989 // FIXME: Use available_externally linkage. However, this currently 990 // breaks LLVM's build due to undefined symbols. 991 // return llvm::GlobalVariable::AvailableExternallyLinkage; 992 return llvm::GlobalVariable::WeakODRLinkage; 993 } 994 } 995 996 switch (RD->getTemplateSpecializationKind()) { 997 case TSK_Undeclared: 998 case TSK_ExplicitSpecialization: 999 case TSK_ImplicitInstantiation: 1000 case TSK_ExplicitInstantiationDefinition: 1001 return llvm::GlobalVariable::WeakODRLinkage; 1002 1003 case TSK_ExplicitInstantiationDeclaration: 1004 // FIXME: Use available_externally linkage. However, this currently 1005 // breaks LLVM's build due to undefined symbols. 1006 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1007 return llvm::GlobalVariable::WeakODRLinkage; 1008 } 1009 1010 // Silence GCC warning. 1011 return llvm::GlobalVariable::WeakODRLinkage; 1012} 1013 1014static CodeGenModule::GVALinkage 1015GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) { 1016 // If this is a static data member, compute the kind of template 1017 // specialization. Otherwise, this variable is not part of a 1018 // template. 1019 TemplateSpecializationKind TSK = TSK_Undeclared; 1020 if (VD->isStaticDataMember()) 1021 TSK = VD->getTemplateSpecializationKind(); 1022 1023 Linkage L = VD->getLinkage(); 1024 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 1025 VD->getType()->getLinkage() == UniqueExternalLinkage) 1026 L = UniqueExternalLinkage; 1027 1028 switch (L) { 1029 case NoLinkage: 1030 case InternalLinkage: 1031 case UniqueExternalLinkage: 1032 return CodeGenModule::GVA_Internal; 1033 1034 case ExternalLinkage: 1035 switch (TSK) { 1036 case TSK_Undeclared: 1037 case TSK_ExplicitSpecialization: 1038 1039 // FIXME: ExplicitInstantiationDefinition should be weak! 1040 case TSK_ExplicitInstantiationDefinition: 1041 return CodeGenModule::GVA_StrongExternal; 1042 1043 case TSK_ExplicitInstantiationDeclaration: 1044 llvm_unreachable("Variable should not be instantiated"); 1045 // Fall through to treat this like any other instantiation. 1046 1047 case TSK_ImplicitInstantiation: 1048 return CodeGenModule::GVA_TemplateInstantiation; 1049 } 1050 } 1051 1052 return CodeGenModule::GVA_StrongExternal; 1053} 1054 1055CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1056 return CharUnits::fromQuantity( 1057 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth()); 1058} 1059 1060void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1061 llvm::Constant *Init = 0; 1062 QualType ASTTy = D->getType(); 1063 bool NonConstInit = false; 1064 1065 const Expr *InitExpr = D->getAnyInitializer(); 1066 1067 if (!InitExpr) { 1068 // This is a tentative definition; tentative definitions are 1069 // implicitly initialized with { 0 }. 1070 // 1071 // Note that tentative definitions are only emitted at the end of 1072 // a translation unit, so they should never have incomplete 1073 // type. In addition, EmitTentativeDefinition makes sure that we 1074 // never attempt to emit a tentative definition if a real one 1075 // exists. A use may still exists, however, so we still may need 1076 // to do a RAUW. 1077 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1078 Init = EmitNullConstant(D->getType()); 1079 } else { 1080 Init = EmitConstantExpr(InitExpr, D->getType()); 1081 1082 if (!Init) { 1083 QualType T = InitExpr->getType(); 1084 if (getLangOptions().CPlusPlus) { 1085 EmitCXXGlobalVarDeclInitFunc(D); 1086 Init = EmitNullConstant(T); 1087 NonConstInit = true; 1088 } else { 1089 ErrorUnsupported(D, "static initializer"); 1090 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1091 } 1092 } 1093 } 1094 1095 const llvm::Type* InitType = Init->getType(); 1096 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1097 1098 // Strip off a bitcast if we got one back. 1099 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1100 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1101 // all zero index gep. 1102 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1103 Entry = CE->getOperand(0); 1104 } 1105 1106 // Entry is now either a Function or GlobalVariable. 1107 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1108 1109 // We have a definition after a declaration with the wrong type. 1110 // We must make a new GlobalVariable* and update everything that used OldGV 1111 // (a declaration or tentative definition) with the new GlobalVariable* 1112 // (which will be a definition). 1113 // 1114 // This happens if there is a prototype for a global (e.g. 1115 // "extern int x[];") and then a definition of a different type (e.g. 1116 // "int x[10];"). This also happens when an initializer has a different type 1117 // from the type of the global (this happens with unions). 1118 if (GV == 0 || 1119 GV->getType()->getElementType() != InitType || 1120 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1121 1122 // Remove the old entry from GlobalDeclMap so that we'll create a new one. 1123 GlobalDeclMap.erase(getMangledName(D)); 1124 1125 // Make a new global with the correct type, this is now guaranteed to work. 1126 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1127 GV->takeName(cast<llvm::GlobalValue>(Entry)); 1128 1129 // Replace all uses of the old global with the new global 1130 llvm::Constant *NewPtrForOldDecl = 1131 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1132 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1133 1134 // Erase the old global, since it is no longer used. 1135 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1136 } 1137 1138 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1139 SourceManager &SM = Context.getSourceManager(); 1140 AddAnnotation(EmitAnnotateAttr(GV, AA, 1141 SM.getInstantiationLineNumber(D->getLocation()))); 1142 } 1143 1144 GV->setInitializer(Init); 1145 1146 // If it is safe to mark the global 'constant', do so now. 1147 GV->setConstant(false); 1148 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1149 GV->setConstant(true); 1150 1151 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1152 1153 // Set the llvm linkage type as appropriate. 1154 GVALinkage Linkage = GetLinkageForVariable(getContext(), D); 1155 if (Linkage == GVA_Internal) 1156 GV->setLinkage(llvm::Function::InternalLinkage); 1157 else if (D->hasAttr<DLLImportAttr>()) 1158 GV->setLinkage(llvm::Function::DLLImportLinkage); 1159 else if (D->hasAttr<DLLExportAttr>()) 1160 GV->setLinkage(llvm::Function::DLLExportLinkage); 1161 else if (D->hasAttr<WeakAttr>()) { 1162 if (GV->isConstant()) 1163 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1164 else 1165 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1166 } else if (Linkage == GVA_TemplateInstantiation) 1167 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1168 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon && 1169 !D->hasExternalStorage() && !D->getInit() && 1170 !D->getAttr<SectionAttr>()) { 1171 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1172 // common vars aren't constant even if declared const. 1173 GV->setConstant(false); 1174 } else 1175 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1176 1177 SetCommonAttributes(D, GV); 1178 1179 // Emit global variable debug information. 1180 if (CGDebugInfo *DI = getDebugInfo()) { 1181 DI->setLocation(D->getLocation()); 1182 DI->EmitGlobalVariable(GV, D); 1183 } 1184} 1185 1186/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1187/// implement a function with no prototype, e.g. "int foo() {}". If there are 1188/// existing call uses of the old function in the module, this adjusts them to 1189/// call the new function directly. 1190/// 1191/// This is not just a cleanup: the always_inline pass requires direct calls to 1192/// functions to be able to inline them. If there is a bitcast in the way, it 1193/// won't inline them. Instcombine normally deletes these calls, but it isn't 1194/// run at -O0. 1195static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1196 llvm::Function *NewFn) { 1197 // If we're redefining a global as a function, don't transform it. 1198 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1199 if (OldFn == 0) return; 1200 1201 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1202 llvm::SmallVector<llvm::Value*, 4> ArgList; 1203 1204 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1205 UI != E; ) { 1206 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1207 unsigned OpNo = UI.getOperandNo(); 1208 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++); 1209 if (!CI || OpNo != 0) continue; 1210 1211 // If the return types don't match exactly, and if the call isn't dead, then 1212 // we can't transform this call. 1213 if (CI->getType() != NewRetTy && !CI->use_empty()) 1214 continue; 1215 1216 // If the function was passed too few arguments, don't transform. If extra 1217 // arguments were passed, we silently drop them. If any of the types 1218 // mismatch, we don't transform. 1219 unsigned ArgNo = 0; 1220 bool DontTransform = false; 1221 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1222 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1223 if (CI->getNumOperands()-1 == ArgNo || 1224 CI->getOperand(ArgNo+1)->getType() != AI->getType()) { 1225 DontTransform = true; 1226 break; 1227 } 1228 } 1229 if (DontTransform) 1230 continue; 1231 1232 // Okay, we can transform this. Create the new call instruction and copy 1233 // over the required information. 1234 ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo); 1235 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1236 ArgList.end(), "", CI); 1237 ArgList.clear(); 1238 if (!NewCall->getType()->isVoidTy()) 1239 NewCall->takeName(CI); 1240 NewCall->setAttributes(CI->getAttributes()); 1241 NewCall->setCallingConv(CI->getCallingConv()); 1242 1243 // Finally, remove the old call, replacing any uses with the new one. 1244 if (!CI->use_empty()) 1245 CI->replaceAllUsesWith(NewCall); 1246 1247 // Copy any custom metadata attached with CI. 1248 if (llvm::MDNode *DbgNode = CI->getMetadata("dbg")) 1249 NewCall->setMetadata("dbg", DbgNode); 1250 CI->eraseFromParent(); 1251 } 1252} 1253 1254 1255void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1256 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1257 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1258 getMangleContext().mangleInitDiscriminator(); 1259 // Get or create the prototype for the function. 1260 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1261 1262 // Strip off a bitcast if we got one back. 1263 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1264 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1265 Entry = CE->getOperand(0); 1266 } 1267 1268 1269 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1270 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1271 1272 // If the types mismatch then we have to rewrite the definition. 1273 assert(OldFn->isDeclaration() && 1274 "Shouldn't replace non-declaration"); 1275 1276 // F is the Function* for the one with the wrong type, we must make a new 1277 // Function* and update everything that used F (a declaration) with the new 1278 // Function* (which will be a definition). 1279 // 1280 // This happens if there is a prototype for a function 1281 // (e.g. "int f()") and then a definition of a different type 1282 // (e.g. "int f(int x)"). Start by making a new function of the 1283 // correct type, RAUW, then steal the name. 1284 GlobalDeclMap.erase(getMangledName(D)); 1285 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1286 NewFn->takeName(OldFn); 1287 1288 // If this is an implementation of a function without a prototype, try to 1289 // replace any existing uses of the function (which may be calls) with uses 1290 // of the new function 1291 if (D->getType()->isFunctionNoProtoType()) { 1292 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1293 OldFn->removeDeadConstantUsers(); 1294 } 1295 1296 // Replace uses of F with the Function we will endow with a body. 1297 if (!Entry->use_empty()) { 1298 llvm::Constant *NewPtrForOldDecl = 1299 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1300 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1301 } 1302 1303 // Ok, delete the old function now, which is dead. 1304 OldFn->eraseFromParent(); 1305 1306 Entry = NewFn; 1307 } 1308 1309 llvm::Function *Fn = cast<llvm::Function>(Entry); 1310 1311 CodeGenFunction(*this).GenerateCode(D, Fn); 1312 1313 SetFunctionDefinitionAttributes(D, Fn); 1314 SetLLVMFunctionAttributesForDefinition(D, Fn); 1315 1316 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1317 AddGlobalCtor(Fn, CA->getPriority()); 1318 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1319 AddGlobalDtor(Fn, DA->getPriority()); 1320} 1321 1322void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { 1323 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1324 assert(AA && "Not an alias?"); 1325 1326 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1327 1328 // Unique the name through the identifier table. 1329 const char *AliaseeName = 1330 getContext().Idents.get(AA->getAliasee()).getNameStart(); 1331 1332 // Create a reference to the named value. This ensures that it is emitted 1333 // if a deferred decl. 1334 llvm::Constant *Aliasee; 1335 if (isa<llvm::FunctionType>(DeclTy)) 1336 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl()); 1337 else 1338 Aliasee = GetOrCreateLLVMGlobal(AliaseeName, 1339 llvm::PointerType::getUnqual(DeclTy), 0); 1340 1341 // Create the new alias itself, but don't set a name yet. 1342 llvm::GlobalValue *GA = 1343 new llvm::GlobalAlias(Aliasee->getType(), 1344 llvm::Function::ExternalLinkage, 1345 "", Aliasee, &getModule()); 1346 1347 // See if there is already something with the alias' name in the module. 1348 const char *MangledName = getMangledName(D); 1349 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 1350 1351 if (Entry && !Entry->isDeclaration()) { 1352 // If there is a definition in the module, then it wins over the alias. 1353 // This is dubious, but allow it to be safe. Just ignore the alias. 1354 GA->eraseFromParent(); 1355 return; 1356 } 1357 1358 if (Entry) { 1359 // If there is a declaration in the module, then we had an extern followed 1360 // by the alias, as in: 1361 // extern int test6(); 1362 // ... 1363 // int test6() __attribute__((alias("test7"))); 1364 // 1365 // Remove it and replace uses of it with the alias. 1366 1367 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1368 Entry->getType())); 1369 Entry->eraseFromParent(); 1370 } 1371 1372 // Now we know that there is no conflict, set the name. 1373 Entry = GA; 1374 GA->setName(MangledName); 1375 1376 // Set attributes which are particular to an alias; this is a 1377 // specialization of the attributes which may be set on a global 1378 // variable/function. 1379 if (D->hasAttr<DLLExportAttr>()) { 1380 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1381 // The dllexport attribute is ignored for undefined symbols. 1382 if (FD->getBody()) 1383 GA->setLinkage(llvm::Function::DLLExportLinkage); 1384 } else { 1385 GA->setLinkage(llvm::Function::DLLExportLinkage); 1386 } 1387 } else if (D->hasAttr<WeakAttr>() || 1388 D->hasAttr<WeakRefAttr>() || 1389 D->hasAttr<WeakImportAttr>()) { 1390 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1391 } 1392 1393 SetCommonAttributes(D, GA); 1394} 1395 1396/// getBuiltinLibFunction - Given a builtin id for a function like 1397/// "__builtin_fabsf", return a Function* for "fabsf". 1398llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1399 unsigned BuiltinID) { 1400 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1401 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1402 "isn't a lib fn"); 1403 1404 // Get the name, skip over the __builtin_ prefix (if necessary). 1405 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1406 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1407 Name += 10; 1408 1409 const llvm::FunctionType *Ty = 1410 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1411 1412 // Unique the name through the identifier table. 1413 Name = getContext().Idents.get(Name).getNameStart(); 1414 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1415} 1416 1417llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1418 unsigned NumTys) { 1419 return llvm::Intrinsic::getDeclaration(&getModule(), 1420 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1421} 1422 1423llvm::Function *CodeGenModule::getMemCpyFn() { 1424 if (MemCpyFn) return MemCpyFn; 1425 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1426 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 1427} 1428 1429llvm::Function *CodeGenModule::getMemMoveFn() { 1430 if (MemMoveFn) return MemMoveFn; 1431 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1432 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 1433} 1434 1435llvm::Function *CodeGenModule::getMemSetFn() { 1436 if (MemSetFn) return MemSetFn; 1437 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1438 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 1439} 1440 1441static llvm::StringMapEntry<llvm::Constant*> & 1442GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1443 const StringLiteral *Literal, 1444 bool TargetIsLSB, 1445 bool &IsUTF16, 1446 unsigned &StringLength) { 1447 unsigned NumBytes = Literal->getByteLength(); 1448 1449 // Check for simple case. 1450 if (!Literal->containsNonAsciiOrNull()) { 1451 StringLength = NumBytes; 1452 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1453 StringLength)); 1454 } 1455 1456 // Otherwise, convert the UTF8 literals into a byte string. 1457 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1458 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1459 UTF16 *ToPtr = &ToBuf[0]; 1460 1461 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1462 &ToPtr, ToPtr + NumBytes, 1463 strictConversion); 1464 1465 // Check for conversion failure. 1466 if (Result != conversionOK) { 1467 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1468 // this duplicate code. 1469 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1470 StringLength = NumBytes; 1471 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1472 StringLength)); 1473 } 1474 1475 // ConvertUTF8toUTF16 returns the length in ToPtr. 1476 StringLength = ToPtr - &ToBuf[0]; 1477 1478 // Render the UTF-16 string into a byte array and convert to the target byte 1479 // order. 1480 // 1481 // FIXME: This isn't something we should need to do here. 1482 llvm::SmallString<128> AsBytes; 1483 AsBytes.reserve(StringLength * 2); 1484 for (unsigned i = 0; i != StringLength; ++i) { 1485 unsigned short Val = ToBuf[i]; 1486 if (TargetIsLSB) { 1487 AsBytes.push_back(Val & 0xFF); 1488 AsBytes.push_back(Val >> 8); 1489 } else { 1490 AsBytes.push_back(Val >> 8); 1491 AsBytes.push_back(Val & 0xFF); 1492 } 1493 } 1494 // Append one extra null character, the second is automatically added by our 1495 // caller. 1496 AsBytes.push_back(0); 1497 1498 IsUTF16 = true; 1499 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1500} 1501 1502llvm::Constant * 1503CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1504 unsigned StringLength = 0; 1505 bool isUTF16 = false; 1506 llvm::StringMapEntry<llvm::Constant*> &Entry = 1507 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1508 getTargetData().isLittleEndian(), 1509 isUTF16, StringLength); 1510 1511 if (llvm::Constant *C = Entry.getValue()) 1512 return C; 1513 1514 llvm::Constant *Zero = 1515 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1516 llvm::Constant *Zeros[] = { Zero, Zero }; 1517 1518 // If we don't already have it, get __CFConstantStringClassReference. 1519 if (!CFConstantStringClassRef) { 1520 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1521 Ty = llvm::ArrayType::get(Ty, 0); 1522 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1523 "__CFConstantStringClassReference"); 1524 // Decay array -> ptr 1525 CFConstantStringClassRef = 1526 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1527 } 1528 1529 QualType CFTy = getContext().getCFConstantStringType(); 1530 1531 const llvm::StructType *STy = 1532 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1533 1534 std::vector<llvm::Constant*> Fields(4); 1535 1536 // Class pointer. 1537 Fields[0] = CFConstantStringClassRef; 1538 1539 // Flags. 1540 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1541 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1542 llvm::ConstantInt::get(Ty, 0x07C8); 1543 1544 // String pointer. 1545 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1546 1547 llvm::GlobalValue::LinkageTypes Linkage; 1548 bool isConstant; 1549 if (isUTF16) { 1550 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1551 Linkage = llvm::GlobalValue::InternalLinkage; 1552 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1553 // does make plain ascii ones writable. 1554 isConstant = true; 1555 } else { 1556 Linkage = llvm::GlobalValue::PrivateLinkage; 1557 isConstant = !Features.WritableStrings; 1558 } 1559 1560 llvm::GlobalVariable *GV = 1561 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1562 ".str"); 1563 if (isUTF16) { 1564 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1565 GV->setAlignment(Align.getQuantity()); 1566 } 1567 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1568 1569 // String length. 1570 Ty = getTypes().ConvertType(getContext().LongTy); 1571 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1572 1573 // The struct. 1574 C = llvm::ConstantStruct::get(STy, Fields); 1575 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1576 llvm::GlobalVariable::PrivateLinkage, C, 1577 "_unnamed_cfstring_"); 1578 if (const char *Sect = getContext().Target.getCFStringSection()) 1579 GV->setSection(Sect); 1580 Entry.setValue(GV); 1581 1582 return GV; 1583} 1584 1585/// GetStringForStringLiteral - Return the appropriate bytes for a 1586/// string literal, properly padded to match the literal type. 1587std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1588 const char *StrData = E->getStrData(); 1589 unsigned Len = E->getByteLength(); 1590 1591 const ConstantArrayType *CAT = 1592 getContext().getAsConstantArrayType(E->getType()); 1593 assert(CAT && "String isn't pointer or array!"); 1594 1595 // Resize the string to the right size. 1596 std::string Str(StrData, StrData+Len); 1597 uint64_t RealLen = CAT->getSize().getZExtValue(); 1598 1599 if (E->isWide()) 1600 RealLen *= getContext().Target.getWCharWidth()/8; 1601 1602 Str.resize(RealLen, '\0'); 1603 1604 return Str; 1605} 1606 1607/// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1608/// constant array for the given string literal. 1609llvm::Constant * 1610CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1611 // FIXME: This can be more efficient. 1612 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1613 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1614 if (S->isWide()) { 1615 llvm::Type *DestTy = 1616 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1617 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1618 } 1619 return C; 1620} 1621 1622/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1623/// array for the given ObjCEncodeExpr node. 1624llvm::Constant * 1625CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1626 std::string Str; 1627 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1628 1629 return GetAddrOfConstantCString(Str); 1630} 1631 1632 1633/// GenerateWritableString -- Creates storage for a string literal. 1634static llvm::Constant *GenerateStringLiteral(const std::string &str, 1635 bool constant, 1636 CodeGenModule &CGM, 1637 const char *GlobalName) { 1638 // Create Constant for this string literal. Don't add a '\0'. 1639 llvm::Constant *C = 1640 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1641 1642 // Create a global variable for this string 1643 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1644 llvm::GlobalValue::PrivateLinkage, 1645 C, GlobalName); 1646} 1647 1648/// GetAddrOfConstantString - Returns a pointer to a character array 1649/// containing the literal. This contents are exactly that of the 1650/// given string, i.e. it will not be null terminated automatically; 1651/// see GetAddrOfConstantCString. Note that whether the result is 1652/// actually a pointer to an LLVM constant depends on 1653/// Feature.WriteableStrings. 1654/// 1655/// The result has pointer to array type. 1656llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1657 const char *GlobalName) { 1658 bool IsConstant = !Features.WritableStrings; 1659 1660 // Get the default prefix if a name wasn't specified. 1661 if (!GlobalName) 1662 GlobalName = ".str"; 1663 1664 // Don't share any string literals if strings aren't constant. 1665 if (!IsConstant) 1666 return GenerateStringLiteral(str, false, *this, GlobalName); 1667 1668 llvm::StringMapEntry<llvm::Constant *> &Entry = 1669 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1670 1671 if (Entry.getValue()) 1672 return Entry.getValue(); 1673 1674 // Create a global variable for this. 1675 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1676 Entry.setValue(C); 1677 return C; 1678} 1679 1680/// GetAddrOfConstantCString - Returns a pointer to a character 1681/// array containing the literal and a terminating '\-' 1682/// character. The result has pointer to array type. 1683llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1684 const char *GlobalName){ 1685 return GetAddrOfConstantString(str + '\0', GlobalName); 1686} 1687 1688/// EmitObjCPropertyImplementations - Emit information for synthesized 1689/// properties for an implementation. 1690void CodeGenModule::EmitObjCPropertyImplementations(const 1691 ObjCImplementationDecl *D) { 1692 for (ObjCImplementationDecl::propimpl_iterator 1693 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1694 ObjCPropertyImplDecl *PID = *i; 1695 1696 // Dynamic is just for type-checking. 1697 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1698 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1699 1700 // Determine which methods need to be implemented, some may have 1701 // been overridden. Note that ::isSynthesized is not the method 1702 // we want, that just indicates if the decl came from a 1703 // property. What we want to know is if the method is defined in 1704 // this implementation. 1705 if (!D->getInstanceMethod(PD->getGetterName())) 1706 CodeGenFunction(*this).GenerateObjCGetter( 1707 const_cast<ObjCImplementationDecl *>(D), PID); 1708 if (!PD->isReadOnly() && 1709 !D->getInstanceMethod(PD->getSetterName())) 1710 CodeGenFunction(*this).GenerateObjCSetter( 1711 const_cast<ObjCImplementationDecl *>(D), PID); 1712 } 1713 } 1714} 1715 1716/// EmitNamespace - Emit all declarations in a namespace. 1717void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1718 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1719 I != E; ++I) 1720 EmitTopLevelDecl(*I); 1721} 1722 1723// EmitLinkageSpec - Emit all declarations in a linkage spec. 1724void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1725 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1726 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1727 ErrorUnsupported(LSD, "linkage spec"); 1728 return; 1729 } 1730 1731 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1732 I != E; ++I) 1733 EmitTopLevelDecl(*I); 1734} 1735 1736/// EmitTopLevelDecl - Emit code for a single top level declaration. 1737void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1738 // If an error has occurred, stop code generation, but continue 1739 // parsing and semantic analysis (to ensure all warnings and errors 1740 // are emitted). 1741 if (Diags.hasErrorOccurred()) 1742 return; 1743 1744 // Ignore dependent declarations. 1745 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1746 return; 1747 1748 switch (D->getKind()) { 1749 case Decl::CXXConversion: 1750 case Decl::CXXMethod: 1751 case Decl::Function: 1752 // Skip function templates 1753 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1754 return; 1755 1756 EmitGlobal(cast<FunctionDecl>(D)); 1757 break; 1758 1759 case Decl::Var: 1760 EmitGlobal(cast<VarDecl>(D)); 1761 break; 1762 1763 // C++ Decls 1764 case Decl::Namespace: 1765 EmitNamespace(cast<NamespaceDecl>(D)); 1766 break; 1767 // No code generation needed. 1768 case Decl::UsingShadow: 1769 case Decl::Using: 1770 case Decl::UsingDirective: 1771 case Decl::ClassTemplate: 1772 case Decl::FunctionTemplate: 1773 case Decl::NamespaceAlias: 1774 break; 1775 case Decl::CXXConstructor: 1776 // Skip function templates 1777 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1778 return; 1779 1780 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1781 break; 1782 case Decl::CXXDestructor: 1783 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1784 break; 1785 1786 case Decl::StaticAssert: 1787 // Nothing to do. 1788 break; 1789 1790 // Objective-C Decls 1791 1792 // Forward declarations, no (immediate) code generation. 1793 case Decl::ObjCClass: 1794 case Decl::ObjCForwardProtocol: 1795 case Decl::ObjCCategory: 1796 case Decl::ObjCInterface: 1797 break; 1798 1799 case Decl::ObjCProtocol: 1800 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1801 break; 1802 1803 case Decl::ObjCCategoryImpl: 1804 // Categories have properties but don't support synthesize so we 1805 // can ignore them here. 1806 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1807 break; 1808 1809 case Decl::ObjCImplementation: { 1810 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1811 EmitObjCPropertyImplementations(OMD); 1812 Runtime->GenerateClass(OMD); 1813 break; 1814 } 1815 case Decl::ObjCMethod: { 1816 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1817 // If this is not a prototype, emit the body. 1818 if (OMD->getBody()) 1819 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1820 break; 1821 } 1822 case Decl::ObjCCompatibleAlias: 1823 // compatibility-alias is a directive and has no code gen. 1824 break; 1825 1826 case Decl::LinkageSpec: 1827 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 1828 break; 1829 1830 case Decl::FileScopeAsm: { 1831 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1832 llvm::StringRef AsmString = AD->getAsmString()->getString(); 1833 1834 const std::string &S = getModule().getModuleInlineAsm(); 1835 if (S.empty()) 1836 getModule().setModuleInlineAsm(AsmString); 1837 else 1838 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 1839 break; 1840 } 1841 1842 default: 1843 // Make sure we handled everything we should, every other kind is a 1844 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 1845 // function. Need to recode Decl::Kind to do that easily. 1846 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1847 } 1848} 1849