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