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