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