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