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