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