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