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