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 "CGDebugInfo.h" 15 #include "CodeGenModule.h" 16 #include "CodeGenFunction.h" 17 #include "CGCall.h" 18 #include "CGObjCRuntime.h" 19 #include "Mangle.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/Basic/Diagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "llvm/CallingConv.h" 27 #include "llvm/Module.h" 28 #include "llvm/Intrinsics.h" 29 #include "llvm/Target/TargetData.h" 30 using namespace clang; 31 using namespace CodeGen; 32 33 34 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 35 llvm::Module &M, const llvm::TargetData &TD, 36 Diagnostic &diags, bool GenerateDebugInfo) 37 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags), 38 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0), 39 CFConstantStringClassRef(0), NSConcreteGlobalBlock(0), 40 NSConcreteStackBlock(0),BlockDescriptorType(0), GenericBlockLiteralType(0) { 41 42 if (Features.ObjC1) { 43 if (Features.NeXTRuntime) { 44 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this) 45 : CreateMacObjCRuntime(*this); 46 } else { 47 Runtime = CreateGNUObjCRuntime(*this); 48 } 49 } 50 51 // If debug info generation is enabled, create the CGDebugInfo object. 52 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0; 53 54 Block.GlobalUniqueCount = 0; 55 } 56 57 CodeGenModule::~CodeGenModule() { 58 delete Runtime; 59 delete DebugInfo; 60 } 61 62 void CodeGenModule::Release() { 63 EmitDeferred(); 64 EmitAliases(); 65 if (Runtime) 66 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 67 AddGlobalCtor(ObjCInitFunction); 68 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 69 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 70 EmitAnnotations(); 71 EmitLLVMUsed(); 72 BindRuntimeFunctions(); 73 } 74 75 void CodeGenModule::BindRuntimeFunctions() { 76 // Deal with protecting runtime function names. 77 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) { 78 llvm::Function *Fn = RuntimeFunctions[i].first; 79 const std::string &Name = RuntimeFunctions[i].second; 80 81 // Discard unused runtime functions. 82 if (Fn->use_empty()) { 83 Fn->eraseFromParent(); 84 continue; 85 } 86 87 // See if there is a conflict against a function. 88 llvm::Function *Conflict = TheModule.getFunction(Name); 89 if (Conflict) { 90 // Decide which version to take. If the conflict is a definition 91 // we are forced to take that, otherwise assume the runtime 92 // knows best. 93 if (!Conflict->isDeclaration()) { 94 llvm::Value *Casted = 95 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType()); 96 Fn->replaceAllUsesWith(Casted); 97 Fn->eraseFromParent(); 98 } else { 99 Fn->takeName(Conflict); 100 llvm::Value *Casted = 101 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType()); 102 Conflict->replaceAllUsesWith(Casted); 103 Conflict->eraseFromParent(); 104 } 105 } else { 106 // FIXME: There still may be conflicts with aliases and 107 // variables. 108 Fn->setName(Name); 109 } 110 } 111 } 112 113 /// ErrorUnsupported - Print out an error that codegen doesn't support the 114 /// specified stmt yet. 115 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 116 bool OmitOnError) { 117 if (OmitOnError && getDiags().hasErrorOccurred()) 118 return; 119 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 120 "cannot compile this %0 yet"); 121 std::string Msg = Type; 122 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 123 << Msg << S->getSourceRange(); 124 } 125 126 /// ErrorUnsupported - Print out an error that codegen doesn't support the 127 /// specified decl yet. 128 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 129 bool OmitOnError) { 130 if (OmitOnError && getDiags().hasErrorOccurred()) 131 return; 132 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 133 "cannot compile this %0 yet"); 134 std::string Msg = Type; 135 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 136 } 137 138 /// setGlobalVisibility - Set the visibility for the given LLVM 139 /// GlobalValue according to the given clang AST visibility value. 140 static void setGlobalVisibility(llvm::GlobalValue *GV, 141 VisibilityAttr::VisibilityTypes Vis) { 142 switch (Vis) { 143 default: assert(0 && "Unknown visibility!"); 144 case VisibilityAttr::DefaultVisibility: 145 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 146 break; 147 case VisibilityAttr::HiddenVisibility: 148 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 149 break; 150 case VisibilityAttr::ProtectedVisibility: 151 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 152 break; 153 } 154 } 155 156 /// \brief Retrieves the mangled name for the given declaration. 157 /// 158 /// If the given declaration requires a mangled name, returns an 159 /// IdentifierInfo* containing the mangled name. Otherwise, returns 160 /// the name of the declaration as an identifier. 161 /// 162 /// FIXME: Returning an IdentifierInfo* here is a total hack. We 163 /// really need some kind of string abstraction that either stores a 164 /// mangled name or stores an IdentifierInfo*. This will require 165 /// changes to the GlobalDeclMap, too. (I disagree, I think what we 166 /// actually need is for Sema to provide some notion of which Decls 167 /// refer to the same semantic decl. We shouldn't need to mangle the 168 /// names and see what comes out the same to figure this out. - DWD) 169 /// 170 /// FIXME: Performance here is going to be terribly until we start 171 /// caching mangled names. However, we should fix the problem above 172 /// first. 173 const char *CodeGenModule::getMangledName(const NamedDecl *ND) { 174 llvm::SmallString<256> Name; 175 llvm::raw_svector_ostream Out(Name); 176 if (!mangleName(ND, Context, Out)) 177 return ND->getIdentifier()->getName(); 178 179 Name += '\0'; 180 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()) 181 .getKeyData(); 182 } 183 184 /// AddGlobalCtor - Add a function to the list that will be called before 185 /// main() runs. 186 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 187 // FIXME: Type coercion of void()* types. 188 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 189 } 190 191 /// AddGlobalDtor - Add a function to the list that will be called 192 /// when the module is unloaded. 193 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 194 // FIXME: Type coercion of void()* types. 195 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 196 } 197 198 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 199 // Ctor function type is void()*. 200 llvm::FunctionType* CtorFTy = 201 llvm::FunctionType::get(llvm::Type::VoidTy, 202 std::vector<const llvm::Type*>(), 203 false); 204 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 205 206 // Get the type of a ctor entry, { i32, void ()* }. 207 llvm::StructType* CtorStructTy = 208 llvm::StructType::get(llvm::Type::Int32Ty, 209 llvm::PointerType::getUnqual(CtorFTy), NULL); 210 211 // Construct the constructor and destructor arrays. 212 std::vector<llvm::Constant*> Ctors; 213 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 214 std::vector<llvm::Constant*> S; 215 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false)); 216 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 217 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 218 } 219 220 if (!Ctors.empty()) { 221 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 222 new llvm::GlobalVariable(AT, false, 223 llvm::GlobalValue::AppendingLinkage, 224 llvm::ConstantArray::get(AT, Ctors), 225 GlobalName, 226 &TheModule); 227 } 228 } 229 230 void CodeGenModule::EmitAnnotations() { 231 if (Annotations.empty()) 232 return; 233 234 // Create a new global variable for the ConstantStruct in the Module. 235 llvm::Constant *Array = 236 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 237 Annotations.size()), 238 Annotations); 239 llvm::GlobalValue *gv = 240 new llvm::GlobalVariable(Array->getType(), false, 241 llvm::GlobalValue::AppendingLinkage, Array, 242 "llvm.global.annotations", &TheModule); 243 gv->setSection("llvm.metadata"); 244 } 245 246 void CodeGenModule::SetGlobalValueAttributes(const Decl *D, 247 bool IsInternal, 248 bool IsInline, 249 llvm::GlobalValue *GV, 250 bool ForDefinition) { 251 // FIXME: Set up linkage and many other things. Note, this is a simple 252 // approximation of what we really want. 253 if (!ForDefinition) { 254 // Only a few attributes are set on declarations. 255 if (D->getAttr<DLLImportAttr>()) { 256 // The dllimport attribute is overridden by a subsequent declaration as 257 // dllexport. 258 if (!D->getAttr<DLLExportAttr>()) { 259 // dllimport attribute can be applied only to function decls, not to 260 // definitions. 261 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 262 if (!FD->getBody()) 263 GV->setLinkage(llvm::Function::DLLImportLinkage); 264 } else 265 GV->setLinkage(llvm::Function::DLLImportLinkage); 266 } 267 } else if (D->getAttr<WeakAttr>()) 268 GV->setLinkage(llvm::Function::ExternalWeakLinkage); 269 } else { 270 if (IsInternal) { 271 GV->setLinkage(llvm::Function::InternalLinkage); 272 } else { 273 if (D->getAttr<DLLExportAttr>()) { 274 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 275 // The dllexport attribute is ignored for undefined symbols. 276 if (FD->getBody()) 277 GV->setLinkage(llvm::Function::DLLExportLinkage); 278 } else 279 GV->setLinkage(llvm::Function::DLLExportLinkage); 280 } else if (D->getAttr<WeakAttr>() || IsInline) 281 GV->setLinkage(llvm::Function::WeakLinkage); 282 } 283 } 284 285 // FIXME: Figure out the relative priority of the attribute, 286 // -fvisibility, and private_extern. 287 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 288 setGlobalVisibility(GV, attr->getVisibility()); 289 // FIXME: else handle -fvisibility 290 291 // Prefaced with special LLVM marker to indicate that the name 292 // should not be munged. 293 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) 294 GV->setName("\01" + ALA->getLabel()); 295 296 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 297 GV->setSection(SA->getName()); 298 299 // Only add to llvm.used when we see a definition, otherwise we 300 // might add multiple times or risk the value being replaced by a 301 // subsequent RAUW. 302 if (ForDefinition) { 303 if (D->getAttr<UsedAttr>()) 304 AddUsedGlobal(GV); 305 } 306 } 307 308 void CodeGenModule::SetFunctionAttributes(const Decl *D, 309 const CGFunctionInfo &Info, 310 llvm::Function *F) { 311 AttributeListType AttributeList; 312 ConstructAttributeList(Info, D, AttributeList); 313 314 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 315 AttributeList.size())); 316 317 // Set the appropriate calling convention for the Function. 318 if (D->getAttr<FastCallAttr>()) 319 F->setCallingConv(llvm::CallingConv::X86_FastCall); 320 321 if (D->getAttr<StdCallAttr>()) 322 F->setCallingConv(llvm::CallingConv::X86_StdCall); 323 } 324 325 /// SetFunctionAttributesForDefinition - Set function attributes 326 /// specific to a function definition. 327 void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D, 328 llvm::Function *F) { 329 if (isa<ObjCMethodDecl>(D)) { 330 SetGlobalValueAttributes(D, true, false, F, true); 331 } else { 332 const FunctionDecl *FD = cast<FunctionDecl>(D); 333 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static, 334 FD->isInline(), F, true); 335 } 336 337 if (!Features.Exceptions) 338 F->addFnAttr(llvm::Attribute::NoUnwind); 339 340 if (D->getAttr<AlwaysInlineAttr>()) 341 F->addFnAttr(llvm::Attribute::AlwaysInline); 342 343 if (D->getAttr<NoinlineAttr>()) 344 F->addFnAttr(llvm::Attribute::NoInline); 345 } 346 347 void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD, 348 llvm::Function *F) { 349 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F); 350 351 SetFunctionAttributesForDefinition(MD, F); 352 } 353 354 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 355 llvm::Function *F) { 356 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); 357 358 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static, 359 FD->isInline(), F, false); 360 } 361 362 363 void CodeGenModule::EmitAliases() { 364 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) { 365 const FunctionDecl *D = Aliases[i]; 366 const AliasAttr *AA = D->getAttr<AliasAttr>(); 367 368 // This is something of a hack, if the FunctionDecl got overridden 369 // then its attributes will be moved to the new declaration. In 370 // this case the current decl has no alias attribute, but we will 371 // eventually see it. 372 if (!AA) 373 continue; 374 375 const std::string& aliaseeName = AA->getAliasee(); 376 llvm::Function *aliasee = getModule().getFunction(aliaseeName); 377 if (!aliasee) { 378 // FIXME: This isn't unsupported, this is just an error, which 379 // sema should catch, but... 380 ErrorUnsupported(D, "alias referencing a missing function"); 381 continue; 382 } 383 384 llvm::GlobalValue *GA = 385 new llvm::GlobalAlias(aliasee->getType(), 386 llvm::Function::ExternalLinkage, 387 getMangledName(D), aliasee, 388 &getModule()); 389 390 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)]; 391 if (Entry) { 392 // If we created a dummy function for this then replace it. 393 GA->takeName(Entry); 394 395 llvm::Value *Casted = 396 llvm::ConstantExpr::getBitCast(GA, Entry->getType()); 397 Entry->replaceAllUsesWith(Casted); 398 Entry->eraseFromParent(); 399 400 Entry = GA; 401 } 402 403 // Alias should never be internal or inline. 404 SetGlobalValueAttributes(D, false, false, GA, true); 405 } 406 } 407 408 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 409 assert(!GV->isDeclaration() && 410 "Only globals with definition can force usage."); 411 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 412 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy)); 413 } 414 415 void CodeGenModule::EmitLLVMUsed() { 416 // Don't create llvm.used if there is no need. 417 if (LLVMUsed.empty()) 418 return; 419 420 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(), 421 LLVMUsed.size()); 422 llvm::GlobalVariable *GV = 423 new llvm::GlobalVariable(ATy, false, 424 llvm::GlobalValue::AppendingLinkage, 425 llvm::ConstantArray::get(ATy, LLVMUsed), 426 "llvm.used", &getModule()); 427 428 GV->setSection("llvm.metadata"); 429 } 430 431 void CodeGenModule::EmitDeferred() { 432 // Emit code for any deferred decl which was used. Since a 433 // previously unused static decl may become used during the 434 // generation of code for a static function, iterate until no 435 // changes are made. 436 bool Changed; 437 do { 438 Changed = false; 439 440 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(), 441 e = DeferredDecls.end(); i != e; ) { 442 const ValueDecl *D = *i; 443 444 // Check if we have used a decl with the same name 445 // FIXME: The AST should have some sort of aggregate decls or 446 // global symbol map. 447 // FIXME: This is missing some important cases. For example, we 448 // need to check for uses in an alias. 449 if (!GlobalDeclMap.count(getMangledName(D))) { 450 ++i; 451 continue; 452 } 453 454 // Emit the definition. 455 EmitGlobalDefinition(D); 456 457 // Erase the used decl from the list. 458 i = DeferredDecls.erase(i); 459 460 // Remember that we made a change. 461 Changed = true; 462 } 463 } while (Changed); 464 } 465 466 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 467 /// annotation information for a given GlobalValue. The annotation struct is 468 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 469 /// GlobalValue being annotated. The second field is the constant string 470 /// created from the AnnotateAttr's annotation. The third field is a constant 471 /// string containing the name of the translation unit. The fourth field is 472 /// the line number in the file of the annotated value declaration. 473 /// 474 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 475 /// appears to. 476 /// 477 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 478 const AnnotateAttr *AA, 479 unsigned LineNo) { 480 llvm::Module *M = &getModule(); 481 482 // get [N x i8] constants for the annotation string, and the filename string 483 // which are the 2nd and 3rd elements of the global annotation structure. 484 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 485 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true); 486 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(), 487 true); 488 489 // Get the two global values corresponding to the ConstantArrays we just 490 // created to hold the bytes of the strings. 491 llvm::GlobalValue *annoGV = 492 new llvm::GlobalVariable(anno->getType(), false, 493 llvm::GlobalValue::InternalLinkage, anno, 494 GV->getName() + ".str", M); 495 // translation unit name string, emitted into the llvm.metadata section. 496 llvm::GlobalValue *unitGV = 497 new llvm::GlobalVariable(unit->getType(), false, 498 llvm::GlobalValue::InternalLinkage, unit, ".str", M); 499 500 // Create the ConstantStruct that is the global annotion. 501 llvm::Constant *Fields[4] = { 502 llvm::ConstantExpr::getBitCast(GV, SBP), 503 llvm::ConstantExpr::getBitCast(annoGV, SBP), 504 llvm::ConstantExpr::getBitCast(unitGV, SBP), 505 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo) 506 }; 507 return llvm::ConstantStruct::get(Fields, 4, false); 508 } 509 510 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 511 // Never defer when EmitAllDecls is specified or the decl has 512 // attribute used. 513 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>()) 514 return false; 515 516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 517 // Constructors and destructors should never be deferred. 518 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>()) 519 return false; 520 521 if (FD->getStorageClass() != FunctionDecl::Static) 522 return false; 523 } else { 524 const VarDecl *VD = cast<VarDecl>(Global); 525 assert(VD->isFileVarDecl() && "Invalid decl."); 526 527 if (VD->getStorageClass() != VarDecl::Static) 528 return false; 529 } 530 531 return true; 532 } 533 534 void CodeGenModule::EmitGlobal(const ValueDecl *Global) { 535 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 536 // Aliases are deferred until code for everything else has been 537 // emitted. 538 if (FD->getAttr<AliasAttr>()) { 539 assert(!FD->isThisDeclarationADefinition() && 540 "Function alias cannot have a definition!"); 541 Aliases.push_back(FD); 542 return; 543 } 544 545 // Forward declarations are emitted lazily on first use. 546 if (!FD->isThisDeclarationADefinition()) 547 return; 548 } else { 549 const VarDecl *VD = cast<VarDecl>(Global); 550 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 551 552 // Forward declarations are emitted lazily on first use. 553 if (!VD->getInit() && VD->hasExternalStorage()) 554 return; 555 } 556 557 // Defer code generation when possible. 558 if (MayDeferGeneration(Global)) { 559 DeferredDecls.push_back(Global); 560 return; 561 } 562 563 // Otherwise emit the definition. 564 EmitGlobalDefinition(Global); 565 } 566 567 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) { 568 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 569 EmitGlobalFunctionDefinition(FD); 570 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 571 EmitGlobalVarDefinition(VD); 572 } else { 573 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 574 } 575 } 576 577 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) { 578 assert(D->hasGlobalStorage() && "Not a global variable"); 579 580 QualType ASTTy = D->getType(); 581 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 582 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 583 584 // Lookup the entry, lazily creating it if necessary. 585 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)]; 586 if (!Entry) { 587 llvm::GlobalVariable *GV = 588 new llvm::GlobalVariable(Ty, false, 589 llvm::GlobalValue::ExternalLinkage, 590 0, getMangledName(D), &getModule(), 591 0, ASTTy.getAddressSpace()); 592 Entry = GV; 593 594 // Handle things which are present even on external declarations. 595 596 // FIXME: This code is overly simple and should be merged with 597 // other global handling. 598 599 GV->setConstant(D->getType().isConstant(Context)); 600 601 // FIXME: Merge with other attribute handling code. 602 603 if (D->getStorageClass() == VarDecl::PrivateExtern) 604 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility); 605 606 if (D->getAttr<WeakAttr>()) 607 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 608 } 609 610 // Make sure the result is of the correct type. 611 return llvm::ConstantExpr::getBitCast(Entry, PTy); 612 } 613 614 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 615 llvm::Constant *Init = 0; 616 QualType ASTTy = D->getType(); 617 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy); 618 619 if (D->getInit() == 0) { 620 // This is a tentative definition; tentative definitions are 621 // implicitly initialized with { 0 } 622 const llvm::Type* InitTy; 623 if (ASTTy->isIncompleteArrayType()) { 624 // An incomplete array is normally [ TYPE x 0 ], but we need 625 // to fix it to [ TYPE x 1 ]. 626 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy); 627 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1); 628 } else { 629 InitTy = VarTy; 630 } 631 Init = llvm::Constant::getNullValue(InitTy); 632 } else { 633 Init = EmitConstantExpr(D->getInit()); 634 if (!Init) { 635 ErrorUnsupported(D, "static initializer"); 636 QualType T = D->getInit()->getType(); 637 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 638 } 639 } 640 const llvm::Type* InitType = Init->getType(); 641 642 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)]; 643 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry); 644 645 if (!GV) { 646 GV = new llvm::GlobalVariable(InitType, false, 647 llvm::GlobalValue::ExternalLinkage, 648 0, getMangledName(D), 649 &getModule(), 0, ASTTy.getAddressSpace()); 650 651 } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) { 652 // If we already have this global and it has an initializer, then 653 // we are in the rare situation where we emitted the defining 654 // declaration of the global and are now being asked to emit a 655 // definition which would be common. This occurs, for example, in 656 // the following situation because statics can be emitted out of 657 // order: 658 // 659 // static int x; 660 // static int *y = &x; 661 // static int x = 10; 662 // int **z = &y; 663 // 664 // Bail here so we don't blow away the definition. Note that if we 665 // can't distinguish here if we emitted a definition with a null 666 // initializer, but this case is safe. 667 assert(!D->getInit() && "Emitting multiple definitions of a decl!"); 668 return; 669 670 } else if (GV->getType() != 671 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) { 672 // We have a definition after a prototype with the wrong type. 673 // We must make a new GlobalVariable* and update everything that used OldGV 674 // (a declaration or tentative definition) with the new GlobalVariable* 675 // (which will be a definition). 676 // 677 // This happens if there is a prototype for a global (e.g. "extern int x[];") 678 // and then a definition of a different type (e.g. "int x[10];"). This also 679 // happens when an initializer has a different type from the type of the 680 // global (this happens with unions). 681 // 682 // FIXME: This also ends up happening if there's a definition followed by 683 // a tentative definition! (Although Sema rejects that construct 684 // at the moment.) 685 686 // Save the old global 687 llvm::GlobalVariable *OldGV = GV; 688 689 // Make a new global with the correct type 690 GV = new llvm::GlobalVariable(InitType, false, 691 llvm::GlobalValue::ExternalLinkage, 692 0, getMangledName(D), 693 &getModule(), 0, ASTTy.getAddressSpace()); 694 // Steal the name of the old global 695 GV->takeName(OldGV); 696 697 // Replace all uses of the old global with the new global 698 llvm::Constant *NewPtrForOldDecl = 699 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 700 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 701 702 // Erase the old global, since it is no longer used. 703 OldGV->eraseFromParent(); 704 } 705 706 Entry = GV; 707 708 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 709 SourceManager &SM = Context.getSourceManager(); 710 AddAnnotation(EmitAnnotateAttr(GV, AA, 711 SM.getInstantiationLineNumber(D->getLocation()))); 712 } 713 714 GV->setInitializer(Init); 715 GV->setConstant(D->getType().isConstant(Context)); 716 GV->setAlignment(getContext().getDeclAlignInBytes(D)); 717 718 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 719 setGlobalVisibility(GV, attr->getVisibility()); 720 // FIXME: else handle -fvisibility 721 722 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) { 723 // Prefaced with special LLVM marker to indicate that the name 724 // should not be munged. 725 GV->setName("\01" + ALA->getLabel()); 726 } 727 728 // Set the llvm linkage type as appropriate. 729 if (D->getStorageClass() == VarDecl::Static) 730 GV->setLinkage(llvm::Function::InternalLinkage); 731 else if (D->getAttr<DLLImportAttr>()) 732 GV->setLinkage(llvm::Function::DLLImportLinkage); 733 else if (D->getAttr<DLLExportAttr>()) 734 GV->setLinkage(llvm::Function::DLLExportLinkage); 735 else if (D->getAttr<WeakAttr>()) 736 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 737 else { 738 // FIXME: This isn't right. This should handle common linkage and other 739 // stuff. 740 switch (D->getStorageClass()) { 741 case VarDecl::Static: assert(0 && "This case handled above"); 742 case VarDecl::Auto: 743 case VarDecl::Register: 744 assert(0 && "Can't have auto or register globals"); 745 case VarDecl::None: 746 if (!D->getInit()) 747 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 748 else 749 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 750 break; 751 case VarDecl::Extern: 752 // FIXME: common 753 break; 754 755 case VarDecl::PrivateExtern: 756 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 757 // FIXME: common 758 break; 759 } 760 } 761 762 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 763 GV->setSection(SA->getName()); 764 765 if (D->getAttr<UsedAttr>()) 766 AddUsedGlobal(GV); 767 768 // Emit global variable debug information. 769 CGDebugInfo *DI = getDebugInfo(); 770 if(DI) { 771 DI->setLocation(D->getLocation()); 772 DI->EmitGlobalVariable(GV, D); 773 } 774 } 775 776 llvm::GlobalValue * 777 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D, 778 const llvm::Type *Ty) { 779 if (!Ty) 780 Ty = getTypes().ConvertType(D->getType()); 781 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 782 llvm::Function::ExternalLinkage, 783 getMangledName(D), 784 &getModule()); 785 SetFunctionAttributes(D, F); 786 return F; 787 } 788 789 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) { 790 QualType ASTTy = D->getType(); 791 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 792 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 793 794 // Lookup the entry, lazily creating it if necessary. 795 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)]; 796 if (!Entry) 797 Entry = getModule().getFunction(getMangledName(D)); 798 if (!Entry) 799 Entry = EmitForwardFunctionDefinition(D, 0); 800 801 return llvm::ConstantExpr::getBitCast(Entry, PTy); 802 } 803 804 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) { 805 const llvm::FunctionType *Ty = 806 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType())); 807 808 // As a special case, make sure that definitions of K&R function 809 // "type foo()" aren't declared as varargs (which forces the backend 810 // to do unnecessary work). 811 if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg()) 812 Ty = llvm::FunctionType::get(Ty->getReturnType(), 813 std::vector<const llvm::Type*>(), 814 false); 815 816 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)]; 817 if (!Entry) { 818 Entry = EmitForwardFunctionDefinition(D, Ty); 819 } else { 820 // If the types mismatch then we have to rewrite the definition. 821 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) { 822 // Otherwise, we have a definition after a prototype with the 823 // wrong type. F is the Function* for the one with the wrong 824 // type, we must make a new Function* and update everything that 825 // used F (a declaration) with the new Function* (which will be 826 // a definition). 827 // 828 // This happens if there is a prototype for a function 829 // (e.g. "int f()") and then a definition of a different type 830 // (e.g. "int f(int x)"). Start by making a new function of the 831 // correct type, RAUW, then steal the name. 832 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty); 833 NewFn->takeName(Entry); 834 835 // Replace uses of F with the Function we will endow with a body. 836 llvm::Constant *NewPtrForOldDecl = 837 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 838 Entry->replaceAllUsesWith(NewPtrForOldDecl); 839 840 // Ok, delete the old function now, which is dead. 841 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration"); 842 Entry->eraseFromParent(); 843 844 Entry = NewFn; 845 } 846 } 847 848 llvm::Function *Fn = cast<llvm::Function>(Entry); 849 CodeGenFunction(*this).GenerateCode(D, Fn); 850 851 SetFunctionAttributesForDefinition(D, Fn); 852 853 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) { 854 AddGlobalCtor(Fn, CA->getPriority()); 855 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) { 856 AddGlobalDtor(Fn, DA->getPriority()); 857 } 858 } 859 860 llvm::Function * 861 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 862 const std::string &Name) { 863 llvm::Function *Fn = llvm::Function::Create(FTy, 864 llvm::Function::ExternalLinkage, 865 "", &TheModule); 866 RuntimeFunctions.push_back(std::make_pair(Fn, Name)); 867 return Fn; 868 } 869 870 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 871 // Make sure that this type is translated. 872 Types.UpdateCompletedType(TD); 873 } 874 875 876 /// getBuiltinLibFunction 877 llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 878 if (BuiltinID > BuiltinFunctions.size()) 879 BuiltinFunctions.resize(BuiltinID); 880 881 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 882 // a slot for it. 883 assert(BuiltinID && "Invalid Builtin ID"); 884 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 885 if (FunctionSlot) 886 return FunctionSlot; 887 888 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 889 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 890 "isn't a lib fn"); 891 892 // Get the name, skip over the __builtin_ prefix (if necessary). 893 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 894 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 895 Name += 10; 896 897 // Get the type for the builtin. 898 Builtin::Context::GetBuiltinTypeError Error; 899 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error); 900 assert(Error == Builtin::Context::GE_None && "Can't get builtin type"); 901 902 const llvm::FunctionType *Ty = 903 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 904 905 // FIXME: This has a serious problem with code like this: 906 // void abs() {} 907 // ... __builtin_abs(x); 908 // The two versions of abs will collide. The fix is for the builtin to win, 909 // and for the existing one to be turned into a constantexpr cast of the 910 // builtin. In the case where the existing one is a static function, it 911 // should just be renamed. 912 if (llvm::Function *Existing = getModule().getFunction(Name)) { 913 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 914 return FunctionSlot = Existing; 915 assert(Existing == 0 && "FIXME: Name collision"); 916 } 917 918 llvm::GlobalValue *&ExitingFn = GlobalDeclMap[getContext().Idents.get(Name).getName()]; 919 if (ExitingFn) { 920 llvm::Function *Fn = dyn_cast<llvm::Function>(ExitingFn); 921 assert(Fn && "builting mixing with non-function"); 922 return FunctionSlot = llvm::ConstantExpr::getBitCast(Fn, Ty); 923 } 924 925 // FIXME: param attributes for sext/zext etc. 926 return FunctionSlot = ExitingFn = 927 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name, 928 &getModule()); 929 } 930 931 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 932 unsigned NumTys) { 933 return llvm::Intrinsic::getDeclaration(&getModule(), 934 (llvm::Intrinsic::ID)IID, Tys, NumTys); 935 } 936 937 llvm::Function *CodeGenModule::getMemCpyFn() { 938 if (MemCpyFn) return MemCpyFn; 939 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 940 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 941 } 942 943 llvm::Function *CodeGenModule::getMemMoveFn() { 944 if (MemMoveFn) return MemMoveFn; 945 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 946 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 947 } 948 949 llvm::Function *CodeGenModule::getMemSetFn() { 950 if (MemSetFn) return MemSetFn; 951 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 952 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 953 } 954 955 static void appendFieldAndPadding(CodeGenModule &CGM, 956 std::vector<llvm::Constant*>& Fields, 957 FieldDecl *FieldD, FieldDecl *NextFieldD, 958 llvm::Constant* Field, 959 RecordDecl* RD, const llvm::StructType *STy) 960 { 961 // Append the field. 962 Fields.push_back(Field); 963 964 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD); 965 966 int NextStructFieldNo; 967 if (!NextFieldD) { 968 NextStructFieldNo = STy->getNumElements(); 969 } else { 970 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD); 971 } 972 973 // Append padding 974 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) { 975 llvm::Constant *C = 976 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1)); 977 978 Fields.push_back(C); 979 } 980 } 981 982 // We still need to work out the details of handling UTF-16. 983 // See: <rdr://2996215> 984 llvm::Constant *CodeGenModule:: 985 GetAddrOfConstantCFString(const std::string &str) { 986 llvm::StringMapEntry<llvm::Constant *> &Entry = 987 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 988 989 if (Entry.getValue()) 990 return Entry.getValue(); 991 992 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 993 llvm::Constant *Zeros[] = { Zero, Zero }; 994 995 if (!CFConstantStringClassRef) { 996 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 997 Ty = llvm::ArrayType::get(Ty, 0); 998 999 // FIXME: This is fairly broken if 1000 // __CFConstantStringClassReference is already defined, in that it 1001 // will get renamed and the user will most likely see an opaque 1002 // error message. This is a general issue with relying on 1003 // particular names. 1004 llvm::GlobalVariable *GV = 1005 new llvm::GlobalVariable(Ty, false, 1006 llvm::GlobalVariable::ExternalLinkage, 0, 1007 "__CFConstantStringClassReference", 1008 &getModule()); 1009 1010 // Decay array -> ptr 1011 CFConstantStringClassRef = 1012 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1013 } 1014 1015 QualType CFTy = getContext().getCFConstantStringType(); 1016 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl(); 1017 1018 const llvm::StructType *STy = 1019 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1020 1021 std::vector<llvm::Constant*> Fields; 1022 RecordDecl::field_iterator Field = CFRD->field_begin(); 1023 1024 // Class pointer. 1025 FieldDecl *CurField = *Field++; 1026 FieldDecl *NextField = *Field++; 1027 appendFieldAndPadding(*this, Fields, CurField, NextField, 1028 CFConstantStringClassRef, CFRD, STy); 1029 1030 // Flags. 1031 CurField = NextField; 1032 NextField = *Field++; 1033 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1034 appendFieldAndPadding(*this, Fields, CurField, NextField, 1035 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy); 1036 1037 // String pointer. 1038 CurField = NextField; 1039 NextField = *Field++; 1040 llvm::Constant *C = llvm::ConstantArray::get(str); 1041 C = new llvm::GlobalVariable(C->getType(), true, 1042 llvm::GlobalValue::InternalLinkage, 1043 C, ".str", &getModule()); 1044 appendFieldAndPadding(*this, Fields, CurField, NextField, 1045 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2), 1046 CFRD, STy); 1047 1048 // String length. 1049 CurField = NextField; 1050 NextField = 0; 1051 Ty = getTypes().ConvertType(getContext().LongTy); 1052 appendFieldAndPadding(*this, Fields, CurField, NextField, 1053 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy); 1054 1055 // The struct. 1056 C = llvm::ConstantStruct::get(STy, Fields); 1057 llvm::GlobalVariable *GV = 1058 new llvm::GlobalVariable(C->getType(), true, 1059 llvm::GlobalVariable::InternalLinkage, 1060 C, "", &getModule()); 1061 1062 GV->setSection("__DATA,__cfstring"); 1063 Entry.setValue(GV); 1064 1065 return GV; 1066 } 1067 1068 /// GetStringForStringLiteral - Return the appropriate bytes for a 1069 /// string literal, properly padded to match the literal type. 1070 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1071 const char *StrData = E->getStrData(); 1072 unsigned Len = E->getByteLength(); 1073 1074 const ConstantArrayType *CAT = 1075 getContext().getAsConstantArrayType(E->getType()); 1076 assert(CAT && "String isn't pointer or array!"); 1077 1078 // Resize the string to the right size. 1079 std::string Str(StrData, StrData+Len); 1080 uint64_t RealLen = CAT->getSize().getZExtValue(); 1081 1082 if (E->isWide()) 1083 RealLen *= getContext().Target.getWCharWidth()/8; 1084 1085 Str.resize(RealLen, '\0'); 1086 1087 return Str; 1088 } 1089 1090 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1091 /// constant array for the given string literal. 1092 llvm::Constant * 1093 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1094 // FIXME: This can be more efficient. 1095 return GetAddrOfConstantString(GetStringForStringLiteral(S)); 1096 } 1097 1098 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1099 /// array for the given ObjCEncodeExpr node. 1100 llvm::Constant * 1101 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1102 std::string Str; 1103 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1104 1105 llvm::Constant *C = llvm::ConstantArray::get(Str); 1106 C = new llvm::GlobalVariable(C->getType(), true, 1107 llvm::GlobalValue::InternalLinkage, 1108 C, ".str", &getModule()); 1109 return C; 1110 } 1111 1112 1113 /// GenerateWritableString -- Creates storage for a string literal. 1114 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1115 bool constant, 1116 CodeGenModule &CGM, 1117 const char *GlobalName) { 1118 // Create Constant for this string literal. Don't add a '\0'. 1119 llvm::Constant *C = llvm::ConstantArray::get(str, false); 1120 1121 // Create a global variable for this string 1122 return new llvm::GlobalVariable(C->getType(), constant, 1123 llvm::GlobalValue::InternalLinkage, 1124 C, GlobalName ? GlobalName : ".str", 1125 &CGM.getModule()); 1126 } 1127 1128 /// GetAddrOfConstantString - Returns a pointer to a character array 1129 /// containing the literal. This contents are exactly that of the 1130 /// given string, i.e. it will not be null terminated automatically; 1131 /// see GetAddrOfConstantCString. Note that whether the result is 1132 /// actually a pointer to an LLVM constant depends on 1133 /// Feature.WriteableStrings. 1134 /// 1135 /// The result has pointer to array type. 1136 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1137 const char *GlobalName) { 1138 // Don't share any string literals if writable-strings is turned on. 1139 if (Features.WritableStrings) 1140 return GenerateStringLiteral(str, false, *this, GlobalName); 1141 1142 llvm::StringMapEntry<llvm::Constant *> &Entry = 1143 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1144 1145 if (Entry.getValue()) 1146 return Entry.getValue(); 1147 1148 // Create a global variable for this. 1149 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1150 Entry.setValue(C); 1151 return C; 1152 } 1153 1154 /// GetAddrOfConstantCString - Returns a pointer to a character 1155 /// array containing the literal and a terminating '\-' 1156 /// character. The result has pointer to array type. 1157 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1158 const char *GlobalName){ 1159 return GetAddrOfConstantString(str + '\0', GlobalName); 1160 } 1161 1162 /// EmitObjCPropertyImplementations - Emit information for synthesized 1163 /// properties for an implementation. 1164 void CodeGenModule::EmitObjCPropertyImplementations(const 1165 ObjCImplementationDecl *D) { 1166 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(), 1167 e = D->propimpl_end(); i != e; ++i) { 1168 ObjCPropertyImplDecl *PID = *i; 1169 1170 // Dynamic is just for type-checking. 1171 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1172 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1173 1174 // Determine which methods need to be implemented, some may have 1175 // been overridden. Note that ::isSynthesized is not the method 1176 // we want, that just indicates if the decl came from a 1177 // property. What we want to know is if the method is defined in 1178 // this implementation. 1179 if (!D->getInstanceMethod(PD->getGetterName())) 1180 CodeGenFunction(*this).GenerateObjCGetter( 1181 const_cast<ObjCImplementationDecl *>(D), PID); 1182 if (!PD->isReadOnly() && 1183 !D->getInstanceMethod(PD->getSetterName())) 1184 CodeGenFunction(*this).GenerateObjCSetter( 1185 const_cast<ObjCImplementationDecl *>(D), PID); 1186 } 1187 } 1188 } 1189 1190 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1191 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1192 // If an error has occurred, stop code generation, but continue 1193 // parsing and semantic analysis (to ensure all warnings and errors 1194 // are emitted). 1195 if (Diags.hasErrorOccurred()) 1196 return; 1197 1198 switch (D->getKind()) { 1199 case Decl::Function: 1200 case Decl::Var: 1201 EmitGlobal(cast<ValueDecl>(D)); 1202 break; 1203 1204 case Decl::Namespace: 1205 ErrorUnsupported(D, "namespace"); 1206 break; 1207 1208 // Objective-C Decls 1209 1210 // Forward declarations, no (immediate) code generation. 1211 case Decl::ObjCClass: 1212 case Decl::ObjCCategory: 1213 case Decl::ObjCForwardProtocol: 1214 case Decl::ObjCInterface: 1215 break; 1216 1217 case Decl::ObjCProtocol: 1218 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1219 break; 1220 1221 case Decl::ObjCCategoryImpl: 1222 // Categories have properties but don't support synthesize so we 1223 // can ignore them here. 1224 1225 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1226 break; 1227 1228 case Decl::ObjCImplementation: { 1229 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1230 EmitObjCPropertyImplementations(OMD); 1231 Runtime->GenerateClass(OMD); 1232 break; 1233 } 1234 case Decl::ObjCMethod: { 1235 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1236 // If this is not a prototype, emit the body. 1237 if (OMD->getBody()) 1238 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1239 break; 1240 } 1241 case Decl::ObjCCompatibleAlias: 1242 // compatibility-alias is a directive and has no code gen. 1243 break; 1244 1245 case Decl::LinkageSpec: { 1246 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D); 1247 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx) 1248 ErrorUnsupported(LSD, "linkage spec"); 1249 // FIXME: implement C++ linkage, C linkage works mostly by C 1250 // language reuse already. 1251 break; 1252 } 1253 1254 case Decl::FileScopeAsm: { 1255 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1256 std::string AsmString(AD->getAsmString()->getStrData(), 1257 AD->getAsmString()->getByteLength()); 1258 1259 const std::string &S = getModule().getModuleInlineAsm(); 1260 if (S.empty()) 1261 getModule().setModuleInlineAsm(AsmString); 1262 else 1263 getModule().setModuleInlineAsm(S + '\n' + AsmString); 1264 break; 1265 } 1266 1267 default: 1268 // Make sure we handled everything we should, every other kind is 1269 // a non-top-level decl. FIXME: Would be nice to have an 1270 // isTopLevelDeclKind function. Need to recode Decl::Kind to do 1271 // that easily. 1272 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1273 } 1274 } 1275