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