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