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