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