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