1 //===-- X86Subtarget.cpp - X86 Subtarget Information ----------------------===//
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 file implements the X86 specific subclass of TargetSubtargetInfo.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86.h"
15 
16 #include "X86CallLowering.h"
17 #include "X86LegalizerInfo.h"
18 #include "X86RegisterBankInfo.h"
19 #include "X86Subtarget.h"
20 #include "MCTargetDesc/X86BaseInfo.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
24 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
25 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
26 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/ConstantRange.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/CodeGen.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include <cassert>
39 #include <string>
40 
41 #if defined(_MSC_VER)
42 #include <intrin.h>
43 #endif
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "subtarget"
48 
49 #define GET_SUBTARGETINFO_TARGET_DESC
50 #define GET_SUBTARGETINFO_CTOR
51 #include "X86GenSubtargetInfo.inc"
52 
53 // Temporary option to control early if-conversion for x86 while adding machine
54 // models.
55 static cl::opt<bool>
56 X86EarlyIfConv("x86-early-ifcvt", cl::Hidden,
57                cl::desc("Enable early if-conversion on X86"));
58 
59 
60 /// Classify a blockaddress reference for the current subtarget according to how
61 /// we should reference it in a non-pcrel context.
62 unsigned char X86Subtarget::classifyBlockAddressReference() const {
63   return classifyLocalReference(nullptr);
64 }
65 
66 /// Classify a global variable reference for the current subtarget according to
67 /// how we should reference it in a non-pcrel context.
68 unsigned char
69 X86Subtarget::classifyGlobalReference(const GlobalValue *GV) const {
70   return classifyGlobalReference(GV, *GV->getParent());
71 }
72 
73 unsigned char
74 X86Subtarget::classifyLocalReference(const GlobalValue *GV) const {
75   // 64 bits can use %rip addressing for anything local.
76   if (is64Bit())
77     return X86II::MO_NO_FLAG;
78 
79   // If this is for a position dependent executable, the static linker can
80   // figure it out.
81   if (!isPositionIndependent())
82     return X86II::MO_NO_FLAG;
83 
84   // The COFF dynamic linker just patches the executable sections.
85   if (isTargetCOFF())
86     return X86II::MO_NO_FLAG;
87 
88   if (isTargetDarwin()) {
89     // 32 bit macho has no relocation for a-b if a is undefined, even if
90     // b is in the section that is being relocated.
91     // This means we have to use o load even for GVs that are known to be
92     // local to the dso.
93     if (GV && (GV->isDeclarationForLinker() || GV->hasCommonLinkage()))
94       return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
95 
96     return X86II::MO_PIC_BASE_OFFSET;
97   }
98 
99   return X86II::MO_GOTOFF;
100 }
101 
102 unsigned char X86Subtarget::classifyGlobalReference(const GlobalValue *GV,
103                                                     const Module &M) const {
104   // Large model never uses stubs.
105   if (TM.getCodeModel() == CodeModel::Large)
106     return X86II::MO_NO_FLAG;
107 
108   // Absolute symbols can be referenced directly.
109   if (GV) {
110     if (Optional<ConstantRange> CR = GV->getAbsoluteSymbolRange()) {
111       // See if we can use the 8-bit immediate form. Note that some instructions
112       // will sign extend the immediate operand, so to be conservative we only
113       // accept the range [0,128).
114       if (CR->getUnsignedMax().ult(128))
115         return X86II::MO_ABS8;
116       else
117         return X86II::MO_NO_FLAG;
118     }
119   }
120 
121   if (TM.shouldAssumeDSOLocal(M, GV))
122     return classifyLocalReference(GV);
123 
124   if (isTargetCOFF())
125     return X86II::MO_DLLIMPORT;
126 
127   if (is64Bit())
128     return X86II::MO_GOTPCREL;
129 
130   if (isTargetDarwin()) {
131     if (!isPositionIndependent())
132       return X86II::MO_DARWIN_NONLAZY;
133     return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
134   }
135 
136   return X86II::MO_GOT;
137 }
138 
139 unsigned char
140 X86Subtarget::classifyGlobalFunctionReference(const GlobalValue *GV) const {
141   return classifyGlobalFunctionReference(GV, *GV->getParent());
142 }
143 
144 unsigned char
145 X86Subtarget::classifyGlobalFunctionReference(const GlobalValue *GV,
146                                               const Module &M) const {
147   const Function *F = dyn_cast_or_null<Function>(GV);
148 
149   // Do not use the PLT when explicitly told to do so for ELF 64-bit
150   // target.
151   if (isTargetELF() && is64Bit() && F &&
152       F->hasFnAttribute(Attribute::NonLazyBind) &&
153       GV->isDeclarationForLinker())
154     return X86II::MO_GOTPCREL;
155 
156   if (TM.shouldAssumeDSOLocal(M, GV))
157     return X86II::MO_NO_FLAG;
158 
159   if (isTargetCOFF()) {
160     assert(GV->hasDLLImportStorageClass() &&
161            "shouldAssumeDSOLocal gave inconsistent answer");
162     return X86II::MO_DLLIMPORT;
163   }
164 
165   if (isTargetELF()) {
166     if (is64Bit() && F && (CallingConv::X86_RegCall == F->getCallingConv()))
167       // According to psABI, PLT stub clobbers XMM8-XMM15.
168       // In Regcall calling convention those registers are used for passing
169       // parameters. Thus we need to prevent lazy binding in Regcall.
170       return X86II::MO_GOTPCREL;
171     return X86II::MO_PLT;
172   }
173 
174   if (is64Bit()) {
175     if (F && F->hasFnAttribute(Attribute::NonLazyBind))
176       // If the function is marked as non-lazy, generate an indirect call
177       // which loads from the GOT directly. This avoids runtime overhead
178       // at the cost of eager binding (and one extra byte of encoding).
179       return X86II::MO_GOTPCREL;
180     return X86II::MO_NO_FLAG;
181   }
182 
183   return X86II::MO_NO_FLAG;
184 }
185 
186 /// This function returns the name of a function which has an interface like
187 /// the non-standard bzero function, if such a function exists on the
188 /// current subtarget and it is considered preferable over memset with zero
189 /// passed as the second argument. Otherwise it returns null.
190 const char *X86Subtarget::getBZeroEntry() const {
191   // Darwin 10 has a __bzero entry point for this purpose.
192   if (getTargetTriple().isMacOSX() &&
193       !getTargetTriple().isMacOSXVersionLT(10, 6))
194     return "__bzero";
195 
196   return nullptr;
197 }
198 
199 bool X86Subtarget::hasSinCos() const {
200   if (getTargetTriple().isMacOSX()) {
201     return !getTargetTriple().isMacOSXVersionLT(10, 9) && is64Bit();
202   } else if (getTargetTriple().isOSFuchsia()) {
203     return true;
204   }
205   return false;
206 }
207 
208 /// Return true if the subtarget allows calls to immediate address.
209 bool X86Subtarget::isLegalToCallImmediateAddr() const {
210   // FIXME: I386 PE/COFF supports PC relative calls using IMAGE_REL_I386_REL32
211   // but WinCOFFObjectWriter::RecordRelocation cannot emit them.  Once it does,
212   // the following check for Win32 should be removed.
213   if (In64BitMode || isTargetWin32())
214     return false;
215   return isTargetELF() || TM.getRelocationModel() == Reloc::Static;
216 }
217 
218 void X86Subtarget::initSubtargetFeatures(StringRef CPU, StringRef FS) {
219   std::string CPUName = CPU;
220   if (CPUName.empty())
221     CPUName = "generic";
222 
223   // Make sure 64-bit features are available in 64-bit mode. (But make sure
224   // SSE2 can be turned off explicitly.)
225   std::string FullFS = FS;
226   if (In64BitMode) {
227     if (!FullFS.empty())
228       FullFS = "+64bit,+sse2," + FullFS;
229     else
230       FullFS = "+64bit,+sse2";
231   }
232 
233   // LAHF/SAHF are always supported in non-64-bit mode.
234   if (!In64BitMode) {
235     if (!FullFS.empty())
236       FullFS = "+sahf," + FullFS;
237     else
238       FullFS = "+sahf";
239   }
240 
241   // Parse features string and set the CPU.
242   ParseSubtargetFeatures(CPUName, FullFS);
243 
244   // All CPUs that implement SSE4.2 or SSE4A support unaligned accesses of
245   // 16-bytes and under that are reasonably fast. These features were
246   // introduced with Intel's Nehalem/Silvermont and AMD's Family10h
247   // micro-architectures respectively.
248   if (hasSSE42() || hasSSE4A())
249     IsUAMem16Slow = false;
250 
251   InstrItins = getInstrItineraryForCPU(CPUName);
252 
253   // It's important to keep the MCSubtargetInfo feature bits in sync with
254   // target data structure which is shared with MC code emitter, etc.
255   if (In64BitMode)
256     ToggleFeature(X86::Mode64Bit);
257   else if (In32BitMode)
258     ToggleFeature(X86::Mode32Bit);
259   else if (In16BitMode)
260     ToggleFeature(X86::Mode16Bit);
261   else
262     llvm_unreachable("Not 16-bit, 32-bit or 64-bit mode!");
263 
264   DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel
265                << ", 3DNowLevel " << X863DNowLevel
266                << ", 64bit " << HasX86_64 << "\n");
267   assert((!In64BitMode || HasX86_64) &&
268          "64-bit code requested on a subtarget that doesn't support it!");
269 
270   // Stack alignment is 16 bytes on Darwin, Linux, kFreeBSD and Solaris (both
271   // 32 and 64 bit) and for all 64-bit targets.
272   if (StackAlignOverride)
273     stackAlignment = StackAlignOverride;
274   else if (isTargetDarwin() || isTargetLinux() || isTargetSolaris() ||
275            isTargetKFreeBSD() || In64BitMode)
276     stackAlignment = 16;
277 
278   // Gather is available since Haswell (AVX2 set). So technically, we can generate Gathers
279   // on all AVX2 processors. But the overhead on HSW is high. Skylake Client processor has
280   // faster Gathers than HSW and performance is similar to Skylake Server (AVX-512).
281   // The specified overhead is relative to the Load operation."2" is the number provided
282   // by Intel architects, This parameter is used for cost estimation of Gather Op and
283   // comparison with other alternatives.
284   if (X86ProcFamily == IntelSkylake || hasAVX512())
285     GatherOverhead = 2;
286   if (hasAVX512())
287     ScatterOverhead = 2;
288 }
289 
290 void X86Subtarget::initializeEnvironment() {
291   X86SSELevel = NoSSE;
292   X863DNowLevel = NoThreeDNow;
293   HasX87 = false;
294   HasCMov = false;
295   HasX86_64 = false;
296   HasPOPCNT = false;
297   HasSSE4A = false;
298   HasAES = false;
299   HasFXSR = false;
300   HasXSAVE = false;
301   HasXSAVEOPT = false;
302   HasXSAVEC = false;
303   HasXSAVES = false;
304   HasPCLMUL = false;
305   HasFMA = false;
306   HasFMA4 = false;
307   HasXOP = false;
308   HasTBM = false;
309   HasLWP = false;
310   HasMOVBE = false;
311   HasRDRAND = false;
312   HasF16C = false;
313   HasFSGSBase = false;
314   HasLZCNT = false;
315   HasBMI = false;
316   HasBMI2 = false;
317   HasVBMI = false;
318   HasIFMA = false;
319   HasRTM = false;
320   HasERI = false;
321   HasCDI = false;
322   HasPFI = false;
323   HasDQI = false;
324   HasVPOPCNTDQ = false;
325   HasBWI = false;
326   HasVLX = false;
327   HasADX = false;
328   HasPKU = false;
329   HasSHA = false;
330   HasPRFCHW = false;
331   HasRDSEED = false;
332   HasLAHFSAHF = false;
333   HasMWAITX = false;
334   HasCLZERO = false;
335   HasMPX = false;
336   HasSGX = false;
337   HasCLFLUSHOPT = false;
338   HasCLWB = false;
339   IsPMULLDSlow = false;
340   IsSHLDSlow = false;
341   IsUAMem16Slow = false;
342   IsUAMem32Slow = false;
343   HasSSEUnalignedMem = false;
344   HasCmpxchg16b = false;
345   UseLeaForSP = false;
346   HasFastPartialYMMorZMMWrite = false;
347   HasFastScalarFSQRT = false;
348   HasFastVectorFSQRT = false;
349   HasFastLZCNT = false;
350   HasFastSHLDRotate = false;
351   HasMacroFusion = false;
352   HasERMSB = false;
353   HasSlowDivide32 = false;
354   HasSlowDivide64 = false;
355   PadShortFunctions = false;
356   SlowTwoMemOps = false;
357   LEAUsesAG = false;
358   SlowLEA = false;
359   Slow3OpsLEA = false;
360   SlowIncDec = false;
361   stackAlignment = 4;
362   // FIXME: this is a known good value for Yonah. How about others?
363   MaxInlineSizeThreshold = 128;
364   UseSoftFloat = false;
365   X86ProcFamily = Others;
366   GatherOverhead = 1024;
367   ScatterOverhead = 1024;
368 }
369 
370 X86Subtarget &X86Subtarget::initializeSubtargetDependencies(StringRef CPU,
371                                                             StringRef FS) {
372   initializeEnvironment();
373   initSubtargetFeatures(CPU, FS);
374   return *this;
375 }
376 
377 X86Subtarget::X86Subtarget(const Triple &TT, StringRef CPU, StringRef FS,
378                            const X86TargetMachine &TM,
379                            unsigned StackAlignOverride)
380     : X86GenSubtargetInfo(TT, CPU, FS), X86ProcFamily(Others),
381       PICStyle(PICStyles::None), TM(TM), TargetTriple(TT),
382       StackAlignOverride(StackAlignOverride),
383       In64BitMode(TargetTriple.getArch() == Triple::x86_64),
384       In32BitMode(TargetTriple.getArch() == Triple::x86 &&
385                   TargetTriple.getEnvironment() != Triple::CODE16),
386       In16BitMode(TargetTriple.getArch() == Triple::x86 &&
387                   TargetTriple.getEnvironment() == Triple::CODE16),
388       InstrInfo(initializeSubtargetDependencies(CPU, FS)), TLInfo(TM, *this),
389       FrameLowering(*this, getStackAlignment()) {
390   // Determine the PICStyle based on the target selected.
391   if (!isPositionIndependent())
392     setPICStyle(PICStyles::None);
393   else if (is64Bit())
394     setPICStyle(PICStyles::RIPRel);
395   else if (isTargetCOFF())
396     setPICStyle(PICStyles::None);
397   else if (isTargetDarwin())
398     setPICStyle(PICStyles::StubPIC);
399   else if (isTargetELF())
400     setPICStyle(PICStyles::GOT);
401 
402   CallLoweringInfo.reset(new X86CallLowering(*getTargetLowering()));
403   Legalizer.reset(new X86LegalizerInfo(*this, TM));
404 
405   auto *RBI = new X86RegisterBankInfo(*getRegisterInfo());
406   RegBankInfo.reset(RBI);
407   InstSelector.reset(createX86InstructionSelector(TM, *this, *RBI));
408 }
409 
410 const CallLowering *X86Subtarget::getCallLowering() const {
411   return CallLoweringInfo.get();
412 }
413 
414 const InstructionSelector *X86Subtarget::getInstructionSelector() const {
415   return InstSelector.get();
416 }
417 
418 const LegalizerInfo *X86Subtarget::getLegalizerInfo() const {
419   return Legalizer.get();
420 }
421 
422 const RegisterBankInfo *X86Subtarget::getRegBankInfo() const {
423   return RegBankInfo.get();
424 }
425 
426 bool X86Subtarget::enableEarlyIfConversion() const {
427   return hasCMov() && X86EarlyIfConv;
428 }
429