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 "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCall.h" 18 #include "CGDebugInfo.h" 19 #include "CGObjCRuntime.h" 20 #include "CGOpenCLRuntime.h" 21 #include "CodeGenFunction.h" 22 #include "CodeGenPGO.h" 23 #include "CodeGenTBAA.h" 24 #include "TargetInfo.h" 25 #include "clang/AST/ASTContext.h" 26 #include "clang/AST/CharUnits.h" 27 #include "clang/AST/DeclCXX.h" 28 #include "clang/AST/DeclObjC.h" 29 #include "clang/AST/DeclTemplate.h" 30 #include "clang/AST/Mangle.h" 31 #include "clang/AST/RecordLayout.h" 32 #include "clang/AST/RecursiveASTVisitor.h" 33 #include "clang/Basic/Builtins.h" 34 #include "clang/Basic/CharInfo.h" 35 #include "clang/Basic/Diagnostic.h" 36 #include "clang/Basic/Module.h" 37 #include "clang/Basic/SourceManager.h" 38 #include "clang/Basic/TargetInfo.h" 39 #include "clang/Basic/Version.h" 40 #include "clang/Frontend/CodeGenOptions.h" 41 #include "clang/Sema/SemaDiagnostic.h" 42 #include "llvm/ADT/APSInt.h" 43 #include "llvm/ADT/Triple.h" 44 #include "llvm/IR/CallSite.h" 45 #include "llvm/IR/CallingConv.h" 46 #include "llvm/IR/DataLayout.h" 47 #include "llvm/IR/Intrinsics.h" 48 #include "llvm/IR/LLVMContext.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/ProfileData/InstrProfReader.h" 51 #include "llvm/Support/ConvertUTF.h" 52 #include "llvm/Support/ErrorHandling.h" 53 54 using namespace clang; 55 using namespace CodeGen; 56 57 static const char AnnotationSection[] = "llvm.metadata"; 58 59 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 60 switch (CGM.getTarget().getCXXABI().getKind()) { 61 case TargetCXXABI::GenericAArch64: 62 case TargetCXXABI::GenericARM: 63 case TargetCXXABI::iOS: 64 case TargetCXXABI::iOS64: 65 case TargetCXXABI::GenericItanium: 66 return CreateItaniumCXXABI(CGM); 67 case TargetCXXABI::Microsoft: 68 return CreateMicrosoftCXXABI(CGM); 69 } 70 71 llvm_unreachable("invalid C++ ABI kind"); 72 } 73 74 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 75 llvm::Module &M, const llvm::DataLayout &TD, 76 DiagnosticsEngine &diags) 77 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 78 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()), 79 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0), 80 TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0), 81 OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0), 82 NoObjCARCExceptionsMetadata(0), RRData(0), PGOReader(nullptr), 83 CFConstantStringClassRef(0), 84 ConstantStringClassRef(0), NSConstantStringType(0), 85 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0), 86 BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0), 87 LifetimeStartFn(0), LifetimeEndFn(0), 88 SanitizerBlacklist( 89 llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)), 90 SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled 91 : LangOpts.Sanitize) { 92 93 // Initialize the type cache. 94 llvm::LLVMContext &LLVMContext = M.getContext(); 95 VoidTy = llvm::Type::getVoidTy(LLVMContext); 96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 97 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 98 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 99 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 100 FloatTy = llvm::Type::getFloatTy(LLVMContext); 101 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 102 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 103 PointerAlignInBytes = 104 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 105 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 106 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 107 Int8PtrTy = Int8Ty->getPointerTo(0); 108 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 109 110 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 111 112 if (LangOpts.ObjC1) 113 createObjCRuntime(); 114 if (LangOpts.OpenCL) 115 createOpenCLRuntime(); 116 if (LangOpts.CUDA) 117 createCUDARuntime(); 118 119 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 120 if (SanOpts.Thread || 121 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 122 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 123 getCXXABI().getMangleContext()); 124 125 // If debug info or coverage generation is enabled, create the CGDebugInfo 126 // object. 127 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 128 CodeGenOpts.EmitGcovArcs || 129 CodeGenOpts.EmitGcovNotes) 130 DebugInfo = new CGDebugInfo(*this); 131 132 Block.GlobalUniqueCount = 0; 133 134 if (C.getLangOpts().ObjCAutoRefCount) 135 ARCData = new ARCEntrypoints(); 136 RRData = new RREntrypoints(); 137 138 if (!CodeGenOpts.InstrProfileInput.empty()) { 139 if (llvm::error_code EC = llvm::IndexedInstrProfReader::create( 140 CodeGenOpts.InstrProfileInput, PGOReader)) { 141 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 142 "Could not read profile: %0"); 143 getDiags().Report(DiagID) << EC.message(); 144 } 145 } 146 } 147 148 CodeGenModule::~CodeGenModule() { 149 delete ObjCRuntime; 150 delete OpenCLRuntime; 151 delete CUDARuntime; 152 delete TheTargetCodeGenInfo; 153 delete TBAA; 154 delete DebugInfo; 155 delete ARCData; 156 delete RRData; 157 } 158 159 void CodeGenModule::createObjCRuntime() { 160 // This is just isGNUFamily(), but we want to force implementors of 161 // new ABIs to decide how best to do this. 162 switch (LangOpts.ObjCRuntime.getKind()) { 163 case ObjCRuntime::GNUstep: 164 case ObjCRuntime::GCC: 165 case ObjCRuntime::ObjFW: 166 ObjCRuntime = CreateGNUObjCRuntime(*this); 167 return; 168 169 case ObjCRuntime::FragileMacOSX: 170 case ObjCRuntime::MacOSX: 171 case ObjCRuntime::iOS: 172 ObjCRuntime = CreateMacObjCRuntime(*this); 173 return; 174 } 175 llvm_unreachable("bad runtime kind"); 176 } 177 178 void CodeGenModule::createOpenCLRuntime() { 179 OpenCLRuntime = new CGOpenCLRuntime(*this); 180 } 181 182 void CodeGenModule::createCUDARuntime() { 183 CUDARuntime = CreateNVCUDARuntime(*this); 184 } 185 186 void CodeGenModule::applyReplacements() { 187 for (ReplacementsTy::iterator I = Replacements.begin(), 188 E = Replacements.end(); 189 I != E; ++I) { 190 StringRef MangledName = I->first(); 191 llvm::Constant *Replacement = I->second; 192 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 193 if (!Entry) 194 continue; 195 llvm::Function *OldF = cast<llvm::Function>(Entry); 196 llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement); 197 if (!NewF) { 198 if (llvm::GlobalAlias *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 199 NewF = dyn_cast<llvm::Function>(Alias->getAliasedGlobal()); 200 } else { 201 llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement); 202 assert(CE->getOpcode() == llvm::Instruction::BitCast || 203 CE->getOpcode() == llvm::Instruction::GetElementPtr); 204 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 205 } 206 } 207 208 // Replace old with new, but keep the old order. 209 OldF->replaceAllUsesWith(Replacement); 210 if (NewF) { 211 NewF->removeFromParent(); 212 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF); 213 } 214 OldF->eraseFromParent(); 215 } 216 } 217 218 void CodeGenModule::checkAliases() { 219 // Check if the constructed aliases are well formed. It is really unfortunate 220 // that we have to do this in CodeGen, but we only construct mangled names 221 // and aliases during codegen. 222 bool Error = false; 223 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 224 E = Aliases.end(); I != E; ++I) { 225 const GlobalDecl &GD = *I; 226 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 227 const AliasAttr *AA = D->getAttr<AliasAttr>(); 228 StringRef MangledName = getMangledName(GD); 229 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 230 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry); 231 llvm::GlobalValue *GV = Alias->getAliasedGlobal(); 232 if (!GV) { 233 Error = true; 234 getDiags().Report(AA->getLocation(), diag::err_cyclic_alias); 235 } else if (GV->isDeclaration()) { 236 Error = true; 237 getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined); 238 } 239 240 // We have to handle alias to weak aliases in here. LLVM itself disallows 241 // this since the object semantics would not match the IL one. For 242 // compatibility with gcc we implement it by just pointing the alias 243 // to its aliasee's aliasee. We also warn, since the user is probably 244 // expecting the link to be weak. 245 llvm::Constant *Aliasee = Alias->getAliasee(); 246 llvm::GlobalValue *AliaseeGV; 247 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) { 248 assert((CE->getOpcode() == llvm::Instruction::BitCast || 249 CE->getOpcode() == llvm::Instruction::AddrSpaceCast) && 250 "Unsupported aliasee"); 251 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 252 } else { 253 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 254 } 255 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 256 if (GA->mayBeOverridden()) { 257 getDiags().Report(AA->getLocation(), diag::warn_alias_to_weak_alias) 258 << GA->getAliasedGlobal()->getName() << GA->getName(); 259 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 260 GA->getAliasee(), Alias->getType()); 261 Alias->setAliasee(Aliasee); 262 } 263 } 264 } 265 if (!Error) 266 return; 267 268 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 269 E = Aliases.end(); I != E; ++I) { 270 const GlobalDecl &GD = *I; 271 StringRef MangledName = getMangledName(GD); 272 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 273 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry); 274 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 275 Alias->eraseFromParent(); 276 } 277 } 278 279 void CodeGenModule::clear() { 280 DeferredDeclsToEmit.clear(); 281 } 282 283 void CodeGenModule::Release() { 284 EmitDeferred(); 285 applyReplacements(); 286 checkAliases(); 287 EmitCXXGlobalInitFunc(); 288 EmitCXXGlobalDtorFunc(); 289 EmitCXXThreadLocalInitFunc(); 290 if (ObjCRuntime) 291 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 292 AddGlobalCtor(ObjCInitFunction); 293 if (getCodeGenOpts().ProfileInstrGenerate) 294 if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this)) 295 AddGlobalCtor(PGOInit, 0); 296 if (PGOReader && PGOStats.isOutOfDate()) 297 getDiags().Report(diag::warn_profile_data_out_of_date) 298 << PGOStats.Visited << PGOStats.Missing << PGOStats.Mismatched; 299 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 300 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 301 EmitGlobalAnnotations(); 302 EmitStaticExternCAliases(); 303 emitLLVMUsed(); 304 305 if (CodeGenOpts.Autolink && 306 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 307 EmitModuleLinkOptions(); 308 } 309 if (CodeGenOpts.DwarfVersion) 310 // We actually want the latest version when there are conflicts. 311 // We can change from Warning to Latest if such mode is supported. 312 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 313 CodeGenOpts.DwarfVersion); 314 if (DebugInfo) 315 // We support a single version in the linked module: error out when 316 // modules do not have the same version. We are going to implement dropping 317 // debug info when the version number is not up-to-date. Once that is 318 // done, the bitcode linker is not going to see modules with different 319 // version numbers. 320 getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version", 321 llvm::DEBUG_METADATA_VERSION); 322 323 SimplifyPersonality(); 324 325 if (getCodeGenOpts().EmitDeclMetadata) 326 EmitDeclMetadata(); 327 328 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 329 EmitCoverageFile(); 330 331 if (DebugInfo) 332 DebugInfo->finalize(); 333 334 EmitVersionIdentMetadata(); 335 } 336 337 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 338 // Make sure that this type is translated. 339 Types.UpdateCompletedType(TD); 340 } 341 342 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 343 if (!TBAA) 344 return 0; 345 return TBAA->getTBAAInfo(QTy); 346 } 347 348 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 349 if (!TBAA) 350 return 0; 351 return TBAA->getTBAAInfoForVTablePtr(); 352 } 353 354 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 355 if (!TBAA) 356 return 0; 357 return TBAA->getTBAAStructInfo(QTy); 358 } 359 360 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) { 361 if (!TBAA) 362 return 0; 363 return TBAA->getTBAAStructTypeInfo(QTy); 364 } 365 366 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 367 llvm::MDNode *AccessN, 368 uint64_t O) { 369 if (!TBAA) 370 return 0; 371 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 372 } 373 374 /// Decorate the instruction with a TBAA tag. For both scalar TBAA 375 /// and struct-path aware TBAA, the tag has the same format: 376 /// base type, access type and offset. 377 /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 378 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 379 llvm::MDNode *TBAAInfo, 380 bool ConvertTypeToTag) { 381 if (ConvertTypeToTag && TBAA) 382 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 383 TBAA->getTBAAScalarTagInfo(TBAAInfo)); 384 else 385 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 386 } 387 388 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 389 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 390 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 391 } 392 393 /// ErrorUnsupported - Print out an error that codegen doesn't support the 394 /// specified stmt yet. 395 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 396 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 397 "cannot compile this %0 yet"); 398 std::string Msg = Type; 399 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 400 << Msg << S->getSourceRange(); 401 } 402 403 /// ErrorUnsupported - Print out an error that codegen doesn't support the 404 /// specified decl yet. 405 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 406 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 407 "cannot compile this %0 yet"); 408 std::string Msg = Type; 409 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 410 } 411 412 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 413 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 414 } 415 416 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 417 const NamedDecl *D) const { 418 // Internal definitions always have default visibility. 419 if (GV->hasLocalLinkage()) { 420 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 421 return; 422 } 423 424 // Set visibility for definitions. 425 LinkageInfo LV = D->getLinkageAndVisibility(); 426 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 427 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 428 } 429 430 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 431 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 432 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 433 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 434 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 435 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 436 } 437 438 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 439 CodeGenOptions::TLSModel M) { 440 switch (M) { 441 case CodeGenOptions::GeneralDynamicTLSModel: 442 return llvm::GlobalVariable::GeneralDynamicTLSModel; 443 case CodeGenOptions::LocalDynamicTLSModel: 444 return llvm::GlobalVariable::LocalDynamicTLSModel; 445 case CodeGenOptions::InitialExecTLSModel: 446 return llvm::GlobalVariable::InitialExecTLSModel; 447 case CodeGenOptions::LocalExecTLSModel: 448 return llvm::GlobalVariable::LocalExecTLSModel; 449 } 450 llvm_unreachable("Invalid TLS model!"); 451 } 452 453 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV, 454 const VarDecl &D) const { 455 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 456 457 llvm::GlobalVariable::ThreadLocalMode TLM; 458 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 459 460 // Override the TLS model if it is explicitly specified. 461 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 462 TLM = GetLLVMTLSModel(Attr->getModel()); 463 } 464 465 GV->setThreadLocalMode(TLM); 466 } 467 468 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 469 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 470 471 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 472 if (!Str.empty()) 473 return Str; 474 475 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 476 IdentifierInfo *II = ND->getIdentifier(); 477 assert(II && "Attempt to mangle unnamed decl."); 478 479 Str = II->getName(); 480 return Str; 481 } 482 483 SmallString<256> Buffer; 484 llvm::raw_svector_ostream Out(Buffer); 485 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 486 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 487 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 488 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 489 else 490 getCXXABI().getMangleContext().mangleName(ND, Out); 491 492 // Allocate space for the mangled name. 493 Out.flush(); 494 size_t Length = Buffer.size(); 495 char *Name = MangledNamesAllocator.Allocate<char>(Length); 496 std::copy(Buffer.begin(), Buffer.end(), Name); 497 498 Str = StringRef(Name, Length); 499 500 return Str; 501 } 502 503 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 504 const BlockDecl *BD) { 505 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 506 const Decl *D = GD.getDecl(); 507 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 508 if (D == 0) 509 MangleCtx.mangleGlobalBlock(BD, 510 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 511 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 512 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 513 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 514 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 515 else 516 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 517 } 518 519 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 520 return getModule().getNamedValue(Name); 521 } 522 523 /// AddGlobalCtor - Add a function to the list that will be called before 524 /// main() runs. 525 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 526 // FIXME: Type coercion of void()* types. 527 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 528 } 529 530 /// AddGlobalDtor - Add a function to the list that will be called 531 /// when the module is unloaded. 532 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 533 // FIXME: Type coercion of void()* types. 534 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 535 } 536 537 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 538 // Ctor function type is void()*. 539 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 540 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 541 542 // Get the type of a ctor entry, { i32, void ()* }. 543 llvm::StructType *CtorStructTy = 544 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL); 545 546 // Construct the constructor and destructor arrays. 547 SmallVector<llvm::Constant*, 8> Ctors; 548 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 549 llvm::Constant *S[] = { 550 llvm::ConstantInt::get(Int32Ty, I->second, false), 551 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy) 552 }; 553 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 554 } 555 556 if (!Ctors.empty()) { 557 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 558 new llvm::GlobalVariable(TheModule, AT, false, 559 llvm::GlobalValue::AppendingLinkage, 560 llvm::ConstantArray::get(AT, Ctors), 561 GlobalName); 562 } 563 } 564 565 llvm::GlobalValue::LinkageTypes 566 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 567 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 568 569 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 570 571 bool UseThunkForDtorVariant = 572 isa<CXXDestructorDecl>(D) && 573 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 574 GD.getDtorType()); 575 576 return getLLVMLinkageforDeclarator(D, Linkage, /*isConstantVariable=*/false, 577 UseThunkForDtorVariant); 578 } 579 580 581 /// SetFunctionDefinitionAttributes - Set attributes for a global. 582 /// 583 /// FIXME: This is currently only done for aliases and functions, but not for 584 /// variables (these details are set in EmitGlobalVarDefinition for variables). 585 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 586 llvm::GlobalValue *GV) { 587 SetCommonAttributes(D, GV); 588 } 589 590 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 591 const CGFunctionInfo &Info, 592 llvm::Function *F) { 593 unsigned CallingConv; 594 AttributeListType AttributeList; 595 ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 596 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 597 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 598 } 599 600 /// Determines whether the language options require us to model 601 /// unwind exceptions. We treat -fexceptions as mandating this 602 /// except under the fragile ObjC ABI with only ObjC exceptions 603 /// enabled. This means, for example, that C with -fexceptions 604 /// enables this. 605 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 606 // If exceptions are completely disabled, obviously this is false. 607 if (!LangOpts.Exceptions) return false; 608 609 // If C++ exceptions are enabled, this is true. 610 if (LangOpts.CXXExceptions) return true; 611 612 // If ObjC exceptions are enabled, this depends on the ABI. 613 if (LangOpts.ObjCExceptions) { 614 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 615 } 616 617 return true; 618 } 619 620 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 621 llvm::Function *F) { 622 llvm::AttrBuilder B; 623 624 if (CodeGenOpts.UnwindTables) 625 B.addAttribute(llvm::Attribute::UWTable); 626 627 if (!hasUnwindExceptions(LangOpts)) 628 B.addAttribute(llvm::Attribute::NoUnwind); 629 630 if (D->hasAttr<NakedAttr>()) { 631 // Naked implies noinline: we should not be inlining such functions. 632 B.addAttribute(llvm::Attribute::Naked); 633 B.addAttribute(llvm::Attribute::NoInline); 634 } else if (D->hasAttr<OptimizeNoneAttr>()) { 635 // OptimizeNone implies noinline; we should not be inlining such functions. 636 B.addAttribute(llvm::Attribute::OptimizeNone); 637 B.addAttribute(llvm::Attribute::NoInline); 638 } else if (D->hasAttr<NoDuplicateAttr>()) { 639 B.addAttribute(llvm::Attribute::NoDuplicate); 640 } else if (D->hasAttr<NoInlineAttr>()) { 641 B.addAttribute(llvm::Attribute::NoInline); 642 } else if (D->hasAttr<AlwaysInlineAttr>() && 643 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 644 llvm::Attribute::NoInline)) { 645 // (noinline wins over always_inline, and we can't specify both in IR) 646 B.addAttribute(llvm::Attribute::AlwaysInline); 647 } 648 649 if (D->hasAttr<ColdAttr>()) { 650 B.addAttribute(llvm::Attribute::OptimizeForSize); 651 B.addAttribute(llvm::Attribute::Cold); 652 } 653 654 if (D->hasAttr<MinSizeAttr>()) 655 B.addAttribute(llvm::Attribute::MinSize); 656 657 if (D->hasAttr<OptimizeNoneAttr>()) { 658 // OptimizeNone wins over OptimizeForSize and MinSize. 659 B.removeAttribute(llvm::Attribute::OptimizeForSize); 660 B.removeAttribute(llvm::Attribute::MinSize); 661 } 662 663 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 664 B.addAttribute(llvm::Attribute::StackProtect); 665 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 666 B.addAttribute(llvm::Attribute::StackProtectStrong); 667 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 668 B.addAttribute(llvm::Attribute::StackProtectReq); 669 670 // Add sanitizer attributes if function is not blacklisted. 671 if (!SanitizerBlacklist->isIn(*F)) { 672 // When AddressSanitizer is enabled, set SanitizeAddress attribute 673 // unless __attribute__((no_sanitize_address)) is used. 674 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>()) 675 B.addAttribute(llvm::Attribute::SanitizeAddress); 676 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread)) 677 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) { 678 B.addAttribute(llvm::Attribute::SanitizeThread); 679 } 680 // Same for MemorySanitizer and __attribute__((no_sanitize_memory)) 681 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>()) 682 B.addAttribute(llvm::Attribute::SanitizeMemory); 683 } 684 685 F->addAttributes(llvm::AttributeSet::FunctionIndex, 686 llvm::AttributeSet::get( 687 F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 688 689 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 690 F->setUnnamedAddr(true); 691 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 692 if (MD->isVirtual()) 693 F->setUnnamedAddr(true); 694 695 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 696 if (alignment) 697 F->setAlignment(alignment); 698 699 // C++ ABI requires 2-byte alignment for member functions. 700 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 701 F->setAlignment(2); 702 } 703 704 void CodeGenModule::SetCommonAttributes(const Decl *D, 705 llvm::GlobalValue *GV) { 706 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 707 setGlobalVisibility(GV, ND); 708 else 709 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 710 711 if (D->hasAttr<UsedAttr>()) 712 addUsedGlobal(GV); 713 714 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 715 GV->setSection(SA->getName()); 716 717 // Alias cannot have attributes. Filter them here. 718 if (!isa<llvm::GlobalAlias>(GV)) 719 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 720 } 721 722 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 723 llvm::Function *F, 724 const CGFunctionInfo &FI) { 725 SetLLVMFunctionAttributes(D, FI, F); 726 SetLLVMFunctionAttributesForDefinition(D, F); 727 728 F->setLinkage(llvm::Function::InternalLinkage); 729 730 SetCommonAttributes(D, F); 731 } 732 733 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 734 const NamedDecl *ND) { 735 // Set linkage and visibility in case we never see a definition. 736 LinkageInfo LV = ND->getLinkageAndVisibility(); 737 if (LV.getLinkage() != ExternalLinkage) { 738 // Don't set internal linkage on declarations. 739 } else { 740 if (ND->hasAttr<DLLImportAttr>()) { 741 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 742 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 743 } else if (ND->hasAttr<DLLExportAttr>()) { 744 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 745 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 746 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 747 // "extern_weak" is overloaded in LLVM; we probably should have 748 // separate linkage types for this. 749 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 750 } 751 752 // Set visibility on a declaration only if it's explicit. 753 if (LV.isVisibilityExplicit()) 754 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 755 } 756 } 757 758 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 759 llvm::Function *F, 760 bool IsIncompleteFunction) { 761 if (unsigned IID = F->getIntrinsicID()) { 762 // If this is an intrinsic function, set the function's attributes 763 // to the intrinsic's attributes. 764 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 765 (llvm::Intrinsic::ID)IID)); 766 return; 767 } 768 769 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 770 771 if (!IsIncompleteFunction) 772 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 773 774 // Add the Returned attribute for "this", except for iOS 5 and earlier 775 // where substantial code, including the libstdc++ dylib, was compiled with 776 // GCC and does not actually return "this". 777 if (getCXXABI().HasThisReturn(GD) && 778 !(getTarget().getTriple().isiOS() && 779 getTarget().getTriple().isOSVersionLT(6))) { 780 assert(!F->arg_empty() && 781 F->arg_begin()->getType() 782 ->canLosslesslyBitCastTo(F->getReturnType()) && 783 "unexpected this return"); 784 F->addAttribute(1, llvm::Attribute::Returned); 785 } 786 787 // Only a few attributes are set on declarations; these may later be 788 // overridden by a definition. 789 790 setLinkageAndVisibilityForGV(F, FD); 791 792 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 793 F->setSection(SA->getName()); 794 795 // A replaceable global allocation function does not act like a builtin by 796 // default, only if it is invoked by a new-expression or delete-expression. 797 if (FD->isReplaceableGlobalAllocationFunction()) 798 F->addAttribute(llvm::AttributeSet::FunctionIndex, 799 llvm::Attribute::NoBuiltin); 800 } 801 802 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 803 assert(!GV->isDeclaration() && 804 "Only globals with definition can force usage."); 805 LLVMUsed.push_back(GV); 806 } 807 808 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 809 assert(!GV->isDeclaration() && 810 "Only globals with definition can force usage."); 811 LLVMCompilerUsed.push_back(GV); 812 } 813 814 static void emitUsed(CodeGenModule &CGM, StringRef Name, 815 std::vector<llvm::WeakVH> &List) { 816 // Don't create llvm.used if there is no need. 817 if (List.empty()) 818 return; 819 820 // Convert List to what ConstantArray needs. 821 SmallVector<llvm::Constant*, 8> UsedArray; 822 UsedArray.resize(List.size()); 823 for (unsigned i = 0, e = List.size(); i != e; ++i) { 824 UsedArray[i] = 825 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]), 826 CGM.Int8PtrTy); 827 } 828 829 if (UsedArray.empty()) 830 return; 831 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 832 833 llvm::GlobalVariable *GV = 834 new llvm::GlobalVariable(CGM.getModule(), ATy, false, 835 llvm::GlobalValue::AppendingLinkage, 836 llvm::ConstantArray::get(ATy, UsedArray), 837 Name); 838 839 GV->setSection("llvm.metadata"); 840 } 841 842 void CodeGenModule::emitLLVMUsed() { 843 emitUsed(*this, "llvm.used", LLVMUsed); 844 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 845 } 846 847 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 848 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 849 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 850 } 851 852 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 853 llvm::SmallString<32> Opt; 854 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 855 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 856 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 857 } 858 859 void CodeGenModule::AddDependentLib(StringRef Lib) { 860 llvm::SmallString<24> Opt; 861 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 862 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 863 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 864 } 865 866 /// \brief Add link options implied by the given module, including modules 867 /// it depends on, using a postorder walk. 868 static void addLinkOptionsPostorder(CodeGenModule &CGM, 869 Module *Mod, 870 SmallVectorImpl<llvm::Value *> &Metadata, 871 llvm::SmallPtrSet<Module *, 16> &Visited) { 872 // Import this module's parent. 873 if (Mod->Parent && Visited.insert(Mod->Parent)) { 874 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 875 } 876 877 // Import this module's dependencies. 878 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 879 if (Visited.insert(Mod->Imports[I-1])) 880 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 881 } 882 883 // Add linker options to link against the libraries/frameworks 884 // described by this module. 885 llvm::LLVMContext &Context = CGM.getLLVMContext(); 886 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 887 // Link against a framework. Frameworks are currently Darwin only, so we 888 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 889 if (Mod->LinkLibraries[I-1].IsFramework) { 890 llvm::Value *Args[2] = { 891 llvm::MDString::get(Context, "-framework"), 892 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library) 893 }; 894 895 Metadata.push_back(llvm::MDNode::get(Context, Args)); 896 continue; 897 } 898 899 // Link against a library. 900 llvm::SmallString<24> Opt; 901 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 902 Mod->LinkLibraries[I-1].Library, Opt); 903 llvm::Value *OptString = llvm::MDString::get(Context, Opt); 904 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 905 } 906 } 907 908 void CodeGenModule::EmitModuleLinkOptions() { 909 // Collect the set of all of the modules we want to visit to emit link 910 // options, which is essentially the imported modules and all of their 911 // non-explicit child modules. 912 llvm::SetVector<clang::Module *> LinkModules; 913 llvm::SmallPtrSet<clang::Module *, 16> Visited; 914 SmallVector<clang::Module *, 16> Stack; 915 916 // Seed the stack with imported modules. 917 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(), 918 MEnd = ImportedModules.end(); 919 M != MEnd; ++M) { 920 if (Visited.insert(*M)) 921 Stack.push_back(*M); 922 } 923 924 // Find all of the modules to import, making a little effort to prune 925 // non-leaf modules. 926 while (!Stack.empty()) { 927 clang::Module *Mod = Stack.pop_back_val(); 928 929 bool AnyChildren = false; 930 931 // Visit the submodules of this module. 932 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 933 SubEnd = Mod->submodule_end(); 934 Sub != SubEnd; ++Sub) { 935 // Skip explicit children; they need to be explicitly imported to be 936 // linked against. 937 if ((*Sub)->IsExplicit) 938 continue; 939 940 if (Visited.insert(*Sub)) { 941 Stack.push_back(*Sub); 942 AnyChildren = true; 943 } 944 } 945 946 // We didn't find any children, so add this module to the list of 947 // modules to link against. 948 if (!AnyChildren) { 949 LinkModules.insert(Mod); 950 } 951 } 952 953 // Add link options for all of the imported modules in reverse topological 954 // order. We don't do anything to try to order import link flags with respect 955 // to linker options inserted by things like #pragma comment(). 956 SmallVector<llvm::Value *, 16> MetadataArgs; 957 Visited.clear(); 958 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(), 959 MEnd = LinkModules.end(); 960 M != MEnd; ++M) { 961 if (Visited.insert(*M)) 962 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited); 963 } 964 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 965 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 966 967 // Add the linker options metadata flag. 968 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 969 llvm::MDNode::get(getLLVMContext(), 970 LinkerOptionsMetadata)); 971 } 972 973 void CodeGenModule::EmitDeferred() { 974 // Emit code for any potentially referenced deferred decls. Since a 975 // previously unused static decl may become used during the generation of code 976 // for a static function, iterate until no changes are made. 977 978 while (true) { 979 if (!DeferredVTables.empty()) { 980 EmitDeferredVTables(); 981 982 // Emitting a v-table doesn't directly cause more v-tables to 983 // become deferred, although it can cause functions to be 984 // emitted that then need those v-tables. 985 assert(DeferredVTables.empty()); 986 } 987 988 // Stop if we're out of both deferred v-tables and deferred declarations. 989 if (DeferredDeclsToEmit.empty()) break; 990 991 DeferredGlobal &G = DeferredDeclsToEmit.back(); 992 GlobalDecl D = G.GD; 993 llvm::GlobalValue *GV = G.GV; 994 DeferredDeclsToEmit.pop_back(); 995 996 assert(GV == GetGlobalValue(getMangledName(D))); 997 // Check to see if we've already emitted this. This is necessary 998 // for a couple of reasons: first, decls can end up in the 999 // deferred-decls queue multiple times, and second, decls can end 1000 // up with definitions in unusual ways (e.g. by an extern inline 1001 // function acquiring a strong function redefinition). Just 1002 // ignore these cases. 1003 if(!GV->isDeclaration()) 1004 continue; 1005 1006 // Otherwise, emit the definition and move on to the next one. 1007 EmitGlobalDefinition(D, GV); 1008 } 1009 } 1010 1011 void CodeGenModule::EmitGlobalAnnotations() { 1012 if (Annotations.empty()) 1013 return; 1014 1015 // Create a new global variable for the ConstantStruct in the Module. 1016 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1017 Annotations[0]->getType(), Annotations.size()), Annotations); 1018 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 1019 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 1020 "llvm.global.annotations"); 1021 gv->setSection(AnnotationSection); 1022 } 1023 1024 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1025 llvm::Constant *&AStr = AnnotationStrings[Str]; 1026 if (AStr) 1027 return AStr; 1028 1029 // Not found yet, create a new global. 1030 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1031 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 1032 true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 1033 gv->setSection(AnnotationSection); 1034 gv->setUnnamedAddr(true); 1035 AStr = gv; 1036 return gv; 1037 } 1038 1039 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1040 SourceManager &SM = getContext().getSourceManager(); 1041 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1042 if (PLoc.isValid()) 1043 return EmitAnnotationString(PLoc.getFilename()); 1044 return EmitAnnotationString(SM.getBufferName(Loc)); 1045 } 1046 1047 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1048 SourceManager &SM = getContext().getSourceManager(); 1049 PresumedLoc PLoc = SM.getPresumedLoc(L); 1050 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1051 SM.getExpansionLineNumber(L); 1052 return llvm::ConstantInt::get(Int32Ty, LineNo); 1053 } 1054 1055 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1056 const AnnotateAttr *AA, 1057 SourceLocation L) { 1058 // Get the globals for file name, annotation, and the line number. 1059 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1060 *UnitGV = EmitAnnotationUnit(L), 1061 *LineNoCst = EmitAnnotationLineNo(L); 1062 1063 // Create the ConstantStruct for the global annotation. 1064 llvm::Constant *Fields[4] = { 1065 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1066 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1067 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1068 LineNoCst 1069 }; 1070 return llvm::ConstantStruct::getAnon(Fields); 1071 } 1072 1073 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1074 llvm::GlobalValue *GV) { 1075 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1076 // Get the struct elements for these annotations. 1077 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1078 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1079 } 1080 1081 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 1082 // Never defer when EmitAllDecls is specified. 1083 if (LangOpts.EmitAllDecls) 1084 return false; 1085 1086 return !getContext().DeclMustBeEmitted(Global); 1087 } 1088 1089 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 1090 const CXXUuidofExpr* E) { 1091 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1092 // well-formed. 1093 StringRef Uuid = E->getUuidAsStringRef(Context); 1094 std::string Name = "_GUID_" + Uuid.lower(); 1095 std::replace(Name.begin(), Name.end(), '-', '_'); 1096 1097 // Look for an existing global. 1098 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1099 return GV; 1100 1101 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType()); 1102 assert(Init && "failed to initialize as constant"); 1103 1104 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1105 getModule(), Init->getType(), 1106 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1107 return GV; 1108 } 1109 1110 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1111 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1112 assert(AA && "No alias?"); 1113 1114 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1115 1116 // See if there is already something with the target's name in the module. 1117 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1118 if (Entry) { 1119 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1120 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1121 } 1122 1123 llvm::Constant *Aliasee; 1124 if (isa<llvm::FunctionType>(DeclTy)) 1125 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1126 GlobalDecl(cast<FunctionDecl>(VD)), 1127 /*ForVTable=*/false); 1128 else 1129 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1130 llvm::PointerType::getUnqual(DeclTy), 0); 1131 1132 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 1133 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1134 WeakRefReferences.insert(F); 1135 1136 return Aliasee; 1137 } 1138 1139 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1140 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 1141 1142 // Weak references don't produce any output by themselves. 1143 if (Global->hasAttr<WeakRefAttr>()) 1144 return; 1145 1146 // If this is an alias definition (which otherwise looks like a declaration) 1147 // emit it now. 1148 if (Global->hasAttr<AliasAttr>()) 1149 return EmitAliasDefinition(GD); 1150 1151 // If this is CUDA, be selective about which declarations we emit. 1152 if (LangOpts.CUDA) { 1153 if (CodeGenOpts.CUDAIsDevice) { 1154 if (!Global->hasAttr<CUDADeviceAttr>() && 1155 !Global->hasAttr<CUDAGlobalAttr>() && 1156 !Global->hasAttr<CUDAConstantAttr>() && 1157 !Global->hasAttr<CUDASharedAttr>()) 1158 return; 1159 } else { 1160 if (!Global->hasAttr<CUDAHostAttr>() && ( 1161 Global->hasAttr<CUDADeviceAttr>() || 1162 Global->hasAttr<CUDAConstantAttr>() || 1163 Global->hasAttr<CUDASharedAttr>())) 1164 return; 1165 } 1166 } 1167 1168 // Ignore declarations, they will be emitted on their first use. 1169 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 1170 // Forward declarations are emitted lazily on first use. 1171 if (!FD->doesThisDeclarationHaveABody()) { 1172 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1173 return; 1174 1175 StringRef MangledName = getMangledName(GD); 1176 1177 // Compute the function info and LLVM type. 1178 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1179 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1180 1181 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1182 /*DontDefer=*/false); 1183 return; 1184 } 1185 } else { 1186 const VarDecl *VD = cast<VarDecl>(Global); 1187 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1188 1189 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 1190 return; 1191 } 1192 1193 // Defer code generation when possible if this is a static definition, inline 1194 // function etc. These we only want to emit if they are used. 1195 if (!MayDeferGeneration(Global)) { 1196 // Emit the definition if it can't be deferred. 1197 EmitGlobalDefinition(GD); 1198 return; 1199 } 1200 1201 // If we're deferring emission of a C++ variable with an 1202 // initializer, remember the order in which it appeared in the file. 1203 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1204 cast<VarDecl>(Global)->hasInit()) { 1205 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1206 CXXGlobalInits.push_back(0); 1207 } 1208 1209 // If the value has already been used, add it directly to the 1210 // DeferredDeclsToEmit list. 1211 StringRef MangledName = getMangledName(GD); 1212 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) 1213 addDeferredDeclToEmit(GV, GD); 1214 else { 1215 // Otherwise, remember that we saw a deferred decl with this name. The 1216 // first use of the mangled name will cause it to move into 1217 // DeferredDeclsToEmit. 1218 DeferredDecls[MangledName] = GD; 1219 } 1220 } 1221 1222 namespace { 1223 struct FunctionIsDirectlyRecursive : 1224 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1225 const StringRef Name; 1226 const Builtin::Context &BI; 1227 bool Result; 1228 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1229 Name(N), BI(C), Result(false) { 1230 } 1231 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1232 1233 bool TraverseCallExpr(CallExpr *E) { 1234 const FunctionDecl *FD = E->getDirectCallee(); 1235 if (!FD) 1236 return true; 1237 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1238 if (Attr && Name == Attr->getLabel()) { 1239 Result = true; 1240 return false; 1241 } 1242 unsigned BuiltinID = FD->getBuiltinID(); 1243 if (!BuiltinID) 1244 return true; 1245 StringRef BuiltinName = BI.GetName(BuiltinID); 1246 if (BuiltinName.startswith("__builtin_") && 1247 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1248 Result = true; 1249 return false; 1250 } 1251 return true; 1252 } 1253 }; 1254 } 1255 1256 // isTriviallyRecursive - Check if this function calls another 1257 // decl that, because of the asm attribute or the other decl being a builtin, 1258 // ends up pointing to itself. 1259 bool 1260 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1261 StringRef Name; 1262 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1263 // asm labels are a special kind of mangling we have to support. 1264 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1265 if (!Attr) 1266 return false; 1267 Name = Attr->getLabel(); 1268 } else { 1269 Name = FD->getName(); 1270 } 1271 1272 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1273 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1274 return Walker.Result; 1275 } 1276 1277 bool 1278 CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1279 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1280 return true; 1281 const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl()); 1282 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1283 return false; 1284 // PR9614. Avoid cases where the source code is lying to us. An available 1285 // externally function should have an equivalent function somewhere else, 1286 // but a function that calls itself is clearly not equivalent to the real 1287 // implementation. 1288 // This happens in glibc's btowc and in some configure checks. 1289 return !isTriviallyRecursive(F); 1290 } 1291 1292 /// If the type for the method's class was generated by 1293 /// CGDebugInfo::createContextChain(), the cache contains only a 1294 /// limited DIType without any declarations. Since EmitFunctionStart() 1295 /// needs to find the canonical declaration for each method, we need 1296 /// to construct the complete type prior to emitting the method. 1297 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1298 if (!D->isInstance()) 1299 return; 1300 1301 if (CGDebugInfo *DI = getModuleDebugInfo()) 1302 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 1303 const PointerType *ThisPtr = 1304 cast<PointerType>(D->getThisType(getContext())); 1305 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1306 } 1307 } 1308 1309 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 1310 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1311 1312 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1313 Context.getSourceManager(), 1314 "Generating code for declaration"); 1315 1316 if (isa<FunctionDecl>(D)) { 1317 // At -O0, don't generate IR for functions with available_externally 1318 // linkage. 1319 if (!shouldEmitFunction(GD)) 1320 return; 1321 1322 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1323 CompleteDIClassType(Method); 1324 // Make sure to emit the definition(s) before we emit the thunks. 1325 // This is necessary for the generation of certain thunks. 1326 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 1327 EmitCXXConstructor(CD, GD.getCtorType()); 1328 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 1329 EmitCXXDestructor(DD, GD.getDtorType()); 1330 else 1331 EmitGlobalFunctionDefinition(GD, GV); 1332 1333 if (Method->isVirtual()) 1334 getVTables().EmitThunks(GD); 1335 1336 return; 1337 } 1338 1339 return EmitGlobalFunctionDefinition(GD, GV); 1340 } 1341 1342 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1343 return EmitGlobalVarDefinition(VD); 1344 1345 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1346 } 1347 1348 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1349 /// module, create and return an llvm Function with the specified type. If there 1350 /// is something in the module with the specified name, return it potentially 1351 /// bitcasted to the right type. 1352 /// 1353 /// If D is non-null, it specifies a decl that correspond to this. This is used 1354 /// to set the attributes on the function when it is first created. 1355 llvm::Constant * 1356 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1357 llvm::Type *Ty, 1358 GlobalDecl GD, bool ForVTable, 1359 bool DontDefer, 1360 llvm::AttributeSet ExtraAttrs) { 1361 const Decl *D = GD.getDecl(); 1362 1363 // Lookup the entry, lazily creating it if necessary. 1364 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1365 if (Entry) { 1366 if (WeakRefReferences.erase(Entry)) { 1367 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1368 if (FD && !FD->hasAttr<WeakAttr>()) 1369 Entry->setLinkage(llvm::Function::ExternalLinkage); 1370 } 1371 1372 if (Entry->getType()->getElementType() == Ty) 1373 return Entry; 1374 1375 // Make sure the result is of the correct type. 1376 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1377 } 1378 1379 // This function doesn't have a complete type (for example, the return 1380 // type is an incomplete struct). Use a fake type instead, and make 1381 // sure not to try to set attributes. 1382 bool IsIncompleteFunction = false; 1383 1384 llvm::FunctionType *FTy; 1385 if (isa<llvm::FunctionType>(Ty)) { 1386 FTy = cast<llvm::FunctionType>(Ty); 1387 } else { 1388 FTy = llvm::FunctionType::get(VoidTy, false); 1389 IsIncompleteFunction = true; 1390 } 1391 1392 llvm::Function *F = llvm::Function::Create(FTy, 1393 llvm::Function::ExternalLinkage, 1394 MangledName, &getModule()); 1395 assert(F->getName() == MangledName && "name was uniqued!"); 1396 if (D) 1397 SetFunctionAttributes(GD, F, IsIncompleteFunction); 1398 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1399 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1400 F->addAttributes(llvm::AttributeSet::FunctionIndex, 1401 llvm::AttributeSet::get(VMContext, 1402 llvm::AttributeSet::FunctionIndex, 1403 B)); 1404 } 1405 1406 if (!DontDefer) { 1407 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1408 // each other bottoming out with the base dtor. Therefore we emit non-base 1409 // dtors on usage, even if there is no dtor definition in the TU. 1410 if (D && isa<CXXDestructorDecl>(D) && 1411 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1412 GD.getDtorType())) 1413 addDeferredDeclToEmit(F, GD); 1414 1415 // This is the first use or definition of a mangled name. If there is a 1416 // deferred decl with this name, remember that we need to emit it at the end 1417 // of the file. 1418 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1419 if (DDI != DeferredDecls.end()) { 1420 // Move the potentially referenced deferred decl to the 1421 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 1422 // don't need it anymore). 1423 addDeferredDeclToEmit(F, DDI->second); 1424 DeferredDecls.erase(DDI); 1425 1426 // Otherwise, if this is a sized deallocation function, emit a weak 1427 // definition 1428 // for it at the end of the translation unit. 1429 } else if (D && cast<FunctionDecl>(D) 1430 ->getCorrespondingUnsizedGlobalDeallocationFunction()) { 1431 addDeferredDeclToEmit(F, GD); 1432 1433 // Otherwise, there are cases we have to worry about where we're 1434 // using a declaration for which we must emit a definition but where 1435 // we might not find a top-level definition: 1436 // - member functions defined inline in their classes 1437 // - friend functions defined inline in some class 1438 // - special member functions with implicit definitions 1439 // If we ever change our AST traversal to walk into class methods, 1440 // this will be unnecessary. 1441 // 1442 // We also don't emit a definition for a function if it's going to be an 1443 // entry 1444 // in a vtable, unless it's already marked as used. 1445 } else if (getLangOpts().CPlusPlus && D) { 1446 // Look for a declaration that's lexically in a record. 1447 const FunctionDecl *FD = cast<FunctionDecl>(D); 1448 FD = FD->getMostRecentDecl(); 1449 do { 1450 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1451 if (FD->isImplicit() && !ForVTable) { 1452 assert(FD->isUsed() && 1453 "Sema didn't mark implicit function as used!"); 1454 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1455 break; 1456 } else if (FD->doesThisDeclarationHaveABody()) { 1457 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1458 break; 1459 } 1460 } 1461 FD = FD->getPreviousDecl(); 1462 } while (FD); 1463 } 1464 } 1465 1466 getTargetCodeGenInfo().emitTargetMD(D, F, *this); 1467 1468 // Make sure the result is of the requested type. 1469 if (!IsIncompleteFunction) { 1470 assert(F->getType()->getElementType() == Ty); 1471 return F; 1472 } 1473 1474 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1475 return llvm::ConstantExpr::getBitCast(F, PTy); 1476 } 1477 1478 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1479 /// non-null, then this function will use the specified type if it has to 1480 /// create it (this occurs when we see a definition of the function). 1481 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1482 llvm::Type *Ty, 1483 bool ForVTable, 1484 bool DontDefer) { 1485 // If there was no specific requested type, just convert it now. 1486 if (!Ty) 1487 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1488 1489 StringRef MangledName = getMangledName(GD); 1490 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer); 1491 } 1492 1493 /// CreateRuntimeFunction - Create a new runtime function with the specified 1494 /// type and name. 1495 llvm::Constant * 1496 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1497 StringRef Name, 1498 llvm::AttributeSet ExtraAttrs) { 1499 llvm::Constant *C = 1500 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1501 /*DontDefer=*/false, ExtraAttrs); 1502 if (llvm::Function *F = dyn_cast<llvm::Function>(C)) 1503 if (F->empty()) 1504 F->setCallingConv(getRuntimeCC()); 1505 return C; 1506 } 1507 1508 /// isTypeConstant - Determine whether an object of this type can be emitted 1509 /// as a constant. 1510 /// 1511 /// If ExcludeCtor is true, the duration when the object's constructor runs 1512 /// will not be considered. The caller will need to verify that the object is 1513 /// not written to during its construction. 1514 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1515 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1516 return false; 1517 1518 if (Context.getLangOpts().CPlusPlus) { 1519 if (const CXXRecordDecl *Record 1520 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1521 return ExcludeCtor && !Record->hasMutableFields() && 1522 Record->hasTrivialDestructor(); 1523 } 1524 1525 return true; 1526 } 1527 1528 static bool isVarDeclInlineInitializedStaticDataMember(const VarDecl *VD) { 1529 if (!VD->isStaticDataMember()) 1530 return false; 1531 const VarDecl *InitDecl; 1532 const Expr *InitExpr = VD->getAnyInitializer(InitDecl); 1533 if (!InitExpr) 1534 return false; 1535 if (InitDecl->isThisDeclarationADefinition()) 1536 return false; 1537 return true; 1538 } 1539 1540 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1541 /// create and return an llvm GlobalVariable with the specified type. If there 1542 /// is something in the module with the specified name, return it potentially 1543 /// bitcasted to the right type. 1544 /// 1545 /// If D is non-null, it specifies a decl that correspond to this. This is used 1546 /// to set the attributes on the global when it is first created. 1547 llvm::Constant * 1548 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1549 llvm::PointerType *Ty, 1550 const VarDecl *D, 1551 bool UnnamedAddr) { 1552 // Lookup the entry, lazily creating it if necessary. 1553 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1554 if (Entry) { 1555 if (WeakRefReferences.erase(Entry)) { 1556 if (D && !D->hasAttr<WeakAttr>()) 1557 Entry->setLinkage(llvm::Function::ExternalLinkage); 1558 } 1559 1560 if (UnnamedAddr) 1561 Entry->setUnnamedAddr(true); 1562 1563 if (Entry->getType() == Ty) 1564 return Entry; 1565 1566 // Make sure the result is of the correct type. 1567 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1568 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1569 1570 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1571 } 1572 1573 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 1574 llvm::GlobalVariable *GV = 1575 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1576 llvm::GlobalValue::ExternalLinkage, 1577 0, MangledName, 0, 1578 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 1579 1580 // This is the first use or definition of a mangled name. If there is a 1581 // deferred decl with this name, remember that we need to emit it at the end 1582 // of the file. 1583 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1584 if (DDI != DeferredDecls.end()) { 1585 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1586 // list, and remove it from DeferredDecls (since we don't need it anymore). 1587 addDeferredDeclToEmit(GV, DDI->second); 1588 DeferredDecls.erase(DDI); 1589 } 1590 1591 // Handle things which are present even on external declarations. 1592 if (D) { 1593 // FIXME: This code is overly simple and should be merged with other global 1594 // handling. 1595 GV->setConstant(isTypeConstant(D->getType(), false)); 1596 1597 setLinkageAndVisibilityForGV(GV, D); 1598 1599 if (D->getTLSKind()) { 1600 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 1601 CXXThreadLocals.push_back(std::make_pair(D, GV)); 1602 setTLSMode(GV, *D); 1603 } 1604 1605 // If required by the ABI, treat declarations of static data members with 1606 // inline initializers as definitions. 1607 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() && 1608 isVarDeclInlineInitializedStaticDataMember(D)) 1609 EmitGlobalVarDefinition(D); 1610 } 1611 1612 if (AddrSpace != Ty->getAddressSpace()) 1613 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 1614 1615 if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 1616 D->getLanguageLinkage() == CLanguageLinkage && 1617 D->getType().isConstant(Context) && 1618 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 1619 GV->setSection(".cp.rodata"); 1620 1621 getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 1622 1623 return GV; 1624 } 1625 1626 1627 llvm::GlobalVariable * 1628 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1629 llvm::Type *Ty, 1630 llvm::GlobalValue::LinkageTypes Linkage) { 1631 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1632 llvm::GlobalVariable *OldGV = 0; 1633 1634 1635 if (GV) { 1636 // Check if the variable has the right type. 1637 if (GV->getType()->getElementType() == Ty) 1638 return GV; 1639 1640 // Because C++ name mangling, the only way we can end up with an already 1641 // existing global with the same name is if it has been declared extern "C". 1642 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1643 OldGV = GV; 1644 } 1645 1646 // Create a new variable. 1647 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1648 Linkage, 0, Name); 1649 1650 if (OldGV) { 1651 // Replace occurrences of the old variable if needed. 1652 GV->takeName(OldGV); 1653 1654 if (!OldGV->use_empty()) { 1655 llvm::Constant *NewPtrForOldDecl = 1656 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1657 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1658 } 1659 1660 OldGV->eraseFromParent(); 1661 } 1662 1663 return GV; 1664 } 1665 1666 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1667 /// given global variable. If Ty is non-null and if the global doesn't exist, 1668 /// then it will be created with the specified type instead of whatever the 1669 /// normal requested type would be. 1670 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1671 llvm::Type *Ty) { 1672 assert(D->hasGlobalStorage() && "Not a global variable"); 1673 QualType ASTTy = D->getType(); 1674 if (Ty == 0) 1675 Ty = getTypes().ConvertTypeForMem(ASTTy); 1676 1677 llvm::PointerType *PTy = 1678 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1679 1680 StringRef MangledName = getMangledName(D); 1681 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1682 } 1683 1684 /// CreateRuntimeVariable - Create a new runtime global variable with the 1685 /// specified type and name. 1686 llvm::Constant * 1687 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1688 StringRef Name) { 1689 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1690 true); 1691 } 1692 1693 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1694 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1695 1696 if (MayDeferGeneration(D)) { 1697 // If we have not seen a reference to this variable yet, place it 1698 // into the deferred declarations table to be emitted if needed 1699 // later. 1700 StringRef MangledName = getMangledName(D); 1701 if (!GetGlobalValue(MangledName)) { 1702 DeferredDecls[MangledName] = D; 1703 return; 1704 } 1705 } 1706 1707 // The tentative definition is the only definition. 1708 EmitGlobalVarDefinition(D); 1709 } 1710 1711 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1712 return Context.toCharUnitsFromBits( 1713 TheDataLayout.getTypeStoreSizeInBits(Ty)); 1714 } 1715 1716 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 1717 unsigned AddrSpace) { 1718 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 1719 if (D->hasAttr<CUDAConstantAttr>()) 1720 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 1721 else if (D->hasAttr<CUDASharedAttr>()) 1722 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 1723 else 1724 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 1725 } 1726 1727 return AddrSpace; 1728 } 1729 1730 template<typename SomeDecl> 1731 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 1732 llvm::GlobalValue *GV) { 1733 if (!getLangOpts().CPlusPlus) 1734 return; 1735 1736 // Must have 'used' attribute, or else inline assembly can't rely on 1737 // the name existing. 1738 if (!D->template hasAttr<UsedAttr>()) 1739 return; 1740 1741 // Must have internal linkage and an ordinary name. 1742 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 1743 return; 1744 1745 // Must be in an extern "C" context. Entities declared directly within 1746 // a record are not extern "C" even if the record is in such a context. 1747 const SomeDecl *First = D->getFirstDecl(); 1748 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 1749 return; 1750 1751 // OK, this is an internal linkage entity inside an extern "C" linkage 1752 // specification. Make a note of that so we can give it the "expected" 1753 // mangled name if nothing else is using that name. 1754 std::pair<StaticExternCMap::iterator, bool> R = 1755 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 1756 1757 // If we have multiple internal linkage entities with the same name 1758 // in extern "C" regions, none of them gets that name. 1759 if (!R.second) 1760 R.first->second = 0; 1761 } 1762 1763 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1764 llvm::Constant *Init = 0; 1765 QualType ASTTy = D->getType(); 1766 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1767 bool NeedsGlobalCtor = false; 1768 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1769 1770 const VarDecl *InitDecl; 1771 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1772 1773 if (!InitExpr) { 1774 // This is a tentative definition; tentative definitions are 1775 // implicitly initialized with { 0 }. 1776 // 1777 // Note that tentative definitions are only emitted at the end of 1778 // a translation unit, so they should never have incomplete 1779 // type. In addition, EmitTentativeDefinition makes sure that we 1780 // never attempt to emit a tentative definition if a real one 1781 // exists. A use may still exists, however, so we still may need 1782 // to do a RAUW. 1783 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1784 Init = EmitNullConstant(D->getType()); 1785 } else { 1786 initializedGlobalDecl = GlobalDecl(D); 1787 Init = EmitConstantInit(*InitDecl); 1788 1789 if (!Init) { 1790 QualType T = InitExpr->getType(); 1791 if (D->getType()->isReferenceType()) 1792 T = D->getType(); 1793 1794 if (getLangOpts().CPlusPlus) { 1795 Init = EmitNullConstant(T); 1796 NeedsGlobalCtor = true; 1797 } else { 1798 ErrorUnsupported(D, "static initializer"); 1799 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1800 } 1801 } else { 1802 // We don't need an initializer, so remove the entry for the delayed 1803 // initializer position (just in case this entry was delayed) if we 1804 // also don't need to register a destructor. 1805 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1806 DelayedCXXInitPosition.erase(D); 1807 } 1808 } 1809 1810 llvm::Type* InitType = Init->getType(); 1811 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1812 1813 // Strip off a bitcast if we got one back. 1814 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1815 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1816 CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 1817 // All zero index gep. 1818 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1819 Entry = CE->getOperand(0); 1820 } 1821 1822 // Entry is now either a Function or GlobalVariable. 1823 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1824 1825 // We have a definition after a declaration with the wrong type. 1826 // We must make a new GlobalVariable* and update everything that used OldGV 1827 // (a declaration or tentative definition) with the new GlobalVariable* 1828 // (which will be a definition). 1829 // 1830 // This happens if there is a prototype for a global (e.g. 1831 // "extern int x[];") and then a definition of a different type (e.g. 1832 // "int x[10];"). This also happens when an initializer has a different type 1833 // from the type of the global (this happens with unions). 1834 if (GV == 0 || 1835 GV->getType()->getElementType() != InitType || 1836 GV->getType()->getAddressSpace() != 1837 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1838 1839 // Move the old entry aside so that we'll create a new one. 1840 Entry->setName(StringRef()); 1841 1842 // Make a new global with the correct type, this is now guaranteed to work. 1843 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1844 1845 // Replace all uses of the old global with the new global 1846 llvm::Constant *NewPtrForOldDecl = 1847 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1848 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1849 1850 // Erase the old global, since it is no longer used. 1851 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1852 } 1853 1854 MaybeHandleStaticInExternC(D, GV); 1855 1856 if (D->hasAttr<AnnotateAttr>()) 1857 AddGlobalAnnotations(D, GV); 1858 1859 GV->setInitializer(Init); 1860 1861 // If it is safe to mark the global 'constant', do so now. 1862 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1863 isTypeConstant(D->getType(), true)); 1864 1865 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1866 1867 // Set the llvm linkage type as appropriate. 1868 llvm::GlobalValue::LinkageTypes Linkage = 1869 getLLVMLinkageVarDefinition(D, GV->isConstant()); 1870 GV->setLinkage(Linkage); 1871 if (D->hasAttr<DLLImportAttr>()) 1872 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1873 else if (D->hasAttr<DLLExportAttr>()) 1874 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1875 1876 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1877 // common vars aren't constant even if declared const. 1878 GV->setConstant(false); 1879 1880 SetCommonAttributes(D, GV); 1881 1882 // Emit the initializer function if necessary. 1883 if (NeedsGlobalCtor || NeedsGlobalDtor) 1884 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1885 1886 // If we are compiling with ASan, add metadata indicating dynamically 1887 // initialized globals. 1888 if (SanOpts.Address && NeedsGlobalCtor) { 1889 llvm::Module &M = getModule(); 1890 1891 llvm::NamedMDNode *DynamicInitializers = 1892 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals"); 1893 llvm::Value *GlobalToAdd[] = { GV }; 1894 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd); 1895 DynamicInitializers->addOperand(ThisGlobal); 1896 } 1897 1898 // Emit global variable debug information. 1899 if (CGDebugInfo *DI = getModuleDebugInfo()) 1900 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1901 DI->EmitGlobalVariable(GV, D); 1902 } 1903 1904 static bool isVarDeclStrongDefinition(const VarDecl *D, bool NoCommon) { 1905 // Don't give variables common linkage if -fno-common was specified unless it 1906 // was overridden by a NoCommon attribute. 1907 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 1908 return true; 1909 1910 // C11 6.9.2/2: 1911 // A declaration of an identifier for an object that has file scope without 1912 // an initializer, and without a storage-class specifier or with the 1913 // storage-class specifier static, constitutes a tentative definition. 1914 if (D->getInit() || D->hasExternalStorage()) 1915 return true; 1916 1917 // A variable cannot be both common and exist in a section. 1918 if (D->hasAttr<SectionAttr>()) 1919 return true; 1920 1921 // Thread local vars aren't considered common linkage. 1922 if (D->getTLSKind()) 1923 return true; 1924 1925 // Tentative definitions marked with WeakImportAttr are true definitions. 1926 if (D->hasAttr<WeakImportAttr>()) 1927 return true; 1928 1929 return false; 1930 } 1931 1932 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageforDeclarator( 1933 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable, 1934 bool UseThunkForDtorVariant) { 1935 if (Linkage == GVA_Internal) 1936 return llvm::Function::InternalLinkage; 1937 1938 if (D->hasAttr<WeakAttr>()) { 1939 if (IsConstantVariable) 1940 return llvm::GlobalVariable::WeakODRLinkage; 1941 else 1942 return llvm::GlobalVariable::WeakAnyLinkage; 1943 } 1944 1945 // We are guaranteed to have a strong definition somewhere else, 1946 // so we can use available_externally linkage. 1947 if (Linkage == GVA_AvailableExternally) 1948 return llvm::Function::AvailableExternallyLinkage; 1949 1950 // LinkOnceODRLinkage is insufficient if the symbol is required to exist in 1951 // the symbol table. Promote the linkage to WeakODRLinkage to preserve the 1952 // semantics of LinkOnceODRLinkage while providing visibility in the symbol 1953 // table. 1954 llvm::GlobalValue::LinkageTypes OnceLinkage = 1955 llvm::GlobalValue::LinkOnceODRLinkage; 1956 if (D->hasAttr<DLLExportAttr>() || D->hasAttr<DLLImportAttr>()) 1957 OnceLinkage = llvm::GlobalVariable::WeakODRLinkage; 1958 1959 // Note that Apple's kernel linker doesn't support symbol 1960 // coalescing, so we need to avoid linkonce and weak linkages there. 1961 // Normally, this means we just map to internal, but for explicit 1962 // instantiations we'll map to external. 1963 1964 // In C++, the compiler has to emit a definition in every translation unit 1965 // that references the function. We should use linkonce_odr because 1966 // a) if all references in this translation unit are optimized away, we 1967 // don't need to codegen it. b) if the function persists, it needs to be 1968 // merged with other definitions. c) C++ has the ODR, so we know the 1969 // definition is dependable. 1970 if (Linkage == GVA_DiscardableODR) 1971 return !Context.getLangOpts().AppleKext ? OnceLinkage 1972 : llvm::Function::InternalLinkage; 1973 1974 // An explicit instantiation of a template has weak linkage, since 1975 // explicit instantiations can occur in multiple translation units 1976 // and must all be equivalent. However, we are not allowed to 1977 // throw away these explicit instantiations. 1978 if (Linkage == GVA_StrongODR) 1979 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 1980 : llvm::Function::ExternalLinkage; 1981 1982 // Destructor variants in the Microsoft C++ ABI are always linkonce_odr thunks 1983 // emitted on an as-needed basis. 1984 if (UseThunkForDtorVariant) 1985 return OnceLinkage; 1986 1987 // If required by the ABI, give definitions of static data members with inline 1988 // initializers at least linkonce_odr linkage. 1989 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() && 1990 isa<VarDecl>(D) && 1991 isVarDeclInlineInitializedStaticDataMember(cast<VarDecl>(D))) 1992 return OnceLinkage; 1993 1994 // C++ doesn't have tentative definitions and thus cannot have common 1995 // linkage. 1996 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 1997 !isVarDeclStrongDefinition(cast<VarDecl>(D), CodeGenOpts.NoCommon)) 1998 return llvm::GlobalVariable::CommonLinkage; 1999 2000 // selectany symbols are externally visible, so use weak instead of 2001 // linkonce. MSVC optimizes away references to const selectany globals, so 2002 // all definitions should be the same and ODR linkage should be used. 2003 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 2004 if (D->hasAttr<SelectAnyAttr>()) 2005 return llvm::GlobalVariable::WeakODRLinkage; 2006 2007 // Otherwise, we have strong external linkage. 2008 assert(Linkage == GVA_StrongExternal); 2009 return llvm::GlobalVariable::ExternalLinkage; 2010 } 2011 2012 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 2013 const VarDecl *VD, bool IsConstant) { 2014 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 2015 return getLLVMLinkageforDeclarator(VD, Linkage, IsConstant, 2016 /*UseThunkForDtorVariant=*/false); 2017 } 2018 2019 /// Replace the uses of a function that was declared with a non-proto type. 2020 /// We want to silently drop extra arguments from call sites 2021 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2022 llvm::Function *newFn) { 2023 // Fast path. 2024 if (old->use_empty()) return; 2025 2026 llvm::Type *newRetTy = newFn->getReturnType(); 2027 SmallVector<llvm::Value*, 4> newArgs; 2028 2029 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2030 ui != ue; ) { 2031 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 2032 llvm::User *user = use->getUser(); 2033 2034 // Recognize and replace uses of bitcasts. Most calls to 2035 // unprototyped functions will use bitcasts. 2036 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2037 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2038 replaceUsesOfNonProtoConstant(bitcast, newFn); 2039 continue; 2040 } 2041 2042 // Recognize calls to the function. 2043 llvm::CallSite callSite(user); 2044 if (!callSite) continue; 2045 if (!callSite.isCallee(&*use)) continue; 2046 2047 // If the return types don't match exactly, then we can't 2048 // transform this call unless it's dead. 2049 if (callSite->getType() != newRetTy && !callSite->use_empty()) 2050 continue; 2051 2052 // Get the call site's attribute list. 2053 SmallVector<llvm::AttributeSet, 8> newAttrs; 2054 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2055 2056 // Collect any return attributes from the call. 2057 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2058 newAttrs.push_back( 2059 llvm::AttributeSet::get(newFn->getContext(), 2060 oldAttrs.getRetAttributes())); 2061 2062 // If the function was passed too few arguments, don't transform. 2063 unsigned newNumArgs = newFn->arg_size(); 2064 if (callSite.arg_size() < newNumArgs) continue; 2065 2066 // If extra arguments were passed, we silently drop them. 2067 // If any of the types mismatch, we don't transform. 2068 unsigned argNo = 0; 2069 bool dontTransform = false; 2070 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2071 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2072 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2073 dontTransform = true; 2074 break; 2075 } 2076 2077 // Add any parameter attributes. 2078 if (oldAttrs.hasAttributes(argNo + 1)) 2079 newAttrs. 2080 push_back(llvm:: 2081 AttributeSet::get(newFn->getContext(), 2082 oldAttrs.getParamAttributes(argNo + 1))); 2083 } 2084 if (dontTransform) 2085 continue; 2086 2087 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2088 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2089 oldAttrs.getFnAttributes())); 2090 2091 // Okay, we can transform this. Create the new call instruction and copy 2092 // over the required information. 2093 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2094 2095 llvm::CallSite newCall; 2096 if (callSite.isCall()) { 2097 newCall = llvm::CallInst::Create(newFn, newArgs, "", 2098 callSite.getInstruction()); 2099 } else { 2100 llvm::InvokeInst *oldInvoke = 2101 cast<llvm::InvokeInst>(callSite.getInstruction()); 2102 newCall = llvm::InvokeInst::Create(newFn, 2103 oldInvoke->getNormalDest(), 2104 oldInvoke->getUnwindDest(), 2105 newArgs, "", 2106 callSite.getInstruction()); 2107 } 2108 newArgs.clear(); // for the next iteration 2109 2110 if (!newCall->getType()->isVoidTy()) 2111 newCall->takeName(callSite.getInstruction()); 2112 newCall.setAttributes( 2113 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2114 newCall.setCallingConv(callSite.getCallingConv()); 2115 2116 // Finally, remove the old call, replacing any uses with the new one. 2117 if (!callSite->use_empty()) 2118 callSite->replaceAllUsesWith(newCall.getInstruction()); 2119 2120 // Copy debug location attached to CI. 2121 if (!callSite->getDebugLoc().isUnknown()) 2122 newCall->setDebugLoc(callSite->getDebugLoc()); 2123 callSite->eraseFromParent(); 2124 } 2125 } 2126 2127 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2128 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2129 /// existing call uses of the old function in the module, this adjusts them to 2130 /// call the new function directly. 2131 /// 2132 /// This is not just a cleanup: the always_inline pass requires direct calls to 2133 /// functions to be able to inline them. If there is a bitcast in the way, it 2134 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2135 /// run at -O0. 2136 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2137 llvm::Function *NewFn) { 2138 // If we're redefining a global as a function, don't transform it. 2139 if (!isa<llvm::Function>(Old)) return; 2140 2141 replaceUsesOfNonProtoConstant(Old, NewFn); 2142 } 2143 2144 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2145 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2146 // If we have a definition, this might be a deferred decl. If the 2147 // instantiation is explicit, make sure we emit it at the end. 2148 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2149 GetAddrOfGlobalVar(VD); 2150 2151 EmitTopLevelDecl(VD); 2152 } 2153 2154 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 2155 llvm::GlobalValue *GV) { 2156 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 2157 2158 // Compute the function info and LLVM type. 2159 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2160 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2161 2162 // Get or create the prototype for the function. 2163 llvm::Constant *Entry = 2164 GV ? GV 2165 : GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true); 2166 2167 // Strip off a bitcast if we got one back. 2168 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2169 assert(CE->getOpcode() == llvm::Instruction::BitCast); 2170 Entry = CE->getOperand(0); 2171 } 2172 2173 if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) { 2174 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name); 2175 return; 2176 } 2177 2178 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 2179 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 2180 2181 // If the types mismatch then we have to rewrite the definition. 2182 assert(OldFn->isDeclaration() && 2183 "Shouldn't replace non-declaration"); 2184 2185 // F is the Function* for the one with the wrong type, we must make a new 2186 // Function* and update everything that used F (a declaration) with the new 2187 // Function* (which will be a definition). 2188 // 2189 // This happens if there is a prototype for a function 2190 // (e.g. "int f()") and then a definition of a different type 2191 // (e.g. "int f(int x)"). Move the old function aside so that it 2192 // doesn't interfere with GetAddrOfFunction. 2193 OldFn->setName(StringRef()); 2194 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2195 2196 // This might be an implementation of a function without a 2197 // prototype, in which case, try to do special replacement of 2198 // calls which match the new prototype. The really key thing here 2199 // is that we also potentially drop arguments from the call site 2200 // so as to make a direct call, which makes the inliner happier 2201 // and suppresses a number of optimizer warnings (!) about 2202 // dropping arguments. 2203 if (!OldFn->use_empty()) { 2204 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 2205 OldFn->removeDeadConstantUsers(); 2206 } 2207 2208 // Replace uses of F with the Function we will endow with a body. 2209 if (!Entry->use_empty()) { 2210 llvm::Constant *NewPtrForOldDecl = 2211 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 2212 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2213 } 2214 2215 // Ok, delete the old function now, which is dead. 2216 OldFn->eraseFromParent(); 2217 2218 Entry = NewFn; 2219 } 2220 2221 // We need to set linkage and visibility on the function before 2222 // generating code for it because various parts of IR generation 2223 // want to propagate this information down (e.g. to local static 2224 // declarations). 2225 llvm::Function *Fn = cast<llvm::Function>(Entry); 2226 setFunctionLinkage(GD, Fn); 2227 2228 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 2229 setGlobalVisibility(Fn, D); 2230 2231 MaybeHandleStaticInExternC(D, Fn); 2232 2233 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2234 2235 SetFunctionDefinitionAttributes(D, Fn); 2236 SetLLVMFunctionAttributesForDefinition(D, Fn); 2237 2238 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2239 AddGlobalCtor(Fn, CA->getPriority()); 2240 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2241 AddGlobalDtor(Fn, DA->getPriority()); 2242 if (D->hasAttr<AnnotateAttr>()) 2243 AddGlobalAnnotations(D, Fn); 2244 } 2245 2246 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2247 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 2248 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2249 assert(AA && "Not an alias?"); 2250 2251 StringRef MangledName = getMangledName(GD); 2252 2253 // If there is a definition in the module, then it wins over the alias. 2254 // This is dubious, but allow it to be safe. Just ignore the alias. 2255 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2256 if (Entry && !Entry->isDeclaration()) 2257 return; 2258 2259 Aliases.push_back(GD); 2260 2261 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2262 2263 // Create a reference to the named value. This ensures that it is emitted 2264 // if a deferred decl. 2265 llvm::Constant *Aliasee; 2266 if (isa<llvm::FunctionType>(DeclTy)) 2267 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2268 /*ForVTable=*/false); 2269 else 2270 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2271 llvm::PointerType::getUnqual(DeclTy), 0); 2272 2273 // Create the new alias itself, but don't set a name yet. 2274 llvm::GlobalValue *GA = 2275 new llvm::GlobalAlias(Aliasee->getType(), 2276 llvm::Function::ExternalLinkage, 2277 "", Aliasee, &getModule()); 2278 2279 if (Entry) { 2280 assert(Entry->isDeclaration()); 2281 2282 // If there is a declaration in the module, then we had an extern followed 2283 // by the alias, as in: 2284 // extern int test6(); 2285 // ... 2286 // int test6() __attribute__((alias("test7"))); 2287 // 2288 // Remove it and replace uses of it with the alias. 2289 GA->takeName(Entry); 2290 2291 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2292 Entry->getType())); 2293 Entry->eraseFromParent(); 2294 } else { 2295 GA->setName(MangledName); 2296 } 2297 2298 // Set attributes which are particular to an alias; this is a 2299 // specialization of the attributes which may be set on a global 2300 // variable/function. 2301 if (D->hasAttr<DLLExportAttr>()) { 2302 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2303 // The dllexport attribute is ignored for undefined symbols. 2304 if (FD->hasBody()) 2305 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2306 } else { 2307 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2308 } 2309 } else if (D->hasAttr<WeakAttr>() || 2310 D->hasAttr<WeakRefAttr>() || 2311 D->isWeakImported()) { 2312 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2313 } 2314 2315 SetCommonAttributes(D, GA); 2316 } 2317 2318 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2319 ArrayRef<llvm::Type*> Tys) { 2320 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2321 Tys); 2322 } 2323 2324 static llvm::StringMapEntry<llvm::Constant*> & 2325 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2326 const StringLiteral *Literal, 2327 bool TargetIsLSB, 2328 bool &IsUTF16, 2329 unsigned &StringLength) { 2330 StringRef String = Literal->getString(); 2331 unsigned NumBytes = String.size(); 2332 2333 // Check for simple case. 2334 if (!Literal->containsNonAsciiOrNull()) { 2335 StringLength = NumBytes; 2336 return Map.GetOrCreateValue(String); 2337 } 2338 2339 // Otherwise, convert the UTF8 literals into a string of shorts. 2340 IsUTF16 = true; 2341 2342 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2343 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2344 UTF16 *ToPtr = &ToBuf[0]; 2345 2346 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2347 &ToPtr, ToPtr + NumBytes, 2348 strictConversion); 2349 2350 // ConvertUTF8toUTF16 returns the length in ToPtr. 2351 StringLength = ToPtr - &ToBuf[0]; 2352 2353 // Add an explicit null. 2354 *ToPtr = 0; 2355 return Map. 2356 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2357 (StringLength + 1) * 2)); 2358 } 2359 2360 static llvm::StringMapEntry<llvm::Constant*> & 2361 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2362 const StringLiteral *Literal, 2363 unsigned &StringLength) { 2364 StringRef String = Literal->getString(); 2365 StringLength = String.size(); 2366 return Map.GetOrCreateValue(String); 2367 } 2368 2369 llvm::Constant * 2370 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2371 unsigned StringLength = 0; 2372 bool isUTF16 = false; 2373 llvm::StringMapEntry<llvm::Constant*> &Entry = 2374 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2375 getDataLayout().isLittleEndian(), 2376 isUTF16, StringLength); 2377 2378 if (llvm::Constant *C = Entry.getValue()) 2379 return C; 2380 2381 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2382 llvm::Constant *Zeros[] = { Zero, Zero }; 2383 llvm::Value *V; 2384 2385 // If we don't already have it, get __CFConstantStringClassReference. 2386 if (!CFConstantStringClassRef) { 2387 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2388 Ty = llvm::ArrayType::get(Ty, 0); 2389 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2390 "__CFConstantStringClassReference"); 2391 // Decay array -> ptr 2392 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2393 CFConstantStringClassRef = V; 2394 } 2395 else 2396 V = CFConstantStringClassRef; 2397 2398 QualType CFTy = getContext().getCFConstantStringType(); 2399 2400 llvm::StructType *STy = 2401 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2402 2403 llvm::Constant *Fields[4]; 2404 2405 // Class pointer. 2406 Fields[0] = cast<llvm::ConstantExpr>(V); 2407 2408 // Flags. 2409 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2410 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2411 llvm::ConstantInt::get(Ty, 0x07C8); 2412 2413 // String pointer. 2414 llvm::Constant *C = 0; 2415 if (isUTF16) { 2416 ArrayRef<uint16_t> Arr = 2417 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>( 2418 const_cast<char *>(Entry.getKey().data())), 2419 Entry.getKey().size() / 2); 2420 C = llvm::ConstantDataArray::get(VMContext, Arr); 2421 } else { 2422 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2423 } 2424 2425 // Note: -fwritable-strings doesn't make the backing store strings of 2426 // CFStrings writable. (See <rdar://problem/10657500>) 2427 llvm::GlobalVariable *GV = 2428 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2429 llvm::GlobalValue::PrivateLinkage, C, ".str"); 2430 GV->setUnnamedAddr(true); 2431 // Don't enforce the target's minimum global alignment, since the only use 2432 // of the string is via this class initializer. 2433 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 2434 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 2435 // that changes the section it ends in, which surprises ld64. 2436 if (isUTF16) { 2437 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2438 GV->setAlignment(Align.getQuantity()); 2439 GV->setSection("__TEXT,__ustring"); 2440 } else { 2441 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2442 GV->setAlignment(Align.getQuantity()); 2443 GV->setSection("__TEXT,__cstring,cstring_literals"); 2444 } 2445 2446 // String. 2447 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2448 2449 if (isUTF16) 2450 // Cast the UTF16 string to the correct type. 2451 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2452 2453 // String length. 2454 Ty = getTypes().ConvertType(getContext().LongTy); 2455 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2456 2457 // The struct. 2458 C = llvm::ConstantStruct::get(STy, Fields); 2459 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2460 llvm::GlobalVariable::PrivateLinkage, C, 2461 "_unnamed_cfstring_"); 2462 GV->setSection("__DATA,__cfstring"); 2463 Entry.setValue(GV); 2464 2465 return GV; 2466 } 2467 2468 llvm::Constant * 2469 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2470 unsigned StringLength = 0; 2471 llvm::StringMapEntry<llvm::Constant*> &Entry = 2472 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2473 2474 if (llvm::Constant *C = Entry.getValue()) 2475 return C; 2476 2477 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2478 llvm::Constant *Zeros[] = { Zero, Zero }; 2479 llvm::Value *V; 2480 // If we don't already have it, get _NSConstantStringClassReference. 2481 if (!ConstantStringClassRef) { 2482 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2483 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2484 llvm::Constant *GV; 2485 if (LangOpts.ObjCRuntime.isNonFragile()) { 2486 std::string str = 2487 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2488 : "OBJC_CLASS_$_" + StringClass; 2489 GV = getObjCRuntime().GetClassGlobal(str); 2490 // Make sure the result is of the correct type. 2491 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2492 V = llvm::ConstantExpr::getBitCast(GV, PTy); 2493 ConstantStringClassRef = V; 2494 } else { 2495 std::string str = 2496 StringClass.empty() ? "_NSConstantStringClassReference" 2497 : "_" + StringClass + "ClassReference"; 2498 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2499 GV = CreateRuntimeVariable(PTy, str); 2500 // Decay array -> ptr 2501 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2502 ConstantStringClassRef = V; 2503 } 2504 } 2505 else 2506 V = ConstantStringClassRef; 2507 2508 if (!NSConstantStringType) { 2509 // Construct the type for a constant NSString. 2510 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 2511 D->startDefinition(); 2512 2513 QualType FieldTypes[3]; 2514 2515 // const int *isa; 2516 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2517 // const char *str; 2518 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2519 // unsigned int length; 2520 FieldTypes[2] = Context.UnsignedIntTy; 2521 2522 // Create fields 2523 for (unsigned i = 0; i < 3; ++i) { 2524 FieldDecl *Field = FieldDecl::Create(Context, D, 2525 SourceLocation(), 2526 SourceLocation(), 0, 2527 FieldTypes[i], /*TInfo=*/0, 2528 /*BitWidth=*/0, 2529 /*Mutable=*/false, 2530 ICIS_NoInit); 2531 Field->setAccess(AS_public); 2532 D->addDecl(Field); 2533 } 2534 2535 D->completeDefinition(); 2536 QualType NSTy = Context.getTagDeclType(D); 2537 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2538 } 2539 2540 llvm::Constant *Fields[3]; 2541 2542 // Class pointer. 2543 Fields[0] = cast<llvm::ConstantExpr>(V); 2544 2545 // String pointer. 2546 llvm::Constant *C = 2547 llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2548 2549 llvm::GlobalValue::LinkageTypes Linkage; 2550 bool isConstant; 2551 Linkage = llvm::GlobalValue::PrivateLinkage; 2552 isConstant = !LangOpts.WritableStrings; 2553 2554 llvm::GlobalVariable *GV = 2555 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 2556 ".str"); 2557 GV->setUnnamedAddr(true); 2558 // Don't enforce the target's minimum global alignment, since the only use 2559 // of the string is via this class initializer. 2560 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2561 GV->setAlignment(Align.getQuantity()); 2562 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2563 2564 // String length. 2565 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2566 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2567 2568 // The struct. 2569 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2570 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2571 llvm::GlobalVariable::PrivateLinkage, C, 2572 "_unnamed_nsstring_"); 2573 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 2574 const char *NSStringNonFragileABISection = 2575 "__DATA,__objc_stringobj,regular,no_dead_strip"; 2576 // FIXME. Fix section. 2577 GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 2578 ? NSStringNonFragileABISection 2579 : NSStringSection); 2580 Entry.setValue(GV); 2581 2582 return GV; 2583 } 2584 2585 QualType CodeGenModule::getObjCFastEnumerationStateType() { 2586 if (ObjCFastEnumerationStateType.isNull()) { 2587 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 2588 D->startDefinition(); 2589 2590 QualType FieldTypes[] = { 2591 Context.UnsignedLongTy, 2592 Context.getPointerType(Context.getObjCIdType()), 2593 Context.getPointerType(Context.UnsignedLongTy), 2594 Context.getConstantArrayType(Context.UnsignedLongTy, 2595 llvm::APInt(32, 5), ArrayType::Normal, 0) 2596 }; 2597 2598 for (size_t i = 0; i < 4; ++i) { 2599 FieldDecl *Field = FieldDecl::Create(Context, 2600 D, 2601 SourceLocation(), 2602 SourceLocation(), 0, 2603 FieldTypes[i], /*TInfo=*/0, 2604 /*BitWidth=*/0, 2605 /*Mutable=*/false, 2606 ICIS_NoInit); 2607 Field->setAccess(AS_public); 2608 D->addDecl(Field); 2609 } 2610 2611 D->completeDefinition(); 2612 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2613 } 2614 2615 return ObjCFastEnumerationStateType; 2616 } 2617 2618 llvm::Constant * 2619 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2620 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2621 2622 // Don't emit it as the address of the string, emit the string data itself 2623 // as an inline array. 2624 if (E->getCharByteWidth() == 1) { 2625 SmallString<64> Str(E->getString()); 2626 2627 // Resize the string to the right size, which is indicated by its type. 2628 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2629 Str.resize(CAT->getSize().getZExtValue()); 2630 return llvm::ConstantDataArray::getString(VMContext, Str, false); 2631 } 2632 2633 llvm::ArrayType *AType = 2634 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2635 llvm::Type *ElemTy = AType->getElementType(); 2636 unsigned NumElements = AType->getNumElements(); 2637 2638 // Wide strings have either 2-byte or 4-byte elements. 2639 if (ElemTy->getPrimitiveSizeInBits() == 16) { 2640 SmallVector<uint16_t, 32> Elements; 2641 Elements.reserve(NumElements); 2642 2643 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2644 Elements.push_back(E->getCodeUnit(i)); 2645 Elements.resize(NumElements); 2646 return llvm::ConstantDataArray::get(VMContext, Elements); 2647 } 2648 2649 assert(ElemTy->getPrimitiveSizeInBits() == 32); 2650 SmallVector<uint32_t, 32> Elements; 2651 Elements.reserve(NumElements); 2652 2653 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2654 Elements.push_back(E->getCodeUnit(i)); 2655 Elements.resize(NumElements); 2656 return llvm::ConstantDataArray::get(VMContext, Elements); 2657 } 2658 2659 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2660 /// constant array for the given string literal. 2661 llvm::Constant * 2662 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2663 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType()); 2664 2665 llvm::StringMapEntry<llvm::GlobalVariable *> *Entry = nullptr; 2666 llvm::GlobalVariable *GV = nullptr; 2667 if (!LangOpts.WritableStrings) { 2668 llvm::StringMap<llvm::GlobalVariable *> *ConstantStringMap = nullptr; 2669 switch (S->getCharByteWidth()) { 2670 case 1: 2671 ConstantStringMap = &Constant1ByteStringMap; 2672 break; 2673 case 2: 2674 ConstantStringMap = &Constant2ByteStringMap; 2675 break; 2676 case 4: 2677 ConstantStringMap = &Constant4ByteStringMap; 2678 break; 2679 default: 2680 llvm_unreachable("unhandled byte width!"); 2681 } 2682 Entry = &ConstantStringMap->GetOrCreateValue(S->getBytes()); 2683 GV = Entry->getValue(); 2684 } 2685 2686 if (!GV) { 2687 SmallString<256> MangledNameBuffer; 2688 StringRef GlobalVariableName; 2689 llvm::GlobalValue::LinkageTypes LT; 2690 2691 // Mangle the string literal if the ABI allows for it. However, we cannot 2692 // do this if we are compiling with ASan or -fwritable-strings because they 2693 // rely on strings having normal linkage. 2694 if (!LangOpts.WritableStrings && !SanOpts.Address && 2695 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 2696 llvm::raw_svector_ostream Out(MangledNameBuffer); 2697 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 2698 Out.flush(); 2699 2700 LT = llvm::GlobalValue::LinkOnceODRLinkage; 2701 GlobalVariableName = MangledNameBuffer; 2702 } else { 2703 LT = llvm::GlobalValue::PrivateLinkage; 2704 GlobalVariableName = ".str"; 2705 } 2706 2707 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 2708 unsigned AddrSpace = 0; 2709 if (getLangOpts().OpenCL) 2710 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant); 2711 2712 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2713 GV = new llvm::GlobalVariable( 2714 getModule(), C->getType(), !LangOpts.WritableStrings, LT, C, 2715 GlobalVariableName, /*InsertBefore=*/nullptr, 2716 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2717 GV->setUnnamedAddr(true); 2718 if (Entry) 2719 Entry->setValue(GV); 2720 } 2721 2722 if (Align.getQuantity() > GV->getAlignment()) 2723 GV->setAlignment(Align.getQuantity()); 2724 2725 return GV; 2726 } 2727 2728 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2729 /// array for the given ObjCEncodeExpr node. 2730 llvm::Constant * 2731 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2732 std::string Str; 2733 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2734 2735 return GetAddrOfConstantCString(Str); 2736 } 2737 2738 2739 /// GenerateWritableString -- Creates storage for a string literal. 2740 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2741 bool constant, 2742 CodeGenModule &CGM, 2743 const char *GlobalName, 2744 unsigned Alignment) { 2745 // Create Constant for this string literal. Don't add a '\0'. 2746 llvm::Constant *C = 2747 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 2748 2749 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 2750 unsigned AddrSpace = 0; 2751 if (CGM.getLangOpts().OpenCL) 2752 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 2753 2754 // Create a global variable for this string 2755 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 2756 CGM.getModule(), C->getType(), constant, 2757 llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0, 2758 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2759 GV->setAlignment(Alignment); 2760 GV->setUnnamedAddr(true); 2761 return GV; 2762 } 2763 2764 /// GetAddrOfConstantString - Returns a pointer to a character array 2765 /// containing the literal. This contents are exactly that of the 2766 /// given string, i.e. it will not be null terminated automatically; 2767 /// see GetAddrOfConstantCString. Note that whether the result is 2768 /// actually a pointer to an LLVM constant depends on 2769 /// Feature.WriteableStrings. 2770 /// 2771 /// The result has pointer to array type. 2772 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2773 const char *GlobalName, 2774 unsigned Alignment) { 2775 // Get the default prefix if a name wasn't specified. 2776 if (!GlobalName) 2777 GlobalName = ".str"; 2778 2779 if (Alignment == 0) 2780 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy) 2781 .getQuantity(); 2782 2783 // Don't share any string literals if strings aren't constant. 2784 if (LangOpts.WritableStrings) 2785 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2786 2787 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2788 Constant1ByteStringMap.GetOrCreateValue(Str); 2789 2790 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2791 if (Alignment > GV->getAlignment()) { 2792 GV->setAlignment(Alignment); 2793 } 2794 return GV; 2795 } 2796 2797 // Create a global variable for this. 2798 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 2799 Alignment); 2800 Entry.setValue(GV); 2801 return GV; 2802 } 2803 2804 /// GetAddrOfConstantCString - Returns a pointer to a character 2805 /// array containing the literal and a terminating '\0' 2806 /// character. The result has pointer to array type. 2807 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2808 const char *GlobalName, 2809 unsigned Alignment) { 2810 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2811 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2812 } 2813 2814 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary( 2815 const MaterializeTemporaryExpr *E, const Expr *Init) { 2816 assert((E->getStorageDuration() == SD_Static || 2817 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 2818 const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl()); 2819 2820 // If we're not materializing a subobject of the temporary, keep the 2821 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 2822 QualType MaterializedType = Init->getType(); 2823 if (Init == E->GetTemporaryExpr()) 2824 MaterializedType = E->getType(); 2825 2826 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E]; 2827 if (Slot) 2828 return Slot; 2829 2830 // FIXME: If an externally-visible declaration extends multiple temporaries, 2831 // we need to give each temporary the same name in every translation unit (and 2832 // we also need to make the temporaries externally-visible). 2833 SmallString<256> Name; 2834 llvm::raw_svector_ostream Out(Name); 2835 getCXXABI().getMangleContext().mangleReferenceTemporary( 2836 VD, E->getManglingNumber(), Out); 2837 Out.flush(); 2838 2839 APValue *Value = 0; 2840 if (E->getStorageDuration() == SD_Static) { 2841 // We might have a cached constant initializer for this temporary. Note 2842 // that this might have a different value from the value computed by 2843 // evaluating the initializer if the surrounding constant expression 2844 // modifies the temporary. 2845 Value = getContext().getMaterializedTemporaryValue(E, false); 2846 if (Value && Value->isUninit()) 2847 Value = 0; 2848 } 2849 2850 // Try evaluating it now, it might have a constant initializer. 2851 Expr::EvalResult EvalResult; 2852 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 2853 !EvalResult.hasSideEffects()) 2854 Value = &EvalResult.Val; 2855 2856 llvm::Constant *InitialValue = 0; 2857 bool Constant = false; 2858 llvm::Type *Type; 2859 if (Value) { 2860 // The temporary has a constant initializer, use it. 2861 InitialValue = EmitConstantValue(*Value, MaterializedType, 0); 2862 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 2863 Type = InitialValue->getType(); 2864 } else { 2865 // No initializer, the initialization will be provided when we 2866 // initialize the declaration which performed lifetime extension. 2867 Type = getTypes().ConvertTypeForMem(MaterializedType); 2868 } 2869 2870 // Create a global variable for this lifetime-extended temporary. 2871 llvm::GlobalValue::LinkageTypes Linkage = 2872 getLLVMLinkageVarDefinition(VD, Constant); 2873 // There is no need for this temporary to have global linkage if the global 2874 // variable has external linkage. 2875 if (Linkage == llvm::GlobalVariable::ExternalLinkage) 2876 Linkage = llvm::GlobalVariable::PrivateLinkage; 2877 unsigned AddrSpace = GetGlobalVarAddressSpace( 2878 VD, getContext().getTargetAddressSpace(MaterializedType)); 2879 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 2880 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 2881 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 2882 AddrSpace); 2883 setGlobalVisibility(GV, VD); 2884 GV->setAlignment( 2885 getContext().getTypeAlignInChars(MaterializedType).getQuantity()); 2886 if (VD->getTLSKind()) 2887 setTLSMode(GV, *VD); 2888 Slot = GV; 2889 return GV; 2890 } 2891 2892 /// EmitObjCPropertyImplementations - Emit information for synthesized 2893 /// properties for an implementation. 2894 void CodeGenModule::EmitObjCPropertyImplementations(const 2895 ObjCImplementationDecl *D) { 2896 for (const auto *PID : D->property_impls()) { 2897 // Dynamic is just for type-checking. 2898 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2899 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2900 2901 // Determine which methods need to be implemented, some may have 2902 // been overridden. Note that ::isPropertyAccessor is not the method 2903 // we want, that just indicates if the decl came from a 2904 // property. What we want to know is if the method is defined in 2905 // this implementation. 2906 if (!D->getInstanceMethod(PD->getGetterName())) 2907 CodeGenFunction(*this).GenerateObjCGetter( 2908 const_cast<ObjCImplementationDecl *>(D), PID); 2909 if (!PD->isReadOnly() && 2910 !D->getInstanceMethod(PD->getSetterName())) 2911 CodeGenFunction(*this).GenerateObjCSetter( 2912 const_cast<ObjCImplementationDecl *>(D), PID); 2913 } 2914 } 2915 } 2916 2917 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2918 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2919 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2920 ivar; ivar = ivar->getNextIvar()) 2921 if (ivar->getType().isDestructedType()) 2922 return true; 2923 2924 return false; 2925 } 2926 2927 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2928 /// for an implementation. 2929 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2930 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2931 if (needsDestructMethod(D)) { 2932 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2933 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2934 ObjCMethodDecl *DTORMethod = 2935 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2936 cxxSelector, getContext().VoidTy, 0, D, 2937 /*isInstance=*/true, /*isVariadic=*/false, 2938 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2939 /*isDefined=*/false, ObjCMethodDecl::Required); 2940 D->addInstanceMethod(DTORMethod); 2941 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2942 D->setHasDestructors(true); 2943 } 2944 2945 // If the implementation doesn't have any ivar initializers, we don't need 2946 // a .cxx_construct. 2947 if (D->getNumIvarInitializers() == 0) 2948 return; 2949 2950 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2951 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2952 // The constructor returns 'self'. 2953 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2954 D->getLocation(), 2955 D->getLocation(), 2956 cxxSelector, 2957 getContext().getObjCIdType(), 0, 2958 D, /*isInstance=*/true, 2959 /*isVariadic=*/false, 2960 /*isPropertyAccessor=*/true, 2961 /*isImplicitlyDeclared=*/true, 2962 /*isDefined=*/false, 2963 ObjCMethodDecl::Required); 2964 D->addInstanceMethod(CTORMethod); 2965 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2966 D->setHasNonZeroConstructors(true); 2967 } 2968 2969 /// EmitNamespace - Emit all declarations in a namespace. 2970 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2971 for (auto *I : ND->decls()) { 2972 if (const auto *VD = dyn_cast<VarDecl>(I)) 2973 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2974 VD->getTemplateSpecializationKind() != TSK_Undeclared) 2975 continue; 2976 EmitTopLevelDecl(I); 2977 } 2978 } 2979 2980 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2981 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2982 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2983 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2984 ErrorUnsupported(LSD, "linkage spec"); 2985 return; 2986 } 2987 2988 for (auto *I : LSD->decls()) { 2989 // Meta-data for ObjC class includes references to implemented methods. 2990 // Generate class's method definitions first. 2991 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 2992 for (auto *M : OID->methods()) 2993 EmitTopLevelDecl(M); 2994 } 2995 EmitTopLevelDecl(I); 2996 } 2997 } 2998 2999 /// EmitTopLevelDecl - Emit code for a single top level declaration. 3000 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3001 // Ignore dependent declarations. 3002 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3003 return; 3004 3005 switch (D->getKind()) { 3006 case Decl::CXXConversion: 3007 case Decl::CXXMethod: 3008 case Decl::Function: 3009 // Skip function templates 3010 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3011 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3012 return; 3013 3014 EmitGlobal(cast<FunctionDecl>(D)); 3015 break; 3016 3017 case Decl::Var: 3018 // Skip variable templates 3019 if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3020 return; 3021 case Decl::VarTemplateSpecialization: 3022 EmitGlobal(cast<VarDecl>(D)); 3023 break; 3024 3025 // Indirect fields from global anonymous structs and unions can be 3026 // ignored; only the actual variable requires IR gen support. 3027 case Decl::IndirectField: 3028 break; 3029 3030 // C++ Decls 3031 case Decl::Namespace: 3032 EmitNamespace(cast<NamespaceDecl>(D)); 3033 break; 3034 // No code generation needed. 3035 case Decl::UsingShadow: 3036 case Decl::ClassTemplate: 3037 case Decl::VarTemplate: 3038 case Decl::VarTemplatePartialSpecialization: 3039 case Decl::FunctionTemplate: 3040 case Decl::TypeAliasTemplate: 3041 case Decl::Block: 3042 case Decl::Empty: 3043 break; 3044 case Decl::Using: // using X; [C++] 3045 if (CGDebugInfo *DI = getModuleDebugInfo()) 3046 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 3047 return; 3048 case Decl::NamespaceAlias: 3049 if (CGDebugInfo *DI = getModuleDebugInfo()) 3050 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3051 return; 3052 case Decl::UsingDirective: // using namespace X; [C++] 3053 if (CGDebugInfo *DI = getModuleDebugInfo()) 3054 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3055 return; 3056 case Decl::CXXConstructor: 3057 // Skip function templates 3058 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3059 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3060 return; 3061 3062 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3063 break; 3064 case Decl::CXXDestructor: 3065 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 3066 return; 3067 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3068 break; 3069 3070 case Decl::StaticAssert: 3071 // Nothing to do. 3072 break; 3073 3074 // Objective-C Decls 3075 3076 // Forward declarations, no (immediate) code generation. 3077 case Decl::ObjCInterface: 3078 case Decl::ObjCCategory: 3079 break; 3080 3081 case Decl::ObjCProtocol: { 3082 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D); 3083 if (Proto->isThisDeclarationADefinition()) 3084 ObjCRuntime->GenerateProtocol(Proto); 3085 break; 3086 } 3087 3088 case Decl::ObjCCategoryImpl: 3089 // Categories have properties but don't support synthesize so we 3090 // can ignore them here. 3091 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3092 break; 3093 3094 case Decl::ObjCImplementation: { 3095 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 3096 EmitObjCPropertyImplementations(OMD); 3097 EmitObjCIvarInitializations(OMD); 3098 ObjCRuntime->GenerateClass(OMD); 3099 // Emit global variable debug information. 3100 if (CGDebugInfo *DI = getModuleDebugInfo()) 3101 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3102 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3103 OMD->getClassInterface()), OMD->getLocation()); 3104 break; 3105 } 3106 case Decl::ObjCMethod: { 3107 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 3108 // If this is not a prototype, emit the body. 3109 if (OMD->getBody()) 3110 CodeGenFunction(*this).GenerateObjCMethod(OMD); 3111 break; 3112 } 3113 case Decl::ObjCCompatibleAlias: 3114 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3115 break; 3116 3117 case Decl::LinkageSpec: 3118 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3119 break; 3120 3121 case Decl::FileScopeAsm: { 3122 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 3123 StringRef AsmString = AD->getAsmString()->getString(); 3124 3125 const std::string &S = getModule().getModuleInlineAsm(); 3126 if (S.empty()) 3127 getModule().setModuleInlineAsm(AsmString); 3128 else if (S.end()[-1] == '\n') 3129 getModule().setModuleInlineAsm(S + AsmString.str()); 3130 else 3131 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 3132 break; 3133 } 3134 3135 case Decl::Import: { 3136 ImportDecl *Import = cast<ImportDecl>(D); 3137 3138 // Ignore import declarations that come from imported modules. 3139 if (clang::Module *Owner = Import->getOwningModule()) { 3140 if (getLangOpts().CurrentModule.empty() || 3141 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 3142 break; 3143 } 3144 3145 ImportedModules.insert(Import->getImportedModule()); 3146 break; 3147 } 3148 3149 case Decl::ClassTemplateSpecialization: { 3150 const ClassTemplateSpecializationDecl *Spec = 3151 cast<ClassTemplateSpecializationDecl>(D); 3152 if (DebugInfo && 3153 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition) 3154 DebugInfo->completeTemplateDefinition(*Spec); 3155 } 3156 3157 default: 3158 // Make sure we handled everything we should, every other kind is a 3159 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3160 // function. Need to recode Decl::Kind to do that easily. 3161 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3162 } 3163 } 3164 3165 /// Turns the given pointer into a constant. 3166 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3167 const void *Ptr) { 3168 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 3169 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3170 return llvm::ConstantInt::get(i64, PtrInt); 3171 } 3172 3173 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3174 llvm::NamedMDNode *&GlobalMetadata, 3175 GlobalDecl D, 3176 llvm::GlobalValue *Addr) { 3177 if (!GlobalMetadata) 3178 GlobalMetadata = 3179 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3180 3181 // TODO: should we report variant information for ctors/dtors? 3182 llvm::Value *Ops[] = { 3183 Addr, 3184 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 3185 }; 3186 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3187 } 3188 3189 /// For each function which is declared within an extern "C" region and marked 3190 /// as 'used', but has internal linkage, create an alias from the unmangled 3191 /// name to the mangled name if possible. People expect to be able to refer 3192 /// to such functions with an unmangled name from inline assembly within the 3193 /// same translation unit. 3194 void CodeGenModule::EmitStaticExternCAliases() { 3195 for (StaticExternCMap::iterator I = StaticExternCValues.begin(), 3196 E = StaticExternCValues.end(); 3197 I != E; ++I) { 3198 IdentifierInfo *Name = I->first; 3199 llvm::GlobalValue *Val = I->second; 3200 if (Val && !getModule().getNamedValue(Name->getName())) 3201 addUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(), 3202 Name->getName(), Val, &getModule())); 3203 } 3204 } 3205 3206 /// Emits metadata nodes associating all the global values in the 3207 /// current module with the Decls they came from. This is useful for 3208 /// projects using IR gen as a subroutine. 3209 /// 3210 /// Since there's currently no way to associate an MDNode directly 3211 /// with an llvm::GlobalValue, we create a global named metadata 3212 /// with the name 'clang.global.decl.ptrs'. 3213 void CodeGenModule::EmitDeclMetadata() { 3214 llvm::NamedMDNode *GlobalMetadata = 0; 3215 3216 // StaticLocalDeclMap 3217 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 3218 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 3219 I != E; ++I) { 3220 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 3221 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 3222 } 3223 } 3224 3225 /// Emits metadata nodes for all the local variables in the current 3226 /// function. 3227 void CodeGenFunction::EmitDeclMetadata() { 3228 if (LocalDeclMap.empty()) return; 3229 3230 llvm::LLVMContext &Context = getLLVMContext(); 3231 3232 // Find the unique metadata ID for this name. 3233 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3234 3235 llvm::NamedMDNode *GlobalMetadata = 0; 3236 3237 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 3238 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 3239 const Decl *D = I->first; 3240 llvm::Value *Addr = I->second; 3241 3242 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3243 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3244 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 3245 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3246 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3247 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3248 } 3249 } 3250 } 3251 3252 void CodeGenModule::EmitVersionIdentMetadata() { 3253 llvm::NamedMDNode *IdentMetadata = 3254 TheModule.getOrInsertNamedMetadata("llvm.ident"); 3255 std::string Version = getClangFullVersion(); 3256 llvm::LLVMContext &Ctx = TheModule.getContext(); 3257 3258 llvm::Value *IdentNode[] = { 3259 llvm::MDString::get(Ctx, Version) 3260 }; 3261 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3262 } 3263 3264 void CodeGenModule::EmitCoverageFile() { 3265 if (!getCodeGenOpts().CoverageFile.empty()) { 3266 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3267 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3268 llvm::LLVMContext &Ctx = TheModule.getContext(); 3269 llvm::MDString *CoverageFile = 3270 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3271 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3272 llvm::MDNode *CU = CUNode->getOperand(i); 3273 llvm::Value *node[] = { CoverageFile, CU }; 3274 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 3275 GCov->addOperand(N); 3276 } 3277 } 3278 } 3279 } 3280 3281 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid, 3282 QualType GuidType) { 3283 // Sema has checked that all uuid strings are of the form 3284 // "12345678-1234-1234-1234-1234567890ab". 3285 assert(Uuid.size() == 36); 3286 for (unsigned i = 0; i < 36; ++i) { 3287 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3288 else assert(isHexDigit(Uuid[i])); 3289 } 3290 3291 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3292 3293 llvm::Constant *Field3[8]; 3294 for (unsigned Idx = 0; Idx < 8; ++Idx) 3295 Field3[Idx] = llvm::ConstantInt::get( 3296 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 3297 3298 llvm::Constant *Fields[4] = { 3299 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3300 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3301 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3302 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3303 }; 3304 3305 return llvm::ConstantStruct::getAnon(Fields); 3306 } 3307