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