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