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 if (KeyFunction->isInlined()) 1086 return llvm::GlobalVariable::LinkOnceODRLinkage; 1087 1088 return llvm::GlobalVariable::ExternalLinkage; 1089 1090 case TSK_ImplicitInstantiation: 1091 return llvm::GlobalVariable::LinkOnceODRLinkage; 1092 1093 case TSK_ExplicitInstantiationDefinition: 1094 return llvm::GlobalVariable::WeakODRLinkage; 1095 1096 case TSK_ExplicitInstantiationDeclaration: 1097 // FIXME: Use available_externally linkage. However, this currently 1098 // breaks LLVM's build due to undefined symbols. 1099 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1100 return llvm::GlobalVariable::LinkOnceODRLinkage; 1101 } 1102 } 1103 1104 switch (RD->getTemplateSpecializationKind()) { 1105 case TSK_Undeclared: 1106 case TSK_ExplicitSpecialization: 1107 case TSK_ImplicitInstantiation: 1108 return llvm::GlobalVariable::LinkOnceODRLinkage; 1109 1110 case TSK_ExplicitInstantiationDefinition: 1111 return llvm::GlobalVariable::WeakODRLinkage; 1112 1113 case TSK_ExplicitInstantiationDeclaration: 1114 // FIXME: Use available_externally linkage. However, this currently 1115 // breaks LLVM's build due to undefined symbols. 1116 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1117 return llvm::GlobalVariable::LinkOnceODRLinkage; 1118 } 1119 1120 // Silence GCC warning. 1121 return llvm::GlobalVariable::LinkOnceODRLinkage; 1122 } 1123 1124 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1125 return Context.toCharUnitsFromBits( 1126 TheTargetData.getTypeStoreSizeInBits(Ty)); 1127 } 1128 1129 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1130 llvm::Constant *Init = 0; 1131 QualType ASTTy = D->getType(); 1132 bool NonConstInit = false; 1133 1134 const Expr *InitExpr = D->getAnyInitializer(); 1135 1136 if (!InitExpr) { 1137 // This is a tentative definition; tentative definitions are 1138 // implicitly initialized with { 0 }. 1139 // 1140 // Note that tentative definitions are only emitted at the end of 1141 // a translation unit, so they should never have incomplete 1142 // type. In addition, EmitTentativeDefinition makes sure that we 1143 // never attempt to emit a tentative definition if a real one 1144 // exists. A use may still exists, however, so we still may need 1145 // to do a RAUW. 1146 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1147 Init = EmitNullConstant(D->getType()); 1148 } else { 1149 Init = EmitConstantExpr(InitExpr, D->getType()); 1150 if (!Init) { 1151 QualType T = InitExpr->getType(); 1152 if (D->getType()->isReferenceType()) 1153 T = D->getType(); 1154 1155 if (getLangOptions().CPlusPlus) { 1156 Init = EmitNullConstant(T); 1157 NonConstInit = true; 1158 } else { 1159 ErrorUnsupported(D, "static initializer"); 1160 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1161 } 1162 } else { 1163 // We don't need an initializer, so remove the entry for the delayed 1164 // initializer position (just in case this entry was delayed). 1165 if (getLangOptions().CPlusPlus) 1166 DelayedCXXInitPosition.erase(D); 1167 } 1168 } 1169 1170 const llvm::Type* InitType = Init->getType(); 1171 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1172 1173 // Strip off a bitcast if we got one back. 1174 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1175 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1176 // all zero index gep. 1177 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1178 Entry = CE->getOperand(0); 1179 } 1180 1181 // Entry is now either a Function or GlobalVariable. 1182 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1183 1184 // We have a definition after a declaration with the wrong type. 1185 // We must make a new GlobalVariable* and update everything that used OldGV 1186 // (a declaration or tentative definition) with the new GlobalVariable* 1187 // (which will be a definition). 1188 // 1189 // This happens if there is a prototype for a global (e.g. 1190 // "extern int x[];") and then a definition of a different type (e.g. 1191 // "int x[10];"). This also happens when an initializer has a different type 1192 // from the type of the global (this happens with unions). 1193 if (GV == 0 || 1194 GV->getType()->getElementType() != InitType || 1195 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1196 1197 // Move the old entry aside so that we'll create a new one. 1198 Entry->setName(llvm::StringRef()); 1199 1200 // Make a new global with the correct type, this is now guaranteed to work. 1201 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1202 1203 // Replace all uses of the old global with the new global 1204 llvm::Constant *NewPtrForOldDecl = 1205 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1206 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1207 1208 // Erase the old global, since it is no longer used. 1209 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1210 } 1211 1212 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1213 SourceManager &SM = Context.getSourceManager(); 1214 AddAnnotation(EmitAnnotateAttr(GV, AA, 1215 SM.getInstantiationLineNumber(D->getLocation()))); 1216 } 1217 1218 GV->setInitializer(Init); 1219 1220 // If it is safe to mark the global 'constant', do so now. 1221 GV->setConstant(false); 1222 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1223 GV->setConstant(true); 1224 1225 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1226 1227 // Set the llvm linkage type as appropriate. 1228 llvm::GlobalValue::LinkageTypes Linkage = 1229 GetLLVMLinkageVarDefinition(D, GV); 1230 GV->setLinkage(Linkage); 1231 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1232 // common vars aren't constant even if declared const. 1233 GV->setConstant(false); 1234 1235 SetCommonAttributes(D, GV); 1236 1237 // Emit the initializer function if necessary. 1238 if (NonConstInit) 1239 EmitCXXGlobalVarDeclInitFunc(D, GV); 1240 1241 // Emit global variable debug information. 1242 if (CGDebugInfo *DI = getDebugInfo()) { 1243 DI->setLocation(D->getLocation()); 1244 DI->EmitGlobalVariable(GV, D); 1245 } 1246 } 1247 1248 llvm::GlobalValue::LinkageTypes 1249 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 1250 llvm::GlobalVariable *GV) { 1251 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1252 if (Linkage == GVA_Internal) 1253 return llvm::Function::InternalLinkage; 1254 else if (D->hasAttr<DLLImportAttr>()) 1255 return llvm::Function::DLLImportLinkage; 1256 else if (D->hasAttr<DLLExportAttr>()) 1257 return llvm::Function::DLLExportLinkage; 1258 else if (D->hasAttr<WeakAttr>()) { 1259 if (GV->isConstant()) 1260 return llvm::GlobalVariable::WeakODRLinkage; 1261 else 1262 return llvm::GlobalVariable::WeakAnyLinkage; 1263 } else if (Linkage == GVA_TemplateInstantiation || 1264 Linkage == GVA_ExplicitTemplateInstantiation) 1265 // FIXME: It seems like we can provide more specific linkage here 1266 // (LinkOnceODR, WeakODR). 1267 return llvm::GlobalVariable::WeakAnyLinkage; 1268 else if (!getLangOptions().CPlusPlus && 1269 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1270 D->getAttr<CommonAttr>()) && 1271 !D->hasExternalStorage() && !D->getInit() && 1272 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) { 1273 // Thread local vars aren't considered common linkage. 1274 return llvm::GlobalVariable::CommonLinkage; 1275 } 1276 return llvm::GlobalVariable::ExternalLinkage; 1277 } 1278 1279 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1280 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1281 /// existing call uses of the old function in the module, this adjusts them to 1282 /// call the new function directly. 1283 /// 1284 /// This is not just a cleanup: the always_inline pass requires direct calls to 1285 /// functions to be able to inline them. If there is a bitcast in the way, it 1286 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1287 /// run at -O0. 1288 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1289 llvm::Function *NewFn) { 1290 // If we're redefining a global as a function, don't transform it. 1291 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1292 if (OldFn == 0) return; 1293 1294 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1295 llvm::SmallVector<llvm::Value*, 4> ArgList; 1296 1297 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1298 UI != E; ) { 1299 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1300 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1301 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1302 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1303 llvm::CallSite CS(CI); 1304 if (!CI || !CS.isCallee(I)) continue; 1305 1306 // If the return types don't match exactly, and if the call isn't dead, then 1307 // we can't transform this call. 1308 if (CI->getType() != NewRetTy && !CI->use_empty()) 1309 continue; 1310 1311 // If the function was passed too few arguments, don't transform. If extra 1312 // arguments were passed, we silently drop them. If any of the types 1313 // mismatch, we don't transform. 1314 unsigned ArgNo = 0; 1315 bool DontTransform = false; 1316 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1317 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1318 if (CS.arg_size() == ArgNo || 1319 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1320 DontTransform = true; 1321 break; 1322 } 1323 } 1324 if (DontTransform) 1325 continue; 1326 1327 // Okay, we can transform this. Create the new call instruction and copy 1328 // over the required information. 1329 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1330 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1331 ArgList.end(), "", CI); 1332 ArgList.clear(); 1333 if (!NewCall->getType()->isVoidTy()) 1334 NewCall->takeName(CI); 1335 NewCall->setAttributes(CI->getAttributes()); 1336 NewCall->setCallingConv(CI->getCallingConv()); 1337 1338 // Finally, remove the old call, replacing any uses with the new one. 1339 if (!CI->use_empty()) 1340 CI->replaceAllUsesWith(NewCall); 1341 1342 // Copy debug location attached to CI. 1343 if (!CI->getDebugLoc().isUnknown()) 1344 NewCall->setDebugLoc(CI->getDebugLoc()); 1345 CI->eraseFromParent(); 1346 } 1347 } 1348 1349 1350 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1351 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1352 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1353 // Get or create the prototype for the function. 1354 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1355 1356 // Strip off a bitcast if we got one back. 1357 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1358 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1359 Entry = CE->getOperand(0); 1360 } 1361 1362 1363 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1364 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1365 1366 // If the types mismatch then we have to rewrite the definition. 1367 assert(OldFn->isDeclaration() && 1368 "Shouldn't replace non-declaration"); 1369 1370 // F is the Function* for the one with the wrong type, we must make a new 1371 // Function* and update everything that used F (a declaration) with the new 1372 // Function* (which will be a definition). 1373 // 1374 // This happens if there is a prototype for a function 1375 // (e.g. "int f()") and then a definition of a different type 1376 // (e.g. "int f(int x)"). Move the old function aside so that it 1377 // doesn't interfere with GetAddrOfFunction. 1378 OldFn->setName(llvm::StringRef()); 1379 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1380 1381 // If this is an implementation of a function without a prototype, try to 1382 // replace any existing uses of the function (which may be calls) with uses 1383 // of the new function 1384 if (D->getType()->isFunctionNoProtoType()) { 1385 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1386 OldFn->removeDeadConstantUsers(); 1387 } 1388 1389 // Replace uses of F with the Function we will endow with a body. 1390 if (!Entry->use_empty()) { 1391 llvm::Constant *NewPtrForOldDecl = 1392 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1393 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1394 } 1395 1396 // Ok, delete the old function now, which is dead. 1397 OldFn->eraseFromParent(); 1398 1399 Entry = NewFn; 1400 } 1401 1402 // We need to set linkage and visibility on the function before 1403 // generating code for it because various parts of IR generation 1404 // want to propagate this information down (e.g. to local static 1405 // declarations). 1406 llvm::Function *Fn = cast<llvm::Function>(Entry); 1407 setFunctionLinkage(D, Fn); 1408 1409 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 1410 setGlobalVisibility(Fn, D); 1411 1412 CodeGenFunction(*this).GenerateCode(D, Fn); 1413 1414 SetFunctionDefinitionAttributes(D, Fn); 1415 SetLLVMFunctionAttributesForDefinition(D, Fn); 1416 1417 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1418 AddGlobalCtor(Fn, CA->getPriority()); 1419 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1420 AddGlobalDtor(Fn, DA->getPriority()); 1421 } 1422 1423 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1424 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1425 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1426 assert(AA && "Not an alias?"); 1427 1428 llvm::StringRef MangledName = getMangledName(GD); 1429 1430 // If there is a definition in the module, then it wins over the alias. 1431 // This is dubious, but allow it to be safe. Just ignore the alias. 1432 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1433 if (Entry && !Entry->isDeclaration()) 1434 return; 1435 1436 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1437 1438 // Create a reference to the named value. This ensures that it is emitted 1439 // if a deferred decl. 1440 llvm::Constant *Aliasee; 1441 if (isa<llvm::FunctionType>(DeclTy)) 1442 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 1443 else 1444 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1445 llvm::PointerType::getUnqual(DeclTy), 0); 1446 1447 // Create the new alias itself, but don't set a name yet. 1448 llvm::GlobalValue *GA = 1449 new llvm::GlobalAlias(Aliasee->getType(), 1450 llvm::Function::ExternalLinkage, 1451 "", Aliasee, &getModule()); 1452 1453 if (Entry) { 1454 assert(Entry->isDeclaration()); 1455 1456 // If there is a declaration in the module, then we had an extern followed 1457 // by the alias, as in: 1458 // extern int test6(); 1459 // ... 1460 // int test6() __attribute__((alias("test7"))); 1461 // 1462 // Remove it and replace uses of it with the alias. 1463 GA->takeName(Entry); 1464 1465 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1466 Entry->getType())); 1467 Entry->eraseFromParent(); 1468 } else { 1469 GA->setName(MangledName); 1470 } 1471 1472 // Set attributes which are particular to an alias; this is a 1473 // specialization of the attributes which may be set on a global 1474 // variable/function. 1475 if (D->hasAttr<DLLExportAttr>()) { 1476 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1477 // The dllexport attribute is ignored for undefined symbols. 1478 if (FD->hasBody()) 1479 GA->setLinkage(llvm::Function::DLLExportLinkage); 1480 } else { 1481 GA->setLinkage(llvm::Function::DLLExportLinkage); 1482 } 1483 } else if (D->hasAttr<WeakAttr>() || 1484 D->hasAttr<WeakRefAttr>() || 1485 D->hasAttr<WeakImportAttr>()) { 1486 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1487 } 1488 1489 SetCommonAttributes(D, GA); 1490 } 1491 1492 /// getBuiltinLibFunction - Given a builtin id for a function like 1493 /// "__builtin_fabsf", return a Function* for "fabsf". 1494 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1495 unsigned BuiltinID) { 1496 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1497 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1498 "isn't a lib fn"); 1499 1500 // Get the name, skip over the __builtin_ prefix (if necessary). 1501 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1502 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1503 Name += 10; 1504 1505 const llvm::FunctionType *Ty = 1506 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1507 1508 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1509 } 1510 1511 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1512 unsigned NumTys) { 1513 return llvm::Intrinsic::getDeclaration(&getModule(), 1514 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1515 } 1516 1517 static llvm::StringMapEntry<llvm::Constant*> & 1518 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1519 const StringLiteral *Literal, 1520 bool TargetIsLSB, 1521 bool &IsUTF16, 1522 unsigned &StringLength) { 1523 llvm::StringRef String = Literal->getString(); 1524 unsigned NumBytes = String.size(); 1525 1526 // Check for simple case. 1527 if (!Literal->containsNonAsciiOrNull()) { 1528 StringLength = NumBytes; 1529 return Map.GetOrCreateValue(String); 1530 } 1531 1532 // Otherwise, convert the UTF8 literals into a byte string. 1533 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1534 const UTF8 *FromPtr = (UTF8 *)String.data(); 1535 UTF16 *ToPtr = &ToBuf[0]; 1536 1537 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1538 &ToPtr, ToPtr + NumBytes, 1539 strictConversion); 1540 1541 // ConvertUTF8toUTF16 returns the length in ToPtr. 1542 StringLength = ToPtr - &ToBuf[0]; 1543 1544 // Render the UTF-16 string into a byte array and convert to the target byte 1545 // order. 1546 // 1547 // FIXME: This isn't something we should need to do here. 1548 llvm::SmallString<128> AsBytes; 1549 AsBytes.reserve(StringLength * 2); 1550 for (unsigned i = 0; i != StringLength; ++i) { 1551 unsigned short Val = ToBuf[i]; 1552 if (TargetIsLSB) { 1553 AsBytes.push_back(Val & 0xFF); 1554 AsBytes.push_back(Val >> 8); 1555 } else { 1556 AsBytes.push_back(Val >> 8); 1557 AsBytes.push_back(Val & 0xFF); 1558 } 1559 } 1560 // Append one extra null character, the second is automatically added by our 1561 // caller. 1562 AsBytes.push_back(0); 1563 1564 IsUTF16 = true; 1565 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1566 } 1567 1568 llvm::Constant * 1569 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1570 unsigned StringLength = 0; 1571 bool isUTF16 = false; 1572 llvm::StringMapEntry<llvm::Constant*> &Entry = 1573 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1574 getTargetData().isLittleEndian(), 1575 isUTF16, StringLength); 1576 1577 if (llvm::Constant *C = Entry.getValue()) 1578 return C; 1579 1580 llvm::Constant *Zero = 1581 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1582 llvm::Constant *Zeros[] = { Zero, Zero }; 1583 1584 // If we don't already have it, get __CFConstantStringClassReference. 1585 if (!CFConstantStringClassRef) { 1586 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1587 Ty = llvm::ArrayType::get(Ty, 0); 1588 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1589 "__CFConstantStringClassReference"); 1590 // Decay array -> ptr 1591 CFConstantStringClassRef = 1592 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1593 } 1594 1595 QualType CFTy = getContext().getCFConstantStringType(); 1596 1597 const llvm::StructType *STy = 1598 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1599 1600 std::vector<llvm::Constant*> Fields(4); 1601 1602 // Class pointer. 1603 Fields[0] = CFConstantStringClassRef; 1604 1605 // Flags. 1606 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1607 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1608 llvm::ConstantInt::get(Ty, 0x07C8); 1609 1610 // String pointer. 1611 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1612 1613 llvm::GlobalValue::LinkageTypes Linkage; 1614 bool isConstant; 1615 if (isUTF16) { 1616 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1617 Linkage = llvm::GlobalValue::InternalLinkage; 1618 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1619 // does make plain ascii ones writable. 1620 isConstant = true; 1621 } else { 1622 Linkage = llvm::GlobalValue::PrivateLinkage; 1623 isConstant = !Features.WritableStrings; 1624 } 1625 1626 llvm::GlobalVariable *GV = 1627 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1628 ".str"); 1629 GV->setUnnamedAddr(true); 1630 if (isUTF16) { 1631 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1632 GV->setAlignment(Align.getQuantity()); 1633 } 1634 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1635 1636 // String length. 1637 Ty = getTypes().ConvertType(getContext().LongTy); 1638 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1639 1640 // The struct. 1641 C = llvm::ConstantStruct::get(STy, Fields); 1642 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1643 llvm::GlobalVariable::PrivateLinkage, C, 1644 "_unnamed_cfstring_"); 1645 if (const char *Sect = getContext().Target.getCFStringSection()) 1646 GV->setSection(Sect); 1647 Entry.setValue(GV); 1648 1649 return GV; 1650 } 1651 1652 llvm::Constant * 1653 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 1654 unsigned StringLength = 0; 1655 bool isUTF16 = false; 1656 llvm::StringMapEntry<llvm::Constant*> &Entry = 1657 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1658 getTargetData().isLittleEndian(), 1659 isUTF16, StringLength); 1660 1661 if (llvm::Constant *C = Entry.getValue()) 1662 return C; 1663 1664 llvm::Constant *Zero = 1665 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1666 llvm::Constant *Zeros[] = { Zero, Zero }; 1667 1668 // If we don't already have it, get _NSConstantStringClassReference. 1669 if (!ConstantStringClassRef) { 1670 std::string StringClass(getLangOptions().ObjCConstantStringClass); 1671 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1672 Ty = llvm::ArrayType::get(Ty, 0); 1673 llvm::Constant *GV; 1674 if (StringClass.empty()) 1675 GV = CreateRuntimeVariable(Ty, 1676 Features.ObjCNonFragileABI ? 1677 "OBJC_CLASS_$_NSConstantString" : 1678 "_NSConstantStringClassReference"); 1679 else { 1680 std::string str; 1681 if (Features.ObjCNonFragileABI) 1682 str = "OBJC_CLASS_$_" + StringClass; 1683 else 1684 str = "_" + StringClass + "ClassReference"; 1685 GV = CreateRuntimeVariable(Ty, str); 1686 } 1687 // Decay array -> ptr 1688 ConstantStringClassRef = 1689 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1690 } 1691 1692 QualType NSTy = getContext().getNSConstantStringType(); 1693 1694 const llvm::StructType *STy = 1695 cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 1696 1697 std::vector<llvm::Constant*> Fields(3); 1698 1699 // Class pointer. 1700 Fields[0] = ConstantStringClassRef; 1701 1702 // String pointer. 1703 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1704 1705 llvm::GlobalValue::LinkageTypes Linkage; 1706 bool isConstant; 1707 if (isUTF16) { 1708 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1709 Linkage = llvm::GlobalValue::InternalLinkage; 1710 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but 1711 // does make plain ascii ones writable. 1712 isConstant = true; 1713 } else { 1714 Linkage = llvm::GlobalValue::PrivateLinkage; 1715 isConstant = !Features.WritableStrings; 1716 } 1717 1718 llvm::GlobalVariable *GV = 1719 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1720 ".str"); 1721 GV->setUnnamedAddr(true); 1722 if (isUTF16) { 1723 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1724 GV->setAlignment(Align.getQuantity()); 1725 } 1726 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1727 1728 // String length. 1729 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1730 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 1731 1732 // The struct. 1733 C = llvm::ConstantStruct::get(STy, Fields); 1734 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1735 llvm::GlobalVariable::PrivateLinkage, C, 1736 "_unnamed_nsstring_"); 1737 // FIXME. Fix section. 1738 if (const char *Sect = 1739 Features.ObjCNonFragileABI 1740 ? getContext().Target.getNSStringNonFragileABISection() 1741 : getContext().Target.getNSStringSection()) 1742 GV->setSection(Sect); 1743 Entry.setValue(GV); 1744 1745 return GV; 1746 } 1747 1748 /// GetStringForStringLiteral - Return the appropriate bytes for a 1749 /// string literal, properly padded to match the literal type. 1750 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1751 const ASTContext &Context = getContext(); 1752 const ConstantArrayType *CAT = 1753 Context.getAsConstantArrayType(E->getType()); 1754 assert(CAT && "String isn't pointer or array!"); 1755 1756 // Resize the string to the right size. 1757 uint64_t RealLen = CAT->getSize().getZExtValue(); 1758 1759 if (E->isWide()) 1760 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth(); 1761 1762 std::string Str = E->getString().str(); 1763 Str.resize(RealLen, '\0'); 1764 1765 return Str; 1766 } 1767 1768 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1769 /// constant array for the given string literal. 1770 llvm::Constant * 1771 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1772 // FIXME: This can be more efficient. 1773 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1774 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1775 if (S->isWide()) { 1776 llvm::Type *DestTy = 1777 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1778 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1779 } 1780 return C; 1781 } 1782 1783 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1784 /// array for the given ObjCEncodeExpr node. 1785 llvm::Constant * 1786 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1787 std::string Str; 1788 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1789 1790 return GetAddrOfConstantCString(Str); 1791 } 1792 1793 1794 /// GenerateWritableString -- Creates storage for a string literal. 1795 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1796 bool constant, 1797 CodeGenModule &CGM, 1798 const char *GlobalName) { 1799 // Create Constant for this string literal. Don't add a '\0'. 1800 llvm::Constant *C = 1801 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1802 1803 // Create a global variable for this string 1804 llvm::GlobalVariable *GV = 1805 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1806 llvm::GlobalValue::PrivateLinkage, 1807 C, GlobalName); 1808 GV->setUnnamedAddr(true); 1809 return GV; 1810 } 1811 1812 /// GetAddrOfConstantString - Returns a pointer to a character array 1813 /// containing the literal. This contents are exactly that of the 1814 /// given string, i.e. it will not be null terminated automatically; 1815 /// see GetAddrOfConstantCString. Note that whether the result is 1816 /// actually a pointer to an LLVM constant depends on 1817 /// Feature.WriteableStrings. 1818 /// 1819 /// The result has pointer to array type. 1820 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1821 const char *GlobalName) { 1822 bool IsConstant = !Features.WritableStrings; 1823 1824 // Get the default prefix if a name wasn't specified. 1825 if (!GlobalName) 1826 GlobalName = ".str"; 1827 1828 // Don't share any string literals if strings aren't constant. 1829 if (!IsConstant) 1830 return GenerateStringLiteral(str, false, *this, GlobalName); 1831 1832 llvm::StringMapEntry<llvm::Constant *> &Entry = 1833 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1834 1835 if (Entry.getValue()) 1836 return Entry.getValue(); 1837 1838 // Create a global variable for this. 1839 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1840 Entry.setValue(C); 1841 return C; 1842 } 1843 1844 /// GetAddrOfConstantCString - Returns a pointer to a character 1845 /// array containing the literal and a terminating '\-' 1846 /// character. The result has pointer to array type. 1847 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1848 const char *GlobalName){ 1849 return GetAddrOfConstantString(str + '\0', GlobalName); 1850 } 1851 1852 /// EmitObjCPropertyImplementations - Emit information for synthesized 1853 /// properties for an implementation. 1854 void CodeGenModule::EmitObjCPropertyImplementations(const 1855 ObjCImplementationDecl *D) { 1856 for (ObjCImplementationDecl::propimpl_iterator 1857 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1858 ObjCPropertyImplDecl *PID = *i; 1859 1860 // Dynamic is just for type-checking. 1861 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1862 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1863 1864 // Determine which methods need to be implemented, some may have 1865 // been overridden. Note that ::isSynthesized is not the method 1866 // we want, that just indicates if the decl came from a 1867 // property. What we want to know is if the method is defined in 1868 // this implementation. 1869 if (!D->getInstanceMethod(PD->getGetterName())) 1870 CodeGenFunction(*this).GenerateObjCGetter( 1871 const_cast<ObjCImplementationDecl *>(D), PID); 1872 if (!PD->isReadOnly() && 1873 !D->getInstanceMethod(PD->getSetterName())) 1874 CodeGenFunction(*this).GenerateObjCSetter( 1875 const_cast<ObjCImplementationDecl *>(D), PID); 1876 } 1877 } 1878 } 1879 1880 /// EmitObjCIvarInitializations - Emit information for ivar initialization 1881 /// for an implementation. 1882 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 1883 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0) 1884 return; 1885 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D)); 1886 assert(DC && "EmitObjCIvarInitializations - null DeclContext"); 1887 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 1888 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 1889 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(), 1890 D->getLocation(), 1891 D->getLocation(), cxxSelector, 1892 getContext().VoidTy, 0, 1893 DC, true, false, true, false, 1894 ObjCMethodDecl::Required); 1895 D->addInstanceMethod(DTORMethod); 1896 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 1897 1898 II = &getContext().Idents.get(".cxx_construct"); 1899 cxxSelector = getContext().Selectors.getSelector(0, &II); 1900 // The constructor returns 'self'. 1901 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 1902 D->getLocation(), 1903 D->getLocation(), cxxSelector, 1904 getContext().getObjCIdType(), 0, 1905 DC, true, false, true, false, 1906 ObjCMethodDecl::Required); 1907 D->addInstanceMethod(CTORMethod); 1908 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 1909 1910 1911 } 1912 1913 /// EmitNamespace - Emit all declarations in a namespace. 1914 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1915 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1916 I != E; ++I) 1917 EmitTopLevelDecl(*I); 1918 } 1919 1920 // EmitLinkageSpec - Emit all declarations in a linkage spec. 1921 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1922 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1923 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1924 ErrorUnsupported(LSD, "linkage spec"); 1925 return; 1926 } 1927 1928 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1929 I != E; ++I) 1930 EmitTopLevelDecl(*I); 1931 } 1932 1933 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1934 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1935 // If an error has occurred, stop code generation, but continue 1936 // parsing and semantic analysis (to ensure all warnings and errors 1937 // are emitted). 1938 if (Diags.hasErrorOccurred()) 1939 return; 1940 1941 // Ignore dependent declarations. 1942 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1943 return; 1944 1945 switch (D->getKind()) { 1946 case Decl::CXXConversion: 1947 case Decl::CXXMethod: 1948 case Decl::Function: 1949 // Skip function templates 1950 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1951 return; 1952 1953 EmitGlobal(cast<FunctionDecl>(D)); 1954 break; 1955 1956 case Decl::Var: 1957 EmitGlobal(cast<VarDecl>(D)); 1958 break; 1959 1960 // C++ Decls 1961 case Decl::Namespace: 1962 EmitNamespace(cast<NamespaceDecl>(D)); 1963 break; 1964 // No code generation needed. 1965 case Decl::UsingShadow: 1966 case Decl::Using: 1967 case Decl::UsingDirective: 1968 case Decl::ClassTemplate: 1969 case Decl::FunctionTemplate: 1970 case Decl::NamespaceAlias: 1971 break; 1972 case Decl::CXXConstructor: 1973 // Skip function templates 1974 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1975 return; 1976 1977 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1978 break; 1979 case Decl::CXXDestructor: 1980 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1981 break; 1982 1983 case Decl::StaticAssert: 1984 // Nothing to do. 1985 break; 1986 1987 // Objective-C Decls 1988 1989 // Forward declarations, no (immediate) code generation. 1990 case Decl::ObjCClass: 1991 case Decl::ObjCForwardProtocol: 1992 case Decl::ObjCInterface: 1993 break; 1994 1995 case Decl::ObjCCategory: { 1996 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 1997 if (CD->IsClassExtension() && CD->hasSynthBitfield()) 1998 Context.ResetObjCLayout(CD->getClassInterface()); 1999 break; 2000 } 2001 2002 2003 case Decl::ObjCProtocol: 2004 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 2005 break; 2006 2007 case Decl::ObjCCategoryImpl: 2008 // Categories have properties but don't support synthesize so we 2009 // can ignore them here. 2010 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2011 break; 2012 2013 case Decl::ObjCImplementation: { 2014 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2015 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield()) 2016 Context.ResetObjCLayout(OMD->getClassInterface()); 2017 EmitObjCPropertyImplementations(OMD); 2018 EmitObjCIvarInitializations(OMD); 2019 Runtime->GenerateClass(OMD); 2020 break; 2021 } 2022 case Decl::ObjCMethod: { 2023 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2024 // If this is not a prototype, emit the body. 2025 if (OMD->getBody()) 2026 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2027 break; 2028 } 2029 case Decl::ObjCCompatibleAlias: 2030 // compatibility-alias is a directive and has no code gen. 2031 break; 2032 2033 case Decl::LinkageSpec: 2034 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2035 break; 2036 2037 case Decl::FileScopeAsm: { 2038 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2039 llvm::StringRef AsmString = AD->getAsmString()->getString(); 2040 2041 const std::string &S = getModule().getModuleInlineAsm(); 2042 if (S.empty()) 2043 getModule().setModuleInlineAsm(AsmString); 2044 else 2045 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2046 break; 2047 } 2048 2049 default: 2050 // Make sure we handled everything we should, every other kind is a 2051 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2052 // function. Need to recode Decl::Kind to do that easily. 2053 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2054 } 2055 } 2056 2057 /// Turns the given pointer into a constant. 2058 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2059 const void *Ptr) { 2060 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2061 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2062 return llvm::ConstantInt::get(i64, PtrInt); 2063 } 2064 2065 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2066 llvm::NamedMDNode *&GlobalMetadata, 2067 GlobalDecl D, 2068 llvm::GlobalValue *Addr) { 2069 if (!GlobalMetadata) 2070 GlobalMetadata = 2071 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2072 2073 // TODO: should we report variant information for ctors/dtors? 2074 llvm::Value *Ops[] = { 2075 Addr, 2076 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2077 }; 2078 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2)); 2079 } 2080 2081 /// Emits metadata nodes associating all the global values in the 2082 /// current module with the Decls they came from. This is useful for 2083 /// projects using IR gen as a subroutine. 2084 /// 2085 /// Since there's currently no way to associate an MDNode directly 2086 /// with an llvm::GlobalValue, we create a global named metadata 2087 /// with the name 'clang.global.decl.ptrs'. 2088 void CodeGenModule::EmitDeclMetadata() { 2089 llvm::NamedMDNode *GlobalMetadata = 0; 2090 2091 // StaticLocalDeclMap 2092 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator 2093 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2094 I != E; ++I) { 2095 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2096 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2097 } 2098 } 2099 2100 /// Emits metadata nodes for all the local variables in the current 2101 /// function. 2102 void CodeGenFunction::EmitDeclMetadata() { 2103 if (LocalDeclMap.empty()) return; 2104 2105 llvm::LLVMContext &Context = getLLVMContext(); 2106 2107 // Find the unique metadata ID for this name. 2108 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2109 2110 llvm::NamedMDNode *GlobalMetadata = 0; 2111 2112 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2113 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2114 const Decl *D = I->first; 2115 llvm::Value *Addr = I->second; 2116 2117 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2118 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2119 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1)); 2120 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2121 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2122 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2123 } 2124 } 2125 } 2126 2127 ///@name Custom Runtime Function Interfaces 2128 ///@{ 2129 // 2130 // FIXME: These can be eliminated once we can have clients just get the required 2131 // AST nodes from the builtin tables. 2132 2133 llvm::Constant *CodeGenModule::getBlockObjectDispose() { 2134 if (BlockObjectDispose) 2135 return BlockObjectDispose; 2136 2137 // If we saw an explicit decl, use that. 2138 if (BlockObjectDisposeDecl) { 2139 return BlockObjectDispose = GetAddrOfFunction( 2140 BlockObjectDisposeDecl, 2141 getTypes().GetFunctionType(BlockObjectDisposeDecl)); 2142 } 2143 2144 // Otherwise construct the function by hand. 2145 const llvm::FunctionType *FTy; 2146 std::vector<const llvm::Type*> ArgTys; 2147 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext); 2148 ArgTys.push_back(PtrToInt8Ty); 2149 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext)); 2150 FTy = llvm::FunctionType::get(ResultType, ArgTys, false); 2151 return BlockObjectDispose = 2152 CreateRuntimeFunction(FTy, "_Block_object_dispose"); 2153 } 2154 2155 llvm::Constant *CodeGenModule::getBlockObjectAssign() { 2156 if (BlockObjectAssign) 2157 return BlockObjectAssign; 2158 2159 // If we saw an explicit decl, use that. 2160 if (BlockObjectAssignDecl) { 2161 return BlockObjectAssign = GetAddrOfFunction( 2162 BlockObjectAssignDecl, 2163 getTypes().GetFunctionType(BlockObjectAssignDecl)); 2164 } 2165 2166 // Otherwise construct the function by hand. 2167 const llvm::FunctionType *FTy; 2168 std::vector<const llvm::Type*> ArgTys; 2169 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext); 2170 ArgTys.push_back(PtrToInt8Ty); 2171 ArgTys.push_back(PtrToInt8Ty); 2172 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext)); 2173 FTy = llvm::FunctionType::get(ResultType, ArgTys, false); 2174 return BlockObjectAssign = 2175 CreateRuntimeFunction(FTy, "_Block_object_assign"); 2176 } 2177 2178 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() { 2179 if (NSConcreteGlobalBlock) 2180 return NSConcreteGlobalBlock; 2181 2182 // If we saw an explicit decl, use that. 2183 if (NSConcreteGlobalBlockDecl) { 2184 return NSConcreteGlobalBlock = GetAddrOfGlobalVar( 2185 NSConcreteGlobalBlockDecl, 2186 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType())); 2187 } 2188 2189 // Otherwise construct the variable by hand. 2190 return NSConcreteGlobalBlock = CreateRuntimeVariable( 2191 PtrToInt8Ty, "_NSConcreteGlobalBlock"); 2192 } 2193 2194 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() { 2195 if (NSConcreteStackBlock) 2196 return NSConcreteStackBlock; 2197 2198 // If we saw an explicit decl, use that. 2199 if (NSConcreteStackBlockDecl) { 2200 return NSConcreteStackBlock = GetAddrOfGlobalVar( 2201 NSConcreteStackBlockDecl, 2202 getTypes().ConvertType(NSConcreteStackBlockDecl->getType())); 2203 } 2204 2205 // Otherwise construct the variable by hand. 2206 return NSConcreteStackBlock = CreateRuntimeVariable( 2207 PtrToInt8Ty, "_NSConcreteStackBlock"); 2208 } 2209 2210 ///@} 2211