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 "CGCall.h" 18 #include "CGObjCRuntime.h" 19 #include "Mangle.h" 20 #include "TargetInfo.h" 21 #include "clang/Frontend/CodeGenOptions.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/CharUnits.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/AST/DeclCXX.h" 26 #include "clang/AST/DeclTemplate.h" 27 #include "clang/AST/RecordLayout.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/Diagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Basic/ConvertUTF.h" 33 #include "llvm/CallingConv.h" 34 #include "llvm/Module.h" 35 #include "llvm/Intrinsics.h" 36 #include "llvm/LLVMContext.h" 37 #include "llvm/ADT/Triple.h" 38 #include "llvm/Target/TargetData.h" 39 #include "llvm/Support/CallSite.h" 40 #include "llvm/Support/ErrorHandling.h" 41 using namespace clang; 42 using namespace CodeGen; 43 44 static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 45 switch (CGM.getContext().Target.getCXXABI()) { 46 case CXXABI_ARM: return *CreateARMCXXABI(CGM); 47 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 48 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 49 } 50 51 llvm_unreachable("invalid C++ ABI kind"); 52 return *CreateItaniumCXXABI(CGM); 53 } 54 55 56 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 57 llvm::Module &M, const llvm::TargetData &TD, 58 Diagnostic &diags) 59 : BlockModule(C, M, TD, Types, *this), Context(C), 60 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 61 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 62 ABI(createCXXABI(*this)), 63 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI), 64 VTables(*this), Runtime(0), 65 CFConstantStringClassRef(0), NSConstantStringClassRef(0), 66 VMContext(M.getContext()), 67 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0), 68 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 69 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0), 70 BlockObjectAssign(0), BlockObjectDispose(0){ 71 72 if (!Features.ObjC1) 73 Runtime = 0; 74 else if (!Features.NeXTRuntime) 75 Runtime = CreateGNUObjCRuntime(*this); 76 else if (Features.ObjCNonFragileABI) 77 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 78 else 79 Runtime = CreateMacObjCRuntime(*this); 80 81 // If debug info generation is enabled, create the CGDebugInfo object. 82 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0; 83 } 84 85 CodeGenModule::~CodeGenModule() { 86 delete Runtime; 87 delete &ABI; 88 delete DebugInfo; 89 } 90 91 void CodeGenModule::createObjCRuntime() { 92 if (!Features.NeXTRuntime) 93 Runtime = CreateGNUObjCRuntime(*this); 94 else if (Features.ObjCNonFragileABI) 95 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 96 else 97 Runtime = CreateMacObjCRuntime(*this); 98 } 99 100 void CodeGenModule::Release() { 101 EmitDeferred(); 102 EmitCXXGlobalInitFunc(); 103 EmitCXXGlobalDtorFunc(); 104 if (Runtime) 105 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 106 AddGlobalCtor(ObjCInitFunction); 107 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 108 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 109 EmitAnnotations(); 110 EmitLLVMUsed(); 111 112 if (getCodeGenOpts().EmitDeclMetadata) 113 EmitDeclMetadata(); 114 } 115 116 bool CodeGenModule::isTargetDarwin() const { 117 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin; 118 } 119 120 /// ErrorUnsupported - Print out an error that codegen doesn't support the 121 /// specified stmt yet. 122 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 123 bool OmitOnError) { 124 if (OmitOnError && getDiags().hasErrorOccurred()) 125 return; 126 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 127 "cannot compile this %0 yet"); 128 std::string Msg = Type; 129 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 130 << Msg << S->getSourceRange(); 131 } 132 133 /// ErrorUnsupported - Print out an error that codegen doesn't support the 134 /// specified decl yet. 135 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 136 bool OmitOnError) { 137 if (OmitOnError && getDiags().hasErrorOccurred()) 138 return; 139 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 140 "cannot compile this %0 yet"); 141 std::string Msg = Type; 142 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 143 } 144 145 LangOptions::VisibilityMode 146 CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 147 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 148 if (VD->getStorageClass() == SC_PrivateExtern) 149 return LangOptions::Hidden; 150 151 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 152 switch (attr->getVisibility()) { 153 default: assert(0 && "Unknown visibility!"); 154 case VisibilityAttr::Default: 155 return LangOptions::Default; 156 case VisibilityAttr::Hidden: 157 return LangOptions::Hidden; 158 case VisibilityAttr::Protected: 159 return LangOptions::Protected; 160 } 161 } 162 163 if (getLangOptions().CPlusPlus) { 164 // Entities subject to an explicit instantiation declaration get default 165 // visibility. 166 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 167 if (Function->getTemplateSpecializationKind() 168 == TSK_ExplicitInstantiationDeclaration) 169 return LangOptions::Default; 170 } else if (const ClassTemplateSpecializationDecl *ClassSpec 171 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 172 if (ClassSpec->getSpecializationKind() 173 == TSK_ExplicitInstantiationDeclaration) 174 return LangOptions::Default; 175 } else if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 176 if (Record->getTemplateSpecializationKind() 177 == TSK_ExplicitInstantiationDeclaration) 178 return LangOptions::Default; 179 } else if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 180 if (Var->isStaticDataMember() && 181 (Var->getTemplateSpecializationKind() 182 == TSK_ExplicitInstantiationDeclaration)) 183 return LangOptions::Default; 184 } 185 186 // If -fvisibility-inlines-hidden was provided, then inline C++ member 187 // functions get "hidden" visibility by default. 188 if (getLangOptions().InlineVisibilityHidden) 189 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 190 if (Method->isInlined()) 191 return LangOptions::Hidden; 192 } 193 194 // If this decl is contained in a class, it should have the same visibility 195 // as the parent class. 196 if (const DeclContext *DC = D->getDeclContext()) 197 if (DC->isRecord()) 198 return getDeclVisibilityMode(cast<Decl>(DC)); 199 200 return getLangOptions().getVisibilityMode(); 201 } 202 203 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 204 const Decl *D) const { 205 // Internal definitions always have default visibility. 206 if (GV->hasLocalLinkage()) { 207 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 208 return; 209 } 210 211 switch (getDeclVisibilityMode(D)) { 212 default: assert(0 && "Unknown visibility!"); 213 case LangOptions::Default: 214 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 215 case LangOptions::Hidden: 216 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 217 case LangOptions::Protected: 218 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 219 } 220 } 221 222 /// Set the symbol visibility of type information (vtable and RTTI) 223 /// associated with the given type. 224 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 225 const CXXRecordDecl *RD, 226 bool IsForRTTI) const { 227 setGlobalVisibility(GV, RD); 228 229 if (!CodeGenOpts.HiddenWeakVTables) 230 return; 231 232 // We want to drop the visibility to hidden for weak type symbols. 233 // This isn't possible if there might be unresolved references 234 // elsewhere that rely on this symbol being visible. 235 236 // This should be kept roughly in sync with setThunkVisibility 237 // in CGVTables.cpp. 238 239 // Preconditions. 240 if (GV->getLinkage() != llvm::GlobalVariable::WeakODRLinkage || 241 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 242 return; 243 244 // Don't override an explicit visibility attribute. 245 if (RD->hasAttr<VisibilityAttr>()) 246 return; 247 248 switch (RD->getTemplateSpecializationKind()) { 249 // We have to disable the optimization if this is an EI definition 250 // because there might be EI declarations in other shared objects. 251 case TSK_ExplicitInstantiationDefinition: 252 case TSK_ExplicitInstantiationDeclaration: 253 return; 254 255 // Every use of a non-template class's type information has to emit it. 256 case TSK_Undeclared: 257 break; 258 259 // In theory, implicit instantiations can ignore the possibility of 260 // an explicit instantiation declaration because there necessarily 261 // must be an EI definition somewhere with default visibility. In 262 // practice, it's possible to have an explicit instantiation for 263 // an arbitrary template class, and linkers aren't necessarily able 264 // to deal with mixed-visibility symbols. 265 case TSK_ExplicitSpecialization: 266 case TSK_ImplicitInstantiation: 267 if (!CodeGenOpts.HiddenWeakTemplateVTables) 268 return; 269 break; 270 } 271 272 // If there's a key function, there may be translation units 273 // that don't have the key function's definition. But ignore 274 // this if we're emitting RTTI under -fno-rtti. 275 if (!IsForRTTI || Features.RTTI) 276 if (Context.getKeyFunction(RD)) 277 return; 278 279 // Otherwise, drop the visibility to hidden. 280 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 281 } 282 283 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 284 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 285 286 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 287 if (!Str.empty()) 288 return Str; 289 290 if (!getMangleContext().shouldMangleDeclName(ND)) { 291 IdentifierInfo *II = ND->getIdentifier(); 292 assert(II && "Attempt to mangle unnamed decl."); 293 294 Str = II->getName(); 295 return Str; 296 } 297 298 llvm::SmallString<256> Buffer; 299 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 300 getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer); 301 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 302 getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer); 303 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 304 getMangleContext().mangleBlock(GD, BD, Buffer); 305 else 306 getMangleContext().mangleName(ND, Buffer); 307 308 // Allocate space for the mangled name. 309 size_t Length = Buffer.size(); 310 char *Name = MangledNamesAllocator.Allocate<char>(Length); 311 std::copy(Buffer.begin(), Buffer.end(), Name); 312 313 Str = llvm::StringRef(Name, Length); 314 315 return Str; 316 } 317 318 void CodeGenModule::getMangledName(GlobalDecl GD, MangleBuffer &Buffer, 319 const BlockDecl *BD) { 320 getMangleContext().mangleBlock(GD, BD, Buffer.getBuffer()); 321 } 322 323 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) { 324 return getModule().getNamedValue(Name); 325 } 326 327 /// AddGlobalCtor - Add a function to the list that will be called before 328 /// main() runs. 329 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 330 // FIXME: Type coercion of void()* types. 331 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 332 } 333 334 /// AddGlobalDtor - Add a function to the list that will be called 335 /// when the module is unloaded. 336 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 337 // FIXME: Type coercion of void()* types. 338 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 339 } 340 341 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 342 // Ctor function type is void()*. 343 llvm::FunctionType* CtorFTy = 344 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 345 std::vector<const llvm::Type*>(), 346 false); 347 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 348 349 // Get the type of a ctor entry, { i32, void ()* }. 350 llvm::StructType* CtorStructTy = 351 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 352 llvm::PointerType::getUnqual(CtorFTy), NULL); 353 354 // Construct the constructor and destructor arrays. 355 std::vector<llvm::Constant*> Ctors; 356 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 357 std::vector<llvm::Constant*> S; 358 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 359 I->second, false)); 360 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 361 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 362 } 363 364 if (!Ctors.empty()) { 365 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 366 new llvm::GlobalVariable(TheModule, AT, false, 367 llvm::GlobalValue::AppendingLinkage, 368 llvm::ConstantArray::get(AT, Ctors), 369 GlobalName); 370 } 371 } 372 373 void CodeGenModule::EmitAnnotations() { 374 if (Annotations.empty()) 375 return; 376 377 // Create a new global variable for the ConstantStruct in the Module. 378 llvm::Constant *Array = 379 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 380 Annotations.size()), 381 Annotations); 382 llvm::GlobalValue *gv = 383 new llvm::GlobalVariable(TheModule, Array->getType(), false, 384 llvm::GlobalValue::AppendingLinkage, Array, 385 "llvm.global.annotations"); 386 gv->setSection("llvm.metadata"); 387 } 388 389 llvm::GlobalValue::LinkageTypes 390 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 391 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 392 393 if (Linkage == GVA_Internal) 394 return llvm::Function::InternalLinkage; 395 396 if (D->hasAttr<DLLExportAttr>()) 397 return llvm::Function::DLLExportLinkage; 398 399 if (D->hasAttr<WeakAttr>()) 400 return llvm::Function::WeakAnyLinkage; 401 402 // In C99 mode, 'inline' functions are guaranteed to have a strong 403 // definition somewhere else, so we can use available_externally linkage. 404 if (Linkage == GVA_C99Inline) 405 return llvm::Function::AvailableExternallyLinkage; 406 407 // In C++, the compiler has to emit a definition in every translation unit 408 // that references the function. We should use linkonce_odr because 409 // a) if all references in this translation unit are optimized away, we 410 // don't need to codegen it. b) if the function persists, it needs to be 411 // merged with other definitions. c) C++ has the ODR, so we know the 412 // definition is dependable. 413 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 414 return llvm::Function::LinkOnceODRLinkage; 415 416 // An explicit instantiation of a template has weak linkage, since 417 // explicit instantiations can occur in multiple translation units 418 // and must all be equivalent. However, we are not allowed to 419 // throw away these explicit instantiations. 420 if (Linkage == GVA_ExplicitTemplateInstantiation) 421 return llvm::Function::WeakODRLinkage; 422 423 // Otherwise, we have strong external linkage. 424 assert(Linkage == GVA_StrongExternal); 425 return llvm::Function::ExternalLinkage; 426 } 427 428 429 /// SetFunctionDefinitionAttributes - Set attributes for a global. 430 /// 431 /// FIXME: This is currently only done for aliases and functions, but not for 432 /// variables (these details are set in EmitGlobalVarDefinition for variables). 433 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 434 llvm::GlobalValue *GV) { 435 SetCommonAttributes(D, GV); 436 } 437 438 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 439 const CGFunctionInfo &Info, 440 llvm::Function *F) { 441 unsigned CallingConv; 442 AttributeListType AttributeList; 443 ConstructAttributeList(Info, D, AttributeList, CallingConv); 444 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 445 AttributeList.size())); 446 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 447 } 448 449 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 450 llvm::Function *F) { 451 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 452 F->addFnAttr(llvm::Attribute::NoUnwind); 453 454 if (D->hasAttr<AlwaysInlineAttr>()) 455 F->addFnAttr(llvm::Attribute::AlwaysInline); 456 457 if (D->hasAttr<NoInlineAttr>()) 458 F->addFnAttr(llvm::Attribute::NoInline); 459 460 if (Features.getStackProtectorMode() == LangOptions::SSPOn) 461 F->addFnAttr(llvm::Attribute::StackProtect); 462 else if (Features.getStackProtectorMode() == LangOptions::SSPReq) 463 F->addFnAttr(llvm::Attribute::StackProtectReq); 464 465 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 466 if (alignment) 467 F->setAlignment(alignment); 468 469 // C++ ABI requires 2-byte alignment for member functions. 470 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 471 F->setAlignment(2); 472 } 473 474 void CodeGenModule::SetCommonAttributes(const Decl *D, 475 llvm::GlobalValue *GV) { 476 setGlobalVisibility(GV, D); 477 478 if (D->hasAttr<UsedAttr>()) 479 AddUsedGlobal(GV); 480 481 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 482 GV->setSection(SA->getName()); 483 484 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 485 } 486 487 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 488 llvm::Function *F, 489 const CGFunctionInfo &FI) { 490 SetLLVMFunctionAttributes(D, FI, F); 491 SetLLVMFunctionAttributesForDefinition(D, F); 492 493 F->setLinkage(llvm::Function::InternalLinkage); 494 495 SetCommonAttributes(D, F); 496 } 497 498 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 499 llvm::Function *F, 500 bool IsIncompleteFunction) { 501 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 502 503 if (!IsIncompleteFunction) 504 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 505 506 // Only a few attributes are set on declarations; these may later be 507 // overridden by a definition. 508 509 if (FD->hasAttr<DLLImportAttr>()) { 510 F->setLinkage(llvm::Function::DLLImportLinkage); 511 } else if (FD->hasAttr<WeakAttr>() || 512 FD->hasAttr<WeakImportAttr>()) { 513 // "extern_weak" is overloaded in LLVM; we probably should have 514 // separate linkage types for this. 515 F->setLinkage(llvm::Function::ExternalWeakLinkage); 516 } else { 517 F->setLinkage(llvm::Function::ExternalLinkage); 518 } 519 520 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 521 F->setSection(SA->getName()); 522 } 523 524 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 525 assert(!GV->isDeclaration() && 526 "Only globals with definition can force usage."); 527 LLVMUsed.push_back(GV); 528 } 529 530 void CodeGenModule::EmitLLVMUsed() { 531 // Don't create llvm.used if there is no need. 532 if (LLVMUsed.empty()) 533 return; 534 535 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 536 537 // Convert LLVMUsed to what ConstantArray needs. 538 std::vector<llvm::Constant*> UsedArray; 539 UsedArray.resize(LLVMUsed.size()); 540 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 541 UsedArray[i] = 542 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 543 i8PTy); 544 } 545 546 if (UsedArray.empty()) 547 return; 548 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 549 550 llvm::GlobalVariable *GV = 551 new llvm::GlobalVariable(getModule(), ATy, false, 552 llvm::GlobalValue::AppendingLinkage, 553 llvm::ConstantArray::get(ATy, UsedArray), 554 "llvm.used"); 555 556 GV->setSection("llvm.metadata"); 557 } 558 559 void CodeGenModule::EmitDeferred() { 560 // Emit code for any potentially referenced deferred decls. Since a 561 // previously unused static decl may become used during the generation of code 562 // for a static function, iterate until no changes are made. 563 564 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 565 if (!DeferredVTables.empty()) { 566 const CXXRecordDecl *RD = DeferredVTables.back(); 567 DeferredVTables.pop_back(); 568 getVTables().GenerateClassData(getVTableLinkage(RD), RD); 569 continue; 570 } 571 572 GlobalDecl D = DeferredDeclsToEmit.back(); 573 DeferredDeclsToEmit.pop_back(); 574 575 // Check to see if we've already emitted this. This is necessary 576 // for a couple of reasons: first, decls can end up in the 577 // deferred-decls queue multiple times, and second, decls can end 578 // up with definitions in unusual ways (e.g. by an extern inline 579 // function acquiring a strong function redefinition). Just 580 // ignore these cases. 581 // 582 // TODO: That said, looking this up multiple times is very wasteful. 583 llvm::StringRef Name = getMangledName(D); 584 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 585 assert(CGRef && "Deferred decl wasn't referenced?"); 586 587 if (!CGRef->isDeclaration()) 588 continue; 589 590 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 591 // purposes an alias counts as a definition. 592 if (isa<llvm::GlobalAlias>(CGRef)) 593 continue; 594 595 // Otherwise, emit the definition and move on to the next one. 596 EmitGlobalDefinition(D); 597 } 598 } 599 600 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 601 /// annotation information for a given GlobalValue. The annotation struct is 602 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 603 /// GlobalValue being annotated. The second field is the constant string 604 /// created from the AnnotateAttr's annotation. The third field is a constant 605 /// string containing the name of the translation unit. The fourth field is 606 /// the line number in the file of the annotated value declaration. 607 /// 608 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 609 /// appears to. 610 /// 611 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 612 const AnnotateAttr *AA, 613 unsigned LineNo) { 614 llvm::Module *M = &getModule(); 615 616 // get [N x i8] constants for the annotation string, and the filename string 617 // which are the 2nd and 3rd elements of the global annotation structure. 618 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 619 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 620 AA->getAnnotation(), true); 621 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 622 M->getModuleIdentifier(), 623 true); 624 625 // Get the two global values corresponding to the ConstantArrays we just 626 // created to hold the bytes of the strings. 627 llvm::GlobalValue *annoGV = 628 new llvm::GlobalVariable(*M, anno->getType(), false, 629 llvm::GlobalValue::PrivateLinkage, anno, 630 GV->getName()); 631 // translation unit name string, emitted into the llvm.metadata section. 632 llvm::GlobalValue *unitGV = 633 new llvm::GlobalVariable(*M, unit->getType(), false, 634 llvm::GlobalValue::PrivateLinkage, unit, 635 ".str"); 636 637 // Create the ConstantStruct for the global annotation. 638 llvm::Constant *Fields[4] = { 639 llvm::ConstantExpr::getBitCast(GV, SBP), 640 llvm::ConstantExpr::getBitCast(annoGV, SBP), 641 llvm::ConstantExpr::getBitCast(unitGV, SBP), 642 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 643 }; 644 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 645 } 646 647 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 648 // Never defer when EmitAllDecls is specified. 649 if (Features.EmitAllDecls) 650 return false; 651 652 return !getContext().DeclMustBeEmitted(Global); 653 } 654 655 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 656 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 657 assert(AA && "No alias?"); 658 659 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 660 661 // See if there is already something with the target's name in the module. 662 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 663 664 llvm::Constant *Aliasee; 665 if (isa<llvm::FunctionType>(DeclTy)) 666 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 667 else 668 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 669 llvm::PointerType::getUnqual(DeclTy), 0); 670 if (!Entry) { 671 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 672 F->setLinkage(llvm::Function::ExternalWeakLinkage); 673 WeakRefReferences.insert(F); 674 } 675 676 return Aliasee; 677 } 678 679 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 680 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 681 682 // Weak references don't produce any output by themselves. 683 if (Global->hasAttr<WeakRefAttr>()) 684 return; 685 686 // If this is an alias definition (which otherwise looks like a declaration) 687 // emit it now. 688 if (Global->hasAttr<AliasAttr>()) 689 return EmitAliasDefinition(GD); 690 691 // Ignore declarations, they will be emitted on their first use. 692 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 693 if (FD->getIdentifier()) { 694 llvm::StringRef Name = FD->getName(); 695 if (Name == "_Block_object_assign") { 696 BlockObjectAssignDecl = FD; 697 } else if (Name == "_Block_object_dispose") { 698 BlockObjectDisposeDecl = FD; 699 } 700 } 701 702 // Forward declarations are emitted lazily on first use. 703 if (!FD->isThisDeclarationADefinition()) 704 return; 705 } else { 706 const VarDecl *VD = cast<VarDecl>(Global); 707 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 708 709 if (VD->getIdentifier()) { 710 llvm::StringRef Name = VD->getName(); 711 if (Name == "_NSConcreteGlobalBlock") { 712 NSConcreteGlobalBlockDecl = VD; 713 } else if (Name == "_NSConcreteStackBlock") { 714 NSConcreteStackBlockDecl = VD; 715 } 716 } 717 718 719 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 720 return; 721 } 722 723 // Defer code generation when possible if this is a static definition, inline 724 // function etc. These we only want to emit if they are used. 725 if (!MayDeferGeneration(Global)) { 726 // Emit the definition if it can't be deferred. 727 EmitGlobalDefinition(GD); 728 return; 729 } 730 731 // If we're deferring emission of a C++ variable with an 732 // initializer, remember the order in which it appeared in the file. 733 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) && 734 cast<VarDecl>(Global)->hasInit()) { 735 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 736 CXXGlobalInits.push_back(0); 737 } 738 739 // If the value has already been used, add it directly to the 740 // DeferredDeclsToEmit list. 741 llvm::StringRef MangledName = getMangledName(GD); 742 if (GetGlobalValue(MangledName)) 743 DeferredDeclsToEmit.push_back(GD); 744 else { 745 // Otherwise, remember that we saw a deferred decl with this name. The 746 // first use of the mangled name will cause it to move into 747 // DeferredDeclsToEmit. 748 DeferredDecls[MangledName] = GD; 749 } 750 } 751 752 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 753 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 754 755 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 756 Context.getSourceManager(), 757 "Generating code for declaration"); 758 759 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 760 // At -O0, don't generate IR for functions with available_externally 761 // linkage. 762 if (CodeGenOpts.OptimizationLevel == 0 && 763 !Function->hasAttr<AlwaysInlineAttr>() && 764 getFunctionLinkage(Function) 765 == llvm::Function::AvailableExternallyLinkage) 766 return; 767 768 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 769 if (Method->isVirtual()) 770 getVTables().EmitThunks(GD); 771 772 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 773 return EmitCXXConstructor(CD, GD.getCtorType()); 774 775 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method)) 776 return EmitCXXDestructor(DD, GD.getDtorType()); 777 } 778 779 return EmitGlobalFunctionDefinition(GD); 780 } 781 782 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 783 return EmitGlobalVarDefinition(VD); 784 785 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 786 } 787 788 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 789 /// module, create and return an llvm Function with the specified type. If there 790 /// is something in the module with the specified name, return it potentially 791 /// bitcasted to the right type. 792 /// 793 /// If D is non-null, it specifies a decl that correspond to this. This is used 794 /// to set the attributes on the function when it is first created. 795 llvm::Constant * 796 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName, 797 const llvm::Type *Ty, 798 GlobalDecl D) { 799 // Lookup the entry, lazily creating it if necessary. 800 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 801 if (Entry) { 802 if (WeakRefReferences.count(Entry)) { 803 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 804 if (FD && !FD->hasAttr<WeakAttr>()) 805 Entry->setLinkage(llvm::Function::ExternalLinkage); 806 807 WeakRefReferences.erase(Entry); 808 } 809 810 if (Entry->getType()->getElementType() == Ty) 811 return Entry; 812 813 // Make sure the result is of the correct type. 814 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 815 return llvm::ConstantExpr::getBitCast(Entry, PTy); 816 } 817 818 // This function doesn't have a complete type (for example, the return 819 // type is an incomplete struct). Use a fake type instead, and make 820 // sure not to try to set attributes. 821 bool IsIncompleteFunction = false; 822 823 const llvm::FunctionType *FTy; 824 if (isa<llvm::FunctionType>(Ty)) { 825 FTy = cast<llvm::FunctionType>(Ty); 826 } else { 827 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 828 std::vector<const llvm::Type*>(), false); 829 IsIncompleteFunction = true; 830 } 831 832 llvm::Function *F = llvm::Function::Create(FTy, 833 llvm::Function::ExternalLinkage, 834 MangledName, &getModule()); 835 assert(F->getName() == MangledName && "name was uniqued!"); 836 if (D.getDecl()) 837 SetFunctionAttributes(D, F, IsIncompleteFunction); 838 839 // This is the first use or definition of a mangled name. If there is a 840 // deferred decl with this name, remember that we need to emit it at the end 841 // of the file. 842 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 843 if (DDI != DeferredDecls.end()) { 844 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 845 // list, and remove it from DeferredDecls (since we don't need it anymore). 846 DeferredDeclsToEmit.push_back(DDI->second); 847 DeferredDecls.erase(DDI); 848 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 849 // If this the first reference to a C++ inline function in a class, queue up 850 // the deferred function body for emission. These are not seen as 851 // top-level declarations. 852 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 853 DeferredDeclsToEmit.push_back(D); 854 // A called constructor which has no definition or declaration need be 855 // synthesized. 856 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 857 if (CD->isImplicit()) { 858 assert(CD->isUsed() && "Sema doesn't consider constructor as used."); 859 DeferredDeclsToEmit.push_back(D); 860 } 861 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 862 if (DD->isImplicit()) { 863 assert(DD->isUsed() && "Sema doesn't consider destructor as used."); 864 DeferredDeclsToEmit.push_back(D); 865 } 866 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 867 if (MD->isCopyAssignment() && MD->isImplicit()) { 868 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used."); 869 DeferredDeclsToEmit.push_back(D); 870 } 871 } 872 } 873 874 // Make sure the result is of the requested type. 875 if (!IsIncompleteFunction) { 876 assert(F->getType()->getElementType() == Ty); 877 return F; 878 } 879 880 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 881 return llvm::ConstantExpr::getBitCast(F, PTy); 882 } 883 884 /// GetAddrOfFunction - Return the address of the given function. If Ty is 885 /// non-null, then this function will use the specified type if it has to 886 /// create it (this occurs when we see a definition of the function). 887 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 888 const llvm::Type *Ty) { 889 // If there was no specific requested type, just convert it now. 890 if (!Ty) 891 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 892 893 llvm::StringRef MangledName = getMangledName(GD); 894 return GetOrCreateLLVMFunction(MangledName, Ty, GD); 895 } 896 897 /// CreateRuntimeFunction - Create a new runtime function with the specified 898 /// type and name. 899 llvm::Constant * 900 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 901 llvm::StringRef Name) { 902 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 903 } 904 905 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) { 906 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 907 return false; 908 if (Context.getLangOptions().CPlusPlus && 909 Context.getBaseElementType(D->getType())->getAs<RecordType>()) { 910 // FIXME: We should do something fancier here! 911 return false; 912 } 913 return true; 914 } 915 916 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 917 /// create and return an llvm GlobalVariable with the specified type. If there 918 /// is something in the module with the specified name, return it potentially 919 /// bitcasted to the right type. 920 /// 921 /// If D is non-null, it specifies a decl that correspond to this. This is used 922 /// to set the attributes on the global when it is first created. 923 llvm::Constant * 924 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName, 925 const llvm::PointerType *Ty, 926 const VarDecl *D) { 927 // Lookup the entry, lazily creating it if necessary. 928 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 929 if (Entry) { 930 if (WeakRefReferences.count(Entry)) { 931 if (D && !D->hasAttr<WeakAttr>()) 932 Entry->setLinkage(llvm::Function::ExternalLinkage); 933 934 WeakRefReferences.erase(Entry); 935 } 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 // FIXME: Merge with other attribute handling code. 968 if (D->getStorageClass() == SC_PrivateExtern) 969 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 970 971 if (D->hasAttr<WeakAttr>() || 972 D->hasAttr<WeakImportAttr>()) 973 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 974 975 GV->setThreadLocal(D->isThreadSpecified()); 976 } 977 978 return GV; 979 } 980 981 982 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 983 /// given global variable. If Ty is non-null and if the global doesn't exist, 984 /// then it will be greated with the specified type instead of whatever the 985 /// normal requested type would be. 986 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 987 const llvm::Type *Ty) { 988 assert(D->hasGlobalStorage() && "Not a global variable"); 989 QualType ASTTy = D->getType(); 990 if (Ty == 0) 991 Ty = getTypes().ConvertTypeForMem(ASTTy); 992 993 const llvm::PointerType *PTy = 994 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 995 996 llvm::StringRef MangledName = getMangledName(D); 997 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 998 } 999 1000 /// CreateRuntimeVariable - Create a new runtime global variable with the 1001 /// specified type and name. 1002 llvm::Constant * 1003 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 1004 llvm::StringRef Name) { 1005 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 1006 } 1007 1008 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1009 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1010 1011 if (MayDeferGeneration(D)) { 1012 // If we have not seen a reference to this variable yet, place it 1013 // into the deferred declarations table to be emitted if needed 1014 // later. 1015 llvm::StringRef MangledName = getMangledName(D); 1016 if (!GetGlobalValue(MangledName)) { 1017 DeferredDecls[MangledName] = D; 1018 return; 1019 } 1020 } 1021 1022 // The tentative definition is the only definition. 1023 EmitGlobalVarDefinition(D); 1024 } 1025 1026 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1027 if (DefinitionRequired) 1028 getVTables().GenerateClassData(getVTableLinkage(Class), Class); 1029 } 1030 1031 llvm::GlobalVariable::LinkageTypes 1032 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1033 if (RD->isInAnonymousNamespace() || !RD->hasLinkage()) 1034 return llvm::GlobalVariable::InternalLinkage; 1035 1036 if (const CXXMethodDecl *KeyFunction 1037 = RD->getASTContext().getKeyFunction(RD)) { 1038 // If this class has a key function, use that to determine the linkage of 1039 // the vtable. 1040 const FunctionDecl *Def = 0; 1041 if (KeyFunction->hasBody(Def)) 1042 KeyFunction = cast<CXXMethodDecl>(Def); 1043 1044 switch (KeyFunction->getTemplateSpecializationKind()) { 1045 case TSK_Undeclared: 1046 case TSK_ExplicitSpecialization: 1047 if (KeyFunction->isInlined()) 1048 return llvm::GlobalVariable::WeakODRLinkage; 1049 1050 return llvm::GlobalVariable::ExternalLinkage; 1051 1052 case TSK_ImplicitInstantiation: 1053 case TSK_ExplicitInstantiationDefinition: 1054 return llvm::GlobalVariable::WeakODRLinkage; 1055 1056 case TSK_ExplicitInstantiationDeclaration: 1057 // FIXME: Use available_externally linkage. However, this currently 1058 // breaks LLVM's build due to undefined symbols. 1059 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1060 return llvm::GlobalVariable::WeakODRLinkage; 1061 } 1062 } 1063 1064 switch (RD->getTemplateSpecializationKind()) { 1065 case TSK_Undeclared: 1066 case TSK_ExplicitSpecialization: 1067 case TSK_ImplicitInstantiation: 1068 case TSK_ExplicitInstantiationDefinition: 1069 return llvm::GlobalVariable::WeakODRLinkage; 1070 1071 case TSK_ExplicitInstantiationDeclaration: 1072 // FIXME: Use available_externally linkage. However, this currently 1073 // breaks LLVM's build due to undefined symbols. 1074 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1075 return llvm::GlobalVariable::WeakODRLinkage; 1076 } 1077 1078 // Silence GCC warning. 1079 return llvm::GlobalVariable::WeakODRLinkage; 1080 } 1081 1082 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1083 return CharUnits::fromQuantity( 1084 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth()); 1085 } 1086 1087 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1088 llvm::Constant *Init = 0; 1089 QualType ASTTy = D->getType(); 1090 bool NonConstInit = false; 1091 1092 const Expr *InitExpr = D->getAnyInitializer(); 1093 1094 if (!InitExpr) { 1095 // This is a tentative definition; tentative definitions are 1096 // implicitly initialized with { 0 }. 1097 // 1098 // Note that tentative definitions are only emitted at the end of 1099 // a translation unit, so they should never have incomplete 1100 // type. In addition, EmitTentativeDefinition makes sure that we 1101 // never attempt to emit a tentative definition if a real one 1102 // exists. A use may still exists, however, so we still may need 1103 // to do a RAUW. 1104 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1105 Init = EmitNullConstant(D->getType()); 1106 } else { 1107 Init = EmitConstantExpr(InitExpr, D->getType()); 1108 if (!Init) { 1109 QualType T = InitExpr->getType(); 1110 if (D->getType()->isReferenceType()) 1111 T = D->getType(); 1112 1113 if (getLangOptions().CPlusPlus) { 1114 EmitCXXGlobalVarDeclInitFunc(D); 1115 Init = EmitNullConstant(T); 1116 NonConstInit = true; 1117 } else { 1118 ErrorUnsupported(D, "static initializer"); 1119 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1120 } 1121 } else { 1122 // We don't need an initializer, so remove the entry for the delayed 1123 // initializer position (just in case this entry was delayed). 1124 if (getLangOptions().CPlusPlus) 1125 DelayedCXXInitPosition.erase(D); 1126 } 1127 } 1128 1129 const llvm::Type* InitType = Init->getType(); 1130 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1131 1132 // Strip off a bitcast if we got one back. 1133 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1134 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1135 // all zero index gep. 1136 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1137 Entry = CE->getOperand(0); 1138 } 1139 1140 // Entry is now either a Function or GlobalVariable. 1141 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1142 1143 // We have a definition after a declaration with the wrong type. 1144 // We must make a new GlobalVariable* and update everything that used OldGV 1145 // (a declaration or tentative definition) with the new GlobalVariable* 1146 // (which will be a definition). 1147 // 1148 // This happens if there is a prototype for a global (e.g. 1149 // "extern int x[];") and then a definition of a different type (e.g. 1150 // "int x[10];"). This also happens when an initializer has a different type 1151 // from the type of the global (this happens with unions). 1152 if (GV == 0 || 1153 GV->getType()->getElementType() != InitType || 1154 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1155 1156 // Move the old entry aside so that we'll create a new one. 1157 Entry->setName(llvm::StringRef()); 1158 1159 // Make a new global with the correct type, this is now guaranteed to work. 1160 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1161 1162 // Replace all uses of the old global with the new global 1163 llvm::Constant *NewPtrForOldDecl = 1164 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1165 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1166 1167 // Erase the old global, since it is no longer used. 1168 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1169 } 1170 1171 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1172 SourceManager &SM = Context.getSourceManager(); 1173 AddAnnotation(EmitAnnotateAttr(GV, AA, 1174 SM.getInstantiationLineNumber(D->getLocation()))); 1175 } 1176 1177 GV->setInitializer(Init); 1178 1179 // If it is safe to mark the global 'constant', do so now. 1180 GV->setConstant(false); 1181 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1182 GV->setConstant(true); 1183 1184 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1185 1186 // Set the llvm linkage type as appropriate. 1187 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1188 if (Linkage == GVA_Internal) 1189 GV->setLinkage(llvm::Function::InternalLinkage); 1190 else if (D->hasAttr<DLLImportAttr>()) 1191 GV->setLinkage(llvm::Function::DLLImportLinkage); 1192 else if (D->hasAttr<DLLExportAttr>()) 1193 GV->setLinkage(llvm::Function::DLLExportLinkage); 1194 else if (D->hasAttr<WeakAttr>()) { 1195 if (GV->isConstant()) 1196 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1197 else 1198 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1199 } else if (Linkage == GVA_TemplateInstantiation || 1200 Linkage == GVA_ExplicitTemplateInstantiation) 1201 // FIXME: It seems like we can provide more specific linkage here 1202 // (LinkOnceODR, WeakODR). 1203 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1204 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon && 1205 !D->hasExternalStorage() && !D->getInit() && 1206 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) { 1207 // Thread local vars aren't considered common linkage. 1208 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1209 // common vars aren't constant even if declared const. 1210 GV->setConstant(false); 1211 } else 1212 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1213 1214 SetCommonAttributes(D, GV); 1215 1216 // Emit global variable debug information. 1217 if (CGDebugInfo *DI = getDebugInfo()) { 1218 DI->setLocation(D->getLocation()); 1219 DI->EmitGlobalVariable(GV, D); 1220 } 1221 } 1222 1223 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1224 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1225 /// existing call uses of the old function in the module, this adjusts them to 1226 /// call the new function directly. 1227 /// 1228 /// This is not just a cleanup: the always_inline pass requires direct calls to 1229 /// functions to be able to inline them. If there is a bitcast in the way, it 1230 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1231 /// run at -O0. 1232 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1233 llvm::Function *NewFn) { 1234 // If we're redefining a global as a function, don't transform it. 1235 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1236 if (OldFn == 0) return; 1237 1238 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1239 llvm::SmallVector<llvm::Value*, 4> ArgList; 1240 1241 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1242 UI != E; ) { 1243 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1244 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1245 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1246 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1247 llvm::CallSite CS(CI); 1248 if (!CI || !CS.isCallee(I)) continue; 1249 1250 // If the return types don't match exactly, and if the call isn't dead, then 1251 // we can't transform this call. 1252 if (CI->getType() != NewRetTy && !CI->use_empty()) 1253 continue; 1254 1255 // If the function was passed too few arguments, don't transform. If extra 1256 // arguments were passed, we silently drop them. If any of the types 1257 // mismatch, we don't transform. 1258 unsigned ArgNo = 0; 1259 bool DontTransform = false; 1260 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1261 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1262 if (CS.arg_size() == ArgNo || 1263 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1264 DontTransform = true; 1265 break; 1266 } 1267 } 1268 if (DontTransform) 1269 continue; 1270 1271 // Okay, we can transform this. Create the new call instruction and copy 1272 // over the required information. 1273 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1274 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1275 ArgList.end(), "", CI); 1276 ArgList.clear(); 1277 if (!NewCall->getType()->isVoidTy()) 1278 NewCall->takeName(CI); 1279 NewCall->setAttributes(CI->getAttributes()); 1280 NewCall->setCallingConv(CI->getCallingConv()); 1281 1282 // Finally, remove the old call, replacing any uses with the new one. 1283 if (!CI->use_empty()) 1284 CI->replaceAllUsesWith(NewCall); 1285 1286 // Copy debug location attached to CI. 1287 if (!CI->getDebugLoc().isUnknown()) 1288 NewCall->setDebugLoc(CI->getDebugLoc()); 1289 CI->eraseFromParent(); 1290 } 1291 } 1292 1293 1294 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1295 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1296 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1297 getMangleContext().mangleInitDiscriminator(); 1298 // Get or create the prototype for the function. 1299 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1300 1301 // Strip off a bitcast if we got one back. 1302 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1303 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1304 Entry = CE->getOperand(0); 1305 } 1306 1307 1308 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1309 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1310 1311 // If the types mismatch then we have to rewrite the definition. 1312 assert(OldFn->isDeclaration() && 1313 "Shouldn't replace non-declaration"); 1314 1315 // F is the Function* for the one with the wrong type, we must make a new 1316 // Function* and update everything that used F (a declaration) with the new 1317 // Function* (which will be a definition). 1318 // 1319 // This happens if there is a prototype for a function 1320 // (e.g. "int f()") and then a definition of a different type 1321 // (e.g. "int f(int x)"). Move the old function aside so that it 1322 // doesn't interfere with GetAddrOfFunction. 1323 OldFn->setName(llvm::StringRef()); 1324 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1325 1326 // If this is an implementation of a function without a prototype, try to 1327 // replace any existing uses of the function (which may be calls) with uses 1328 // of the new function 1329 if (D->getType()->isFunctionNoProtoType()) { 1330 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1331 OldFn->removeDeadConstantUsers(); 1332 } 1333 1334 // Replace uses of F with the Function we will endow with a body. 1335 if (!Entry->use_empty()) { 1336 llvm::Constant *NewPtrForOldDecl = 1337 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1338 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1339 } 1340 1341 // Ok, delete the old function now, which is dead. 1342 OldFn->eraseFromParent(); 1343 1344 Entry = NewFn; 1345 } 1346 1347 llvm::Function *Fn = cast<llvm::Function>(Entry); 1348 setFunctionLinkage(D, Fn); 1349 1350 CodeGenFunction(*this).GenerateCode(D, Fn); 1351 1352 SetFunctionDefinitionAttributes(D, Fn); 1353 SetLLVMFunctionAttributesForDefinition(D, Fn); 1354 1355 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1356 AddGlobalCtor(Fn, CA->getPriority()); 1357 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1358 AddGlobalDtor(Fn, DA->getPriority()); 1359 } 1360 1361 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1362 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1363 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1364 assert(AA && "Not an alias?"); 1365 1366 llvm::StringRef MangledName = getMangledName(GD); 1367 1368 // If there is a definition in the module, then it wins over the alias. 1369 // This is dubious, but allow it to be safe. Just ignore the alias. 1370 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1371 if (Entry && !Entry->isDeclaration()) 1372 return; 1373 1374 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1375 1376 // Create a reference to the named value. This ensures that it is emitted 1377 // if a deferred decl. 1378 llvm::Constant *Aliasee; 1379 if (isa<llvm::FunctionType>(DeclTy)) 1380 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 1381 else 1382 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1383 llvm::PointerType::getUnqual(DeclTy), 0); 1384 1385 // Create the new alias itself, but don't set a name yet. 1386 llvm::GlobalValue *GA = 1387 new llvm::GlobalAlias(Aliasee->getType(), 1388 llvm::Function::ExternalLinkage, 1389 "", Aliasee, &getModule()); 1390 1391 if (Entry) { 1392 assert(Entry->isDeclaration()); 1393 1394 // If there is a declaration in the module, then we had an extern followed 1395 // by the alias, as in: 1396 // extern int test6(); 1397 // ... 1398 // int test6() __attribute__((alias("test7"))); 1399 // 1400 // Remove it and replace uses of it with the alias. 1401 GA->takeName(Entry); 1402 1403 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1404 Entry->getType())); 1405 Entry->eraseFromParent(); 1406 } else { 1407 GA->setName(MangledName); 1408 } 1409 1410 // Set attributes which are particular to an alias; this is a 1411 // specialization of the attributes which may be set on a global 1412 // variable/function. 1413 if (D->hasAttr<DLLExportAttr>()) { 1414 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1415 // The dllexport attribute is ignored for undefined symbols. 1416 if (FD->hasBody()) 1417 GA->setLinkage(llvm::Function::DLLExportLinkage); 1418 } else { 1419 GA->setLinkage(llvm::Function::DLLExportLinkage); 1420 } 1421 } else if (D->hasAttr<WeakAttr>() || 1422 D->hasAttr<WeakRefAttr>() || 1423 D->hasAttr<WeakImportAttr>()) { 1424 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1425 } 1426 1427 SetCommonAttributes(D, GA); 1428 } 1429 1430 /// getBuiltinLibFunction - Given a builtin id for a function like 1431 /// "__builtin_fabsf", return a Function* for "fabsf". 1432 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1433 unsigned BuiltinID) { 1434 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1435 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1436 "isn't a lib fn"); 1437 1438 // Get the name, skip over the __builtin_ prefix (if necessary). 1439 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1440 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1441 Name += 10; 1442 1443 const llvm::FunctionType *Ty = 1444 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1445 1446 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1447 } 1448 1449 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1450 unsigned NumTys) { 1451 return llvm::Intrinsic::getDeclaration(&getModule(), 1452 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1453 } 1454 1455 1456 llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType, 1457 const llvm::Type *SrcType, 1458 const llvm::Type *SizeType) { 1459 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1460 return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3); 1461 } 1462 1463 llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType, 1464 const llvm::Type *SrcType, 1465 const llvm::Type *SizeType) { 1466 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1467 return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3); 1468 } 1469 1470 llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType, 1471 const llvm::Type *SizeType) { 1472 const llvm::Type *ArgTypes[2] = { DestType, SizeType }; 1473 return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2); 1474 } 1475 1476 static llvm::StringMapEntry<llvm::Constant*> & 1477 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1478 const StringLiteral *Literal, 1479 bool TargetIsLSB, 1480 bool &IsUTF16, 1481 unsigned &StringLength) { 1482 llvm::StringRef String = Literal->getString(); 1483 unsigned NumBytes = String.size(); 1484 1485 // Check for simple case. 1486 if (!Literal->containsNonAsciiOrNull()) { 1487 StringLength = NumBytes; 1488 return Map.GetOrCreateValue(String); 1489 } 1490 1491 // Otherwise, convert the UTF8 literals into a byte string. 1492 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1493 const UTF8 *FromPtr = (UTF8 *)String.data(); 1494 UTF16 *ToPtr = &ToBuf[0]; 1495 1496 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1497 &ToPtr, ToPtr + NumBytes, 1498 strictConversion); 1499 1500 // Check for conversion failure. 1501 if (Result != conversionOK) { 1502 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1503 // this duplicate code. 1504 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1505 StringLength = NumBytes; 1506 return Map.GetOrCreateValue(String); 1507 } 1508 1509 // ConvertUTF8toUTF16 returns the length in ToPtr. 1510 StringLength = ToPtr - &ToBuf[0]; 1511 1512 // Render the UTF-16 string into a byte array and convert to the target byte 1513 // order. 1514 // 1515 // FIXME: This isn't something we should need to do here. 1516 llvm::SmallString<128> AsBytes; 1517 AsBytes.reserve(StringLength * 2); 1518 for (unsigned i = 0; i != StringLength; ++i) { 1519 unsigned short Val = ToBuf[i]; 1520 if (TargetIsLSB) { 1521 AsBytes.push_back(Val & 0xFF); 1522 AsBytes.push_back(Val >> 8); 1523 } else { 1524 AsBytes.push_back(Val >> 8); 1525 AsBytes.push_back(Val & 0xFF); 1526 } 1527 } 1528 // Append one extra null character, the second is automatically added by our 1529 // caller. 1530 AsBytes.push_back(0); 1531 1532 IsUTF16 = true; 1533 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1534 } 1535 1536 llvm::Constant * 1537 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1538 unsigned StringLength = 0; 1539 bool isUTF16 = false; 1540 llvm::StringMapEntry<llvm::Constant*> &Entry = 1541 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1542 getTargetData().isLittleEndian(), 1543 isUTF16, StringLength); 1544 1545 if (llvm::Constant *C = Entry.getValue()) 1546 return C; 1547 1548 llvm::Constant *Zero = 1549 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1550 llvm::Constant *Zeros[] = { Zero, Zero }; 1551 1552 // If we don't already have it, get __CFConstantStringClassReference. 1553 if (!CFConstantStringClassRef) { 1554 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1555 Ty = llvm::ArrayType::get(Ty, 0); 1556 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1557 "__CFConstantStringClassReference"); 1558 // Decay array -> ptr 1559 CFConstantStringClassRef = 1560 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1561 } 1562 1563 QualType CFTy = getContext().getCFConstantStringType(); 1564 1565 const llvm::StructType *STy = 1566 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1567 1568 std::vector<llvm::Constant*> Fields(4); 1569 1570 // Class pointer. 1571 Fields[0] = CFConstantStringClassRef; 1572 1573 // Flags. 1574 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1575 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1576 llvm::ConstantInt::get(Ty, 0x07C8); 1577 1578 // String pointer. 1579 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1580 1581 llvm::GlobalValue::LinkageTypes Linkage; 1582 bool isConstant; 1583 if (isUTF16) { 1584 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1585 Linkage = llvm::GlobalValue::InternalLinkage; 1586 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1587 // does make plain ascii ones writable. 1588 isConstant = true; 1589 } else { 1590 Linkage = llvm::GlobalValue::PrivateLinkage; 1591 isConstant = !Features.WritableStrings; 1592 } 1593 1594 llvm::GlobalVariable *GV = 1595 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1596 ".str"); 1597 if (isUTF16) { 1598 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1599 GV->setAlignment(Align.getQuantity()); 1600 } 1601 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1602 1603 // String length. 1604 Ty = getTypes().ConvertType(getContext().LongTy); 1605 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1606 1607 // The struct. 1608 C = llvm::ConstantStruct::get(STy, Fields); 1609 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1610 llvm::GlobalVariable::PrivateLinkage, C, 1611 "_unnamed_cfstring_"); 1612 if (const char *Sect = getContext().Target.getCFStringSection()) 1613 GV->setSection(Sect); 1614 Entry.setValue(GV); 1615 1616 return GV; 1617 } 1618 1619 llvm::Constant * 1620 CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) { 1621 unsigned StringLength = 0; 1622 bool isUTF16 = false; 1623 llvm::StringMapEntry<llvm::Constant*> &Entry = 1624 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1625 getTargetData().isLittleEndian(), 1626 isUTF16, StringLength); 1627 1628 if (llvm::Constant *C = Entry.getValue()) 1629 return C; 1630 1631 llvm::Constant *Zero = 1632 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1633 llvm::Constant *Zeros[] = { Zero, Zero }; 1634 1635 // If we don't already have it, get _NSConstantStringClassReference. 1636 if (!NSConstantStringClassRef) { 1637 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1638 Ty = llvm::ArrayType::get(Ty, 0); 1639 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1640 Features.ObjCNonFragileABI ? 1641 "OBJC_CLASS_$_NSConstantString" : 1642 "_NSConstantStringClassReference"); 1643 // Decay array -> ptr 1644 NSConstantStringClassRef = 1645 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1646 } 1647 1648 QualType NSTy = getContext().getNSConstantStringType(); 1649 1650 const llvm::StructType *STy = 1651 cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 1652 1653 std::vector<llvm::Constant*> Fields(3); 1654 1655 // Class pointer. 1656 Fields[0] = NSConstantStringClassRef; 1657 1658 // String pointer. 1659 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1660 1661 llvm::GlobalValue::LinkageTypes Linkage; 1662 bool isConstant; 1663 if (isUTF16) { 1664 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1665 Linkage = llvm::GlobalValue::InternalLinkage; 1666 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but 1667 // does make plain ascii ones writable. 1668 isConstant = true; 1669 } else { 1670 Linkage = llvm::GlobalValue::PrivateLinkage; 1671 isConstant = !Features.WritableStrings; 1672 } 1673 1674 llvm::GlobalVariable *GV = 1675 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1676 ".str"); 1677 if (isUTF16) { 1678 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1679 GV->setAlignment(Align.getQuantity()); 1680 } 1681 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1682 1683 // String length. 1684 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1685 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 1686 1687 // The struct. 1688 C = llvm::ConstantStruct::get(STy, Fields); 1689 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1690 llvm::GlobalVariable::PrivateLinkage, C, 1691 "_unnamed_nsstring_"); 1692 // FIXME. Fix section. 1693 if (const char *Sect = 1694 Features.ObjCNonFragileABI 1695 ? getContext().Target.getNSStringNonFragileABISection() 1696 : getContext().Target.getNSStringSection()) 1697 GV->setSection(Sect); 1698 Entry.setValue(GV); 1699 1700 return GV; 1701 } 1702 1703 /// GetStringForStringLiteral - Return the appropriate bytes for a 1704 /// string literal, properly padded to match the literal type. 1705 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1706 const ConstantArrayType *CAT = 1707 getContext().getAsConstantArrayType(E->getType()); 1708 assert(CAT && "String isn't pointer or array!"); 1709 1710 // Resize the string to the right size. 1711 uint64_t RealLen = CAT->getSize().getZExtValue(); 1712 1713 if (E->isWide()) 1714 RealLen *= getContext().Target.getWCharWidth()/8; 1715 1716 std::string Str = E->getString().str(); 1717 Str.resize(RealLen, '\0'); 1718 1719 return Str; 1720 } 1721 1722 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1723 /// constant array for the given string literal. 1724 llvm::Constant * 1725 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1726 // FIXME: This can be more efficient. 1727 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1728 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1729 if (S->isWide()) { 1730 llvm::Type *DestTy = 1731 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1732 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1733 } 1734 return C; 1735 } 1736 1737 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1738 /// array for the given ObjCEncodeExpr node. 1739 llvm::Constant * 1740 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1741 std::string Str; 1742 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1743 1744 return GetAddrOfConstantCString(Str); 1745 } 1746 1747 1748 /// GenerateWritableString -- Creates storage for a string literal. 1749 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1750 bool constant, 1751 CodeGenModule &CGM, 1752 const char *GlobalName) { 1753 // Create Constant for this string literal. Don't add a '\0'. 1754 llvm::Constant *C = 1755 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1756 1757 // Create a global variable for this string 1758 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1759 llvm::GlobalValue::PrivateLinkage, 1760 C, GlobalName); 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