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 VMContext(M.getContext()) { 54 55 if (!Features.ObjC1) 56 Runtime = 0; 57 else if (!Features.NeXTRuntime) 58 Runtime = CreateGNUObjCRuntime(*this); 59 else if (Features.ObjCNonFragileABI) 60 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 61 else 62 Runtime = CreateMacObjCRuntime(*this); 63 64 // If debug info generation is enabled, create the CGDebugInfo object. 65 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0; 66 } 67 68 CodeGenModule::~CodeGenModule() { 69 delete Runtime; 70 delete DebugInfo; 71 } 72 73 void CodeGenModule::createObjCRuntime() { 74 if (!Features.NeXTRuntime) 75 Runtime = CreateGNUObjCRuntime(*this); 76 else if (Features.ObjCNonFragileABI) 77 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 78 else 79 Runtime = CreateMacObjCRuntime(*this); 80 } 81 82 void CodeGenModule::Release() { 83 EmitDeferred(); 84 EmitCXXGlobalInitFunc(); 85 EmitCXXGlobalDtorFunc(); 86 if (Runtime) 87 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 88 AddGlobalCtor(ObjCInitFunction); 89 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 90 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 91 EmitAnnotations(); 92 EmitLLVMUsed(); 93 } 94 95 bool CodeGenModule::isTargetDarwin() const { 96 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin; 97 } 98 99 /// ErrorUnsupported - Print out an error that codegen doesn't support the 100 /// specified stmt yet. 101 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 102 bool OmitOnError) { 103 if (OmitOnError && getDiags().hasErrorOccurred()) 104 return; 105 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 106 "cannot compile this %0 yet"); 107 std::string Msg = Type; 108 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 109 << Msg << S->getSourceRange(); 110 } 111 112 /// ErrorUnsupported - Print out an error that codegen doesn't support the 113 /// specified decl yet. 114 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 115 bool OmitOnError) { 116 if (OmitOnError && getDiags().hasErrorOccurred()) 117 return; 118 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 119 "cannot compile this %0 yet"); 120 std::string Msg = Type; 121 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 122 } 123 124 LangOptions::VisibilityMode 125 CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 126 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 127 if (VD->getStorageClass() == VarDecl::PrivateExtern) 128 return LangOptions::Hidden; 129 130 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 131 switch (attr->getVisibility()) { 132 default: assert(0 && "Unknown visibility!"); 133 case VisibilityAttr::DefaultVisibility: 134 return LangOptions::Default; 135 case VisibilityAttr::HiddenVisibility: 136 return LangOptions::Hidden; 137 case VisibilityAttr::ProtectedVisibility: 138 return LangOptions::Protected; 139 } 140 } 141 142 // This decl should have the same visibility as its parent. 143 if (const DeclContext *DC = D->getDeclContext()) 144 return getDeclVisibilityMode(cast<Decl>(DC)); 145 146 return getLangOptions().getVisibilityMode(); 147 } 148 149 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 150 const Decl *D) const { 151 // Internal definitions always have default visibility. 152 if (GV->hasLocalLinkage()) { 153 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 154 return; 155 } 156 157 switch (getDeclVisibilityMode(D)) { 158 default: assert(0 && "Unknown visibility!"); 159 case LangOptions::Default: 160 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 161 case LangOptions::Hidden: 162 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 163 case LangOptions::Protected: 164 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 165 } 166 } 167 168 void CodeGenModule::getMangledName(MangleBuffer &Buffer, GlobalDecl GD) { 169 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 170 171 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 172 return getMangledCXXCtorName(Buffer, D, GD.getCtorType()); 173 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 174 return getMangledCXXDtorName(Buffer, D, GD.getDtorType()); 175 176 return getMangledName(Buffer, ND); 177 } 178 179 /// \brief Retrieves the mangled name for the given declaration. 180 /// 181 /// If the given declaration requires a mangled name, returns an 182 /// const char* containing the mangled name. Otherwise, returns 183 /// the unmangled name. 184 /// 185 void CodeGenModule::getMangledName(MangleBuffer &Buffer, 186 const NamedDecl *ND) { 187 if (!getMangleContext().shouldMangleDeclName(ND)) { 188 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 189 Buffer.setString(ND->getNameAsCString()); 190 return; 191 } 192 193 getMangleContext().mangleName(ND, Buffer.getBuffer()); 194 } 195 196 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) { 197 return getModule().getNamedValue(Name); 198 } 199 200 /// AddGlobalCtor - Add a function to the list that will be called before 201 /// main() runs. 202 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 203 // FIXME: Type coercion of void()* types. 204 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 205 } 206 207 /// AddGlobalDtor - Add a function to the list that will be called 208 /// when the module is unloaded. 209 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 210 // FIXME: Type coercion of void()* types. 211 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 212 } 213 214 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 215 // Ctor function type is void()*. 216 llvm::FunctionType* CtorFTy = 217 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 218 std::vector<const llvm::Type*>(), 219 false); 220 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 221 222 // Get the type of a ctor entry, { i32, void ()* }. 223 llvm::StructType* CtorStructTy = 224 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 225 llvm::PointerType::getUnqual(CtorFTy), NULL); 226 227 // Construct the constructor and destructor arrays. 228 std::vector<llvm::Constant*> Ctors; 229 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 230 std::vector<llvm::Constant*> S; 231 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 232 I->second, false)); 233 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 234 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 235 } 236 237 if (!Ctors.empty()) { 238 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 239 new llvm::GlobalVariable(TheModule, AT, false, 240 llvm::GlobalValue::AppendingLinkage, 241 llvm::ConstantArray::get(AT, Ctors), 242 GlobalName); 243 } 244 } 245 246 void CodeGenModule::EmitAnnotations() { 247 if (Annotations.empty()) 248 return; 249 250 // Create a new global variable for the ConstantStruct in the Module. 251 llvm::Constant *Array = 252 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 253 Annotations.size()), 254 Annotations); 255 llvm::GlobalValue *gv = 256 new llvm::GlobalVariable(TheModule, Array->getType(), false, 257 llvm::GlobalValue::AppendingLinkage, Array, 258 "llvm.global.annotations"); 259 gv->setSection("llvm.metadata"); 260 } 261 262 static CodeGenModule::GVALinkage 263 GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, 264 const LangOptions &Features) { 265 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; 266 267 Linkage L = FD->getLinkage(); 268 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 269 FD->getType()->getLinkage() == UniqueExternalLinkage) 270 L = UniqueExternalLinkage; 271 272 switch (L) { 273 case NoLinkage: 274 case InternalLinkage: 275 case UniqueExternalLinkage: 276 return CodeGenModule::GVA_Internal; 277 278 case ExternalLinkage: 279 switch (FD->getTemplateSpecializationKind()) { 280 case TSK_Undeclared: 281 case TSK_ExplicitSpecialization: 282 External = CodeGenModule::GVA_StrongExternal; 283 break; 284 285 case TSK_ExplicitInstantiationDefinition: 286 return CodeGenModule::GVA_ExplicitTemplateInstantiation; 287 288 case TSK_ExplicitInstantiationDeclaration: 289 case TSK_ImplicitInstantiation: 290 External = CodeGenModule::GVA_TemplateInstantiation; 291 break; 292 } 293 } 294 295 if (!FD->isInlined()) 296 return External; 297 298 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 299 // GNU or C99 inline semantics. Determine whether this symbol should be 300 // externally visible. 301 if (FD->isInlineDefinitionExternallyVisible()) 302 return External; 303 304 // C99 inline semantics, where the symbol is not externally visible. 305 return CodeGenModule::GVA_C99Inline; 306 } 307 308 // C++0x [temp.explicit]p9: 309 // [ Note: The intent is that an inline function that is the subject of 310 // an explicit instantiation declaration will still be implicitly 311 // instantiated when used so that the body can be considered for 312 // inlining, but that no out-of-line copy of the inline function would be 313 // generated in the translation unit. -- end note ] 314 if (FD->getTemplateSpecializationKind() 315 == TSK_ExplicitInstantiationDeclaration) 316 return CodeGenModule::GVA_C99Inline; 317 318 return CodeGenModule::GVA_CXXInline; 319 } 320 321 llvm::GlobalValue::LinkageTypes 322 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 323 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features); 324 325 if (Linkage == GVA_Internal) { 326 return llvm::Function::InternalLinkage; 327 } else if (D->hasAttr<DLLExportAttr>()) { 328 return llvm::Function::DLLExportLinkage; 329 } else if (D->hasAttr<WeakAttr>()) { 330 return llvm::Function::WeakAnyLinkage; 331 } else if (Linkage == GVA_C99Inline) { 332 // In C99 mode, 'inline' functions are guaranteed to have a strong 333 // definition somewhere else, so we can use available_externally linkage. 334 return llvm::Function::AvailableExternallyLinkage; 335 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) { 336 // In C++, the compiler has to emit a definition in every translation unit 337 // that references the function. We should use linkonce_odr because 338 // a) if all references in this translation unit are optimized away, we 339 // don't need to codegen it. b) if the function persists, it needs to be 340 // merged with other definitions. c) C++ has the ODR, so we know the 341 // definition is dependable. 342 return llvm::Function::LinkOnceODRLinkage; 343 } else if (Linkage == GVA_ExplicitTemplateInstantiation) { 344 // An explicit instantiation of a template has weak linkage, since 345 // explicit instantiations can occur in multiple translation units 346 // and must all be equivalent. However, we are not allowed to 347 // throw away these explicit instantiations. 348 return llvm::Function::WeakODRLinkage; 349 } else { 350 assert(Linkage == GVA_StrongExternal); 351 // Otherwise, we have strong external linkage. 352 return llvm::Function::ExternalLinkage; 353 } 354 } 355 356 357 /// SetFunctionDefinitionAttributes - Set attributes for a global. 358 /// 359 /// FIXME: This is currently only done for aliases and functions, but not for 360 /// variables (these details are set in EmitGlobalVarDefinition for variables). 361 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 362 llvm::GlobalValue *GV) { 363 GV->setLinkage(getFunctionLinkage(D)); 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 // If the value has already been used, add it directly to the 693 // DeferredDeclsToEmit list. 694 MangleBuffer MangledName; 695 getMangledName(MangledName, GD); 696 if (GetGlobalValue(MangledName)) 697 DeferredDeclsToEmit.push_back(GD); 698 else { 699 // Otherwise, remember that we saw a deferred decl with this name. The 700 // first use of the mangled name will cause it to move into 701 // DeferredDeclsToEmit. 702 DeferredDecls[MangledName] = GD; 703 } 704 return; 705 } 706 707 // Otherwise emit the definition. 708 EmitGlobalDefinition(GD); 709 } 710 711 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 712 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 713 714 PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(), 715 Context.getSourceManager(), 716 "Generating code for declaration"); 717 718 if (isa<CXXMethodDecl>(D)) 719 getVTables().EmitVTableRelatedData(GD); 720 721 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 722 EmitCXXConstructor(CD, GD.getCtorType()); 723 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 724 EmitCXXDestructor(DD, GD.getDtorType()); 725 else if (isa<FunctionDecl>(D)) 726 EmitGlobalFunctionDefinition(GD); 727 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 728 EmitGlobalVarDefinition(VD); 729 else { 730 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 731 } 732 } 733 734 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 735 /// module, create and return an llvm Function with the specified type. If there 736 /// is something in the module with the specified name, return it potentially 737 /// bitcasted to the right type. 738 /// 739 /// If D is non-null, it specifies a decl that correspond to this. This is used 740 /// to set the attributes on the function when it is first created. 741 llvm::Constant * 742 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName, 743 const llvm::Type *Ty, 744 GlobalDecl D) { 745 // Lookup the entry, lazily creating it if necessary. 746 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 747 if (Entry) { 748 if (WeakRefReferences.count(Entry)) { 749 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 750 if (FD && !FD->hasAttr<WeakAttr>()) 751 Entry->setLinkage(llvm::Function::ExternalLinkage); 752 753 WeakRefReferences.erase(Entry); 754 } 755 756 if (Entry->getType()->getElementType() == Ty) 757 return Entry; 758 759 // Make sure the result is of the correct type. 760 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 761 return llvm::ConstantExpr::getBitCast(Entry, PTy); 762 } 763 764 // This function doesn't have a complete type (for example, the return 765 // type is an incomplete struct). Use a fake type instead, and make 766 // sure not to try to set attributes. 767 bool IsIncompleteFunction = false; 768 if (!isa<llvm::FunctionType>(Ty)) { 769 Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 770 std::vector<const llvm::Type*>(), false); 771 IsIncompleteFunction = true; 772 } 773 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 774 llvm::Function::ExternalLinkage, 775 MangledName, &getModule()); 776 assert(F->getName() == MangledName && "name was uniqued!"); 777 if (D.getDecl()) 778 SetFunctionAttributes(D, F, IsIncompleteFunction); 779 780 // This is the first use or definition of a mangled name. If there is a 781 // deferred decl with this name, remember that we need to emit it at the end 782 // of the file. 783 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 784 if (DDI != DeferredDecls.end()) { 785 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 786 // list, and remove it from DeferredDecls (since we don't need it anymore). 787 DeferredDeclsToEmit.push_back(DDI->second); 788 DeferredDecls.erase(DDI); 789 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 790 // If this the first reference to a C++ inline function in a class, queue up 791 // the deferred function body for emission. These are not seen as 792 // top-level declarations. 793 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 794 DeferredDeclsToEmit.push_back(D); 795 // A called constructor which has no definition or declaration need be 796 // synthesized. 797 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 798 if (CD->isImplicit()) { 799 assert(CD->isUsed() && "Sema doesn't consider constructor as used."); 800 DeferredDeclsToEmit.push_back(D); 801 } 802 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 803 if (DD->isImplicit()) { 804 assert(DD->isUsed() && "Sema doesn't consider destructor as used."); 805 DeferredDeclsToEmit.push_back(D); 806 } 807 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 808 if (MD->isCopyAssignment() && MD->isImplicit()) { 809 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used."); 810 DeferredDeclsToEmit.push_back(D); 811 } 812 } 813 } 814 815 return F; 816 } 817 818 /// GetAddrOfFunction - Return the address of the given function. If Ty is 819 /// non-null, then this function will use the specified type if it has to 820 /// create it (this occurs when we see a definition of the function). 821 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 822 const llvm::Type *Ty) { 823 // If there was no specific requested type, just convert it now. 824 if (!Ty) 825 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 826 MangleBuffer MangledName; 827 getMangledName(MangledName, GD); 828 return GetOrCreateLLVMFunction(MangledName, Ty, GD); 829 } 830 831 /// CreateRuntimeFunction - Create a new runtime function with the specified 832 /// type and name. 833 llvm::Constant * 834 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 835 llvm::StringRef Name) { 836 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 837 } 838 839 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) { 840 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 841 return false; 842 if (Context.getLangOptions().CPlusPlus && 843 Context.getBaseElementType(D->getType())->getAs<RecordType>()) { 844 // FIXME: We should do something fancier here! 845 return false; 846 } 847 return true; 848 } 849 850 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 851 /// create and return an llvm GlobalVariable with the specified type. If there 852 /// is something in the module with the specified name, return it potentially 853 /// bitcasted to the right type. 854 /// 855 /// If D is non-null, it specifies a decl that correspond to this. This is used 856 /// to set the attributes on the global when it is first created. 857 llvm::Constant * 858 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName, 859 const llvm::PointerType *Ty, 860 const VarDecl *D) { 861 // Lookup the entry, lazily creating it if necessary. 862 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 863 if (Entry) { 864 if (WeakRefReferences.count(Entry)) { 865 if (D && !D->hasAttr<WeakAttr>()) 866 Entry->setLinkage(llvm::Function::ExternalLinkage); 867 868 WeakRefReferences.erase(Entry); 869 } 870 871 if (Entry->getType() == Ty) 872 return Entry; 873 874 // Make sure the result is of the correct type. 875 return llvm::ConstantExpr::getBitCast(Entry, Ty); 876 } 877 878 // This is the first use or definition of a mangled name. If there is a 879 // deferred decl with this name, remember that we need to emit it at the end 880 // of the file. 881 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 882 if (DDI != DeferredDecls.end()) { 883 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 884 // list, and remove it from DeferredDecls (since we don't need it anymore). 885 DeferredDeclsToEmit.push_back(DDI->second); 886 DeferredDecls.erase(DDI); 887 } 888 889 llvm::GlobalVariable *GV = 890 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 891 llvm::GlobalValue::ExternalLinkage, 892 0, MangledName, 0, 893 false, Ty->getAddressSpace()); 894 895 // Handle things which are present even on external declarations. 896 if (D) { 897 // FIXME: This code is overly simple and should be merged with other global 898 // handling. 899 GV->setConstant(DeclIsConstantGlobal(Context, D)); 900 901 // FIXME: Merge with other attribute handling code. 902 if (D->getStorageClass() == VarDecl::PrivateExtern) 903 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 904 905 if (D->hasAttr<WeakAttr>() || 906 D->hasAttr<WeakImportAttr>()) 907 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 908 909 GV->setThreadLocal(D->isThreadSpecified()); 910 } 911 912 return GV; 913 } 914 915 916 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 917 /// given global variable. If Ty is non-null and if the global doesn't exist, 918 /// then it will be greated with the specified type instead of whatever the 919 /// normal requested type would be. 920 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 921 const llvm::Type *Ty) { 922 assert(D->hasGlobalStorage() && "Not a global variable"); 923 QualType ASTTy = D->getType(); 924 if (Ty == 0) 925 Ty = getTypes().ConvertTypeForMem(ASTTy); 926 927 const llvm::PointerType *PTy = 928 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 929 930 MangleBuffer MangledName; 931 getMangledName(MangledName, D); 932 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 933 } 934 935 /// CreateRuntimeVariable - Create a new runtime global variable with the 936 /// specified type and name. 937 llvm::Constant * 938 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 939 llvm::StringRef Name) { 940 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 941 } 942 943 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 944 assert(!D->getInit() && "Cannot emit definite definitions here!"); 945 946 if (MayDeferGeneration(D)) { 947 // If we have not seen a reference to this variable yet, place it 948 // into the deferred declarations table to be emitted if needed 949 // later. 950 MangleBuffer MangledName; 951 getMangledName(MangledName, D); 952 if (!GetGlobalValue(MangledName)) { 953 DeferredDecls[MangledName] = D; 954 return; 955 } 956 } 957 958 // The tentative definition is the only definition. 959 EmitGlobalVarDefinition(D); 960 } 961 962 llvm::GlobalVariable::LinkageTypes 963 CodeGenModule::getVtableLinkage(const CXXRecordDecl *RD) { 964 if (RD->isInAnonymousNamespace() || !RD->hasLinkage()) 965 return llvm::GlobalVariable::InternalLinkage; 966 967 if (const CXXMethodDecl *KeyFunction 968 = RD->getASTContext().getKeyFunction(RD)) { 969 // If this class has a key function, use that to determine the linkage of 970 // the vtable. 971 const FunctionDecl *Def = 0; 972 if (KeyFunction->getBody(Def)) 973 KeyFunction = cast<CXXMethodDecl>(Def); 974 975 switch (KeyFunction->getTemplateSpecializationKind()) { 976 case TSK_Undeclared: 977 case TSK_ExplicitSpecialization: 978 if (KeyFunction->isInlined()) 979 return llvm::GlobalVariable::WeakODRLinkage; 980 981 return llvm::GlobalVariable::ExternalLinkage; 982 983 case TSK_ImplicitInstantiation: 984 case TSK_ExplicitInstantiationDefinition: 985 return llvm::GlobalVariable::WeakODRLinkage; 986 987 case TSK_ExplicitInstantiationDeclaration: 988 // FIXME: Use available_externally linkage. However, this currently 989 // breaks LLVM's build due to undefined symbols. 990 // return llvm::GlobalVariable::AvailableExternallyLinkage; 991 return llvm::GlobalVariable::WeakODRLinkage; 992 } 993 } 994 995 switch (RD->getTemplateSpecializationKind()) { 996 case TSK_Undeclared: 997 case TSK_ExplicitSpecialization: 998 case TSK_ImplicitInstantiation: 999 case TSK_ExplicitInstantiationDefinition: 1000 return llvm::GlobalVariable::WeakODRLinkage; 1001 1002 case TSK_ExplicitInstantiationDeclaration: 1003 // FIXME: Use available_externally linkage. However, this currently 1004 // breaks LLVM's build due to undefined symbols. 1005 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1006 return llvm::GlobalVariable::WeakODRLinkage; 1007 } 1008 1009 // Silence GCC warning. 1010 return llvm::GlobalVariable::WeakODRLinkage; 1011 } 1012 1013 static CodeGenModule::GVALinkage 1014 GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) { 1015 // If this is a static data member, compute the kind of template 1016 // specialization. Otherwise, this variable is not part of a 1017 // template. 1018 TemplateSpecializationKind TSK = TSK_Undeclared; 1019 if (VD->isStaticDataMember()) 1020 TSK = VD->getTemplateSpecializationKind(); 1021 1022 Linkage L = VD->getLinkage(); 1023 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 1024 VD->getType()->getLinkage() == UniqueExternalLinkage) 1025 L = UniqueExternalLinkage; 1026 1027 switch (L) { 1028 case NoLinkage: 1029 case InternalLinkage: 1030 case UniqueExternalLinkage: 1031 return CodeGenModule::GVA_Internal; 1032 1033 case ExternalLinkage: 1034 switch (TSK) { 1035 case TSK_Undeclared: 1036 case TSK_ExplicitSpecialization: 1037 return CodeGenModule::GVA_StrongExternal; 1038 1039 case TSK_ExplicitInstantiationDeclaration: 1040 llvm_unreachable("Variable should not be instantiated"); 1041 // Fall through to treat this like any other instantiation. 1042 1043 case TSK_ExplicitInstantiationDefinition: 1044 return CodeGenModule::GVA_ExplicitTemplateInstantiation; 1045 1046 case TSK_ImplicitInstantiation: 1047 return CodeGenModule::GVA_TemplateInstantiation; 1048 } 1049 } 1050 1051 return CodeGenModule::GVA_StrongExternal; 1052 } 1053 1054 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1055 return CharUnits::fromQuantity( 1056 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth()); 1057 } 1058 1059 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1060 llvm::Constant *Init = 0; 1061 QualType ASTTy = D->getType(); 1062 bool NonConstInit = false; 1063 1064 const Expr *InitExpr = D->getAnyInitializer(); 1065 1066 if (!InitExpr) { 1067 // This is a tentative definition; tentative definitions are 1068 // implicitly initialized with { 0 }. 1069 // 1070 // Note that tentative definitions are only emitted at the end of 1071 // a translation unit, so they should never have incomplete 1072 // type. In addition, EmitTentativeDefinition makes sure that we 1073 // never attempt to emit a tentative definition if a real one 1074 // exists. A use may still exists, however, so we still may need 1075 // to do a RAUW. 1076 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1077 Init = EmitNullConstant(D->getType()); 1078 } else { 1079 Init = EmitConstantExpr(InitExpr, D->getType()); 1080 1081 if (!Init) { 1082 QualType T = InitExpr->getType(); 1083 if (getLangOptions().CPlusPlus) { 1084 EmitCXXGlobalVarDeclInitFunc(D); 1085 Init = EmitNullConstant(T); 1086 NonConstInit = true; 1087 } else { 1088 ErrorUnsupported(D, "static initializer"); 1089 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1090 } 1091 } 1092 } 1093 1094 const llvm::Type* InitType = Init->getType(); 1095 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1096 1097 // Strip off a bitcast if we got one back. 1098 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1099 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1100 // all zero index gep. 1101 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1102 Entry = CE->getOperand(0); 1103 } 1104 1105 // Entry is now either a Function or GlobalVariable. 1106 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1107 1108 // We have a definition after a declaration with the wrong type. 1109 // We must make a new GlobalVariable* and update everything that used OldGV 1110 // (a declaration or tentative definition) with the new GlobalVariable* 1111 // (which will be a definition). 1112 // 1113 // This happens if there is a prototype for a global (e.g. 1114 // "extern int x[];") and then a definition of a different type (e.g. 1115 // "int x[10];"). This also happens when an initializer has a different type 1116 // from the type of the global (this happens with unions). 1117 if (GV == 0 || 1118 GV->getType()->getElementType() != InitType || 1119 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1120 1121 // Move the old entry aside so that we'll create a new one. 1122 Entry->setName(llvm::StringRef()); 1123 1124 // Make a new global with the correct type, this is now guaranteed to work. 1125 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1126 1127 // Replace all uses of the old global with the new global 1128 llvm::Constant *NewPtrForOldDecl = 1129 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1130 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1131 1132 // Erase the old global, since it is no longer used. 1133 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1134 } 1135 1136 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1137 SourceManager &SM = Context.getSourceManager(); 1138 AddAnnotation(EmitAnnotateAttr(GV, AA, 1139 SM.getInstantiationLineNumber(D->getLocation()))); 1140 } 1141 1142 GV->setInitializer(Init); 1143 1144 // If it is safe to mark the global 'constant', do so now. 1145 GV->setConstant(false); 1146 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1147 GV->setConstant(true); 1148 1149 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1150 1151 // Set the llvm linkage type as appropriate. 1152 GVALinkage Linkage = GetLinkageForVariable(getContext(), D); 1153 if (Linkage == GVA_Internal) 1154 GV->setLinkage(llvm::Function::InternalLinkage); 1155 else if (D->hasAttr<DLLImportAttr>()) 1156 GV->setLinkage(llvm::Function::DLLImportLinkage); 1157 else if (D->hasAttr<DLLExportAttr>()) 1158 GV->setLinkage(llvm::Function::DLLExportLinkage); 1159 else if (D->hasAttr<WeakAttr>()) { 1160 if (GV->isConstant()) 1161 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1162 else 1163 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1164 } else if (Linkage == GVA_TemplateInstantiation || 1165 Linkage == GVA_ExplicitTemplateInstantiation) 1166 // FIXME: It seems like we can provide more specific linkage here 1167 // (LinkOnceODR, WeakODR). 1168 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1169 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon && 1170 !D->hasExternalStorage() && !D->getInit() && 1171 !D->getAttr<SectionAttr>()) { 1172 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1173 // common vars aren't constant even if declared const. 1174 GV->setConstant(false); 1175 } else 1176 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1177 1178 SetCommonAttributes(D, GV); 1179 1180 // Emit global variable debug information. 1181 if (CGDebugInfo *DI = getDebugInfo()) { 1182 DI->setLocation(D->getLocation()); 1183 DI->EmitGlobalVariable(GV, D); 1184 } 1185 } 1186 1187 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1188 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1189 /// existing call uses of the old function in the module, this adjusts them to 1190 /// call the new function directly. 1191 /// 1192 /// This is not just a cleanup: the always_inline pass requires direct calls to 1193 /// functions to be able to inline them. If there is a bitcast in the way, it 1194 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1195 /// run at -O0. 1196 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1197 llvm::Function *NewFn) { 1198 // If we're redefining a global as a function, don't transform it. 1199 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1200 if (OldFn == 0) return; 1201 1202 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1203 llvm::SmallVector<llvm::Value*, 4> ArgList; 1204 1205 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1206 UI != E; ++UI) { 1207 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1208 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI); 1209 llvm::CallSite CS(CI); 1210 if (!CI || !CS.isCallee(UI)) continue; 1211 1212 // If the return types don't match exactly, and if the call isn't dead, then 1213 // we can't transform this call. 1214 if (CI->getType() != NewRetTy && !CI->use_empty()) 1215 continue; 1216 1217 // If the function was passed too few arguments, don't transform. If extra 1218 // arguments were passed, we silently drop them. If any of the types 1219 // mismatch, we don't transform. 1220 unsigned ArgNo = 0; 1221 bool DontTransform = false; 1222 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1223 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1224 if (CS.arg_size() == ArgNo || 1225 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1226 DontTransform = true; 1227 break; 1228 } 1229 } 1230 if (DontTransform) 1231 continue; 1232 1233 // Okay, we can transform this. Create the new call instruction and copy 1234 // over the required information. 1235 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1236 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1237 ArgList.end(), "", CI); 1238 ArgList.clear(); 1239 if (!NewCall->getType()->isVoidTy()) 1240 NewCall->takeName(CI); 1241 NewCall->setAttributes(CI->getAttributes()); 1242 NewCall->setCallingConv(CI->getCallingConv()); 1243 1244 // Finally, remove the old call, replacing any uses with the new one. 1245 if (!CI->use_empty()) 1246 CI->replaceAllUsesWith(NewCall); 1247 1248 // Copy debug location attached to CI. 1249 if (!CI->getDebugLoc().isUnknown()) 1250 NewCall->setDebugLoc(CI->getDebugLoc()); 1251 CI->eraseFromParent(); 1252 } 1253 } 1254 1255 1256 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1257 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1258 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1259 getMangleContext().mangleInitDiscriminator(); 1260 // Get or create the prototype for the function. 1261 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1262 1263 // Strip off a bitcast if we got one back. 1264 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1265 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1266 Entry = CE->getOperand(0); 1267 } 1268 1269 1270 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1271 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1272 1273 // If the types mismatch then we have to rewrite the definition. 1274 assert(OldFn->isDeclaration() && 1275 "Shouldn't replace non-declaration"); 1276 1277 // F is the Function* for the one with the wrong type, we must make a new 1278 // Function* and update everything that used F (a declaration) with the new 1279 // Function* (which will be a definition). 1280 // 1281 // This happens if there is a prototype for a function 1282 // (e.g. "int f()") and then a definition of a different type 1283 // (e.g. "int f(int x)"). Move the old function aside so that it 1284 // doesn't interfere with GetAddrOfFunction. 1285 OldFn->setName(llvm::StringRef()); 1286 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1287 1288 // If this is an implementation of a function without a prototype, try to 1289 // replace any existing uses of the function (which may be calls) with uses 1290 // of the new function 1291 if (D->getType()->isFunctionNoProtoType()) { 1292 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1293 OldFn->removeDeadConstantUsers(); 1294 } 1295 1296 // Replace uses of F with the Function we will endow with a body. 1297 if (!Entry->use_empty()) { 1298 llvm::Constant *NewPtrForOldDecl = 1299 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1300 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1301 } 1302 1303 // Ok, delete the old function now, which is dead. 1304 OldFn->eraseFromParent(); 1305 1306 Entry = NewFn; 1307 } 1308 1309 llvm::Function *Fn = cast<llvm::Function>(Entry); 1310 1311 CodeGenFunction(*this).GenerateCode(D, Fn); 1312 1313 SetFunctionDefinitionAttributes(D, Fn); 1314 SetLLVMFunctionAttributesForDefinition(D, Fn); 1315 1316 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1317 AddGlobalCtor(Fn, CA->getPriority()); 1318 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1319 AddGlobalDtor(Fn, DA->getPriority()); 1320 } 1321 1322 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1323 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1324 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1325 assert(AA && "Not an alias?"); 1326 1327 MangleBuffer MangledName; 1328 getMangledName(MangledName, GD); 1329 1330 // If there is a definition in the module, then it wins over the alias. 1331 // This is dubious, but allow it to be safe. Just ignore the alias. 1332 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1333 if (Entry && !Entry->isDeclaration()) 1334 return; 1335 1336 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1337 1338 // Create a reference to the named value. This ensures that it is emitted 1339 // if a deferred decl. 1340 llvm::Constant *Aliasee; 1341 if (isa<llvm::FunctionType>(DeclTy)) 1342 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 1343 else 1344 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1345 llvm::PointerType::getUnqual(DeclTy), 0); 1346 1347 // Create the new alias itself, but don't set a name yet. 1348 llvm::GlobalValue *GA = 1349 new llvm::GlobalAlias(Aliasee->getType(), 1350 llvm::Function::ExternalLinkage, 1351 "", Aliasee, &getModule()); 1352 1353 if (Entry) { 1354 assert(Entry->isDeclaration()); 1355 1356 // If there is a declaration in the module, then we had an extern followed 1357 // by the alias, as in: 1358 // extern int test6(); 1359 // ... 1360 // int test6() __attribute__((alias("test7"))); 1361 // 1362 // Remove it and replace uses of it with the alias. 1363 GA->takeName(Entry); 1364 1365 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1366 Entry->getType())); 1367 Entry->eraseFromParent(); 1368 } else { 1369 GA->setName(MangledName.getString()); 1370 } 1371 1372 // Set attributes which are particular to an alias; this is a 1373 // specialization of the attributes which may be set on a global 1374 // variable/function. 1375 if (D->hasAttr<DLLExportAttr>()) { 1376 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1377 // The dllexport attribute is ignored for undefined symbols. 1378 if (FD->getBody()) 1379 GA->setLinkage(llvm::Function::DLLExportLinkage); 1380 } else { 1381 GA->setLinkage(llvm::Function::DLLExportLinkage); 1382 } 1383 } else if (D->hasAttr<WeakAttr>() || 1384 D->hasAttr<WeakRefAttr>() || 1385 D->hasAttr<WeakImportAttr>()) { 1386 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1387 } 1388 1389 SetCommonAttributes(D, GA); 1390 } 1391 1392 /// getBuiltinLibFunction - Given a builtin id for a function like 1393 /// "__builtin_fabsf", return a Function* for "fabsf". 1394 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1395 unsigned BuiltinID) { 1396 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1397 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1398 "isn't a lib fn"); 1399 1400 // Get the name, skip over the __builtin_ prefix (if necessary). 1401 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1402 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1403 Name += 10; 1404 1405 const llvm::FunctionType *Ty = 1406 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1407 1408 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1409 } 1410 1411 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1412 unsigned NumTys) { 1413 return llvm::Intrinsic::getDeclaration(&getModule(), 1414 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1415 } 1416 1417 1418 llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType, 1419 const llvm::Type *SrcType, 1420 const llvm::Type *SizeType) { 1421 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1422 return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3); 1423 } 1424 1425 llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType, 1426 const llvm::Type *SrcType, 1427 const llvm::Type *SizeType) { 1428 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1429 return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3); 1430 } 1431 1432 llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType, 1433 const llvm::Type *SizeType) { 1434 const llvm::Type *ArgTypes[2] = { DestType, SizeType }; 1435 return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2); 1436 } 1437 1438 static llvm::StringMapEntry<llvm::Constant*> & 1439 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1440 const StringLiteral *Literal, 1441 bool TargetIsLSB, 1442 bool &IsUTF16, 1443 unsigned &StringLength) { 1444 unsigned NumBytes = Literal->getByteLength(); 1445 1446 // Check for simple case. 1447 if (!Literal->containsNonAsciiOrNull()) { 1448 StringLength = NumBytes; 1449 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1450 StringLength)); 1451 } 1452 1453 // Otherwise, convert the UTF8 literals into a byte string. 1454 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1455 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1456 UTF16 *ToPtr = &ToBuf[0]; 1457 1458 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1459 &ToPtr, ToPtr + NumBytes, 1460 strictConversion); 1461 1462 // Check for conversion failure. 1463 if (Result != conversionOK) { 1464 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1465 // this duplicate code. 1466 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1467 StringLength = NumBytes; 1468 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1469 StringLength)); 1470 } 1471 1472 // ConvertUTF8toUTF16 returns the length in ToPtr. 1473 StringLength = ToPtr - &ToBuf[0]; 1474 1475 // Render the UTF-16 string into a byte array and convert to the target byte 1476 // order. 1477 // 1478 // FIXME: This isn't something we should need to do here. 1479 llvm::SmallString<128> AsBytes; 1480 AsBytes.reserve(StringLength * 2); 1481 for (unsigned i = 0; i != StringLength; ++i) { 1482 unsigned short Val = ToBuf[i]; 1483 if (TargetIsLSB) { 1484 AsBytes.push_back(Val & 0xFF); 1485 AsBytes.push_back(Val >> 8); 1486 } else { 1487 AsBytes.push_back(Val >> 8); 1488 AsBytes.push_back(Val & 0xFF); 1489 } 1490 } 1491 // Append one extra null character, the second is automatically added by our 1492 // caller. 1493 AsBytes.push_back(0); 1494 1495 IsUTF16 = true; 1496 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1497 } 1498 1499 llvm::Constant * 1500 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1501 unsigned StringLength = 0; 1502 bool isUTF16 = false; 1503 llvm::StringMapEntry<llvm::Constant*> &Entry = 1504 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1505 getTargetData().isLittleEndian(), 1506 isUTF16, StringLength); 1507 1508 if (llvm::Constant *C = Entry.getValue()) 1509 return C; 1510 1511 llvm::Constant *Zero = 1512 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1513 llvm::Constant *Zeros[] = { Zero, Zero }; 1514 1515 // If we don't already have it, get __CFConstantStringClassReference. 1516 if (!CFConstantStringClassRef) { 1517 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1518 Ty = llvm::ArrayType::get(Ty, 0); 1519 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1520 "__CFConstantStringClassReference"); 1521 // Decay array -> ptr 1522 CFConstantStringClassRef = 1523 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1524 } 1525 1526 QualType CFTy = getContext().getCFConstantStringType(); 1527 1528 const llvm::StructType *STy = 1529 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1530 1531 std::vector<llvm::Constant*> Fields(4); 1532 1533 // Class pointer. 1534 Fields[0] = CFConstantStringClassRef; 1535 1536 // Flags. 1537 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1538 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1539 llvm::ConstantInt::get(Ty, 0x07C8); 1540 1541 // String pointer. 1542 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1543 1544 llvm::GlobalValue::LinkageTypes Linkage; 1545 bool isConstant; 1546 if (isUTF16) { 1547 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1548 Linkage = llvm::GlobalValue::InternalLinkage; 1549 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1550 // does make plain ascii ones writable. 1551 isConstant = true; 1552 } else { 1553 Linkage = llvm::GlobalValue::PrivateLinkage; 1554 isConstant = !Features.WritableStrings; 1555 } 1556 1557 llvm::GlobalVariable *GV = 1558 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1559 ".str"); 1560 if (isUTF16) { 1561 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1562 GV->setAlignment(Align.getQuantity()); 1563 } 1564 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1565 1566 // String length. 1567 Ty = getTypes().ConvertType(getContext().LongTy); 1568 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1569 1570 // The struct. 1571 C = llvm::ConstantStruct::get(STy, Fields); 1572 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1573 llvm::GlobalVariable::PrivateLinkage, C, 1574 "_unnamed_cfstring_"); 1575 if (const char *Sect = getContext().Target.getCFStringSection()) 1576 GV->setSection(Sect); 1577 Entry.setValue(GV); 1578 1579 return GV; 1580 } 1581 1582 /// GetStringForStringLiteral - Return the appropriate bytes for a 1583 /// string literal, properly padded to match the literal type. 1584 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1585 const char *StrData = E->getStrData(); 1586 unsigned Len = E->getByteLength(); 1587 1588 const ConstantArrayType *CAT = 1589 getContext().getAsConstantArrayType(E->getType()); 1590 assert(CAT && "String isn't pointer or array!"); 1591 1592 // Resize the string to the right size. 1593 std::string Str(StrData, StrData+Len); 1594 uint64_t RealLen = CAT->getSize().getZExtValue(); 1595 1596 if (E->isWide()) 1597 RealLen *= getContext().Target.getWCharWidth()/8; 1598 1599 Str.resize(RealLen, '\0'); 1600 1601 return Str; 1602 } 1603 1604 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1605 /// constant array for the given string literal. 1606 llvm::Constant * 1607 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1608 // FIXME: This can be more efficient. 1609 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1610 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1611 if (S->isWide()) { 1612 llvm::Type *DestTy = 1613 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1614 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1615 } 1616 return C; 1617 } 1618 1619 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1620 /// array for the given ObjCEncodeExpr node. 1621 llvm::Constant * 1622 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1623 std::string Str; 1624 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1625 1626 return GetAddrOfConstantCString(Str); 1627 } 1628 1629 1630 /// GenerateWritableString -- Creates storage for a string literal. 1631 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1632 bool constant, 1633 CodeGenModule &CGM, 1634 const char *GlobalName) { 1635 // Create Constant for this string literal. Don't add a '\0'. 1636 llvm::Constant *C = 1637 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1638 1639 // Create a global variable for this string 1640 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1641 llvm::GlobalValue::PrivateLinkage, 1642 C, GlobalName); 1643 } 1644 1645 /// GetAddrOfConstantString - Returns a pointer to a character array 1646 /// containing the literal. This contents are exactly that of the 1647 /// given string, i.e. it will not be null terminated automatically; 1648 /// see GetAddrOfConstantCString. Note that whether the result is 1649 /// actually a pointer to an LLVM constant depends on 1650 /// Feature.WriteableStrings. 1651 /// 1652 /// The result has pointer to array type. 1653 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1654 const char *GlobalName) { 1655 bool IsConstant = !Features.WritableStrings; 1656 1657 // Get the default prefix if a name wasn't specified. 1658 if (!GlobalName) 1659 GlobalName = ".str"; 1660 1661 // Don't share any string literals if strings aren't constant. 1662 if (!IsConstant) 1663 return GenerateStringLiteral(str, false, *this, GlobalName); 1664 1665 llvm::StringMapEntry<llvm::Constant *> &Entry = 1666 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1667 1668 if (Entry.getValue()) 1669 return Entry.getValue(); 1670 1671 // Create a global variable for this. 1672 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1673 Entry.setValue(C); 1674 return C; 1675 } 1676 1677 /// GetAddrOfConstantCString - Returns a pointer to a character 1678 /// array containing the literal and a terminating '\-' 1679 /// character. The result has pointer to array type. 1680 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1681 const char *GlobalName){ 1682 return GetAddrOfConstantString(str + '\0', GlobalName); 1683 } 1684 1685 /// EmitObjCPropertyImplementations - Emit information for synthesized 1686 /// properties for an implementation. 1687 void CodeGenModule::EmitObjCPropertyImplementations(const 1688 ObjCImplementationDecl *D) { 1689 for (ObjCImplementationDecl::propimpl_iterator 1690 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1691 ObjCPropertyImplDecl *PID = *i; 1692 1693 // Dynamic is just for type-checking. 1694 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1695 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1696 1697 // Determine which methods need to be implemented, some may have 1698 // been overridden. Note that ::isSynthesized is not the method 1699 // we want, that just indicates if the decl came from a 1700 // property. What we want to know is if the method is defined in 1701 // this implementation. 1702 if (!D->getInstanceMethod(PD->getGetterName())) 1703 CodeGenFunction(*this).GenerateObjCGetter( 1704 const_cast<ObjCImplementationDecl *>(D), PID); 1705 if (!PD->isReadOnly() && 1706 !D->getInstanceMethod(PD->getSetterName())) 1707 CodeGenFunction(*this).GenerateObjCSetter( 1708 const_cast<ObjCImplementationDecl *>(D), PID); 1709 } 1710 } 1711 } 1712 1713 /// EmitNamespace - Emit all declarations in a namespace. 1714 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1715 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1716 I != E; ++I) 1717 EmitTopLevelDecl(*I); 1718 } 1719 1720 // EmitLinkageSpec - Emit all declarations in a linkage spec. 1721 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1722 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1723 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1724 ErrorUnsupported(LSD, "linkage spec"); 1725 return; 1726 } 1727 1728 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1729 I != E; ++I) 1730 EmitTopLevelDecl(*I); 1731 } 1732 1733 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1734 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1735 // If an error has occurred, stop code generation, but continue 1736 // parsing and semantic analysis (to ensure all warnings and errors 1737 // are emitted). 1738 if (Diags.hasErrorOccurred()) 1739 return; 1740 1741 // Ignore dependent declarations. 1742 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1743 return; 1744 1745 switch (D->getKind()) { 1746 case Decl::CXXConversion: 1747 case Decl::CXXMethod: 1748 case Decl::Function: 1749 // Skip function templates 1750 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1751 return; 1752 1753 EmitGlobal(cast<FunctionDecl>(D)); 1754 break; 1755 1756 case Decl::Var: 1757 EmitGlobal(cast<VarDecl>(D)); 1758 break; 1759 1760 // C++ Decls 1761 case Decl::Namespace: 1762 EmitNamespace(cast<NamespaceDecl>(D)); 1763 break; 1764 // No code generation needed. 1765 case Decl::UsingShadow: 1766 case Decl::Using: 1767 case Decl::UsingDirective: 1768 case Decl::ClassTemplate: 1769 case Decl::FunctionTemplate: 1770 case Decl::NamespaceAlias: 1771 break; 1772 case Decl::CXXConstructor: 1773 // Skip function templates 1774 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1775 return; 1776 1777 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1778 break; 1779 case Decl::CXXDestructor: 1780 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1781 break; 1782 1783 case Decl::StaticAssert: 1784 // Nothing to do. 1785 break; 1786 1787 // Objective-C Decls 1788 1789 // Forward declarations, no (immediate) code generation. 1790 case Decl::ObjCClass: 1791 case Decl::ObjCForwardProtocol: 1792 case Decl::ObjCCategory: 1793 case Decl::ObjCInterface: 1794 break; 1795 1796 case Decl::ObjCProtocol: 1797 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1798 break; 1799 1800 case Decl::ObjCCategoryImpl: 1801 // Categories have properties but don't support synthesize so we 1802 // can ignore them here. 1803 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1804 break; 1805 1806 case Decl::ObjCImplementation: { 1807 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1808 EmitObjCPropertyImplementations(OMD); 1809 Runtime->GenerateClass(OMD); 1810 break; 1811 } 1812 case Decl::ObjCMethod: { 1813 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1814 // If this is not a prototype, emit the body. 1815 if (OMD->getBody()) 1816 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1817 break; 1818 } 1819 case Decl::ObjCCompatibleAlias: 1820 // compatibility-alias is a directive and has no code gen. 1821 break; 1822 1823 case Decl::LinkageSpec: 1824 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 1825 break; 1826 1827 case Decl::FileScopeAsm: { 1828 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1829 llvm::StringRef AsmString = AD->getAsmString()->getString(); 1830 1831 const std::string &S = getModule().getModuleInlineAsm(); 1832 if (S.empty()) 1833 getModule().setModuleInlineAsm(AsmString); 1834 else 1835 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 1836 break; 1837 } 1838 1839 default: 1840 // Make sure we handled everything we should, every other kind is a 1841 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 1842 // function. Need to recode Decl::Kind to do that easily. 1843 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1844 } 1845 } 1846