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