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