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