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