1 //===-- ARMBaseInstrInfo.h - ARM Base Instruction Information ---*- C++ -*-===//
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 contains the Base ARM implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_TARGET_ARM_ARMBASEINSTRINFO_H
14 #define LLVM_LIB_TARGET_ARM_ARMBASEINSTRINFO_H
15 
16 #include "MCTargetDesc/ARMBaseInfo.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineOperand.h"
23 #include "llvm/CodeGen/TargetInstrInfo.h"
24 #include <array>
25 #include <cstdint>
26 
27 #define GET_INSTRINFO_HEADER
28 #include "ARMGenInstrInfo.inc"
29 
30 namespace llvm {
31 
32 class ARMBaseRegisterInfo;
33 class ARMSubtarget;
34 
35 class ARMBaseInstrInfo : public ARMGenInstrInfo {
36   const ARMSubtarget &Subtarget;
37 
38 protected:
39   // Can be only subclassed.
40   explicit ARMBaseInstrInfo(const ARMSubtarget &STI);
41 
42   void expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
43                                 unsigned LoadImmOpc, unsigned LoadOpc) const;
44 
45   /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
46   /// and \p DefIdx.
47   /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
48   /// the list is modeled as <Reg:SubReg, SubIdx>.
49   /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
50   /// two elements:
51   /// - %1:sub1, sub0
52   /// - %2<:0>, sub1
53   ///
54   /// \returns true if it is possible to build such an input sequence
55   /// with the pair \p MI, \p DefIdx. False otherwise.
56   ///
57   /// \pre MI.isRegSequenceLike().
58   bool getRegSequenceLikeInputs(
59       const MachineInstr &MI, unsigned DefIdx,
60       SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const override;
61 
62   /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
63   /// and \p DefIdx.
64   /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
65   /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
66   /// - %1:sub1, sub0
67   ///
68   /// \returns true if it is possible to build such an input sequence
69   /// with the pair \p MI, \p DefIdx. False otherwise.
70   ///
71   /// \pre MI.isExtractSubregLike().
72   bool getExtractSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
73                                   RegSubRegPairAndIdx &InputReg) const override;
74 
75   /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
76   /// and \p DefIdx.
77   /// \p [out] BaseReg and \p [out] InsertedReg contain
78   /// the equivalent inputs of INSERT_SUBREG.
79   /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
80   /// - BaseReg: %0:sub0
81   /// - InsertedReg: %1:sub1, sub3
82   ///
83   /// \returns true if it is possible to build such an input sequence
84   /// with the pair \p MI, \p DefIdx. False otherwise.
85   ///
86   /// \pre MI.isInsertSubregLike().
87   bool
88   getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
89                             RegSubRegPair &BaseReg,
90                             RegSubRegPairAndIdx &InsertedReg) const override;
91 
92   /// Commutes the operands in the given instruction.
93   /// The commutable operands are specified by their indices OpIdx1 and OpIdx2.
94   ///
95   /// Do not call this method for a non-commutable instruction or for
96   /// non-commutable pair of operand indices OpIdx1 and OpIdx2.
97   /// Even though the instruction is commutable, the method may still
98   /// fail to commute the operands, null pointer is returned in such cases.
99   MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
100                                        unsigned OpIdx1,
101                                        unsigned OpIdx2) const override;
102   /// If the specific machine instruction is an instruction that moves/copies
103   /// value from one register to another register return destination and source
104   /// registers as machine operands.
105   Optional<DestSourcePair>
106   isCopyInstrImpl(const MachineInstr &MI) const override;
107 
108   /// Specialization of \ref TargetInstrInfo::describeLoadedValue, used to
109   /// enhance debug entry value descriptions for ARM targets.
110   Optional<ParamLoadedValue> describeLoadedValue(const MachineInstr &MI,
111                                                  Register Reg) const override;
112 
113 public:
114   // Return whether the target has an explicit NOP encoding.
115   bool hasNOP() const;
116 
117   // Return the non-pre/post incrementing version of 'Opc'. Return 0
118   // if there is not such an opcode.
119   virtual unsigned getUnindexedOpcode(unsigned Opc) const = 0;
120 
121   MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
122                                       MachineInstr &MI,
123                                       LiveVariables *LV) const override;
124 
125   virtual const ARMBaseRegisterInfo &getRegisterInfo() const = 0;
126   const ARMSubtarget &getSubtarget() const { return Subtarget; }
127 
128   ScheduleHazardRecognizer *
129   CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
130                                const ScheduleDAG *DAG) const override;
131 
132   ScheduleHazardRecognizer *
133   CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
134                                      const ScheduleDAG *DAG) const override;
135 
136   // Branch analysis.
137   bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
138                      MachineBasicBlock *&FBB,
139                      SmallVectorImpl<MachineOperand> &Cond,
140                      bool AllowModify = false) const override;
141   unsigned removeBranch(MachineBasicBlock &MBB,
142                         int *BytesRemoved = nullptr) const override;
143   unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
144                         MachineBasicBlock *FBB, ArrayRef<MachineOperand> Cond,
145                         const DebugLoc &DL,
146                         int *BytesAdded = nullptr) const override;
147 
148   bool
149   reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const override;
150 
151   // Predication support.
152   bool isPredicated(const MachineInstr &MI) const override;
153 
154   // MIR printer helper function to annotate Operands with a comment.
155   std::string
156   createMIROperandComment(const MachineInstr &MI, const MachineOperand &Op,
157                           unsigned OpIdx,
158                           const TargetRegisterInfo *TRI) const override;
159 
160   ARMCC::CondCodes getPredicate(const MachineInstr &MI) const {
161     int PIdx = MI.findFirstPredOperandIdx();
162     return PIdx != -1 ? (ARMCC::CondCodes)MI.getOperand(PIdx).getImm()
163                       : ARMCC::AL;
164   }
165 
166   bool PredicateInstruction(MachineInstr &MI,
167                             ArrayRef<MachineOperand> Pred) const override;
168 
169   bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
170                          ArrayRef<MachineOperand> Pred2) const override;
171 
172   bool DefinesPredicate(MachineInstr &MI,
173                         std::vector<MachineOperand> &Pred) const override;
174 
175   bool isPredicable(const MachineInstr &MI) const override;
176 
177   // CPSR defined in instruction
178   static bool isCPSRDefined(const MachineInstr &MI);
179   bool isAddrMode3OpImm(const MachineInstr &MI, unsigned Op) const;
180   bool isAddrMode3OpMinusReg(const MachineInstr &MI, unsigned Op) const;
181 
182   // Load, scaled register offset
183   bool isLdstScaledReg(const MachineInstr &MI, unsigned Op) const;
184   // Load, scaled register offset, not plus LSL2
185   bool isLdstScaledRegNotPlusLsl2(const MachineInstr &MI, unsigned Op) const;
186   // Minus reg for ldstso addr mode
187   bool isLdstSoMinusReg(const MachineInstr &MI, unsigned Op) const;
188   // Scaled register offset in address mode 2
189   bool isAm2ScaledReg(const MachineInstr &MI, unsigned Op) const;
190   // Load multiple, base reg in list
191   bool isLDMBaseRegInList(const MachineInstr &MI) const;
192   // get LDM variable defs size
193   unsigned getLDMVariableDefsSize(const MachineInstr &MI) const;
194 
195   /// GetInstSize - Returns the size of the specified MachineInstr.
196   ///
197   unsigned getInstSizeInBytes(const MachineInstr &MI) const override;
198 
199   unsigned isLoadFromStackSlot(const MachineInstr &MI,
200                                int &FrameIndex) const override;
201   unsigned isStoreToStackSlot(const MachineInstr &MI,
202                               int &FrameIndex) const override;
203   unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
204                                      int &FrameIndex) const override;
205   unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
206                                     int &FrameIndex) const override;
207 
208   void copyToCPSR(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
209                   unsigned SrcReg, bool KillSrc,
210                   const ARMSubtarget &Subtarget) const;
211   void copyFromCPSR(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
212                     unsigned DestReg, bool KillSrc,
213                     const ARMSubtarget &Subtarget) const;
214 
215   void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
216                    const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg,
217                    bool KillSrc) const override;
218 
219   void storeRegToStackSlot(MachineBasicBlock &MBB,
220                            MachineBasicBlock::iterator MBBI,
221                            Register SrcReg, bool isKill, int FrameIndex,
222                            const TargetRegisterClass *RC,
223                            const TargetRegisterInfo *TRI) const override;
224 
225   void loadRegFromStackSlot(MachineBasicBlock &MBB,
226                             MachineBasicBlock::iterator MBBI,
227                             Register DestReg, int FrameIndex,
228                             const TargetRegisterClass *RC,
229                             const TargetRegisterInfo *TRI) const override;
230 
231   bool expandPostRAPseudo(MachineInstr &MI) const override;
232 
233   bool shouldSink(const MachineInstr &MI) const override;
234 
235   void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
236                      Register DestReg, unsigned SubIdx,
237                      const MachineInstr &Orig,
238                      const TargetRegisterInfo &TRI) const override;
239 
240   MachineInstr &
241   duplicate(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
242             const MachineInstr &Orig) const override;
243 
244   const MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
245                                      unsigned SubIdx, unsigned State,
246                                      const TargetRegisterInfo *TRI) const;
247 
248   bool produceSameValue(const MachineInstr &MI0, const MachineInstr &MI1,
249                         const MachineRegisterInfo *MRI) const override;
250 
251   /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
252   /// determine if two loads are loading from the same base address. It should
253   /// only return true if the base pointers are the same and the only
254   /// differences between the two addresses is the offset. It also returns the
255   /// offsets by reference.
256   bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, int64_t &Offset1,
257                                int64_t &Offset2) const override;
258 
259   /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
260   /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads
261   /// should be scheduled togther. On some targets if two loads are loading from
262   /// addresses in the same cache line, it's better if they are scheduled
263   /// together. This function takes two integers that represent the load offsets
264   /// from the common base address. It returns true if it decides it's desirable
265   /// to schedule the two loads together. "NumLoads" is the number of loads that
266   /// have already been scheduled after Load1.
267   bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
268                                int64_t Offset1, int64_t Offset2,
269                                unsigned NumLoads) const override;
270 
271   bool isSchedulingBoundary(const MachineInstr &MI,
272                             const MachineBasicBlock *MBB,
273                             const MachineFunction &MF) const override;
274 
275   bool isProfitableToIfCvt(MachineBasicBlock &MBB,
276                            unsigned NumCycles, unsigned ExtraPredCycles,
277                            BranchProbability Probability) const override;
278 
279   bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumT,
280                            unsigned ExtraT, MachineBasicBlock &FMBB,
281                            unsigned NumF, unsigned ExtraF,
282                            BranchProbability Probability) const override;
283 
284   bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
285                                  BranchProbability Probability) const override {
286     return NumCycles == 1;
287   }
288 
289   unsigned extraSizeToPredicateInstructions(const MachineFunction &MF,
290                                             unsigned NumInsts) const override;
291   unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const override;
292 
293   bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
294                                  MachineBasicBlock &FMBB) const override;
295 
296   /// analyzeCompare - For a comparison instruction, return the source registers
297   /// in SrcReg and SrcReg2 if having two register operands, and the value it
298   /// compares against in CmpValue. Return true if the comparison instruction
299   /// can be analyzed.
300   bool analyzeCompare(const MachineInstr &MI, Register &SrcReg,
301                       Register &SrcReg2, int &CmpMask,
302                       int &CmpValue) const override;
303 
304   /// optimizeCompareInstr - Convert the instruction to set the zero flag so
305   /// that we can remove a "comparison with zero"; Remove a redundant CMP
306   /// instruction if the flags can be updated in the same way by an earlier
307   /// instruction such as SUB.
308   bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
309                             Register SrcReg2, int CmpMask, int CmpValue,
310                             const MachineRegisterInfo *MRI) const override;
311 
312   bool analyzeSelect(const MachineInstr &MI,
313                      SmallVectorImpl<MachineOperand> &Cond, unsigned &TrueOp,
314                      unsigned &FalseOp, bool &Optimizable) const override;
315 
316   MachineInstr *optimizeSelect(MachineInstr &MI,
317                                SmallPtrSetImpl<MachineInstr *> &SeenMIs,
318                                bool) const override;
319 
320   /// FoldImmediate - 'Reg' is known to be defined by a move immediate
321   /// instruction, try to fold the immediate into the use instruction.
322   bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, Register Reg,
323                      MachineRegisterInfo *MRI) const override;
324 
325   unsigned getNumMicroOps(const InstrItineraryData *ItinData,
326                           const MachineInstr &MI) const override;
327 
328   int getOperandLatency(const InstrItineraryData *ItinData,
329                         const MachineInstr &DefMI, unsigned DefIdx,
330                         const MachineInstr &UseMI,
331                         unsigned UseIdx) const override;
332   int getOperandLatency(const InstrItineraryData *ItinData,
333                         SDNode *DefNode, unsigned DefIdx,
334                         SDNode *UseNode, unsigned UseIdx) const override;
335 
336   /// VFP/NEON execution domains.
337   std::pair<uint16_t, uint16_t>
338   getExecutionDomain(const MachineInstr &MI) const override;
339   void setExecutionDomain(MachineInstr &MI, unsigned Domain) const override;
340 
341   unsigned
342   getPartialRegUpdateClearance(const MachineInstr &, unsigned,
343                                const TargetRegisterInfo *) const override;
344   void breakPartialRegDependency(MachineInstr &, unsigned,
345                                  const TargetRegisterInfo *TRI) const override;
346 
347   /// Get the number of addresses by LDM or VLDM or zero for unknown.
348   unsigned getNumLDMAddresses(const MachineInstr &MI) const;
349 
350   std::pair<unsigned, unsigned>
351   decomposeMachineOperandsTargetFlags(unsigned TF) const override;
352   ArrayRef<std::pair<unsigned, const char *>>
353   getSerializableDirectMachineOperandTargetFlags() const override;
354   ArrayRef<std::pair<unsigned, const char *>>
355   getSerializableBitmaskMachineOperandTargetFlags() const override;
356 
357 private:
358   unsigned getInstBundleLength(const MachineInstr &MI) const;
359 
360   int getVLDMDefCycle(const InstrItineraryData *ItinData,
361                       const MCInstrDesc &DefMCID,
362                       unsigned DefClass,
363                       unsigned DefIdx, unsigned DefAlign) const;
364   int getLDMDefCycle(const InstrItineraryData *ItinData,
365                      const MCInstrDesc &DefMCID,
366                      unsigned DefClass,
367                      unsigned DefIdx, unsigned DefAlign) const;
368   int getVSTMUseCycle(const InstrItineraryData *ItinData,
369                       const MCInstrDesc &UseMCID,
370                       unsigned UseClass,
371                       unsigned UseIdx, unsigned UseAlign) const;
372   int getSTMUseCycle(const InstrItineraryData *ItinData,
373                      const MCInstrDesc &UseMCID,
374                      unsigned UseClass,
375                      unsigned UseIdx, unsigned UseAlign) const;
376   int getOperandLatency(const InstrItineraryData *ItinData,
377                         const MCInstrDesc &DefMCID,
378                         unsigned DefIdx, unsigned DefAlign,
379                         const MCInstrDesc &UseMCID,
380                         unsigned UseIdx, unsigned UseAlign) const;
381 
382   int getOperandLatencyImpl(const InstrItineraryData *ItinData,
383                             const MachineInstr &DefMI, unsigned DefIdx,
384                             const MCInstrDesc &DefMCID, unsigned DefAdj,
385                             const MachineOperand &DefMO, unsigned Reg,
386                             const MachineInstr &UseMI, unsigned UseIdx,
387                             const MCInstrDesc &UseMCID, unsigned UseAdj) const;
388 
389   unsigned getPredicationCost(const MachineInstr &MI) const override;
390 
391   unsigned getInstrLatency(const InstrItineraryData *ItinData,
392                            const MachineInstr &MI,
393                            unsigned *PredCost = nullptr) const override;
394 
395   int getInstrLatency(const InstrItineraryData *ItinData,
396                       SDNode *Node) const override;
397 
398   bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
399                              const MachineRegisterInfo *MRI,
400                              const MachineInstr &DefMI, unsigned DefIdx,
401                              const MachineInstr &UseMI,
402                              unsigned UseIdx) const override;
403   bool hasLowDefLatency(const TargetSchedModel &SchedModel,
404                         const MachineInstr &DefMI,
405                         unsigned DefIdx) const override;
406 
407   /// verifyInstruction - Perform target specific instruction verification.
408   bool verifyInstruction(const MachineInstr &MI,
409                          StringRef &ErrInfo) const override;
410 
411   virtual void expandLoadStackGuard(MachineBasicBlock::iterator MI) const = 0;
412 
413   void expandMEMCPY(MachineBasicBlock::iterator) const;
414 
415   /// Identify instructions that can be folded into a MOVCC instruction, and
416   /// return the defining instruction.
417   MachineInstr *canFoldIntoMOVCC(Register Reg, const MachineRegisterInfo &MRI,
418                                  const TargetInstrInfo *TII) const;
419 
420 private:
421   /// Modeling special VFP / NEON fp MLA / MLS hazards.
422 
423   /// MLxEntryMap - Map fp MLA / MLS to the corresponding entry in the internal
424   /// MLx table.
425   DenseMap<unsigned, unsigned> MLxEntryMap;
426 
427   /// MLxHazardOpcodes - Set of add / sub and multiply opcodes that would cause
428   /// stalls when scheduled together with fp MLA / MLS opcodes.
429   SmallSet<unsigned, 16> MLxHazardOpcodes;
430 
431 public:
432   /// isFpMLxInstruction - Return true if the specified opcode is a fp MLA / MLS
433   /// instruction.
434   bool isFpMLxInstruction(unsigned Opcode) const {
435     return MLxEntryMap.count(Opcode);
436   }
437 
438   /// isFpMLxInstruction - This version also returns the multiply opcode and the
439   /// addition / subtraction opcode to expand to. Return true for 'HasLane' for
440   /// the MLX instructions with an extra lane operand.
441   bool isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
442                           unsigned &AddSubOpc, bool &NegAcc,
443                           bool &HasLane) const;
444 
445   /// canCauseFpMLxStall - Return true if an instruction of the specified opcode
446   /// will cause stalls when scheduled after (within 4-cycle window) a fp
447   /// MLA / MLS instruction.
448   bool canCauseFpMLxStall(unsigned Opcode) const {
449     return MLxHazardOpcodes.count(Opcode);
450   }
451 
452   /// Returns true if the instruction has a shift by immediate that can be
453   /// executed in one cycle less.
454   bool isSwiftFastImmShift(const MachineInstr *MI) const;
455 
456   /// Returns predicate register associated with the given frame instruction.
457   unsigned getFramePred(const MachineInstr &MI) const {
458     assert(isFrameInstr(MI));
459     // Operands of ADJCALLSTACKDOWN/ADJCALLSTACKUP:
460     // - argument declared in the pattern:
461     // 0 - frame size
462     // 1 - arg of CALLSEQ_START/CALLSEQ_END
463     // 2 - predicate code (like ARMCC::AL)
464     // - added by predOps:
465     // 3 - predicate reg
466     return MI.getOperand(3).getReg();
467   }
468 
469   Optional<RegImmPair> isAddImmediate(const MachineInstr &MI,
470                                       Register Reg) const override;
471 };
472 
473 /// Get the operands corresponding to the given \p Pred value. By default, the
474 /// predicate register is assumed to be 0 (no register), but you can pass in a
475 /// \p PredReg if that is not the case.
476 static inline std::array<MachineOperand, 2> predOps(ARMCC::CondCodes Pred,
477                                                     unsigned PredReg = 0) {
478   return {{MachineOperand::CreateImm(static_cast<int64_t>(Pred)),
479            MachineOperand::CreateReg(PredReg, false)}};
480 }
481 
482 /// Get the operand corresponding to the conditional code result. By default,
483 /// this is 0 (no register).
484 static inline MachineOperand condCodeOp(unsigned CCReg = 0) {
485   return MachineOperand::CreateReg(CCReg, false);
486 }
487 
488 /// Get the operand corresponding to the conditional code result for Thumb1.
489 /// This operand will always refer to CPSR and it will have the Define flag set.
490 /// You can optionally set the Dead flag by means of \p isDead.
491 static inline MachineOperand t1CondCodeOp(bool isDead = false) {
492   return MachineOperand::CreateReg(ARM::CPSR,
493                                    /*Define*/ true, /*Implicit*/ false,
494                                    /*Kill*/ false, isDead);
495 }
496 
497 static inline
498 bool isUncondBranchOpcode(int Opc) {
499   return Opc == ARM::B || Opc == ARM::tB || Opc == ARM::t2B;
500 }
501 
502 // This table shows the VPT instruction variants, i.e. the different
503 // mask field encodings, see also B5.6. Predication/conditional execution in
504 // the ArmARM.
505 
506 
507 inline static ARM::PredBlockMask getARMVPTBlockMask(unsigned NumInsts) {
508   switch (NumInsts) {
509   case 1:
510     return ARM::PredBlockMask::T;
511   case 2:
512     return ARM::PredBlockMask::TT;
513   case 3:
514     return ARM::PredBlockMask::TTT;
515   case 4:
516     return ARM::PredBlockMask::TTTT;
517   default:
518     break;
519   };
520   llvm_unreachable("Unexpected number of instruction in a VPT block");
521 }
522 
523 
524 static inline bool isVPTOpcode(int Opc) {
525   return Opc == ARM::MVE_VPTv16i8 || Opc == ARM::MVE_VPTv16u8 ||
526          Opc == ARM::MVE_VPTv16s8 || Opc == ARM::MVE_VPTv8i16 ||
527          Opc == ARM::MVE_VPTv8u16 || Opc == ARM::MVE_VPTv8s16 ||
528          Opc == ARM::MVE_VPTv4i32 || Opc == ARM::MVE_VPTv4u32 ||
529          Opc == ARM::MVE_VPTv4s32 || Opc == ARM::MVE_VPTv4f32 ||
530          Opc == ARM::MVE_VPTv8f16 || Opc == ARM::MVE_VPTv16i8r ||
531          Opc == ARM::MVE_VPTv16u8r || Opc == ARM::MVE_VPTv16s8r ||
532          Opc == ARM::MVE_VPTv8i16r || Opc == ARM::MVE_VPTv8u16r ||
533          Opc == ARM::MVE_VPTv8s16r || Opc == ARM::MVE_VPTv4i32r ||
534          Opc == ARM::MVE_VPTv4u32r || Opc == ARM::MVE_VPTv4s32r ||
535          Opc == ARM::MVE_VPTv4f32r || Opc == ARM::MVE_VPTv8f16r ||
536          Opc == ARM::MVE_VPST;
537 }
538 
539 static inline
540 unsigned VCMPOpcodeToVPT(unsigned Opcode) {
541   switch (Opcode) {
542   default:
543     return 0;
544   case ARM::MVE_VCMPf32:
545     return ARM::MVE_VPTv4f32;
546   case ARM::MVE_VCMPf16:
547     return ARM::MVE_VPTv8f16;
548   case ARM::MVE_VCMPi8:
549     return ARM::MVE_VPTv16i8;
550   case ARM::MVE_VCMPi16:
551     return ARM::MVE_VPTv8i16;
552   case ARM::MVE_VCMPi32:
553     return ARM::MVE_VPTv4i32;
554   case ARM::MVE_VCMPu8:
555     return ARM::MVE_VPTv16u8;
556   case ARM::MVE_VCMPu16:
557     return ARM::MVE_VPTv8u16;
558   case ARM::MVE_VCMPu32:
559     return ARM::MVE_VPTv4u32;
560   case ARM::MVE_VCMPs8:
561     return ARM::MVE_VPTv16s8;
562   case ARM::MVE_VCMPs16:
563     return ARM::MVE_VPTv8s16;
564   case ARM::MVE_VCMPs32:
565     return ARM::MVE_VPTv4s32;
566 
567   case ARM::MVE_VCMPf32r:
568     return ARM::MVE_VPTv4f32r;
569   case ARM::MVE_VCMPf16r:
570     return ARM::MVE_VPTv8f16r;
571   case ARM::MVE_VCMPi8r:
572     return ARM::MVE_VPTv16i8r;
573   case ARM::MVE_VCMPi16r:
574     return ARM::MVE_VPTv8i16r;
575   case ARM::MVE_VCMPi32r:
576     return ARM::MVE_VPTv4i32r;
577   case ARM::MVE_VCMPu8r:
578     return ARM::MVE_VPTv16u8r;
579   case ARM::MVE_VCMPu16r:
580     return ARM::MVE_VPTv8u16r;
581   case ARM::MVE_VCMPu32r:
582     return ARM::MVE_VPTv4u32r;
583   case ARM::MVE_VCMPs8r:
584     return ARM::MVE_VPTv16s8r;
585   case ARM::MVE_VCMPs16r:
586     return ARM::MVE_VPTv8s16r;
587   case ARM::MVE_VCMPs32r:
588     return ARM::MVE_VPTv4s32r;
589   }
590 }
591 
592 static inline
593 unsigned VCTPOpcodeToLSTP(unsigned Opcode, bool IsDoLoop) {
594   switch (Opcode) {
595   default:
596     llvm_unreachable("unhandled vctp opcode");
597     break;
598   case ARM::MVE_VCTP8:
599     return IsDoLoop ? ARM::MVE_DLSTP_8 : ARM::MVE_WLSTP_8;
600   case ARM::MVE_VCTP16:
601     return IsDoLoop ? ARM::MVE_DLSTP_16 : ARM::MVE_WLSTP_16;
602   case ARM::MVE_VCTP32:
603     return IsDoLoop ? ARM::MVE_DLSTP_32 : ARM::MVE_WLSTP_32;
604   case ARM::MVE_VCTP64:
605     return IsDoLoop ? ARM::MVE_DLSTP_64 : ARM::MVE_WLSTP_64;
606   }
607   return 0;
608 }
609 
610 static inline unsigned getTailPredVectorWidth(unsigned Opcode) {
611   switch (Opcode) {
612   default:
613     llvm_unreachable("unhandled vctp opcode");
614   case ARM::MVE_VCTP8:  return 16;
615   case ARM::MVE_VCTP16: return 8;
616   case ARM::MVE_VCTP32: return 4;
617   case ARM::MVE_VCTP64: return 2;
618   }
619   return 0;
620 }
621 
622 static inline
623 bool isVCTP(MachineInstr *MI) {
624   switch (MI->getOpcode()) {
625   default:
626     break;
627   case ARM::MVE_VCTP8:
628   case ARM::MVE_VCTP16:
629   case ARM::MVE_VCTP32:
630   case ARM::MVE_VCTP64:
631     return true;
632   }
633   return false;
634 }
635 
636 static inline
637 bool isLoopStart(MachineInstr &MI) {
638   return MI.getOpcode() == ARM::t2DoLoopStart ||
639          MI.getOpcode() == ARM::t2WhileLoopStart;
640 }
641 
642 static inline
643 bool isCondBranchOpcode(int Opc) {
644   return Opc == ARM::Bcc || Opc == ARM::tBcc || Opc == ARM::t2Bcc;
645 }
646 
647 static inline bool isJumpTableBranchOpcode(int Opc) {
648   return Opc == ARM::BR_JTr || Opc == ARM::BR_JTm_i12 ||
649          Opc == ARM::BR_JTm_rs || Opc == ARM::BR_JTadd || Opc == ARM::tBR_JTr ||
650          Opc == ARM::t2BR_JT;
651 }
652 
653 static inline
654 bool isIndirectBranchOpcode(int Opc) {
655   return Opc == ARM::BX || Opc == ARM::MOVPCRX || Opc == ARM::tBRIND;
656 }
657 
658 static inline bool isPopOpcode(int Opc) {
659   return Opc == ARM::tPOP_RET || Opc == ARM::LDMIA_RET ||
660          Opc == ARM::t2LDMIA_RET || Opc == ARM::tPOP || Opc == ARM::LDMIA_UPD ||
661          Opc == ARM::t2LDMIA_UPD || Opc == ARM::VLDMDIA_UPD;
662 }
663 
664 static inline bool isPushOpcode(int Opc) {
665   return Opc == ARM::tPUSH || Opc == ARM::t2STMDB_UPD ||
666          Opc == ARM::STMDB_UPD || Opc == ARM::VSTMDDB_UPD;
667 }
668 
669 static inline bool isSubImmOpcode(int Opc) {
670   return Opc == ARM::SUBri ||
671          Opc == ARM::tSUBi3 || Opc == ARM::tSUBi8 ||
672          Opc == ARM::tSUBSi3 || Opc == ARM::tSUBSi8 ||
673          Opc == ARM::t2SUBri || Opc == ARM::t2SUBri12 || Opc == ARM::t2SUBSri;
674 }
675 
676 static inline bool isMovRegOpcode(int Opc) {
677   return Opc == ARM::MOVr || Opc == ARM::tMOVr || Opc == ARM::t2MOVr;
678 }
679 
680 /// isValidCoprocessorNumber - decide whether an explicit coprocessor
681 /// number is legal in generic instructions like CDP. The answer can
682 /// vary with the subtarget.
683 static inline bool isValidCoprocessorNumber(unsigned Num,
684                                             const FeatureBitset& featureBits) {
685   // Armv8-A disallows everything *other* than 111x (CP14 and CP15).
686   if (featureBits[ARM::HasV8Ops] && (Num & 0xE) != 0xE)
687     return false;
688 
689   // Armv7 disallows 101x (CP10 and CP11), which clash with VFP/NEON.
690   if (featureBits[ARM::HasV7Ops] && (Num & 0xE) == 0xA)
691     return false;
692 
693   // Armv8.1-M also disallows 100x (CP8,CP9) and 111x (CP14,CP15)
694   // which clash with MVE.
695   if (featureBits[ARM::HasV8_1MMainlineOps] &&
696       ((Num & 0xE) == 0x8 || (Num & 0xE) == 0xE))
697     return false;
698 
699   return true;
700 }
701 
702 /// getInstrPredicate - If instruction is predicated, returns its predicate
703 /// condition, otherwise returns AL. It also returns the condition code
704 /// register by reference.
705 ARMCC::CondCodes getInstrPredicate(const MachineInstr &MI, Register &PredReg);
706 
707 unsigned getMatchingCondBranchOpcode(unsigned Opc);
708 
709 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether
710 /// the instruction is encoded with an 'S' bit is determined by the optional
711 /// CPSR def operand.
712 unsigned convertAddSubFlagsOpcode(unsigned OldOpc);
713 
714 /// emitARMRegPlusImmediate / emitT2RegPlusImmediate - Emits a series of
715 /// instructions to materializea destreg = basereg + immediate in ARM / Thumb2
716 /// code.
717 void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
718                              MachineBasicBlock::iterator &MBBI,
719                              const DebugLoc &dl, Register DestReg,
720                              Register BaseReg, int NumBytes,
721                              ARMCC::CondCodes Pred, Register PredReg,
722                              const ARMBaseInstrInfo &TII, unsigned MIFlags = 0);
723 
724 void emitT2RegPlusImmediate(MachineBasicBlock &MBB,
725                             MachineBasicBlock::iterator &MBBI,
726                             const DebugLoc &dl, Register DestReg,
727                             Register BaseReg, int NumBytes,
728                             ARMCC::CondCodes Pred, Register PredReg,
729                             const ARMBaseInstrInfo &TII, unsigned MIFlags = 0);
730 void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
731                                MachineBasicBlock::iterator &MBBI,
732                                const DebugLoc &dl, Register DestReg,
733                                Register BaseReg, int NumBytes,
734                                const TargetInstrInfo &TII,
735                                const ARMBaseRegisterInfo &MRI,
736                                unsigned MIFlags = 0);
737 
738 /// Tries to add registers to the reglist of a given base-updating
739 /// push/pop instruction to adjust the stack by an additional
740 /// NumBytes. This can save a few bytes per function in code-size, but
741 /// obviously generates more memory traffic. As such, it only takes
742 /// effect in functions being optimised for size.
743 bool tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
744                                 MachineFunction &MF, MachineInstr *MI,
745                                 unsigned NumBytes);
746 
747 /// rewriteARMFrameIndex / rewriteT2FrameIndex -
748 /// Rewrite MI to access 'Offset' bytes from the FP. Return false if the
749 /// offset could not be handled directly in MI, and return the left-over
750 /// portion by reference.
751 bool rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
752                           Register FrameReg, int &Offset,
753                           const ARMBaseInstrInfo &TII);
754 
755 bool rewriteT2FrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
756                          Register FrameReg, int &Offset,
757                          const ARMBaseInstrInfo &TII,
758                          const TargetRegisterInfo *TRI);
759 
760 /// Return true if Reg is defd between From and To
761 bool registerDefinedBetween(unsigned Reg, MachineBasicBlock::iterator From,
762                             MachineBasicBlock::iterator To,
763                             const TargetRegisterInfo *TRI);
764 
765 /// Search backwards from a tBcc to find a tCMPi8 against 0, meaning
766 /// we can convert them to a tCBZ or tCBNZ. Return nullptr if not found.
767 MachineInstr *findCMPToFoldIntoCBZ(MachineInstr *Br,
768                                    const TargetRegisterInfo *TRI);
769 
770 void addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB);
771 void addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB, Register DestReg);
772 
773 void addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond);
774 void addPredicatedMveVpredROp(MachineInstrBuilder &MIB, unsigned Cond,
775                               unsigned Inactive);
776 
777 /// Returns the number of instructions required to materialize the given
778 /// constant in a register, or 3 if a literal pool load is needed.
779 /// If ForCodesize is specified, an approximate cost in bytes is returned.
780 unsigned ConstantMaterializationCost(unsigned Val,
781                                      const ARMSubtarget *Subtarget,
782                                      bool ForCodesize = false);
783 
784 /// Returns true if Val1 has a lower Constant Materialization Cost than Val2.
785 /// Uses the cost from ConstantMaterializationCost, first with ForCodesize as
786 /// specified. If the scores are equal, return the comparison for !ForCodesize.
787 bool HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2,
788                                          const ARMSubtarget *Subtarget,
789                                          bool ForCodesize = false);
790 
791 // Return the immediate if this is ADDri or SUBri, scaled as appropriate.
792 // Returns 0 for unknown instructions.
793 inline int getAddSubImmediate(MachineInstr &MI) {
794   int Scale = 1;
795   unsigned ImmOp;
796   switch (MI.getOpcode()) {
797   case ARM::t2ADDri:
798     ImmOp = 2;
799     break;
800   case ARM::t2SUBri:
801   case ARM::t2SUBri12:
802     ImmOp = 2;
803     Scale = -1;
804     break;
805   case ARM::tSUBi3:
806   case ARM::tSUBi8:
807     ImmOp = 3;
808     Scale = -1;
809     break;
810   default:
811     return 0;
812   }
813   return Scale * MI.getOperand(ImmOp).getImm();
814 }
815 
816 // Given a memory access Opcode, check that the give Imm would be a valid Offset
817 // for this instruction using its addressing mode.
818 inline bool isLegalAddressImm(unsigned Opcode, int Imm,
819                               const TargetInstrInfo *TII) {
820   const MCInstrDesc &Desc = TII->get(Opcode);
821   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
822   switch (AddrMode) {
823   case ARMII::AddrModeT2_i7:
824     return std::abs(Imm) < (((1 << 7) * 1) - 1);
825   case ARMII::AddrModeT2_i7s2:
826     return std::abs(Imm) < (((1 << 7) * 2) - 1) && Imm % 2 == 0;
827   case ARMII::AddrModeT2_i7s4:
828     return std::abs(Imm) < (((1 << 7) * 4) - 1) && Imm % 4 == 0;
829   default:
830     llvm_unreachable("Unhandled Addressing mode");
831   }
832 }
833 
834 } // end namespace llvm
835 
836 #endif // LLVM_LIB_TARGET_ARM_ARMBASEINSTRINFO_H
837