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