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