0c6ff529653f2161bc29ad9b5f5d280c0398a36b
[oota-llvm.git] / lib / Target / ARM / ARMSubtarget.cpp
1 //===-- ARMSubtarget.cpp - ARM 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 ARM specific subclass of TargetSubtargetInfo.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMSubtarget.h"
15 #include "ARMFrameLowering.h"
16 #include "ARMISelLowering.h"
17 #include "ARMInstrInfo.h"
18 #include "ARMJITInfo.h"
19 #include "ARMSelectionDAGInfo.h"
20 #include "ARMSubtarget.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "Thumb1FrameLowering.h"
23 #include "Thumb1InstrInfo.h"
24 #include "Thumb2InstrInfo.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33
34 using namespace llvm;
35
36 #define DEBUG_TYPE "arm-subtarget"
37
38 #define GET_SUBTARGETINFO_TARGET_DESC
39 #define GET_SUBTARGETINFO_CTOR
40 #include "ARMGenSubtargetInfo.inc"
41
42 static cl::opt<bool>
43 ReserveR9("arm-reserve-r9", cl::Hidden,
44           cl::desc("Reserve R9, making it unavailable as GPR"));
45
46 static cl::opt<bool>
47 ArmUseMOVT("arm-use-movt", cl::init(true), cl::Hidden);
48
49 static cl::opt<bool>
50 UseFusedMulOps("arm-use-mulops",
51                cl::init(true), cl::Hidden);
52
53 enum AlignMode {
54   DefaultAlign,
55   StrictAlign,
56   NoStrictAlign
57 };
58
59 static cl::opt<AlignMode>
60 Align(cl::desc("Load/store alignment support"),
61       cl::Hidden, cl::init(DefaultAlign),
62       cl::values(
63           clEnumValN(DefaultAlign,  "arm-default-align",
64                      "Generate unaligned accesses only on hardware/OS "
65                      "combinations that are known to support them"),
66           clEnumValN(StrictAlign,   "arm-strict-align",
67                      "Disallow all unaligned memory accesses"),
68           clEnumValN(NoStrictAlign, "arm-no-strict-align",
69                      "Allow unaligned memory accesses"),
70           clEnumValEnd));
71
72 enum ITMode {
73   DefaultIT,
74   RestrictedIT,
75   NoRestrictedIT
76 };
77
78 static cl::opt<ITMode>
79 IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT),
80    cl::ZeroOrMore,
81    cl::values(clEnumValN(DefaultIT, "arm-default-it",
82                          "Generate IT block based on arch"),
83               clEnumValN(RestrictedIT, "arm-restrict-it",
84                          "Disallow deprecated IT based on ARMv8"),
85               clEnumValN(NoRestrictedIT, "arm-no-restrict-it",
86                          "Allow IT blocks based on ARMv7"),
87               clEnumValEnd));
88
89 static std::string computeDataLayout(ARMSubtarget &ST) {
90   std::string Ret = "";
91
92   if (ST.isLittle())
93     // Little endian.
94     Ret += "e";
95   else
96     // Big endian.
97     Ret += "E";
98
99   Ret += DataLayout::getManglingComponent(ST.getTargetTriple());
100
101   // Pointers are 32 bits and aligned to 32 bits.
102   Ret += "-p:32:32";
103
104   // On thumb, i16,i18 and i1 have natural aligment requirements, but we try to
105   // align to 32.
106   if (ST.isThumb())
107     Ret += "-i1:8:32-i8:8:32-i16:16:32";
108
109   // ABIs other than APCS have 64 bit integers with natural alignment.
110   if (!ST.isAPCS_ABI())
111     Ret += "-i64:64";
112
113   // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
114   // bits, others to 64 bits. We always try to align to 64 bits.
115   if (ST.isAPCS_ABI())
116     Ret += "-f64:32:64";
117
118   // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
119   // to 64. We always ty to give them natural alignment.
120   if (ST.isAPCS_ABI())
121     Ret += "-v64:32:64-v128:32:128";
122   else
123     Ret += "-v128:64:128";
124
125   // On thumb and APCS, only try to align aggregates to 32 bits (the default is
126   // 64 bits).
127   if (ST.isThumb() || ST.isAPCS_ABI())
128     Ret += "-a:0:32";
129
130   // Integer registers are 32 bits.
131   Ret += "-n32";
132
133   // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
134   // aligned everywhere else.
135   if (ST.isTargetNaCl())
136     Ret += "-S128";
137   else if (ST.isAAPCS_ABI())
138     Ret += "-S64";
139   else
140     Ret += "-S32";
141
142   return Ret;
143 }
144
145 /// initializeSubtargetDependencies - Initializes using a CPU and feature string
146 /// so that we can use initializer lists for subtarget initialization.
147 ARMSubtarget &ARMSubtarget::initializeSubtargetDependencies(StringRef CPU,
148                                                             StringRef FS) {
149   initializeEnvironment();
150   resetSubtargetFeatures(CPU, FS);
151   return *this;
152 }
153
154 ARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,
155                            const std::string &FS, TargetMachine &TM,
156                            bool IsLittle, const TargetOptions &Options)
157     : ARMGenSubtargetInfo(TT, CPU, FS), ARMProcFamily(Others),
158       ARMProcClass(None), stackAlignment(4), CPUString(CPU), IsLittle(IsLittle),
159       TargetTriple(TT), Options(Options), TargetABI(ARM_ABI_UNKNOWN),
160       DL(computeDataLayout(initializeSubtargetDependencies(CPU, FS))),
161       TSInfo(DL), JITInfo(),
162       InstrInfo(isThumb1Only()
163                     ? (ARMBaseInstrInfo *)new Thumb1InstrInfo(*this)
164                     : !isThumb()
165                           ? (ARMBaseInstrInfo *)new ARMInstrInfo(*this)
166                           : (ARMBaseInstrInfo *)new Thumb2InstrInfo(*this)),
167       TLInfo(TM),
168       FrameLowering(!isThumb1Only()
169                         ? new ARMFrameLowering(*this)
170                         : (ARMFrameLowering *)new Thumb1FrameLowering(*this)) {}
171
172 void ARMSubtarget::initializeEnvironment() {
173   HasV4TOps = false;
174   HasV5TOps = false;
175   HasV5TEOps = false;
176   HasV6Ops = false;
177   HasV6MOps = false;
178   HasV6T2Ops = false;
179   HasV7Ops = false;
180   HasV8Ops = false;
181   HasVFPv2 = false;
182   HasVFPv3 = false;
183   HasVFPv4 = false;
184   HasFPARMv8 = false;
185   HasNEON = false;
186   UseNEONForSinglePrecisionFP = false;
187   UseMulOps = UseFusedMulOps;
188   SlowFPVMLx = false;
189   HasVMLxForwarding = false;
190   SlowFPBrcc = false;
191   InThumbMode = false;
192   HasThumb2 = false;
193   NoARM = false;
194   PostRAScheduler = false;
195   IsR9Reserved = ReserveR9;
196   UseMovt = false;
197   SupportsTailCall = false;
198   HasFP16 = false;
199   HasD16 = false;
200   HasHardwareDivide = false;
201   HasHardwareDivideInARM = false;
202   HasT2ExtractPack = false;
203   HasDataBarrier = false;
204   Pref32BitThumb = false;
205   AvoidCPSRPartialUpdate = false;
206   AvoidMOVsShifterOperand = false;
207   HasRAS = false;
208   HasMPExtension = false;
209   HasVirtualization = false;
210   FPOnlySP = false;
211   HasPerfMon = false;
212   HasTrustZone = false;
213   HasCrypto = false;
214   HasCRC = false;
215   HasZeroCycleZeroing = false;
216   AllowsUnalignedMem = false;
217   Thumb2DSP = false;
218   UseNaClTrap = false;
219   UnsafeFPMath = false;
220 }
221
222 void ARMSubtarget::resetSubtargetFeatures(const MachineFunction *MF) {
223   AttributeSet FnAttrs = MF->getFunction()->getAttributes();
224   Attribute CPUAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex,
225                                            "target-cpu");
226   Attribute FSAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex,
227                                           "target-features");
228   std::string CPU =
229     !CPUAttr.hasAttribute(Attribute::None) ?CPUAttr.getValueAsString() : "";
230   std::string FS =
231     !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString() : "";
232   if (!FS.empty()) {
233     initializeEnvironment();
234     resetSubtargetFeatures(CPU, FS);
235   }
236 }
237
238 void ARMSubtarget::resetSubtargetFeatures(StringRef CPU, StringRef FS) {
239   if (CPUString.empty()) {
240     if (isTargetIOS() && TargetTriple.getArchName().endswith("v7s"))
241       // Default to the Swift CPU when targeting armv7s/thumbv7s.
242       CPUString = "swift";
243     else
244       CPUString = "generic";
245   }
246
247   // Insert the architecture feature derived from the target triple into the
248   // feature string. This is important for setting features that are implied
249   // based on the architecture version.
250   std::string ArchFS = ARM_MC::ParseARMTriple(TargetTriple.getTriple(),
251                                               CPUString);
252   if (!FS.empty()) {
253     if (!ArchFS.empty())
254       ArchFS = ArchFS + "," + FS.str();
255     else
256       ArchFS = FS;
257   }
258   ParseSubtargetFeatures(CPUString, ArchFS);
259
260   // FIXME: This used enable V6T2 support implicitly for Thumb2 mode.
261   // Assert this for now to make the change obvious.
262   assert(hasV6T2Ops() || !hasThumb2());
263
264   // Keep a pointer to static instruction cost data for the specified CPU.
265   SchedModel = getSchedModelForCPU(CPUString);
266
267   // Initialize scheduling itinerary for the specified CPU.
268   InstrItins = getInstrItineraryForCPU(CPUString);
269
270   if (TargetABI == ARM_ABI_UNKNOWN) {
271     switch (TargetTriple.getEnvironment()) {
272     case Triple::Android:
273     case Triple::EABI:
274     case Triple::EABIHF:
275     case Triple::GNUEABI:
276     case Triple::GNUEABIHF:
277       TargetABI = ARM_ABI_AAPCS;
278       break;
279     default:
280       if ((isTargetIOS() && isMClass()) ||
281           (TargetTriple.isOSBinFormatMachO() &&
282            TargetTriple.getOS() == Triple::UnknownOS))
283         TargetABI = ARM_ABI_AAPCS;
284       else
285         TargetABI = ARM_ABI_APCS;
286       break;
287     }
288   }
289
290   // FIXME: this is invalid for WindowsCE
291   if (isTargetWindows()) {
292     TargetABI = ARM_ABI_AAPCS;
293     NoARM = true;
294   }
295
296   if (isAAPCS_ABI())
297     stackAlignment = 8;
298   if (isTargetNaCl())
299     stackAlignment = 16;
300
301   UseMovt = hasV6T2Ops() && ArmUseMOVT;
302
303   if (isTargetMachO()) {
304     IsR9Reserved = ReserveR9 | !HasV6Ops;
305     SupportsTailCall = !isTargetIOS() || !getTargetTriple().isOSVersionLT(5, 0);
306   } else {
307     IsR9Reserved = ReserveR9;
308     SupportsTailCall = !isThumb1Only();
309   }
310
311   if (!isThumb() || hasThumb2())
312     PostRAScheduler = true;
313
314   switch (Align) {
315     case DefaultAlign:
316       // Assume pre-ARMv6 doesn't support unaligned accesses.
317       //
318       // ARMv6 may or may not support unaligned accesses depending on the
319       // SCTLR.U bit, which is architecture-specific. We assume ARMv6
320       // Darwin and NetBSD targets support unaligned accesses, and others don't.
321       //
322       // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
323       // which raises an alignment fault on unaligned accesses. Linux
324       // defaults this bit to 0 and handles it as a system-wide (not
325       // per-process) setting. It is therefore safe to assume that ARMv7+
326       // Linux targets support unaligned accesses. The same goes for NaCl.
327       //
328       // The above behavior is consistent with GCC.
329       AllowsUnalignedMem =
330           (hasV7Ops() && (isTargetLinux() || isTargetNaCl() ||
331                           isTargetNetBSD())) ||
332           (hasV6Ops() && (isTargetMachO() || isTargetNetBSD()));
333       // The one exception is cortex-m0, which despite being v6, does not
334       // support unaligned accesses. Rather than make the above boolean
335       // expression even more obtuse, just override the value here.
336       if (isThumb1Only() && isMClass())
337         AllowsUnalignedMem = false;
338       break;
339     case StrictAlign:
340       AllowsUnalignedMem = false;
341       break;
342     case NoStrictAlign:
343       AllowsUnalignedMem = true;
344       break;
345   }
346
347   switch (IT) {
348   case DefaultIT:
349     RestrictIT = hasV8Ops() ? true : false;
350     break;
351   case RestrictedIT:
352     RestrictIT = true;
353     break;
354   case NoRestrictedIT:
355     RestrictIT = false;
356     break;
357   }
358
359   // NEON f32 ops are non-IEEE 754 compliant. Darwin is ok with it by default.
360   uint64_t Bits = getFeatureBits();
361   if ((Bits & ARM::ProcA5 || Bits & ARM::ProcA8) && // Where this matters
362       (Options.UnsafeFPMath || isTargetDarwin()))
363     UseNEONForSinglePrecisionFP = true;
364 }
365
366 /// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.
367 bool
368 ARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,
369                                  Reloc::Model RelocM) const {
370   if (RelocM == Reloc::Static)
371     return false;
372
373   // Materializable GVs (in JIT lazy compilation mode) do not require an extra
374   // load from stub.
375   bool isDecl = GV->hasAvailableExternallyLinkage();
376   if (GV->isDeclaration() && !GV->isMaterializable())
377     isDecl = true;
378
379   if (!isTargetMachO()) {
380     // Extra load is needed for all externally visible.
381     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
382       return false;
383     return true;
384   } else {
385     if (RelocM == Reloc::PIC_) {
386       // If this is a strong reference to a definition, it is definitely not
387       // through a stub.
388       if (!isDecl && !GV->isWeakForLinker())
389         return false;
390
391       // Unless we have a symbol with hidden visibility, we have to go through a
392       // normal $non_lazy_ptr stub because this symbol might be resolved late.
393       if (!GV->hasHiddenVisibility())  // Non-hidden $non_lazy_ptr reference.
394         return true;
395
396       // If symbol visibility is hidden, we have a stub for common symbol
397       // references and external declarations.
398       if (isDecl || GV->hasCommonLinkage())
399         // Hidden $non_lazy_ptr reference.
400         return true;
401
402       return false;
403     } else {
404       // If this is a strong reference to a definition, it is definitely not
405       // through a stub.
406       if (!isDecl && !GV->isWeakForLinker())
407         return false;
408
409       // Unless we have a symbol with hidden visibility, we have to go through a
410       // normal $non_lazy_ptr stub because this symbol might be resolved late.
411       if (!GV->hasHiddenVisibility())  // Non-hidden $non_lazy_ptr reference.
412         return true;
413     }
414   }
415
416   return false;
417 }
418
419 unsigned ARMSubtarget::getMispredictionPenalty() const {
420   return SchedModel->MispredictPenalty;
421 }
422
423 bool ARMSubtarget::hasSinCos() const {
424   return getTargetTriple().getOS() == Triple::IOS &&
425     !getTargetTriple().isOSVersionLT(7, 0);
426 }
427
428 // Enable the PostMachineScheduler if the target selects it instead of
429 // PostRAScheduler. Currently only available on the command line via
430 // -misched-postra.
431 bool ARMSubtarget::enablePostMachineScheduler() const {
432   return PostRAScheduler;
433 }
434
435 bool ARMSubtarget::enableAtomicExpandLoadLinked() const {
436   return hasAnyDataBarrier() && !isThumb1Only();
437 }
438
439 bool ARMSubtarget::enablePostRAScheduler(
440            CodeGenOpt::Level OptLevel,
441            TargetSubtargetInfo::AntiDepBreakMode& Mode,
442            RegClassVector& CriticalPathRCs) const {
443   Mode = TargetSubtargetInfo::ANTIDEP_NONE;
444   return PostRAScheduler && OptLevel >= CodeGenOpt::Default;
445 }
446
447 bool ARMSubtarget::useMovt(const MachineFunction &MF) const {
448   // NOTE Windows on ARM needs to use mov.w/mov.t pairs to materialise 32-bit
449   // immediates as it is inherently position independent, and may be out of
450   // range otherwise.
451   return UseMovt && (isTargetWindows() ||
452                      !MF.getFunction()->getAttributes().hasAttribute(
453                          AttributeSet::FunctionIndex, Attribute::MinSize));
454 }
455
456 bool ARMSubtarget::shouldCoalesce(MachineInstr *MI,
457                                   const TargetRegisterClass *SrcRC,
458                                   unsigned SubReg,
459                                   const TargetRegisterClass *DstRC,
460                                   unsigned DstSubReg,
461                                   const TargetRegisterClass *NewRC) const {
462   auto MBB = MI->getParent();
463   auto MF = MBB->getParent();
464   const MachineRegisterInfo &MRI = MF->getRegInfo();
465   // If not copying into a sub-register this should be ok because we shouldn't
466   // need to split the reg.
467   if (!DstSubReg)
468     return true;
469   // Small registers don't frequently cause a problem, so we can coalesce them.
470   if (NewRC->getSize() < 32 && DstRC->getSize() < 32 && SrcRC->getSize() < 32)
471     return true;
472
473   auto NewRCWeight =
474               MRI.getTargetRegisterInfo()->getRegClassWeight(NewRC);
475   auto SrcRCWeight =
476               MRI.getTargetRegisterInfo()->getRegClassWeight(SrcRC);
477   auto DstRCWeight =
478               MRI.getTargetRegisterInfo()->getRegClassWeight(DstRC);
479   // If the source register class is more expensive than the destination, the
480   // coalescing is probably profitable.
481   if (SrcRCWeight.RegWeight > NewRCWeight.RegWeight)
482     return true;
483   if (DstRCWeight.RegWeight > NewRCWeight.RegWeight)
484     return true;
485
486   // If the register allocator isn't constrained, we can always allow coalescing
487   // unfortunately we don't know yet if we will be constrained.
488   // The goal of this heuristic is to restrict how many expensive registers
489   // we allow to coalesce in a given basic block.
490   auto AFI = MF->getInfo<ARMFunctionInfo>();
491   auto It = AFI->getCoalescedWeight(MBB);
492
493   DEBUG(dbgs() << "\tARM::shouldCoalesce - Coalesced Weight: " << It->second << "\n");
494   DEBUG(dbgs() << "\tARM::shouldCoalesce - Reg Weight: " << NewRCWeight.RegWeight << "\n");
495   unsigned SizeMultiplier = MBB->size()/100;
496   SizeMultiplier = SizeMultiplier ? SizeMultiplier : 1;
497   if (It->second < NewRCWeight.WeightLimit * SizeMultiplier) {
498     It->second += NewRCWeight.RegWeight;
499     return true;
500   }
501   return false;
502 }