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