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