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