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