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 llvm::GlobalValue *GV = G.GV; 1248 G.GV = nullptr; 1249 1250 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 1251 // to get GlobalValue with exactly the type we need, not something that 1252 // might had been created for another decl with the same mangled name but 1253 // different type. 1254 // FIXME: Support for variables is not implemented yet. 1255 if (isa<FunctionDecl>(D.getDecl())) 1256 GV = cast<llvm::GlobalValue>(GetAddrOfGlobal(D, /*IsForDefinition=*/true)); 1257 else 1258 if (!GV) 1259 GV = GetGlobalValue(getMangledName(D)); 1260 1261 // Check to see if we've already emitted this. This is necessary 1262 // for a couple of reasons: first, decls can end up in the 1263 // deferred-decls queue multiple times, and second, decls can end 1264 // up with definitions in unusual ways (e.g. by an extern inline 1265 // function acquiring a strong function redefinition). Just 1266 // ignore these cases. 1267 if (GV && !GV->isDeclaration()) 1268 continue; 1269 1270 // Otherwise, emit the definition and move on to the next one. 1271 EmitGlobalDefinition(D, GV); 1272 1273 // If we found out that we need to emit more decls, do that recursively. 1274 // This has the advantage that the decls are emitted in a DFS and related 1275 // ones are close together, which is convenient for testing. 1276 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 1277 EmitDeferred(); 1278 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 1279 } 1280 } 1281 } 1282 1283 void CodeGenModule::EmitGlobalAnnotations() { 1284 if (Annotations.empty()) 1285 return; 1286 1287 // Create a new global variable for the ConstantStruct in the Module. 1288 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1289 Annotations[0]->getType(), Annotations.size()), Annotations); 1290 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 1291 llvm::GlobalValue::AppendingLinkage, 1292 Array, "llvm.global.annotations"); 1293 gv->setSection(AnnotationSection); 1294 } 1295 1296 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1297 llvm::Constant *&AStr = AnnotationStrings[Str]; 1298 if (AStr) 1299 return AStr; 1300 1301 // Not found yet, create a new global. 1302 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1303 auto *gv = 1304 new llvm::GlobalVariable(getModule(), s->getType(), true, 1305 llvm::GlobalValue::PrivateLinkage, s, ".str"); 1306 gv->setSection(AnnotationSection); 1307 gv->setUnnamedAddr(true); 1308 AStr = gv; 1309 return gv; 1310 } 1311 1312 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1313 SourceManager &SM = getContext().getSourceManager(); 1314 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1315 if (PLoc.isValid()) 1316 return EmitAnnotationString(PLoc.getFilename()); 1317 return EmitAnnotationString(SM.getBufferName(Loc)); 1318 } 1319 1320 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1321 SourceManager &SM = getContext().getSourceManager(); 1322 PresumedLoc PLoc = SM.getPresumedLoc(L); 1323 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1324 SM.getExpansionLineNumber(L); 1325 return llvm::ConstantInt::get(Int32Ty, LineNo); 1326 } 1327 1328 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1329 const AnnotateAttr *AA, 1330 SourceLocation L) { 1331 // Get the globals for file name, annotation, and the line number. 1332 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1333 *UnitGV = EmitAnnotationUnit(L), 1334 *LineNoCst = EmitAnnotationLineNo(L); 1335 1336 // Create the ConstantStruct for the global annotation. 1337 llvm::Constant *Fields[4] = { 1338 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1339 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1340 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1341 LineNoCst 1342 }; 1343 return llvm::ConstantStruct::getAnon(Fields); 1344 } 1345 1346 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1347 llvm::GlobalValue *GV) { 1348 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1349 // Get the struct elements for these annotations. 1350 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1351 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1352 } 1353 1354 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 1355 SourceLocation Loc) const { 1356 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1357 // Blacklist by function name. 1358 if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 1359 return true; 1360 // Blacklist by location. 1361 if (Loc.isValid()) 1362 return SanitizerBL.isBlacklistedLocation(Loc); 1363 // If location is unknown, this may be a compiler-generated function. Assume 1364 // it's located in the main file. 1365 auto &SM = Context.getSourceManager(); 1366 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1367 return SanitizerBL.isBlacklistedFile(MainFile->getName()); 1368 } 1369 return false; 1370 } 1371 1372 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 1373 SourceLocation Loc, QualType Ty, 1374 StringRef Category) const { 1375 // For now globals can be blacklisted only in ASan and KASan. 1376 if (!LangOpts.Sanitize.hasOneOf( 1377 SanitizerKind::Address | SanitizerKind::KernelAddress)) 1378 return false; 1379 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1380 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 1381 return true; 1382 if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 1383 return true; 1384 // Check global type. 1385 if (!Ty.isNull()) { 1386 // Drill down the array types: if global variable of a fixed type is 1387 // blacklisted, we also don't instrument arrays of them. 1388 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 1389 Ty = AT->getElementType(); 1390 Ty = Ty.getCanonicalType().getUnqualifiedType(); 1391 // We allow to blacklist only record types (classes, structs etc.) 1392 if (Ty->isRecordType()) { 1393 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 1394 if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 1395 return true; 1396 } 1397 } 1398 return false; 1399 } 1400 1401 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1402 // Never defer when EmitAllDecls is specified. 1403 if (LangOpts.EmitAllDecls) 1404 return true; 1405 1406 return getContext().DeclMustBeEmitted(Global); 1407 } 1408 1409 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 1410 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 1411 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1412 // Implicit template instantiations may change linkage if they are later 1413 // explicitly instantiated, so they should not be emitted eagerly. 1414 return false; 1415 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1416 // codegen for global variables, because they may be marked as threadprivate. 1417 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1418 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1419 return false; 1420 1421 return true; 1422 } 1423 1424 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 1425 const CXXUuidofExpr* E) { 1426 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1427 // well-formed. 1428 StringRef Uuid = E->getUuidAsStringRef(Context); 1429 std::string Name = "_GUID_" + Uuid.lower(); 1430 std::replace(Name.begin(), Name.end(), '-', '_'); 1431 1432 // Contains a 32-bit field. 1433 CharUnits Alignment = CharUnits::fromQuantity(4); 1434 1435 // Look for an existing global. 1436 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1437 return ConstantAddress(GV, Alignment); 1438 1439 llvm::Constant *Init = EmitUuidofInitializer(Uuid); 1440 assert(Init && "failed to initialize as constant"); 1441 1442 auto *GV = new llvm::GlobalVariable( 1443 getModule(), Init->getType(), 1444 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1445 if (supportsCOMDAT()) 1446 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 1447 return ConstantAddress(GV, Alignment); 1448 } 1449 1450 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1451 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1452 assert(AA && "No alias?"); 1453 1454 CharUnits Alignment = getContext().getDeclAlign(VD); 1455 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1456 1457 // See if there is already something with the target's name in the module. 1458 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1459 if (Entry) { 1460 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1461 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1462 return ConstantAddress(Ptr, Alignment); 1463 } 1464 1465 llvm::Constant *Aliasee; 1466 if (isa<llvm::FunctionType>(DeclTy)) 1467 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1468 GlobalDecl(cast<FunctionDecl>(VD)), 1469 /*ForVTable=*/false); 1470 else 1471 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1472 llvm::PointerType::getUnqual(DeclTy), 1473 nullptr); 1474 1475 auto *F = cast<llvm::GlobalValue>(Aliasee); 1476 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1477 WeakRefReferences.insert(F); 1478 1479 return ConstantAddress(Aliasee, Alignment); 1480 } 1481 1482 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1483 const auto *Global = cast<ValueDecl>(GD.getDecl()); 1484 1485 // Weak references don't produce any output by themselves. 1486 if (Global->hasAttr<WeakRefAttr>()) 1487 return; 1488 1489 // If this is an alias definition (which otherwise looks like a declaration) 1490 // emit it now. 1491 if (Global->hasAttr<AliasAttr>()) 1492 return EmitAliasDefinition(GD); 1493 1494 // If this is CUDA, be selective about which declarations we emit. 1495 if (LangOpts.CUDA) { 1496 if (LangOpts.CUDAIsDevice) { 1497 if (!Global->hasAttr<CUDADeviceAttr>() && 1498 !Global->hasAttr<CUDAGlobalAttr>() && 1499 !Global->hasAttr<CUDAConstantAttr>() && 1500 !Global->hasAttr<CUDASharedAttr>()) 1501 return; 1502 } else { 1503 if (!Global->hasAttr<CUDAHostAttr>() && ( 1504 Global->hasAttr<CUDADeviceAttr>() || 1505 Global->hasAttr<CUDAConstantAttr>() || 1506 Global->hasAttr<CUDASharedAttr>())) 1507 return; 1508 } 1509 } 1510 1511 // If this is OpenMP device, check if it is legal to emit this global 1512 // normally. 1513 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1514 return; 1515 1516 // Ignore declarations, they will be emitted on their first use. 1517 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1518 // Forward declarations are emitted lazily on first use. 1519 if (!FD->doesThisDeclarationHaveABody()) { 1520 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1521 return; 1522 1523 StringRef MangledName = getMangledName(GD); 1524 1525 // Compute the function info and LLVM type. 1526 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1527 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1528 1529 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1530 /*DontDefer=*/false); 1531 return; 1532 } 1533 } else { 1534 const auto *VD = cast<VarDecl>(Global); 1535 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1536 1537 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 1538 !Context.isMSStaticDataMemberInlineDefinition(VD)) 1539 return; 1540 } 1541 1542 // Defer code generation to first use when possible, e.g. if this is an inline 1543 // function. If the global must always be emitted, do it eagerly if possible 1544 // to benefit from cache locality. 1545 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1546 // Emit the definition if it can't be deferred. 1547 EmitGlobalDefinition(GD); 1548 return; 1549 } 1550 1551 // If we're deferring emission of a C++ variable with an 1552 // initializer, remember the order in which it appeared in the file. 1553 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1554 cast<VarDecl>(Global)->hasInit()) { 1555 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1556 CXXGlobalInits.push_back(nullptr); 1557 } 1558 1559 StringRef MangledName = getMangledName(GD); 1560 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) { 1561 // The value has already been used and should therefore be emitted. 1562 addDeferredDeclToEmit(GV, GD); 1563 } else if (MustBeEmitted(Global)) { 1564 // The value must be emitted, but cannot be emitted eagerly. 1565 assert(!MayBeEmittedEagerly(Global)); 1566 addDeferredDeclToEmit(/*GV=*/nullptr, GD); 1567 } else { 1568 // Otherwise, remember that we saw a deferred decl with this name. The 1569 // first use of the mangled name will cause it to move into 1570 // DeferredDeclsToEmit. 1571 DeferredDecls[MangledName] = GD; 1572 } 1573 } 1574 1575 namespace { 1576 struct FunctionIsDirectlyRecursive : 1577 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1578 const StringRef Name; 1579 const Builtin::Context &BI; 1580 bool Result; 1581 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1582 Name(N), BI(C), Result(false) { 1583 } 1584 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1585 1586 bool TraverseCallExpr(CallExpr *E) { 1587 const FunctionDecl *FD = E->getDirectCallee(); 1588 if (!FD) 1589 return true; 1590 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1591 if (Attr && Name == Attr->getLabel()) { 1592 Result = true; 1593 return false; 1594 } 1595 unsigned BuiltinID = FD->getBuiltinID(); 1596 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1597 return true; 1598 StringRef BuiltinName = BI.getName(BuiltinID); 1599 if (BuiltinName.startswith("__builtin_") && 1600 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1601 Result = true; 1602 return false; 1603 } 1604 return true; 1605 } 1606 }; 1607 1608 struct DLLImportFunctionVisitor 1609 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 1610 bool SafeToInline = true; 1611 1612 bool VisitVarDecl(VarDecl *VD) { 1613 // A thread-local variable cannot be imported. 1614 SafeToInline = !VD->getTLSKind(); 1615 return SafeToInline; 1616 } 1617 1618 // Make sure we're not referencing non-imported vars or functions. 1619 bool VisitDeclRefExpr(DeclRefExpr *E) { 1620 ValueDecl *VD = E->getDecl(); 1621 if (isa<FunctionDecl>(VD)) 1622 SafeToInline = VD->hasAttr<DLLImportAttr>(); 1623 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 1624 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 1625 return SafeToInline; 1626 } 1627 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 1628 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 1629 return SafeToInline; 1630 } 1631 bool VisitCXXNewExpr(CXXNewExpr *E) { 1632 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 1633 return SafeToInline; 1634 } 1635 }; 1636 } 1637 1638 // isTriviallyRecursive - Check if this function calls another 1639 // decl that, because of the asm attribute or the other decl being a builtin, 1640 // ends up pointing to itself. 1641 bool 1642 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1643 StringRef Name; 1644 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1645 // asm labels are a special kind of mangling we have to support. 1646 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1647 if (!Attr) 1648 return false; 1649 Name = Attr->getLabel(); 1650 } else { 1651 Name = FD->getName(); 1652 } 1653 1654 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1655 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1656 return Walker.Result; 1657 } 1658 1659 bool 1660 CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1661 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1662 return true; 1663 const auto *F = cast<FunctionDecl>(GD.getDecl()); 1664 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1665 return false; 1666 1667 if (F->hasAttr<DLLImportAttr>()) { 1668 // Check whether it would be safe to inline this dllimport function. 1669 DLLImportFunctionVisitor Visitor; 1670 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 1671 if (!Visitor.SafeToInline) 1672 return false; 1673 } 1674 1675 // PR9614. Avoid cases where the source code is lying to us. An available 1676 // externally function should have an equivalent function somewhere else, 1677 // but a function that calls itself is clearly not equivalent to the real 1678 // implementation. 1679 // This happens in glibc's btowc and in some configure checks. 1680 return !isTriviallyRecursive(F); 1681 } 1682 1683 /// If the type for the method's class was generated by 1684 /// CGDebugInfo::createContextChain(), the cache contains only a 1685 /// limited DIType without any declarations. Since EmitFunctionStart() 1686 /// needs to find the canonical declaration for each method, we need 1687 /// to construct the complete type prior to emitting the method. 1688 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1689 if (!D->isInstance()) 1690 return; 1691 1692 if (CGDebugInfo *DI = getModuleDebugInfo()) 1693 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 1694 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1695 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1696 } 1697 } 1698 1699 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 1700 const auto *D = cast<ValueDecl>(GD.getDecl()); 1701 1702 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1703 Context.getSourceManager(), 1704 "Generating code for declaration"); 1705 1706 if (isa<FunctionDecl>(D)) { 1707 // At -O0, don't generate IR for functions with available_externally 1708 // linkage. 1709 if (!shouldEmitFunction(GD)) 1710 return; 1711 1712 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1713 CompleteDIClassType(Method); 1714 // Make sure to emit the definition(s) before we emit the thunks. 1715 // This is necessary for the generation of certain thunks. 1716 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 1717 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 1718 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 1719 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1720 else 1721 EmitGlobalFunctionDefinition(GD, GV); 1722 1723 if (Method->isVirtual()) 1724 getVTables().EmitThunks(GD); 1725 1726 return; 1727 } 1728 1729 return EmitGlobalFunctionDefinition(GD, GV); 1730 } 1731 1732 if (const auto *VD = dyn_cast<VarDecl>(D)) 1733 return EmitGlobalVarDefinition(VD); 1734 1735 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1736 } 1737 1738 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1739 llvm::Function *NewFn); 1740 1741 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1742 /// module, create and return an llvm Function with the specified type. If there 1743 /// is something in the module with the specified name, return it potentially 1744 /// bitcasted to the right type. 1745 /// 1746 /// If D is non-null, it specifies a decl that correspond to this. This is used 1747 /// to set the attributes on the function when it is first created. 1748 llvm::Constant * 1749 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1750 llvm::Type *Ty, 1751 GlobalDecl GD, bool ForVTable, 1752 bool DontDefer, bool IsThunk, 1753 llvm::AttributeSet ExtraAttrs, 1754 bool IsForDefinition) { 1755 const Decl *D = GD.getDecl(); 1756 1757 // Lookup the entry, lazily creating it if necessary. 1758 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1759 if (Entry) { 1760 if (WeakRefReferences.erase(Entry)) { 1761 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1762 if (FD && !FD->hasAttr<WeakAttr>()) 1763 Entry->setLinkage(llvm::Function::ExternalLinkage); 1764 } 1765 1766 // Handle dropped DLL attributes. 1767 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 1768 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 1769 1770 // If there are two attempts to define the same mangled name, issue an 1771 // error. 1772 if (IsForDefinition && !Entry->isDeclaration()) { 1773 GlobalDecl OtherGD; 1774 // Check that GD is not yet in ExplicitDefinitions is required to make 1775 // sure that we issue an error only once. 1776 if (lookupRepresentativeDecl(MangledName, OtherGD) && 1777 (GD.getCanonicalDecl().getDecl() != 1778 OtherGD.getCanonicalDecl().getDecl()) && 1779 DiagnosedConflictingDefinitions.insert(GD).second) { 1780 getDiags().Report(D->getLocation(), 1781 diag::err_duplicate_mangled_name); 1782 getDiags().Report(OtherGD.getDecl()->getLocation(), 1783 diag::note_previous_definition); 1784 } 1785 } 1786 1787 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 1788 (Entry->getType()->getElementType() == Ty)) { 1789 return Entry; 1790 } 1791 1792 // Make sure the result is of the correct type. 1793 // (If function is requested for a definition, we always need to create a new 1794 // function, not just return a bitcast.) 1795 if (!IsForDefinition) 1796 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1797 } 1798 1799 // This function doesn't have a complete type (for example, the return 1800 // type is an incomplete struct). Use a fake type instead, and make 1801 // sure not to try to set attributes. 1802 bool IsIncompleteFunction = false; 1803 1804 llvm::FunctionType *FTy; 1805 if (isa<llvm::FunctionType>(Ty)) { 1806 FTy = cast<llvm::FunctionType>(Ty); 1807 } else { 1808 FTy = llvm::FunctionType::get(VoidTy, false); 1809 IsIncompleteFunction = true; 1810 } 1811 1812 llvm::Function *F = 1813 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 1814 Entry ? StringRef() : MangledName, &getModule()); 1815 1816 // If we already created a function with the same mangled name (but different 1817 // type) before, take its name and add it to the list of functions to be 1818 // replaced with F at the end of CodeGen. 1819 // 1820 // This happens if there is a prototype for a function (e.g. "int f()") and 1821 // then a definition of a different type (e.g. "int f(int x)"). 1822 if (Entry) { 1823 F->takeName(Entry); 1824 1825 // This might be an implementation of a function without a prototype, in 1826 // which case, try to do special replacement of calls which match the new 1827 // prototype. The really key thing here is that we also potentially drop 1828 // arguments from the call site so as to make a direct call, which makes the 1829 // inliner happier and suppresses a number of optimizer warnings (!) about 1830 // dropping arguments. 1831 if (!Entry->use_empty()) { 1832 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 1833 Entry->removeDeadConstantUsers(); 1834 } 1835 1836 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 1837 F, Entry->getType()->getElementType()->getPointerTo()); 1838 addGlobalValReplacement(Entry, BC); 1839 } 1840 1841 assert(F->getName() == MangledName && "name was uniqued!"); 1842 if (D) 1843 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 1844 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1845 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1846 F->addAttributes(llvm::AttributeSet::FunctionIndex, 1847 llvm::AttributeSet::get(VMContext, 1848 llvm::AttributeSet::FunctionIndex, 1849 B)); 1850 } 1851 1852 if (!DontDefer) { 1853 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1854 // each other bottoming out with the base dtor. Therefore we emit non-base 1855 // dtors on usage, even if there is no dtor definition in the TU. 1856 if (D && isa<CXXDestructorDecl>(D) && 1857 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1858 GD.getDtorType())) 1859 addDeferredDeclToEmit(F, GD); 1860 1861 // This is the first use or definition of a mangled name. If there is a 1862 // deferred decl with this name, remember that we need to emit it at the end 1863 // of the file. 1864 auto DDI = DeferredDecls.find(MangledName); 1865 if (DDI != DeferredDecls.end()) { 1866 // Move the potentially referenced deferred decl to the 1867 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 1868 // don't need it anymore). 1869 addDeferredDeclToEmit(F, DDI->second); 1870 DeferredDecls.erase(DDI); 1871 1872 // Otherwise, there are cases we have to worry about where we're 1873 // using a declaration for which we must emit a definition but where 1874 // we might not find a top-level definition: 1875 // - member functions defined inline in their classes 1876 // - friend functions defined inline in some class 1877 // - special member functions with implicit definitions 1878 // If we ever change our AST traversal to walk into class methods, 1879 // this will be unnecessary. 1880 // 1881 // We also don't emit a definition for a function if it's going to be an 1882 // entry in a vtable, unless it's already marked as used. 1883 } else if (getLangOpts().CPlusPlus && D) { 1884 // Look for a declaration that's lexically in a record. 1885 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 1886 FD = FD->getPreviousDecl()) { 1887 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1888 if (FD->doesThisDeclarationHaveABody()) { 1889 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1890 break; 1891 } 1892 } 1893 } 1894 } 1895 } 1896 1897 // Make sure the result is of the requested type. 1898 if (!IsIncompleteFunction) { 1899 assert(F->getType()->getElementType() == Ty); 1900 return F; 1901 } 1902 1903 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1904 return llvm::ConstantExpr::getBitCast(F, PTy); 1905 } 1906 1907 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1908 /// non-null, then this function will use the specified type if it has to 1909 /// create it (this occurs when we see a definition of the function). 1910 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1911 llvm::Type *Ty, 1912 bool ForVTable, 1913 bool DontDefer, 1914 bool IsForDefinition) { 1915 // If there was no specific requested type, just convert it now. 1916 if (!Ty) { 1917 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1918 auto CanonTy = Context.getCanonicalType(FD->getType()); 1919 Ty = getTypes().ConvertFunctionType(CanonTy, FD); 1920 } 1921 1922 StringRef MangledName = getMangledName(GD); 1923 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 1924 /*IsThunk=*/false, llvm::AttributeSet(), 1925 IsForDefinition); 1926 } 1927 1928 /// CreateRuntimeFunction - Create a new runtime function with the specified 1929 /// type and name. 1930 llvm::Constant * 1931 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1932 StringRef Name, 1933 llvm::AttributeSet ExtraAttrs) { 1934 llvm::Constant *C = 1935 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1936 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 1937 if (auto *F = dyn_cast<llvm::Function>(C)) 1938 if (F->empty()) 1939 F->setCallingConv(getRuntimeCC()); 1940 return C; 1941 } 1942 1943 /// CreateBuiltinFunction - Create a new builtin function with the specified 1944 /// type and name. 1945 llvm::Constant * 1946 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, 1947 StringRef Name, 1948 llvm::AttributeSet ExtraAttrs) { 1949 llvm::Constant *C = 1950 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1951 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 1952 if (auto *F = dyn_cast<llvm::Function>(C)) 1953 if (F->empty()) 1954 F->setCallingConv(getBuiltinCC()); 1955 return C; 1956 } 1957 1958 /// isTypeConstant - Determine whether an object of this type can be emitted 1959 /// as a constant. 1960 /// 1961 /// If ExcludeCtor is true, the duration when the object's constructor runs 1962 /// will not be considered. The caller will need to verify that the object is 1963 /// not written to during its construction. 1964 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1965 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1966 return false; 1967 1968 if (Context.getLangOpts().CPlusPlus) { 1969 if (const CXXRecordDecl *Record 1970 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1971 return ExcludeCtor && !Record->hasMutableFields() && 1972 Record->hasTrivialDestructor(); 1973 } 1974 1975 return true; 1976 } 1977 1978 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1979 /// create and return an llvm GlobalVariable with the specified type. If there 1980 /// is something in the module with the specified name, return it potentially 1981 /// bitcasted to the right type. 1982 /// 1983 /// If D is non-null, it specifies a decl that correspond to this. This is used 1984 /// to set the attributes on the global when it is first created. 1985 llvm::Constant * 1986 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1987 llvm::PointerType *Ty, 1988 const VarDecl *D) { 1989 // Lookup the entry, lazily creating it if necessary. 1990 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1991 if (Entry) { 1992 if (WeakRefReferences.erase(Entry)) { 1993 if (D && !D->hasAttr<WeakAttr>()) 1994 Entry->setLinkage(llvm::Function::ExternalLinkage); 1995 } 1996 1997 // Handle dropped DLL attributes. 1998 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 1999 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 2000 2001 if (Entry->getType() == Ty) 2002 return Entry; 2003 2004 // Make sure the result is of the correct type. 2005 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2006 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2007 2008 return llvm::ConstantExpr::getBitCast(Entry, Ty); 2009 } 2010 2011 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 2012 auto *GV = new llvm::GlobalVariable( 2013 getModule(), Ty->getElementType(), false, 2014 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 2015 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2016 2017 // This is the first use or definition of a mangled name. If there is a 2018 // deferred decl with this name, remember that we need to emit it at the end 2019 // of the file. 2020 auto DDI = DeferredDecls.find(MangledName); 2021 if (DDI != DeferredDecls.end()) { 2022 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2023 // list, and remove it from DeferredDecls (since we don't need it anymore). 2024 addDeferredDeclToEmit(GV, DDI->second); 2025 DeferredDecls.erase(DDI); 2026 } 2027 2028 // Handle things which are present even on external declarations. 2029 if (D) { 2030 // FIXME: This code is overly simple and should be merged with other global 2031 // handling. 2032 GV->setConstant(isTypeConstant(D->getType(), false)); 2033 2034 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2035 2036 setLinkageAndVisibilityForGV(GV, D); 2037 2038 if (D->getTLSKind()) { 2039 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 2040 CXXThreadLocals.push_back(D); 2041 setTLSMode(GV, *D); 2042 } 2043 2044 // If required by the ABI, treat declarations of static data members with 2045 // inline initializers as definitions. 2046 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2047 EmitGlobalVarDefinition(D); 2048 } 2049 2050 // Handle XCore specific ABI requirements. 2051 if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 2052 D->getLanguageLinkage() == CLanguageLinkage && 2053 D->getType().isConstant(Context) && 2054 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 2055 GV->setSection(".cp.rodata"); 2056 } 2057 2058 if (AddrSpace != Ty->getAddressSpace()) 2059 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2060 2061 return GV; 2062 } 2063 2064 llvm::Constant * 2065 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 2066 bool IsForDefinition) { 2067 if (isa<CXXConstructorDecl>(GD.getDecl())) 2068 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()), 2069 getFromCtorType(GD.getCtorType()), 2070 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 2071 /*DontDefer=*/false, IsForDefinition); 2072 else if (isa<CXXDestructorDecl>(GD.getDecl())) 2073 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()), 2074 getFromDtorType(GD.getDtorType()), 2075 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 2076 /*DontDefer=*/false, IsForDefinition); 2077 else if (isa<CXXMethodDecl>(GD.getDecl())) { 2078 auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 2079 cast<CXXMethodDecl>(GD.getDecl())); 2080 auto Ty = getTypes().GetFunctionType(*FInfo); 2081 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 2082 IsForDefinition); 2083 } else if (isa<FunctionDecl>(GD.getDecl())) { 2084 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2085 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2086 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 2087 IsForDefinition); 2088 } else 2089 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 2090 } 2091 2092 llvm::GlobalVariable * 2093 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 2094 llvm::Type *Ty, 2095 llvm::GlobalValue::LinkageTypes Linkage) { 2096 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 2097 llvm::GlobalVariable *OldGV = nullptr; 2098 2099 if (GV) { 2100 // Check if the variable has the right type. 2101 if (GV->getType()->getElementType() == Ty) 2102 return GV; 2103 2104 // Because C++ name mangling, the only way we can end up with an already 2105 // existing global with the same name is if it has been declared extern "C". 2106 assert(GV->isDeclaration() && "Declaration has wrong type!"); 2107 OldGV = GV; 2108 } 2109 2110 // Create a new variable. 2111 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 2112 Linkage, nullptr, Name); 2113 2114 if (OldGV) { 2115 // Replace occurrences of the old variable if needed. 2116 GV->takeName(OldGV); 2117 2118 if (!OldGV->use_empty()) { 2119 llvm::Constant *NewPtrForOldDecl = 2120 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 2121 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 2122 } 2123 2124 OldGV->eraseFromParent(); 2125 } 2126 2127 if (supportsCOMDAT() && GV->isWeakForLinker() && 2128 !GV->hasAvailableExternallyLinkage()) 2129 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2130 2131 return GV; 2132 } 2133 2134 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2135 /// given global variable. If Ty is non-null and if the global doesn't exist, 2136 /// then it will be created with the specified type instead of whatever the 2137 /// normal requested type would be. 2138 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2139 llvm::Type *Ty) { 2140 assert(D->hasGlobalStorage() && "Not a global variable"); 2141 QualType ASTTy = D->getType(); 2142 if (!Ty) 2143 Ty = getTypes().ConvertTypeForMem(ASTTy); 2144 2145 llvm::PointerType *PTy = 2146 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2147 2148 StringRef MangledName = getMangledName(D); 2149 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 2150 } 2151 2152 /// CreateRuntimeVariable - Create a new runtime global variable with the 2153 /// specified type and name. 2154 llvm::Constant * 2155 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 2156 StringRef Name) { 2157 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2158 } 2159 2160 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2161 assert(!D->getInit() && "Cannot emit definite definitions here!"); 2162 2163 if (!MustBeEmitted(D)) { 2164 // If we have not seen a reference to this variable yet, place it 2165 // into the deferred declarations table to be emitted if needed 2166 // later. 2167 StringRef MangledName = getMangledName(D); 2168 if (!GetGlobalValue(MangledName)) { 2169 DeferredDecls[MangledName] = D; 2170 return; 2171 } 2172 } 2173 2174 // The tentative definition is the only definition. 2175 EmitGlobalVarDefinition(D); 2176 } 2177 2178 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 2179 return Context.toCharUnitsFromBits( 2180 getDataLayout().getTypeStoreSizeInBits(Ty)); 2181 } 2182 2183 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 2184 unsigned AddrSpace) { 2185 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 2186 if (D->hasAttr<CUDAConstantAttr>()) 2187 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 2188 else if (D->hasAttr<CUDASharedAttr>()) 2189 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 2190 else 2191 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 2192 } 2193 2194 return AddrSpace; 2195 } 2196 2197 template<typename SomeDecl> 2198 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2199 llvm::GlobalValue *GV) { 2200 if (!getLangOpts().CPlusPlus) 2201 return; 2202 2203 // Must have 'used' attribute, or else inline assembly can't rely on 2204 // the name existing. 2205 if (!D->template hasAttr<UsedAttr>()) 2206 return; 2207 2208 // Must have internal linkage and an ordinary name. 2209 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2210 return; 2211 2212 // Must be in an extern "C" context. Entities declared directly within 2213 // a record are not extern "C" even if the record is in such a context. 2214 const SomeDecl *First = D->getFirstDecl(); 2215 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2216 return; 2217 2218 // OK, this is an internal linkage entity inside an extern "C" linkage 2219 // specification. Make a note of that so we can give it the "expected" 2220 // mangled name if nothing else is using that name. 2221 std::pair<StaticExternCMap::iterator, bool> R = 2222 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2223 2224 // If we have multiple internal linkage entities with the same name 2225 // in extern "C" regions, none of them gets that name. 2226 if (!R.second) 2227 R.first->second = nullptr; 2228 } 2229 2230 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 2231 if (!CGM.supportsCOMDAT()) 2232 return false; 2233 2234 if (D.hasAttr<SelectAnyAttr>()) 2235 return true; 2236 2237 GVALinkage Linkage; 2238 if (auto *VD = dyn_cast<VarDecl>(&D)) 2239 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 2240 else 2241 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 2242 2243 switch (Linkage) { 2244 case GVA_Internal: 2245 case GVA_AvailableExternally: 2246 case GVA_StrongExternal: 2247 return false; 2248 case GVA_DiscardableODR: 2249 case GVA_StrongODR: 2250 return true; 2251 } 2252 llvm_unreachable("No such linkage"); 2253 } 2254 2255 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 2256 llvm::GlobalObject &GO) { 2257 if (!shouldBeInCOMDAT(*this, D)) 2258 return; 2259 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 2260 } 2261 2262 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 2263 llvm::Constant *Init = nullptr; 2264 QualType ASTTy = D->getType(); 2265 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2266 bool NeedsGlobalCtor = false; 2267 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2268 2269 const VarDecl *InitDecl; 2270 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2271 2272 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization as part 2273 // of their declaration." 2274 if (getLangOpts().CPlusPlus && getLangOpts().CUDAIsDevice 2275 && D->hasAttr<CUDASharedAttr>()) { 2276 if (InitExpr) { 2277 const auto *C = dyn_cast<CXXConstructExpr>(InitExpr); 2278 if (C == nullptr || !C->getConstructor()->hasTrivialBody()) 2279 Error(D->getLocation(), 2280 "__shared__ variable cannot have an initialization."); 2281 } 2282 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2283 } else if (!InitExpr) { 2284 // This is a tentative definition; tentative definitions are 2285 // implicitly initialized with { 0 }. 2286 // 2287 // Note that tentative definitions are only emitted at the end of 2288 // a translation unit, so they should never have incomplete 2289 // type. In addition, EmitTentativeDefinition makes sure that we 2290 // never attempt to emit a tentative definition if a real one 2291 // exists. A use may still exists, however, so we still may need 2292 // to do a RAUW. 2293 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2294 Init = EmitNullConstant(D->getType()); 2295 } else { 2296 initializedGlobalDecl = GlobalDecl(D); 2297 Init = EmitConstantInit(*InitDecl); 2298 2299 if (!Init) { 2300 QualType T = InitExpr->getType(); 2301 if (D->getType()->isReferenceType()) 2302 T = D->getType(); 2303 2304 if (getLangOpts().CPlusPlus) { 2305 Init = EmitNullConstant(T); 2306 NeedsGlobalCtor = true; 2307 } else { 2308 ErrorUnsupported(D, "static initializer"); 2309 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2310 } 2311 } else { 2312 // We don't need an initializer, so remove the entry for the delayed 2313 // initializer position (just in case this entry was delayed) if we 2314 // also don't need to register a destructor. 2315 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2316 DelayedCXXInitPosition.erase(D); 2317 } 2318 } 2319 2320 llvm::Type* InitType = Init->getType(); 2321 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 2322 2323 // Strip off a bitcast if we got one back. 2324 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2325 assert(CE->getOpcode() == llvm::Instruction::BitCast || 2326 CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2327 // All zero index gep. 2328 CE->getOpcode() == llvm::Instruction::GetElementPtr); 2329 Entry = CE->getOperand(0); 2330 } 2331 2332 // Entry is now either a Function or GlobalVariable. 2333 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2334 2335 // We have a definition after a declaration with the wrong type. 2336 // We must make a new GlobalVariable* and update everything that used OldGV 2337 // (a declaration or tentative definition) with the new GlobalVariable* 2338 // (which will be a definition). 2339 // 2340 // This happens if there is a prototype for a global (e.g. 2341 // "extern int x[];") and then a definition of a different type (e.g. 2342 // "int x[10];"). This also happens when an initializer has a different type 2343 // from the type of the global (this happens with unions). 2344 if (!GV || 2345 GV->getType()->getElementType() != InitType || 2346 GV->getType()->getAddressSpace() != 2347 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2348 2349 // Move the old entry aside so that we'll create a new one. 2350 Entry->setName(StringRef()); 2351 2352 // Make a new global with the correct type, this is now guaranteed to work. 2353 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 2354 2355 // Replace all uses of the old global with the new global 2356 llvm::Constant *NewPtrForOldDecl = 2357 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2358 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2359 2360 // Erase the old global, since it is no longer used. 2361 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2362 } 2363 2364 MaybeHandleStaticInExternC(D, GV); 2365 2366 if (D->hasAttr<AnnotateAttr>()) 2367 AddGlobalAnnotations(D, GV); 2368 2369 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 2370 // the device. [...]" 2371 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 2372 // __device__, declares a variable that: [...] 2373 // Is accessible from all the threads within the grid and from the host 2374 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 2375 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2376 if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice && 2377 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) { 2378 GV->setExternallyInitialized(true); 2379 } 2380 GV->setInitializer(Init); 2381 2382 // If it is safe to mark the global 'constant', do so now. 2383 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2384 isTypeConstant(D->getType(), true)); 2385 2386 // If it is in a read-only section, mark it 'constant'. 2387 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 2388 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 2389 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 2390 GV->setConstant(true); 2391 } 2392 2393 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2394 2395 // Set the llvm linkage type as appropriate. 2396 llvm::GlobalValue::LinkageTypes Linkage = 2397 getLLVMLinkageVarDefinition(D, GV->isConstant()); 2398 2399 // On Darwin, if the normal linkage of a C++ thread_local variable is 2400 // LinkOnce or Weak, we keep the normal linkage to prevent multiple 2401 // copies within a linkage unit; otherwise, the backing variable has 2402 // internal linkage and all accesses should just be calls to the 2403 // Itanium-specified entry point, which has the normal linkage of the 2404 // variable. This is to preserve the ability to change the implementation 2405 // behind the scenes. 2406 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 2407 Context.getTargetInfo().getTriple().isOSDarwin() && 2408 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 2409 !llvm::GlobalVariable::isWeakLinkage(Linkage)) 2410 Linkage = llvm::GlobalValue::InternalLinkage; 2411 2412 GV->setLinkage(Linkage); 2413 if (D->hasAttr<DLLImportAttr>()) 2414 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 2415 else if (D->hasAttr<DLLExportAttr>()) 2416 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 2417 else 2418 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2419 2420 if (Linkage == llvm::GlobalVariable::CommonLinkage) 2421 // common vars aren't constant even if declared const. 2422 GV->setConstant(false); 2423 2424 setNonAliasAttributes(D, GV); 2425 2426 if (D->getTLSKind() && !GV->isThreadLocal()) { 2427 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 2428 CXXThreadLocals.push_back(D); 2429 setTLSMode(GV, *D); 2430 } 2431 2432 maybeSetTrivialComdat(*D, *GV); 2433 2434 // Emit the initializer function if necessary. 2435 if (NeedsGlobalCtor || NeedsGlobalDtor) 2436 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 2437 2438 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 2439 2440 // Emit global variable debug information. 2441 if (CGDebugInfo *DI = getModuleDebugInfo()) 2442 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2443 DI->EmitGlobalVariable(GV, D); 2444 } 2445 2446 static bool isVarDeclStrongDefinition(const ASTContext &Context, 2447 CodeGenModule &CGM, const VarDecl *D, 2448 bool NoCommon) { 2449 // Don't give variables common linkage if -fno-common was specified unless it 2450 // was overridden by a NoCommon attribute. 2451 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 2452 return true; 2453 2454 // C11 6.9.2/2: 2455 // A declaration of an identifier for an object that has file scope without 2456 // an initializer, and without a storage-class specifier or with the 2457 // storage-class specifier static, constitutes a tentative definition. 2458 if (D->getInit() || D->hasExternalStorage()) 2459 return true; 2460 2461 // A variable cannot be both common and exist in a section. 2462 if (D->hasAttr<SectionAttr>()) 2463 return true; 2464 2465 // Thread local vars aren't considered common linkage. 2466 if (D->getTLSKind()) 2467 return true; 2468 2469 // Tentative definitions marked with WeakImportAttr are true definitions. 2470 if (D->hasAttr<WeakImportAttr>()) 2471 return true; 2472 2473 // A variable cannot be both common and exist in a comdat. 2474 if (shouldBeInCOMDAT(CGM, *D)) 2475 return true; 2476 2477 // Declarations with a required alignment do not have common linakge in MSVC 2478 // mode. 2479 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2480 if (D->hasAttr<AlignedAttr>()) 2481 return true; 2482 QualType VarType = D->getType(); 2483 if (Context.isAlignmentRequired(VarType)) 2484 return true; 2485 2486 if (const auto *RT = VarType->getAs<RecordType>()) { 2487 const RecordDecl *RD = RT->getDecl(); 2488 for (const FieldDecl *FD : RD->fields()) { 2489 if (FD->isBitField()) 2490 continue; 2491 if (FD->hasAttr<AlignedAttr>()) 2492 return true; 2493 if (Context.isAlignmentRequired(FD->getType())) 2494 return true; 2495 } 2496 } 2497 } 2498 2499 return false; 2500 } 2501 2502 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 2503 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 2504 if (Linkage == GVA_Internal) 2505 return llvm::Function::InternalLinkage; 2506 2507 if (D->hasAttr<WeakAttr>()) { 2508 if (IsConstantVariable) 2509 return llvm::GlobalVariable::WeakODRLinkage; 2510 else 2511 return llvm::GlobalVariable::WeakAnyLinkage; 2512 } 2513 2514 // We are guaranteed to have a strong definition somewhere else, 2515 // so we can use available_externally linkage. 2516 if (Linkage == GVA_AvailableExternally) 2517 return llvm::Function::AvailableExternallyLinkage; 2518 2519 // Note that Apple's kernel linker doesn't support symbol 2520 // coalescing, so we need to avoid linkonce and weak linkages there. 2521 // Normally, this means we just map to internal, but for explicit 2522 // instantiations we'll map to external. 2523 2524 // In C++, the compiler has to emit a definition in every translation unit 2525 // that references the function. We should use linkonce_odr because 2526 // a) if all references in this translation unit are optimized away, we 2527 // don't need to codegen it. b) if the function persists, it needs to be 2528 // merged with other definitions. c) C++ has the ODR, so we know the 2529 // definition is dependable. 2530 if (Linkage == GVA_DiscardableODR) 2531 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 2532 : llvm::Function::InternalLinkage; 2533 2534 // An explicit instantiation of a template has weak linkage, since 2535 // explicit instantiations can occur in multiple translation units 2536 // and must all be equivalent. However, we are not allowed to 2537 // throw away these explicit instantiations. 2538 if (Linkage == GVA_StrongODR) 2539 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 2540 : llvm::Function::ExternalLinkage; 2541 2542 // C++ doesn't have tentative definitions and thus cannot have common 2543 // linkage. 2544 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 2545 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 2546 CodeGenOpts.NoCommon)) 2547 return llvm::GlobalVariable::CommonLinkage; 2548 2549 // selectany symbols are externally visible, so use weak instead of 2550 // linkonce. MSVC optimizes away references to const selectany globals, so 2551 // all definitions should be the same and ODR linkage should be used. 2552 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 2553 if (D->hasAttr<SelectAnyAttr>()) 2554 return llvm::GlobalVariable::WeakODRLinkage; 2555 2556 // Otherwise, we have strong external linkage. 2557 assert(Linkage == GVA_StrongExternal); 2558 return llvm::GlobalVariable::ExternalLinkage; 2559 } 2560 2561 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 2562 const VarDecl *VD, bool IsConstant) { 2563 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 2564 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 2565 } 2566 2567 /// Replace the uses of a function that was declared with a non-proto type. 2568 /// We want to silently drop extra arguments from call sites 2569 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2570 llvm::Function *newFn) { 2571 // Fast path. 2572 if (old->use_empty()) return; 2573 2574 llvm::Type *newRetTy = newFn->getReturnType(); 2575 SmallVector<llvm::Value*, 4> newArgs; 2576 SmallVector<llvm::OperandBundleDef, 1> newBundles; 2577 2578 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2579 ui != ue; ) { 2580 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 2581 llvm::User *user = use->getUser(); 2582 2583 // Recognize and replace uses of bitcasts. Most calls to 2584 // unprototyped functions will use bitcasts. 2585 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2586 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2587 replaceUsesOfNonProtoConstant(bitcast, newFn); 2588 continue; 2589 } 2590 2591 // Recognize calls to the function. 2592 llvm::CallSite callSite(user); 2593 if (!callSite) continue; 2594 if (!callSite.isCallee(&*use)) continue; 2595 2596 // If the return types don't match exactly, then we can't 2597 // transform this call unless it's dead. 2598 if (callSite->getType() != newRetTy && !callSite->use_empty()) 2599 continue; 2600 2601 // Get the call site's attribute list. 2602 SmallVector<llvm::AttributeSet, 8> newAttrs; 2603 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2604 2605 // Collect any return attributes from the call. 2606 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2607 newAttrs.push_back( 2608 llvm::AttributeSet::get(newFn->getContext(), 2609 oldAttrs.getRetAttributes())); 2610 2611 // If the function was passed too few arguments, don't transform. 2612 unsigned newNumArgs = newFn->arg_size(); 2613 if (callSite.arg_size() < newNumArgs) continue; 2614 2615 // If extra arguments were passed, we silently drop them. 2616 // If any of the types mismatch, we don't transform. 2617 unsigned argNo = 0; 2618 bool dontTransform = false; 2619 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2620 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2621 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2622 dontTransform = true; 2623 break; 2624 } 2625 2626 // Add any parameter attributes. 2627 if (oldAttrs.hasAttributes(argNo + 1)) 2628 newAttrs. 2629 push_back(llvm:: 2630 AttributeSet::get(newFn->getContext(), 2631 oldAttrs.getParamAttributes(argNo + 1))); 2632 } 2633 if (dontTransform) 2634 continue; 2635 2636 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2637 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2638 oldAttrs.getFnAttributes())); 2639 2640 // Okay, we can transform this. Create the new call instruction and copy 2641 // over the required information. 2642 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2643 2644 // Copy over any operand bundles. 2645 callSite.getOperandBundlesAsDefs(newBundles); 2646 2647 llvm::CallSite newCall; 2648 if (callSite.isCall()) { 2649 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 2650 callSite.getInstruction()); 2651 } else { 2652 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2653 newCall = llvm::InvokeInst::Create(newFn, 2654 oldInvoke->getNormalDest(), 2655 oldInvoke->getUnwindDest(), 2656 newArgs, newBundles, "", 2657 callSite.getInstruction()); 2658 } 2659 newArgs.clear(); // for the next iteration 2660 2661 if (!newCall->getType()->isVoidTy()) 2662 newCall->takeName(callSite.getInstruction()); 2663 newCall.setAttributes( 2664 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2665 newCall.setCallingConv(callSite.getCallingConv()); 2666 2667 // Finally, remove the old call, replacing any uses with the new one. 2668 if (!callSite->use_empty()) 2669 callSite->replaceAllUsesWith(newCall.getInstruction()); 2670 2671 // Copy debug location attached to CI. 2672 if (callSite->getDebugLoc()) 2673 newCall->setDebugLoc(callSite->getDebugLoc()); 2674 2675 callSite->eraseFromParent(); 2676 } 2677 } 2678 2679 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2680 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2681 /// existing call uses of the old function in the module, this adjusts them to 2682 /// call the new function directly. 2683 /// 2684 /// This is not just a cleanup: the always_inline pass requires direct calls to 2685 /// functions to be able to inline them. If there is a bitcast in the way, it 2686 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2687 /// run at -O0. 2688 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2689 llvm::Function *NewFn) { 2690 // If we're redefining a global as a function, don't transform it. 2691 if (!isa<llvm::Function>(Old)) return; 2692 2693 replaceUsesOfNonProtoConstant(Old, NewFn); 2694 } 2695 2696 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2697 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2698 // If we have a definition, this might be a deferred decl. If the 2699 // instantiation is explicit, make sure we emit it at the end. 2700 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2701 GetAddrOfGlobalVar(VD); 2702 2703 EmitTopLevelDecl(VD); 2704 } 2705 2706 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 2707 llvm::GlobalValue *GV) { 2708 const auto *D = cast<FunctionDecl>(GD.getDecl()); 2709 2710 // Compute the function info and LLVM type. 2711 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2712 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2713 2714 // Get or create the prototype for the function. 2715 if (!GV || (GV->getType()->getElementType() != Ty)) 2716 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 2717 /*DontDefer=*/true, 2718 /*IsForDefinition=*/true)); 2719 2720 // Already emitted. 2721 if (!GV->isDeclaration()) 2722 return; 2723 2724 // We need to set linkage and visibility on the function before 2725 // generating code for it because various parts of IR generation 2726 // want to propagate this information down (e.g. to local static 2727 // declarations). 2728 auto *Fn = cast<llvm::Function>(GV); 2729 setFunctionLinkage(GD, Fn); 2730 setFunctionDLLStorageClass(GD, Fn); 2731 2732 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 2733 setGlobalVisibility(Fn, D); 2734 2735 MaybeHandleStaticInExternC(D, Fn); 2736 2737 maybeSetTrivialComdat(*D, *Fn); 2738 2739 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2740 2741 setFunctionDefinitionAttributes(D, Fn); 2742 SetLLVMFunctionAttributesForDefinition(D, Fn); 2743 2744 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2745 AddGlobalCtor(Fn, CA->getPriority()); 2746 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2747 AddGlobalDtor(Fn, DA->getPriority()); 2748 if (D->hasAttr<AnnotateAttr>()) 2749 AddGlobalAnnotations(D, Fn); 2750 } 2751 2752 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2753 const auto *D = cast<ValueDecl>(GD.getDecl()); 2754 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2755 assert(AA && "Not an alias?"); 2756 2757 StringRef MangledName = getMangledName(GD); 2758 2759 if (AA->getAliasee() == MangledName) { 2760 Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 2761 return; 2762 } 2763 2764 // If there is a definition in the module, then it wins over the alias. 2765 // This is dubious, but allow it to be safe. Just ignore the alias. 2766 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2767 if (Entry && !Entry->isDeclaration()) 2768 return; 2769 2770 Aliases.push_back(GD); 2771 2772 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2773 2774 // Create a reference to the named value. This ensures that it is emitted 2775 // if a deferred decl. 2776 llvm::Constant *Aliasee; 2777 if (isa<llvm::FunctionType>(DeclTy)) 2778 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2779 /*ForVTable=*/false); 2780 else 2781 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2782 llvm::PointerType::getUnqual(DeclTy), 2783 /*D=*/nullptr); 2784 2785 // Create the new alias itself, but don't set a name yet. 2786 auto *GA = llvm::GlobalAlias::create( 2787 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2788 2789 if (Entry) { 2790 if (GA->getAliasee() == Entry) { 2791 Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 2792 return; 2793 } 2794 2795 assert(Entry->isDeclaration()); 2796 2797 // If there is a declaration in the module, then we had an extern followed 2798 // by the alias, as in: 2799 // extern int test6(); 2800 // ... 2801 // int test6() __attribute__((alias("test7"))); 2802 // 2803 // Remove it and replace uses of it with the alias. 2804 GA->takeName(Entry); 2805 2806 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2807 Entry->getType())); 2808 Entry->eraseFromParent(); 2809 } else { 2810 GA->setName(MangledName); 2811 } 2812 2813 // Set attributes which are particular to an alias; this is a 2814 // specialization of the attributes which may be set on a global 2815 // variable/function. 2816 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 2817 D->isWeakImported()) { 2818 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2819 } 2820 2821 if (const auto *VD = dyn_cast<VarDecl>(D)) 2822 if (VD->getTLSKind()) 2823 setTLSMode(GA, *VD); 2824 2825 setAliasAttributes(D, GA); 2826 } 2827 2828 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2829 ArrayRef<llvm::Type*> Tys) { 2830 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2831 Tys); 2832 } 2833 2834 static llvm::StringMapEntry<llvm::GlobalVariable *> & 2835 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 2836 const StringLiteral *Literal, bool TargetIsLSB, 2837 bool &IsUTF16, unsigned &StringLength) { 2838 StringRef String = Literal->getString(); 2839 unsigned NumBytes = String.size(); 2840 2841 // Check for simple case. 2842 if (!Literal->containsNonAsciiOrNull()) { 2843 StringLength = NumBytes; 2844 return *Map.insert(std::make_pair(String, nullptr)).first; 2845 } 2846 2847 // Otherwise, convert the UTF8 literals into a string of shorts. 2848 IsUTF16 = true; 2849 2850 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2851 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2852 UTF16 *ToPtr = &ToBuf[0]; 2853 2854 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2855 &ToPtr, ToPtr + NumBytes, 2856 strictConversion); 2857 2858 // ConvertUTF8toUTF16 returns the length in ToPtr. 2859 StringLength = ToPtr - &ToBuf[0]; 2860 2861 // Add an explicit null. 2862 *ToPtr = 0; 2863 return *Map.insert(std::make_pair( 2864 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2865 (StringLength + 1) * 2), 2866 nullptr)).first; 2867 } 2868 2869 static llvm::StringMapEntry<llvm::GlobalVariable *> & 2870 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 2871 const StringLiteral *Literal, unsigned &StringLength) { 2872 StringRef String = Literal->getString(); 2873 StringLength = String.size(); 2874 return *Map.insert(std::make_pair(String, nullptr)).first; 2875 } 2876 2877 ConstantAddress 2878 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2879 unsigned StringLength = 0; 2880 bool isUTF16 = false; 2881 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2882 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2883 getDataLayout().isLittleEndian(), isUTF16, 2884 StringLength); 2885 2886 if (auto *C = Entry.second) 2887 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2888 2889 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2890 llvm::Constant *Zeros[] = { Zero, Zero }; 2891 llvm::Value *V; 2892 2893 // If we don't already have it, get __CFConstantStringClassReference. 2894 if (!CFConstantStringClassRef) { 2895 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2896 Ty = llvm::ArrayType::get(Ty, 0); 2897 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2898 "__CFConstantStringClassReference"); 2899 // Decay array -> ptr 2900 V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 2901 CFConstantStringClassRef = V; 2902 } 2903 else 2904 V = CFConstantStringClassRef; 2905 2906 QualType CFTy = getContext().getCFConstantStringType(); 2907 2908 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2909 2910 llvm::Constant *Fields[4]; 2911 2912 // Class pointer. 2913 Fields[0] = cast<llvm::ConstantExpr>(V); 2914 2915 // Flags. 2916 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2917 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2918 llvm::ConstantInt::get(Ty, 0x07C8); 2919 2920 // String pointer. 2921 llvm::Constant *C = nullptr; 2922 if (isUTF16) { 2923 auto Arr = llvm::makeArrayRef( 2924 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 2925 Entry.first().size() / 2); 2926 C = llvm::ConstantDataArray::get(VMContext, Arr); 2927 } else { 2928 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 2929 } 2930 2931 // Note: -fwritable-strings doesn't make the backing store strings of 2932 // CFStrings writable. (See <rdar://problem/10657500>) 2933 auto *GV = 2934 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2935 llvm::GlobalValue::PrivateLinkage, C, ".str"); 2936 GV->setUnnamedAddr(true); 2937 // Don't enforce the target's minimum global alignment, since the only use 2938 // of the string is via this class initializer. 2939 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 2940 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 2941 // that changes the section it ends in, which surprises ld64. 2942 if (isUTF16) { 2943 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2944 GV->setAlignment(Align.getQuantity()); 2945 GV->setSection("__TEXT,__ustring"); 2946 } else { 2947 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2948 GV->setAlignment(Align.getQuantity()); 2949 GV->setSection("__TEXT,__cstring,cstring_literals"); 2950 } 2951 2952 // String. 2953 Fields[2] = 2954 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 2955 2956 if (isUTF16) 2957 // Cast the UTF16 string to the correct type. 2958 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2959 2960 // String length. 2961 Ty = getTypes().ConvertType(getContext().LongTy); 2962 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2963 2964 CharUnits Alignment = getPointerAlign(); 2965 2966 // The struct. 2967 C = llvm::ConstantStruct::get(STy, Fields); 2968 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2969 llvm::GlobalVariable::PrivateLinkage, C, 2970 "_unnamed_cfstring_"); 2971 GV->setSection("__DATA,__cfstring"); 2972 GV->setAlignment(Alignment.getQuantity()); 2973 Entry.second = GV; 2974 2975 return ConstantAddress(GV, Alignment); 2976 } 2977 2978 ConstantAddress 2979 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2980 unsigned StringLength = 0; 2981 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2982 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2983 2984 if (auto *C = Entry.second) 2985 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2986 2987 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2988 llvm::Constant *Zeros[] = { Zero, Zero }; 2989 llvm::Value *V; 2990 // If we don't already have it, get _NSConstantStringClassReference. 2991 if (!ConstantStringClassRef) { 2992 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2993 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2994 llvm::Constant *GV; 2995 if (LangOpts.ObjCRuntime.isNonFragile()) { 2996 std::string str = 2997 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2998 : "OBJC_CLASS_$_" + StringClass; 2999 GV = getObjCRuntime().GetClassGlobal(str); 3000 // Make sure the result is of the correct type. 3001 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3002 V = llvm::ConstantExpr::getBitCast(GV, PTy); 3003 ConstantStringClassRef = V; 3004 } else { 3005 std::string str = 3006 StringClass.empty() ? "_NSConstantStringClassReference" 3007 : "_" + StringClass + "ClassReference"; 3008 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 3009 GV = CreateRuntimeVariable(PTy, str); 3010 // Decay array -> ptr 3011 V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros); 3012 ConstantStringClassRef = V; 3013 } 3014 } else 3015 V = ConstantStringClassRef; 3016 3017 if (!NSConstantStringType) { 3018 // Construct the type for a constant NSString. 3019 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 3020 D->startDefinition(); 3021 3022 QualType FieldTypes[3]; 3023 3024 // const int *isa; 3025 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 3026 // const char *str; 3027 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 3028 // unsigned int length; 3029 FieldTypes[2] = Context.UnsignedIntTy; 3030 3031 // Create fields 3032 for (unsigned i = 0; i < 3; ++i) { 3033 FieldDecl *Field = FieldDecl::Create(Context, D, 3034 SourceLocation(), 3035 SourceLocation(), nullptr, 3036 FieldTypes[i], /*TInfo=*/nullptr, 3037 /*BitWidth=*/nullptr, 3038 /*Mutable=*/false, 3039 ICIS_NoInit); 3040 Field->setAccess(AS_public); 3041 D->addDecl(Field); 3042 } 3043 3044 D->completeDefinition(); 3045 QualType NSTy = Context.getTagDeclType(D); 3046 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 3047 } 3048 3049 llvm::Constant *Fields[3]; 3050 3051 // Class pointer. 3052 Fields[0] = cast<llvm::ConstantExpr>(V); 3053 3054 // String pointer. 3055 llvm::Constant *C = 3056 llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3057 3058 llvm::GlobalValue::LinkageTypes Linkage; 3059 bool isConstant; 3060 Linkage = llvm::GlobalValue::PrivateLinkage; 3061 isConstant = !LangOpts.WritableStrings; 3062 3063 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 3064 Linkage, C, ".str"); 3065 GV->setUnnamedAddr(true); 3066 // Don't enforce the target's minimum global alignment, since the only use 3067 // of the string is via this class initializer. 3068 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 3069 GV->setAlignment(Align.getQuantity()); 3070 Fields[1] = 3071 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3072 3073 // String length. 3074 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3075 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 3076 3077 // The struct. 3078 CharUnits Alignment = getPointerAlign(); 3079 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 3080 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3081 llvm::GlobalVariable::PrivateLinkage, C, 3082 "_unnamed_nsstring_"); 3083 GV->setAlignment(Alignment.getQuantity()); 3084 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 3085 const char *NSStringNonFragileABISection = 3086 "__DATA,__objc_stringobj,regular,no_dead_strip"; 3087 // FIXME. Fix section. 3088 GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 3089 ? NSStringNonFragileABISection 3090 : NSStringSection); 3091 Entry.second = GV; 3092 3093 return ConstantAddress(GV, Alignment); 3094 } 3095 3096 QualType CodeGenModule::getObjCFastEnumerationStateType() { 3097 if (ObjCFastEnumerationStateType.isNull()) { 3098 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 3099 D->startDefinition(); 3100 3101 QualType FieldTypes[] = { 3102 Context.UnsignedLongTy, 3103 Context.getPointerType(Context.getObjCIdType()), 3104 Context.getPointerType(Context.UnsignedLongTy), 3105 Context.getConstantArrayType(Context.UnsignedLongTy, 3106 llvm::APInt(32, 5), ArrayType::Normal, 0) 3107 }; 3108 3109 for (size_t i = 0; i < 4; ++i) { 3110 FieldDecl *Field = FieldDecl::Create(Context, 3111 D, 3112 SourceLocation(), 3113 SourceLocation(), nullptr, 3114 FieldTypes[i], /*TInfo=*/nullptr, 3115 /*BitWidth=*/nullptr, 3116 /*Mutable=*/false, 3117 ICIS_NoInit); 3118 Field->setAccess(AS_public); 3119 D->addDecl(Field); 3120 } 3121 3122 D->completeDefinition(); 3123 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 3124 } 3125 3126 return ObjCFastEnumerationStateType; 3127 } 3128 3129 llvm::Constant * 3130 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3131 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3132 3133 // Don't emit it as the address of the string, emit the string data itself 3134 // as an inline array. 3135 if (E->getCharByteWidth() == 1) { 3136 SmallString<64> Str(E->getString()); 3137 3138 // Resize the string to the right size, which is indicated by its type. 3139 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3140 Str.resize(CAT->getSize().getZExtValue()); 3141 return llvm::ConstantDataArray::getString(VMContext, Str, false); 3142 } 3143 3144 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3145 llvm::Type *ElemTy = AType->getElementType(); 3146 unsigned NumElements = AType->getNumElements(); 3147 3148 // Wide strings have either 2-byte or 4-byte elements. 3149 if (ElemTy->getPrimitiveSizeInBits() == 16) { 3150 SmallVector<uint16_t, 32> Elements; 3151 Elements.reserve(NumElements); 3152 3153 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3154 Elements.push_back(E->getCodeUnit(i)); 3155 Elements.resize(NumElements); 3156 return llvm::ConstantDataArray::get(VMContext, Elements); 3157 } 3158 3159 assert(ElemTy->getPrimitiveSizeInBits() == 32); 3160 SmallVector<uint32_t, 32> Elements; 3161 Elements.reserve(NumElements); 3162 3163 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3164 Elements.push_back(E->getCodeUnit(i)); 3165 Elements.resize(NumElements); 3166 return llvm::ConstantDataArray::get(VMContext, Elements); 3167 } 3168 3169 static llvm::GlobalVariable * 3170 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 3171 CodeGenModule &CGM, StringRef GlobalName, 3172 CharUnits Alignment) { 3173 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 3174 unsigned AddrSpace = 0; 3175 if (CGM.getLangOpts().OpenCL) 3176 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3177 3178 llvm::Module &M = CGM.getModule(); 3179 // Create a global variable for this string 3180 auto *GV = new llvm::GlobalVariable( 3181 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 3182 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 3183 GV->setAlignment(Alignment.getQuantity()); 3184 GV->setUnnamedAddr(true); 3185 if (GV->isWeakForLinker()) { 3186 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 3187 GV->setComdat(M.getOrInsertComdat(GV->getName())); 3188 } 3189 3190 return GV; 3191 } 3192 3193 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 3194 /// constant array for the given string literal. 3195 ConstantAddress 3196 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 3197 StringRef Name) { 3198 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3199 3200 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 3201 llvm::GlobalVariable **Entry = nullptr; 3202 if (!LangOpts.WritableStrings) { 3203 Entry = &ConstantStringMap[C]; 3204 if (auto GV = *Entry) { 3205 if (Alignment.getQuantity() > GV->getAlignment()) 3206 GV->setAlignment(Alignment.getQuantity()); 3207 return ConstantAddress(GV, Alignment); 3208 } 3209 } 3210 3211 SmallString<256> MangledNameBuffer; 3212 StringRef GlobalVariableName; 3213 llvm::GlobalValue::LinkageTypes LT; 3214 3215 // Mangle the string literal if the ABI allows for it. However, we cannot 3216 // do this if we are compiling with ASan or -fwritable-strings because they 3217 // rely on strings having normal linkage. 3218 if (!LangOpts.WritableStrings && 3219 !LangOpts.Sanitize.has(SanitizerKind::Address) && 3220 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 3221 llvm::raw_svector_ostream Out(MangledNameBuffer); 3222 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 3223 3224 LT = llvm::GlobalValue::LinkOnceODRLinkage; 3225 GlobalVariableName = MangledNameBuffer; 3226 } else { 3227 LT = llvm::GlobalValue::PrivateLinkage; 3228 GlobalVariableName = Name; 3229 } 3230 3231 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 3232 if (Entry) 3233 *Entry = GV; 3234 3235 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 3236 QualType()); 3237 return ConstantAddress(GV, Alignment); 3238 } 3239 3240 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3241 /// array for the given ObjCEncodeExpr node. 3242 ConstantAddress 3243 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3244 std::string Str; 3245 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3246 3247 return GetAddrOfConstantCString(Str); 3248 } 3249 3250 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 3251 /// the literal and a terminating '\0' character. 3252 /// The result has pointer to array type. 3253 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 3254 const std::string &Str, const char *GlobalName) { 3255 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 3256 CharUnits Alignment = 3257 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3258 3259 llvm::Constant *C = 3260 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 3261 3262 // Don't share any string literals if strings aren't constant. 3263 llvm::GlobalVariable **Entry = nullptr; 3264 if (!LangOpts.WritableStrings) { 3265 Entry = &ConstantStringMap[C]; 3266 if (auto GV = *Entry) { 3267 if (Alignment.getQuantity() > GV->getAlignment()) 3268 GV->setAlignment(Alignment.getQuantity()); 3269 return ConstantAddress(GV, Alignment); 3270 } 3271 } 3272 3273 // Get the default prefix if a name wasn't specified. 3274 if (!GlobalName) 3275 GlobalName = ".str"; 3276 // Create a global variable for this. 3277 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 3278 GlobalName, Alignment); 3279 if (Entry) 3280 *Entry = GV; 3281 return ConstantAddress(GV, Alignment); 3282 } 3283 3284 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3285 const MaterializeTemporaryExpr *E, const Expr *Init) { 3286 assert((E->getStorageDuration() == SD_Static || 3287 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 3288 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3289 3290 // If we're not materializing a subobject of the temporary, keep the 3291 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3292 QualType MaterializedType = Init->getType(); 3293 if (Init == E->GetTemporaryExpr()) 3294 MaterializedType = E->getType(); 3295 3296 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 3297 3298 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 3299 return ConstantAddress(Slot, Align); 3300 3301 // FIXME: If an externally-visible declaration extends multiple temporaries, 3302 // we need to give each temporary the same name in every translation unit (and 3303 // we also need to make the temporaries externally-visible). 3304 SmallString<256> Name; 3305 llvm::raw_svector_ostream Out(Name); 3306 getCXXABI().getMangleContext().mangleReferenceTemporary( 3307 VD, E->getManglingNumber(), Out); 3308 3309 APValue *Value = nullptr; 3310 if (E->getStorageDuration() == SD_Static) { 3311 // We might have a cached constant initializer for this temporary. Note 3312 // that this might have a different value from the value computed by 3313 // evaluating the initializer if the surrounding constant expression 3314 // modifies the temporary. 3315 Value = getContext().getMaterializedTemporaryValue(E, false); 3316 if (Value && Value->isUninit()) 3317 Value = nullptr; 3318 } 3319 3320 // Try evaluating it now, it might have a constant initializer. 3321 Expr::EvalResult EvalResult; 3322 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3323 !EvalResult.hasSideEffects()) 3324 Value = &EvalResult.Val; 3325 3326 llvm::Constant *InitialValue = nullptr; 3327 bool Constant = false; 3328 llvm::Type *Type; 3329 if (Value) { 3330 // The temporary has a constant initializer, use it. 3331 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3332 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3333 Type = InitialValue->getType(); 3334 } else { 3335 // No initializer, the initialization will be provided when we 3336 // initialize the declaration which performed lifetime extension. 3337 Type = getTypes().ConvertTypeForMem(MaterializedType); 3338 } 3339 3340 // Create a global variable for this lifetime-extended temporary. 3341 llvm::GlobalValue::LinkageTypes Linkage = 3342 getLLVMLinkageVarDefinition(VD, Constant); 3343 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 3344 const VarDecl *InitVD; 3345 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 3346 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 3347 // Temporaries defined inside a class get linkonce_odr linkage because the 3348 // class can be defined in multipe translation units. 3349 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 3350 } else { 3351 // There is no need for this temporary to have external linkage if the 3352 // VarDecl has external linkage. 3353 Linkage = llvm::GlobalVariable::InternalLinkage; 3354 } 3355 } 3356 unsigned AddrSpace = GetGlobalVarAddressSpace( 3357 VD, getContext().getTargetAddressSpace(MaterializedType)); 3358 auto *GV = new llvm::GlobalVariable( 3359 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 3360 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 3361 AddrSpace); 3362 setGlobalVisibility(GV, VD); 3363 GV->setAlignment(Align.getQuantity()); 3364 if (supportsCOMDAT() && GV->isWeakForLinker()) 3365 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3366 if (VD->getTLSKind()) 3367 setTLSMode(GV, *VD); 3368 MaterializedGlobalTemporaryMap[E] = GV; 3369 return ConstantAddress(GV, Align); 3370 } 3371 3372 /// EmitObjCPropertyImplementations - Emit information for synthesized 3373 /// properties for an implementation. 3374 void CodeGenModule::EmitObjCPropertyImplementations(const 3375 ObjCImplementationDecl *D) { 3376 for (const auto *PID : D->property_impls()) { 3377 // Dynamic is just for type-checking. 3378 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3379 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3380 3381 // Determine which methods need to be implemented, some may have 3382 // been overridden. Note that ::isPropertyAccessor is not the method 3383 // we want, that just indicates if the decl came from a 3384 // property. What we want to know is if the method is defined in 3385 // this implementation. 3386 if (!D->getInstanceMethod(PD->getGetterName())) 3387 CodeGenFunction(*this).GenerateObjCGetter( 3388 const_cast<ObjCImplementationDecl *>(D), PID); 3389 if (!PD->isReadOnly() && 3390 !D->getInstanceMethod(PD->getSetterName())) 3391 CodeGenFunction(*this).GenerateObjCSetter( 3392 const_cast<ObjCImplementationDecl *>(D), PID); 3393 } 3394 } 3395 } 3396 3397 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 3398 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 3399 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 3400 ivar; ivar = ivar->getNextIvar()) 3401 if (ivar->getType().isDestructedType()) 3402 return true; 3403 3404 return false; 3405 } 3406 3407 static bool AllTrivialInitializers(CodeGenModule &CGM, 3408 ObjCImplementationDecl *D) { 3409 CodeGenFunction CGF(CGM); 3410 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 3411 E = D->init_end(); B != E; ++B) { 3412 CXXCtorInitializer *CtorInitExp = *B; 3413 Expr *Init = CtorInitExp->getInit(); 3414 if (!CGF.isTrivialInitializer(Init)) 3415 return false; 3416 } 3417 return true; 3418 } 3419 3420 /// EmitObjCIvarInitializations - Emit information for ivar initialization 3421 /// for an implementation. 3422 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 3423 // We might need a .cxx_destruct even if we don't have any ivar initializers. 3424 if (needsDestructMethod(D)) { 3425 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3426 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3427 ObjCMethodDecl *DTORMethod = 3428 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 3429 cxxSelector, getContext().VoidTy, nullptr, D, 3430 /*isInstance=*/true, /*isVariadic=*/false, 3431 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 3432 /*isDefined=*/false, ObjCMethodDecl::Required); 3433 D->addInstanceMethod(DTORMethod); 3434 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 3435 D->setHasDestructors(true); 3436 } 3437 3438 // If the implementation doesn't have any ivar initializers, we don't need 3439 // a .cxx_construct. 3440 if (D->getNumIvarInitializers() == 0 || 3441 AllTrivialInitializers(*this, D)) 3442 return; 3443 3444 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 3445 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3446 // The constructor returns 'self'. 3447 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3448 D->getLocation(), 3449 D->getLocation(), 3450 cxxSelector, 3451 getContext().getObjCIdType(), 3452 nullptr, D, /*isInstance=*/true, 3453 /*isVariadic=*/false, 3454 /*isPropertyAccessor=*/true, 3455 /*isImplicitlyDeclared=*/true, 3456 /*isDefined=*/false, 3457 ObjCMethodDecl::Required); 3458 D->addInstanceMethod(CTORMethod); 3459 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 3460 D->setHasNonZeroConstructors(true); 3461 } 3462 3463 /// EmitNamespace - Emit all declarations in a namespace. 3464 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 3465 for (auto *I : ND->decls()) { 3466 if (const auto *VD = dyn_cast<VarDecl>(I)) 3467 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 3468 VD->getTemplateSpecializationKind() != TSK_Undeclared) 3469 continue; 3470 EmitTopLevelDecl(I); 3471 } 3472 } 3473 3474 // EmitLinkageSpec - Emit all declarations in a linkage spec. 3475 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3476 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3477 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3478 ErrorUnsupported(LSD, "linkage spec"); 3479 return; 3480 } 3481 3482 for (auto *I : LSD->decls()) { 3483 // Meta-data for ObjC class includes references to implemented methods. 3484 // Generate class's method definitions first. 3485 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 3486 for (auto *M : OID->methods()) 3487 EmitTopLevelDecl(M); 3488 } 3489 EmitTopLevelDecl(I); 3490 } 3491 } 3492 3493 /// EmitTopLevelDecl - Emit code for a single top level declaration. 3494 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3495 // Ignore dependent declarations. 3496 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3497 return; 3498 3499 switch (D->getKind()) { 3500 case Decl::CXXConversion: 3501 case Decl::CXXMethod: 3502 case Decl::Function: 3503 // Skip function templates 3504 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3505 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3506 return; 3507 3508 EmitGlobal(cast<FunctionDecl>(D)); 3509 // Always provide some coverage mapping 3510 // even for the functions that aren't emitted. 3511 AddDeferredUnusedCoverageMapping(D); 3512 break; 3513 3514 case Decl::Var: 3515 // Skip variable templates 3516 if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3517 return; 3518 case Decl::VarTemplateSpecialization: 3519 EmitGlobal(cast<VarDecl>(D)); 3520 break; 3521 3522 // Indirect fields from global anonymous structs and unions can be 3523 // ignored; only the actual variable requires IR gen support. 3524 case Decl::IndirectField: 3525 break; 3526 3527 // C++ Decls 3528 case Decl::Namespace: 3529 EmitNamespace(cast<NamespaceDecl>(D)); 3530 break; 3531 // No code generation needed. 3532 case Decl::UsingShadow: 3533 case Decl::ClassTemplate: 3534 case Decl::VarTemplate: 3535 case Decl::VarTemplatePartialSpecialization: 3536 case Decl::FunctionTemplate: 3537 case Decl::TypeAliasTemplate: 3538 case Decl::Block: 3539 case Decl::Empty: 3540 break; 3541 case Decl::Using: // using X; [C++] 3542 if (CGDebugInfo *DI = getModuleDebugInfo()) 3543 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 3544 return; 3545 case Decl::NamespaceAlias: 3546 if (CGDebugInfo *DI = getModuleDebugInfo()) 3547 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3548 return; 3549 case Decl::UsingDirective: // using namespace X; [C++] 3550 if (CGDebugInfo *DI = getModuleDebugInfo()) 3551 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3552 return; 3553 case Decl::CXXConstructor: 3554 // Skip function templates 3555 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3556 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3557 return; 3558 3559 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3560 break; 3561 case Decl::CXXDestructor: 3562 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 3563 return; 3564 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3565 break; 3566 3567 case Decl::StaticAssert: 3568 // Nothing to do. 3569 break; 3570 3571 // Objective-C Decls 3572 3573 // Forward declarations, no (immediate) code generation. 3574 case Decl::ObjCInterface: 3575 case Decl::ObjCCategory: 3576 break; 3577 3578 case Decl::ObjCProtocol: { 3579 auto *Proto = cast<ObjCProtocolDecl>(D); 3580 if (Proto->isThisDeclarationADefinition()) 3581 ObjCRuntime->GenerateProtocol(Proto); 3582 break; 3583 } 3584 3585 case Decl::ObjCCategoryImpl: 3586 // Categories have properties but don't support synthesize so we 3587 // can ignore them here. 3588 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3589 break; 3590 3591 case Decl::ObjCImplementation: { 3592 auto *OMD = cast<ObjCImplementationDecl>(D); 3593 EmitObjCPropertyImplementations(OMD); 3594 EmitObjCIvarInitializations(OMD); 3595 ObjCRuntime->GenerateClass(OMD); 3596 // Emit global variable debug information. 3597 if (CGDebugInfo *DI = getModuleDebugInfo()) 3598 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3599 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3600 OMD->getClassInterface()), OMD->getLocation()); 3601 break; 3602 } 3603 case Decl::ObjCMethod: { 3604 auto *OMD = cast<ObjCMethodDecl>(D); 3605 // If this is not a prototype, emit the body. 3606 if (OMD->getBody()) 3607 CodeGenFunction(*this).GenerateObjCMethod(OMD); 3608 break; 3609 } 3610 case Decl::ObjCCompatibleAlias: 3611 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3612 break; 3613 3614 case Decl::LinkageSpec: 3615 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3616 break; 3617 3618 case Decl::FileScopeAsm: { 3619 // File-scope asm is ignored during device-side CUDA compilation. 3620 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 3621 break; 3622 // File-scope asm is ignored during device-side OpenMP compilation. 3623 if (LangOpts.OpenMPIsDevice) 3624 break; 3625 auto *AD = cast<FileScopeAsmDecl>(D); 3626 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3627 break; 3628 } 3629 3630 case Decl::Import: { 3631 auto *Import = cast<ImportDecl>(D); 3632 3633 // Ignore import declarations that come from imported modules. 3634 if (Import->getImportedOwningModule()) 3635 break; 3636 if (CGDebugInfo *DI = getModuleDebugInfo()) 3637 DI->EmitImportDecl(*Import); 3638 3639 ImportedModules.insert(Import->getImportedModule()); 3640 break; 3641 } 3642 3643 case Decl::OMPThreadPrivate: 3644 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 3645 break; 3646 3647 case Decl::ClassTemplateSpecialization: { 3648 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 3649 if (DebugInfo && 3650 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 3651 Spec->hasDefinition()) 3652 DebugInfo->completeTemplateDefinition(*Spec); 3653 break; 3654 } 3655 3656 default: 3657 // Make sure we handled everything we should, every other kind is a 3658 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3659 // function. Need to recode Decl::Kind to do that easily. 3660 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3661 break; 3662 } 3663 } 3664 3665 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 3666 // Do we need to generate coverage mapping? 3667 if (!CodeGenOpts.CoverageMapping) 3668 return; 3669 switch (D->getKind()) { 3670 case Decl::CXXConversion: 3671 case Decl::CXXMethod: 3672 case Decl::Function: 3673 case Decl::ObjCMethod: 3674 case Decl::CXXConstructor: 3675 case Decl::CXXDestructor: { 3676 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 3677 return; 3678 auto I = DeferredEmptyCoverageMappingDecls.find(D); 3679 if (I == DeferredEmptyCoverageMappingDecls.end()) 3680 DeferredEmptyCoverageMappingDecls[D] = true; 3681 break; 3682 } 3683 default: 3684 break; 3685 }; 3686 } 3687 3688 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 3689 // Do we need to generate coverage mapping? 3690 if (!CodeGenOpts.CoverageMapping) 3691 return; 3692 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 3693 if (Fn->isTemplateInstantiation()) 3694 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 3695 } 3696 auto I = DeferredEmptyCoverageMappingDecls.find(D); 3697 if (I == DeferredEmptyCoverageMappingDecls.end()) 3698 DeferredEmptyCoverageMappingDecls[D] = false; 3699 else 3700 I->second = false; 3701 } 3702 3703 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 3704 std::vector<const Decl *> DeferredDecls; 3705 for (const auto &I : DeferredEmptyCoverageMappingDecls) { 3706 if (!I.second) 3707 continue; 3708 DeferredDecls.push_back(I.first); 3709 } 3710 // Sort the declarations by their location to make sure that the tests get a 3711 // predictable order for the coverage mapping for the unused declarations. 3712 if (CodeGenOpts.DumpCoverageMapping) 3713 std::sort(DeferredDecls.begin(), DeferredDecls.end(), 3714 [] (const Decl *LHS, const Decl *RHS) { 3715 return LHS->getLocStart() < RHS->getLocStart(); 3716 }); 3717 for (const auto *D : DeferredDecls) { 3718 switch (D->getKind()) { 3719 case Decl::CXXConversion: 3720 case Decl::CXXMethod: 3721 case Decl::Function: 3722 case Decl::ObjCMethod: { 3723 CodeGenPGO PGO(*this); 3724 GlobalDecl GD(cast<FunctionDecl>(D)); 3725 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3726 getFunctionLinkage(GD)); 3727 break; 3728 } 3729 case Decl::CXXConstructor: { 3730 CodeGenPGO PGO(*this); 3731 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 3732 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3733 getFunctionLinkage(GD)); 3734 break; 3735 } 3736 case Decl::CXXDestructor: { 3737 CodeGenPGO PGO(*this); 3738 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 3739 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3740 getFunctionLinkage(GD)); 3741 break; 3742 } 3743 default: 3744 break; 3745 }; 3746 } 3747 } 3748 3749 /// Turns the given pointer into a constant. 3750 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3751 const void *Ptr) { 3752 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 3753 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3754 return llvm::ConstantInt::get(i64, PtrInt); 3755 } 3756 3757 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3758 llvm::NamedMDNode *&GlobalMetadata, 3759 GlobalDecl D, 3760 llvm::GlobalValue *Addr) { 3761 if (!GlobalMetadata) 3762 GlobalMetadata = 3763 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3764 3765 // TODO: should we report variant information for ctors/dtors? 3766 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 3767 llvm::ConstantAsMetadata::get(GetPointerConstant( 3768 CGM.getLLVMContext(), D.getDecl()))}; 3769 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3770 } 3771 3772 /// For each function which is declared within an extern "C" region and marked 3773 /// as 'used', but has internal linkage, create an alias from the unmangled 3774 /// name to the mangled name if possible. People expect to be able to refer 3775 /// to such functions with an unmangled name from inline assembly within the 3776 /// same translation unit. 3777 void CodeGenModule::EmitStaticExternCAliases() { 3778 for (auto &I : StaticExternCValues) { 3779 IdentifierInfo *Name = I.first; 3780 llvm::GlobalValue *Val = I.second; 3781 if (Val && !getModule().getNamedValue(Name->getName())) 3782 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 3783 } 3784 } 3785 3786 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 3787 GlobalDecl &Result) const { 3788 auto Res = Manglings.find(MangledName); 3789 if (Res == Manglings.end()) 3790 return false; 3791 Result = Res->getValue(); 3792 return true; 3793 } 3794 3795 /// Emits metadata nodes associating all the global values in the 3796 /// current module with the Decls they came from. This is useful for 3797 /// projects using IR gen as a subroutine. 3798 /// 3799 /// Since there's currently no way to associate an MDNode directly 3800 /// with an llvm::GlobalValue, we create a global named metadata 3801 /// with the name 'clang.global.decl.ptrs'. 3802 void CodeGenModule::EmitDeclMetadata() { 3803 llvm::NamedMDNode *GlobalMetadata = nullptr; 3804 3805 for (auto &I : MangledDeclNames) { 3806 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 3807 // Some mangled names don't necessarily have an associated GlobalValue 3808 // in this module, e.g. if we mangled it for DebugInfo. 3809 if (Addr) 3810 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 3811 } 3812 } 3813 3814 /// Emits metadata nodes for all the local variables in the current 3815 /// function. 3816 void CodeGenFunction::EmitDeclMetadata() { 3817 if (LocalDeclMap.empty()) return; 3818 3819 llvm::LLVMContext &Context = getLLVMContext(); 3820 3821 // Find the unique metadata ID for this name. 3822 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3823 3824 llvm::NamedMDNode *GlobalMetadata = nullptr; 3825 3826 for (auto &I : LocalDeclMap) { 3827 const Decl *D = I.first; 3828 llvm::Value *Addr = I.second.getPointer(); 3829 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3830 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3831 Alloca->setMetadata( 3832 DeclPtrKind, llvm::MDNode::get( 3833 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 3834 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3835 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3836 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3837 } 3838 } 3839 } 3840 3841 void CodeGenModule::EmitVersionIdentMetadata() { 3842 llvm::NamedMDNode *IdentMetadata = 3843 TheModule.getOrInsertNamedMetadata("llvm.ident"); 3844 std::string Version = getClangFullVersion(); 3845 llvm::LLVMContext &Ctx = TheModule.getContext(); 3846 3847 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 3848 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3849 } 3850 3851 void CodeGenModule::EmitTargetMetadata() { 3852 // Warning, new MangledDeclNames may be appended within this loop. 3853 // We rely on MapVector insertions adding new elements to the end 3854 // of the container. 3855 // FIXME: Move this loop into the one target that needs it, and only 3856 // loop over those declarations for which we couldn't emit the target 3857 // metadata when we emitted the declaration. 3858 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 3859 auto Val = *(MangledDeclNames.begin() + I); 3860 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 3861 llvm::GlobalValue *GV = GetGlobalValue(Val.second); 3862 getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 3863 } 3864 } 3865 3866 void CodeGenModule::EmitCoverageFile() { 3867 if (!getCodeGenOpts().CoverageFile.empty()) { 3868 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3869 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3870 llvm::LLVMContext &Ctx = TheModule.getContext(); 3871 llvm::MDString *CoverageFile = 3872 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3873 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3874 llvm::MDNode *CU = CUNode->getOperand(i); 3875 llvm::Metadata *Elts[] = {CoverageFile, CU}; 3876 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 3877 } 3878 } 3879 } 3880 } 3881 3882 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 3883 // Sema has checked that all uuid strings are of the form 3884 // "12345678-1234-1234-1234-1234567890ab". 3885 assert(Uuid.size() == 36); 3886 for (unsigned i = 0; i < 36; ++i) { 3887 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3888 else assert(isHexDigit(Uuid[i])); 3889 } 3890 3891 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 3892 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3893 3894 llvm::Constant *Field3[8]; 3895 for (unsigned Idx = 0; Idx < 8; ++Idx) 3896 Field3[Idx] = llvm::ConstantInt::get( 3897 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 3898 3899 llvm::Constant *Fields[4] = { 3900 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3901 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3902 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3903 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3904 }; 3905 3906 return llvm::ConstantStruct::getAnon(Fields); 3907 } 3908 3909 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 3910 bool ForEH) { 3911 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 3912 // FIXME: should we even be calling this method if RTTI is disabled 3913 // and it's not for EH? 3914 if (!ForEH && !getLangOpts().RTTI) 3915 return llvm::Constant::getNullValue(Int8PtrTy); 3916 3917 if (ForEH && Ty->isObjCObjectPointerType() && 3918 LangOpts.ObjCRuntime.isGNUFamily()) 3919 return ObjCRuntime->GetEHType(Ty); 3920 3921 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 3922 } 3923 3924 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 3925 for (auto RefExpr : D->varlists()) { 3926 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 3927 bool PerformInit = 3928 VD->getAnyInitializer() && 3929 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 3930 /*ForRef=*/false); 3931 3932 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 3933 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 3934 VD, Addr, RefExpr->getLocStart(), PerformInit)) 3935 CXXGlobalInits.push_back(InitFunction); 3936 } 3937 } 3938 3939 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 3940 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 3941 if (InternalId) 3942 return InternalId; 3943 3944 if (isExternallyVisible(T->getLinkage())) { 3945 std::string OutName; 3946 llvm::raw_string_ostream Out(OutName); 3947 getCXXABI().getMangleContext().mangleTypeName(T, Out); 3948 3949 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 3950 } else { 3951 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 3952 llvm::ArrayRef<llvm::Metadata *>()); 3953 } 3954 3955 return InternalId; 3956 } 3957 3958 void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD, 3959 llvm::GlobalVariable *VTable, 3960 CharUnits Offset, 3961 const CXXRecordDecl *RD) { 3962 llvm::Metadata *MD = 3963 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 3964 llvm::Metadata *BitsetOps[] = { 3965 MD, llvm::ConstantAsMetadata::get(VTable), 3966 llvm::ConstantAsMetadata::get( 3967 llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 3968 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 3969 3970 if (CodeGenOpts.SanitizeCfiCrossDso) { 3971 if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 3972 llvm::Metadata *BitsetOps2[] = { 3973 llvm::ConstantAsMetadata::get(TypeId), 3974 llvm::ConstantAsMetadata::get(VTable), 3975 llvm::ConstantAsMetadata::get( 3976 llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 3977 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 3978 } 3979 } 3980 } 3981 3982 // Fills in the supplied string map with the set of target features for the 3983 // passed in function. 3984 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 3985 const FunctionDecl *FD) { 3986 StringRef TargetCPU = Target.getTargetOpts().CPU; 3987 if (const auto *TD = FD->getAttr<TargetAttr>()) { 3988 // If we have a TargetAttr build up the feature map based on that. 3989 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 3990 3991 // Make a copy of the features as passed on the command line into the 3992 // beginning of the additional features from the function to override. 3993 ParsedAttr.first.insert(ParsedAttr.first.begin(), 3994 Target.getTargetOpts().FeaturesAsWritten.begin(), 3995 Target.getTargetOpts().FeaturesAsWritten.end()); 3996 3997 if (ParsedAttr.second != "") 3998 TargetCPU = ParsedAttr.second; 3999 4000 // Now populate the feature map, first with the TargetCPU which is either 4001 // the default or a new one from the target attribute string. Then we'll use 4002 // the passed in features (FeaturesAsWritten) along with the new ones from 4003 // the attribute. 4004 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 4005 } else { 4006 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 4007 Target.getTargetOpts().Features); 4008 } 4009 } 4010