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