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