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