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