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