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