1 //===-- TargetMachine.cpp - General Target Information ---------------------==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file describes the general parts of a Target machine. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Target/TargetMachine.h" 14 #include "llvm/Analysis/TargetTransformInfo.h" 15 #include "llvm/IR/Function.h" 16 #include "llvm/IR/GlobalAlias.h" 17 #include "llvm/IR/GlobalValue.h" 18 #include "llvm/IR/GlobalVariable.h" 19 #include "llvm/IR/LegacyPassManager.h" 20 #include "llvm/IR/Mangler.h" 21 #include "llvm/MC/MCAsmInfo.h" 22 #include "llvm/MC/MCContext.h" 23 #include "llvm/MC/MCInstrInfo.h" 24 #include "llvm/MC/MCRegisterInfo.h" 25 #include "llvm/MC/MCSectionMachO.h" 26 #include "llvm/MC/MCSubtargetInfo.h" 27 #include "llvm/MC/MCTargetOptions.h" 28 #include "llvm/MC/SectionKind.h" 29 #include "llvm/Target/TargetLoweringObjectFile.h" 30 using namespace llvm; 31 32 //--------------------------------------------------------------------------- 33 // TargetMachine Class 34 // 35 36 TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString, 37 const Triple &TT, StringRef CPU, StringRef FS, 38 const TargetOptions &Options) 39 : TheTarget(T), DL(DataLayoutString), TargetTriple(TT), 40 TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr), 41 MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false), 42 O0WantsFastISel(false), DefaultOptions(Options), Options(Options) {} 43 44 TargetMachine::~TargetMachine() = default; 45 46 bool TargetMachine::isPositionIndependent() const { 47 return getRelocationModel() == Reloc::PIC_; 48 } 49 50 /// Reset the target options based on the function's attributes. 51 /// setFunctionAttributes should have made the raw attribute value consistent 52 /// with the command line flag if used. 53 // 54 // FIXME: This function needs to go away for a number of reasons: 55 // a) global state on the TargetMachine is terrible in general, 56 // b) these target options should be passed only on the function 57 // and not on the TargetMachine (via TargetOptions) at all. 58 void TargetMachine::resetTargetOptions(const Function &F) const { 59 #define RESET_OPTION(X, Y) \ 60 do { \ 61 Options.X = F.getFnAttribute(Y).getValueAsBool(); \ 62 } while (0) 63 64 RESET_OPTION(UnsafeFPMath, "unsafe-fp-math"); 65 RESET_OPTION(NoInfsFPMath, "no-infs-fp-math"); 66 RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math"); 67 RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math"); 68 RESET_OPTION(ApproxFuncFPMath, "approx-func-fp-math"); 69 } 70 71 /// Returns the code generation relocation model. The choices are static, PIC, 72 /// and dynamic-no-pic. 73 Reloc::Model TargetMachine::getRelocationModel() const { return RM; } 74 75 /// Returns the code model. The choices are small, kernel, medium, large, and 76 /// target default. 77 CodeModel::Model TargetMachine::getCodeModel() const { return CMModel; } 78 79 /// Get the IR-specified TLS model for Var. 80 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) { 81 switch (GV->getThreadLocalMode()) { 82 case GlobalVariable::NotThreadLocal: 83 llvm_unreachable("getSelectedTLSModel for non-TLS variable"); 84 break; 85 case GlobalVariable::GeneralDynamicTLSModel: 86 return TLSModel::GeneralDynamic; 87 case GlobalVariable::LocalDynamicTLSModel: 88 return TLSModel::LocalDynamic; 89 case GlobalVariable::InitialExecTLSModel: 90 return TLSModel::InitialExec; 91 case GlobalVariable::LocalExecTLSModel: 92 return TLSModel::LocalExec; 93 } 94 llvm_unreachable("invalid TLS model"); 95 } 96 97 bool TargetMachine::shouldAssumeDSOLocal(const Module &M, 98 const GlobalValue *GV) const { 99 const Triple &TT = getTargetTriple(); 100 Reloc::Model RM = getRelocationModel(); 101 102 // According to the llvm language reference, we should be able to 103 // just return false in here if we have a GV, as we know it is 104 // dso_preemptable. At this point in time, the various IR producers 105 // have not been transitioned to always produce a dso_local when it 106 // is possible to do so. 107 // 108 // As a result we still have some logic in here to improve the quality of the 109 // generated code. 110 if (!GV) 111 return false; 112 113 // If the IR producer requested that this GV be treated as dso local, obey. 114 if (GV->isDSOLocal()) 115 return true; 116 117 if (TT.isOSBinFormatCOFF()) { 118 // DLLImport explicitly marks the GV as external. 119 if (GV->hasDLLImportStorageClass()) 120 return false; 121 122 // On MinGW, variables that haven't been declared with DLLImport may still 123 // end up automatically imported by the linker. To make this feasible, 124 // don't assume the variables to be DSO local unless we actually know 125 // that for sure. This only has to be done for variables; for functions 126 // the linker can insert thunks for calling functions from another DLL. 127 if (TT.isWindowsGNUEnvironment() && GV->isDeclarationForLinker() && 128 isa<GlobalVariable>(GV)) 129 return false; 130 131 // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain 132 // unresolved in the link, they can be resolved to zero, which is outside 133 // the current DSO. 134 if (GV->hasExternalWeakLinkage()) 135 return false; 136 137 // Every other GV is local on COFF. 138 return true; 139 } 140 141 if (TT.isOSBinFormatGOFF()) 142 return true; 143 144 if (TT.isOSBinFormatMachO()) { 145 if (RM == Reloc::Static) 146 return true; 147 return GV->isStrongDefinitionForLinker(); 148 } 149 150 assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() || 151 TT.isOSBinFormatXCOFF()); 152 return false; 153 } 154 155 bool TargetMachine::useEmulatedTLS() const { 156 // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls 157 // was specified explicitly; otherwise uses target triple to decide default. 158 if (Options.ExplicitEmulatedTLS) 159 return Options.EmulatedTLS; 160 return getTargetTriple().hasDefaultEmulatedTLS(); 161 } 162 163 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const { 164 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default; 165 Reloc::Model RM = getRelocationModel(); 166 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE; 167 bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV); 168 169 TLSModel::Model Model; 170 if (IsSharedLibrary) { 171 if (IsLocal) 172 Model = TLSModel::LocalDynamic; 173 else 174 Model = TLSModel::GeneralDynamic; 175 } else { 176 if (IsLocal) 177 Model = TLSModel::LocalExec; 178 else 179 Model = TLSModel::InitialExec; 180 } 181 182 // If the user specified a more specific model, use that. 183 TLSModel::Model SelectedModel = getSelectedTLSModel(GV); 184 if (SelectedModel > Model) 185 return SelectedModel; 186 187 return Model; 188 } 189 190 /// Returns the optimization level: None, Less, Default, or Aggressive. 191 CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; } 192 193 void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; } 194 195 TargetTransformInfo TargetMachine::getTargetTransformInfo(const Function &F) { 196 return TargetTransformInfo(F.getParent()->getDataLayout()); 197 } 198 199 void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name, 200 const GlobalValue *GV, Mangler &Mang, 201 bool MayAlwaysUsePrivate) const { 202 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) { 203 // Simple case: If GV is not private, it is not important to find out if 204 // private labels are legal in this case or not. 205 Mang.getNameWithPrefix(Name, GV, false); 206 return; 207 } 208 const TargetLoweringObjectFile *TLOF = getObjFileLowering(); 209 TLOF->getNameWithPrefix(Name, GV, *this); 210 } 211 212 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const { 213 const TargetLoweringObjectFile *TLOF = getObjFileLowering(); 214 // XCOFF symbols could have special naming convention. 215 if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this)) 216 return TargetSymbol; 217 218 SmallString<128> NameStr; 219 getNameWithPrefix(NameStr, GV, TLOF->getMangler()); 220 return TLOF->getContext().getOrCreateSymbol(NameStr); 221 } 222 223 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() { 224 // Since Analysis can't depend on Target, use a std::function to invert the 225 // dependency. 226 return TargetIRAnalysis( 227 [this](const Function &F) { return this->getTargetTransformInfo(F); }); 228 } 229 230 std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) { 231 if (Version == "none") 232 return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true. 233 std::pair<int, int> Ret; 234 if (!Version.consumeInteger(10, Ret.first) && Version.consume_front(".")) 235 Version.consumeInteger(10, Ret.second); 236 return Ret; 237 } 238