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