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