SystemZISelDAGToDAG.cpp revision 276479
1251607Sdim//===-- SystemZISelDAGToDAG.cpp - A dag to dag inst selector for SystemZ --===//
2251607Sdim//
3251607Sdim//                     The LLVM Compiler Infrastructure
4251607Sdim//
5251607Sdim// This file is distributed under the University of Illinois Open Source
6251607Sdim// License. See LICENSE.TXT for details.
7251607Sdim//
8251607Sdim//===----------------------------------------------------------------------===//
9251607Sdim//
10251607Sdim// This file defines an instruction selector for the SystemZ target.
11251607Sdim//
12251607Sdim//===----------------------------------------------------------------------===//
13251607Sdim
14251607Sdim#include "SystemZTargetMachine.h"
15261991Sdim#include "llvm/Analysis/AliasAnalysis.h"
16251607Sdim#include "llvm/CodeGen/SelectionDAGISel.h"
17251607Sdim#include "llvm/Support/Debug.h"
18251607Sdim#include "llvm/Support/raw_ostream.h"
19251607Sdim
20251607Sdimusing namespace llvm;
21251607Sdim
22276479Sdim#define DEBUG_TYPE "systemz-isel"
23276479Sdim
24251607Sdimnamespace {
25251607Sdim// Used to build addressing modes.
26251607Sdimstruct SystemZAddressingMode {
27251607Sdim  // The shape of the address.
28251607Sdim  enum AddrForm {
29251607Sdim    // base+displacement
30251607Sdim    FormBD,
31251607Sdim
32251607Sdim    // base+displacement+index for load and store operands
33251607Sdim    FormBDXNormal,
34251607Sdim
35251607Sdim    // base+displacement+index for load address operands
36251607Sdim    FormBDXLA,
37251607Sdim
38251607Sdim    // base+displacement+index+ADJDYNALLOC
39251607Sdim    FormBDXDynAlloc
40251607Sdim  };
41251607Sdim  AddrForm Form;
42251607Sdim
43251607Sdim  // The type of displacement.  The enum names here correspond directly
44251607Sdim  // to the definitions in SystemZOperand.td.  We could split them into
45251607Sdim  // flags -- single/pair, 128-bit, etc. -- but it hardly seems worth it.
46251607Sdim  enum DispRange {
47251607Sdim    Disp12Only,
48251607Sdim    Disp12Pair,
49251607Sdim    Disp20Only,
50251607Sdim    Disp20Only128,
51251607Sdim    Disp20Pair
52251607Sdim  };
53251607Sdim  DispRange DR;
54251607Sdim
55251607Sdim  // The parts of the address.  The address is equivalent to:
56251607Sdim  //
57251607Sdim  //     Base + Disp + Index + (IncludesDynAlloc ? ADJDYNALLOC : 0)
58251607Sdim  SDValue Base;
59251607Sdim  int64_t Disp;
60251607Sdim  SDValue Index;
61251607Sdim  bool IncludesDynAlloc;
62251607Sdim
63251607Sdim  SystemZAddressingMode(AddrForm form, DispRange dr)
64251607Sdim    : Form(form), DR(dr), Base(), Disp(0), Index(),
65251607Sdim      IncludesDynAlloc(false) {}
66251607Sdim
67251607Sdim  // True if the address can have an index register.
68251607Sdim  bool hasIndexField() { return Form != FormBD; }
69251607Sdim
70251607Sdim  // True if the address can (and must) include ADJDYNALLOC.
71251607Sdim  bool isDynAlloc() { return Form == FormBDXDynAlloc; }
72251607Sdim
73251607Sdim  void dump() {
74251607Sdim    errs() << "SystemZAddressingMode " << this << '\n';
75251607Sdim
76251607Sdim    errs() << " Base ";
77276479Sdim    if (Base.getNode())
78251607Sdim      Base.getNode()->dump();
79251607Sdim    else
80251607Sdim      errs() << "null\n";
81251607Sdim
82251607Sdim    if (hasIndexField()) {
83251607Sdim      errs() << " Index ";
84276479Sdim      if (Index.getNode())
85251607Sdim        Index.getNode()->dump();
86251607Sdim      else
87251607Sdim        errs() << "null\n";
88251607Sdim    }
89251607Sdim
90251607Sdim    errs() << " Disp " << Disp;
91251607Sdim    if (IncludesDynAlloc)
92251607Sdim      errs() << " + ADJDYNALLOC";
93251607Sdim    errs() << '\n';
94251607Sdim  }
95251607Sdim};
96251607Sdim
97261991Sdim// Return a mask with Count low bits set.
98261991Sdimstatic uint64_t allOnes(unsigned int Count) {
99261991Sdim  return Count == 0 ? 0 : (uint64_t(1) << (Count - 1) << 1) - 1;
100261991Sdim}
101261991Sdim
102261991Sdim// Represents operands 2 to 5 of the ROTATE AND ... SELECTED BITS operation
103261991Sdim// given by Opcode.  The operands are: Input (R2), Start (I3), End (I4) and
104261991Sdim// Rotate (I5).  The combined operand value is effectively:
105261991Sdim//
106261991Sdim//   (or (rotl Input, Rotate), ~Mask)
107261991Sdim//
108261991Sdim// for RNSBG and:
109261991Sdim//
110261991Sdim//   (and (rotl Input, Rotate), Mask)
111261991Sdim//
112261991Sdim// otherwise.  The output value has BitSize bits, although Input may be
113261991Sdim// narrower (in which case the upper bits are don't care).
114261991Sdimstruct RxSBGOperands {
115261991Sdim  RxSBGOperands(unsigned Op, SDValue N)
116261991Sdim    : Opcode(Op), BitSize(N.getValueType().getSizeInBits()),
117261991Sdim      Mask(allOnes(BitSize)), Input(N), Start(64 - BitSize), End(63),
118261991Sdim      Rotate(0) {}
119261991Sdim
120261991Sdim  unsigned Opcode;
121261991Sdim  unsigned BitSize;
122261991Sdim  uint64_t Mask;
123261991Sdim  SDValue Input;
124261991Sdim  unsigned Start;
125261991Sdim  unsigned End;
126261991Sdim  unsigned Rotate;
127261991Sdim};
128261991Sdim
129251607Sdimclass SystemZDAGToDAGISel : public SelectionDAGISel {
130251607Sdim  const SystemZTargetLowering &Lowering;
131251607Sdim  const SystemZSubtarget &Subtarget;
132251607Sdim
133251607Sdim  // Used by SystemZOperands.td to create integer constants.
134261991Sdim  inline SDValue getImm(const SDNode *Node, uint64_t Imm) const {
135251607Sdim    return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
136251607Sdim  }
137251607Sdim
138261991Sdim  const SystemZTargetMachine &getTargetMachine() const {
139261991Sdim    return static_cast<const SystemZTargetMachine &>(TM);
140261991Sdim  }
141261991Sdim
142261991Sdim  const SystemZInstrInfo *getInstrInfo() const {
143261991Sdim    return getTargetMachine().getInstrInfo();
144261991Sdim  }
145261991Sdim
146251607Sdim  // Try to fold more of the base or index of AM into AM, where IsBase
147251607Sdim  // selects between the base and index.
148261991Sdim  bool expandAddress(SystemZAddressingMode &AM, bool IsBase) const;
149251607Sdim
150251607Sdim  // Try to describe N in AM, returning true on success.
151261991Sdim  bool selectAddress(SDValue N, SystemZAddressingMode &AM) const;
152251607Sdim
153251607Sdim  // Extract individual target operands from matched address AM.
154251607Sdim  void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
155261991Sdim                          SDValue &Base, SDValue &Disp) const;
156251607Sdim  void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
157261991Sdim                          SDValue &Base, SDValue &Disp, SDValue &Index) const;
158251607Sdim
159251607Sdim  // Try to match Addr as a FormBD address with displacement type DR.
160251607Sdim  // Return true on success, storing the base and displacement in
161251607Sdim  // Base and Disp respectively.
162251607Sdim  bool selectBDAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
163261991Sdim                    SDValue &Base, SDValue &Disp) const;
164251607Sdim
165261991Sdim  // Try to match Addr as a FormBDX address with displacement type DR.
166261991Sdim  // Return true on success and if the result had no index.  Store the
167261991Sdim  // base and displacement in Base and Disp respectively.
168261991Sdim  bool selectMVIAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
169261991Sdim                     SDValue &Base, SDValue &Disp) const;
170261991Sdim
171251607Sdim  // Try to match Addr as a FormBDX* address of form Form with
172251607Sdim  // displacement type DR.  Return true on success, storing the base,
173251607Sdim  // displacement and index in Base, Disp and Index respectively.
174251607Sdim  bool selectBDXAddr(SystemZAddressingMode::AddrForm Form,
175251607Sdim                     SystemZAddressingMode::DispRange DR, SDValue Addr,
176261991Sdim                     SDValue &Base, SDValue &Disp, SDValue &Index) const;
177251607Sdim
178251607Sdim  // PC-relative address matching routines used by SystemZOperands.td.
179261991Sdim  bool selectPCRelAddress(SDValue Addr, SDValue &Target) const {
180261991Sdim    if (SystemZISD::isPCREL(Addr.getOpcode())) {
181251607Sdim      Target = Addr.getOperand(0);
182251607Sdim      return true;
183251607Sdim    }
184251607Sdim    return false;
185251607Sdim  }
186251607Sdim
187251607Sdim  // BD matching routines used by SystemZOperands.td.
188261991Sdim  bool selectBDAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp) const {
189251607Sdim    return selectBDAddr(SystemZAddressingMode::Disp12Only, Addr, Base, Disp);
190251607Sdim  }
191261991Sdim  bool selectBDAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
192251607Sdim    return selectBDAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
193251607Sdim  }
194261991Sdim  bool selectBDAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp) const {
195251607Sdim    return selectBDAddr(SystemZAddressingMode::Disp20Only, Addr, Base, Disp);
196251607Sdim  }
197261991Sdim  bool selectBDAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
198251607Sdim    return selectBDAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
199251607Sdim  }
200251607Sdim
201261991Sdim  // MVI matching routines used by SystemZOperands.td.
202261991Sdim  bool selectMVIAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
203261991Sdim    return selectMVIAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
204261991Sdim  }
205261991Sdim  bool selectMVIAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
206261991Sdim    return selectMVIAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
207261991Sdim  }
208261991Sdim
209251607Sdim  // BDX matching routines used by SystemZOperands.td.
210251607Sdim  bool selectBDXAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
211261991Sdim                           SDValue &Index) const {
212251607Sdim    return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
213251607Sdim                         SystemZAddressingMode::Disp12Only,
214251607Sdim                         Addr, Base, Disp, Index);
215251607Sdim  }
216251607Sdim  bool selectBDXAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
217261991Sdim                           SDValue &Index) const {
218251607Sdim    return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
219251607Sdim                         SystemZAddressingMode::Disp12Pair,
220251607Sdim                         Addr, Base, Disp, Index);
221251607Sdim  }
222251607Sdim  bool selectDynAlloc12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
223261991Sdim                            SDValue &Index) const {
224251607Sdim    return selectBDXAddr(SystemZAddressingMode::FormBDXDynAlloc,
225251607Sdim                         SystemZAddressingMode::Disp12Only,
226251607Sdim                         Addr, Base, Disp, Index);
227251607Sdim  }
228251607Sdim  bool selectBDXAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp,
229261991Sdim                           SDValue &Index) const {
230251607Sdim    return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
231251607Sdim                         SystemZAddressingMode::Disp20Only,
232251607Sdim                         Addr, Base, Disp, Index);
233251607Sdim  }
234251607Sdim  bool selectBDXAddr20Only128(SDValue Addr, SDValue &Base, SDValue &Disp,
235261991Sdim                              SDValue &Index) const {
236251607Sdim    return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
237251607Sdim                         SystemZAddressingMode::Disp20Only128,
238251607Sdim                         Addr, Base, Disp, Index);
239251607Sdim  }
240251607Sdim  bool selectBDXAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
241261991Sdim                           SDValue &Index) const {
242251607Sdim    return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
243251607Sdim                         SystemZAddressingMode::Disp20Pair,
244251607Sdim                         Addr, Base, Disp, Index);
245251607Sdim  }
246251607Sdim  bool selectLAAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
247261991Sdim                          SDValue &Index) const {
248251607Sdim    return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
249251607Sdim                         SystemZAddressingMode::Disp12Pair,
250251607Sdim                         Addr, Base, Disp, Index);
251251607Sdim  }
252251607Sdim  bool selectLAAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
253261991Sdim                          SDValue &Index) const {
254251607Sdim    return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
255251607Sdim                         SystemZAddressingMode::Disp20Pair,
256251607Sdim                         Addr, Base, Disp, Index);
257251607Sdim  }
258251607Sdim
259261991Sdim  // Check whether (or Op (and X InsertMask)) is effectively an insertion
260261991Sdim  // of X into bits InsertMask of some Y != Op.  Return true if so and
261261991Sdim  // set Op to that Y.
262261991Sdim  bool detectOrAndInsertion(SDValue &Op, uint64_t InsertMask) const;
263261991Sdim
264261991Sdim  // Try to update RxSBG so that only the bits of RxSBG.Input in Mask are used.
265261991Sdim  // Return true on success.
266261991Sdim  bool refineRxSBGMask(RxSBGOperands &RxSBG, uint64_t Mask) const;
267261991Sdim
268261991Sdim  // Try to fold some of RxSBG.Input into other fields of RxSBG.
269261991Sdim  // Return true on success.
270261991Sdim  bool expandRxSBG(RxSBGOperands &RxSBG) const;
271261991Sdim
272261991Sdim  // Return an undefined value of type VT.
273261991Sdim  SDValue getUNDEF(SDLoc DL, EVT VT) const;
274261991Sdim
275261991Sdim  // Convert N to VT, if it isn't already.
276261991Sdim  SDValue convertTo(SDLoc DL, EVT VT, SDValue N) const;
277261991Sdim
278261991Sdim  // Try to implement AND or shift node N using RISBG with the zero flag set.
279261991Sdim  // Return the selected node on success, otherwise return null.
280261991Sdim  SDNode *tryRISBGZero(SDNode *N);
281261991Sdim
282261991Sdim  // Try to use RISBG or Opcode to implement OR or XOR node N.
283261991Sdim  // Return the selected node on success, otherwise return null.
284261991Sdim  SDNode *tryRxSBG(SDNode *N, unsigned Opcode);
285261991Sdim
286251607Sdim  // If Op0 is null, then Node is a constant that can be loaded using:
287251607Sdim  //
288251607Sdim  //   (Opcode UpperVal LowerVal)
289251607Sdim  //
290251607Sdim  // If Op0 is nonnull, then Node can be implemented using:
291251607Sdim  //
292251607Sdim  //   (Opcode (Opcode Op0 UpperVal) LowerVal)
293251607Sdim  SDNode *splitLargeImmediate(unsigned Opcode, SDNode *Node, SDValue Op0,
294251607Sdim                              uint64_t UpperVal, uint64_t LowerVal);
295251607Sdim
296261991Sdim  // Return true if Load and Store are loads and stores of the same size
297261991Sdim  // and are guaranteed not to overlap.  Such operations can be implemented
298261991Sdim  // using block (SS-format) instructions.
299261991Sdim  //
300261991Sdim  // Partial overlap would lead to incorrect code, since the block operations
301261991Sdim  // are logically bytewise, even though they have a fast path for the
302261991Sdim  // non-overlapping case.  We also need to avoid full overlap (i.e. two
303261991Sdim  // addresses that might be equal at run time) because although that case
304261991Sdim  // would be handled correctly, it might be implemented by millicode.
305261991Sdim  bool canUseBlockOperation(StoreSDNode *Store, LoadSDNode *Load) const;
306261991Sdim
307261991Sdim  // N is a (store (load Y), X) pattern.  Return true if it can use an MVC
308261991Sdim  // from Y to X.
309261991Sdim  bool storeLoadCanUseMVC(SDNode *N) const;
310261991Sdim
311261991Sdim  // N is a (store (op (load A[0]), (load A[1])), X) pattern.  Return true
312261991Sdim  // if A[1 - I] == X and if N can use a block operation like NC from A[I]
313261991Sdim  // to X.
314261991Sdim  bool storeLoadCanUseBlockBinary(SDNode *N, unsigned I) const;
315261991Sdim
316251607Sdimpublic:
317251607Sdim  SystemZDAGToDAGISel(SystemZTargetMachine &TM, CodeGenOpt::Level OptLevel)
318251607Sdim    : SelectionDAGISel(TM, OptLevel),
319251607Sdim      Lowering(*TM.getTargetLowering()),
320251607Sdim      Subtarget(*TM.getSubtargetImpl()) { }
321251607Sdim
322251607Sdim  // Override MachineFunctionPass.
323276479Sdim  const char *getPassName() const override {
324251607Sdim    return "SystemZ DAG->DAG Pattern Instruction Selection";
325251607Sdim  }
326251607Sdim
327251607Sdim  // Override SelectionDAGISel.
328276479Sdim  SDNode *Select(SDNode *Node) override;
329276479Sdim  bool SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
330276479Sdim                                    std::vector<SDValue> &OutOps) override;
331251607Sdim
332251607Sdim  // Include the pieces autogenerated from the target description.
333251607Sdim  #include "SystemZGenDAGISel.inc"
334251607Sdim};
335251607Sdim} // end anonymous namespace
336251607Sdim
337251607SdimFunctionPass *llvm::createSystemZISelDag(SystemZTargetMachine &TM,
338251607Sdim                                         CodeGenOpt::Level OptLevel) {
339251607Sdim  return new SystemZDAGToDAGISel(TM, OptLevel);
340251607Sdim}
341251607Sdim
342251607Sdim// Return true if Val should be selected as a displacement for an address
343251607Sdim// with range DR.  Here we're interested in the range of both the instruction
344251607Sdim// described by DR and of any pairing instruction.
345251607Sdimstatic bool selectDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
346251607Sdim  switch (DR) {
347251607Sdim  case SystemZAddressingMode::Disp12Only:
348251607Sdim    return isUInt<12>(Val);
349251607Sdim
350251607Sdim  case SystemZAddressingMode::Disp12Pair:
351251607Sdim  case SystemZAddressingMode::Disp20Only:
352251607Sdim  case SystemZAddressingMode::Disp20Pair:
353251607Sdim    return isInt<20>(Val);
354251607Sdim
355251607Sdim  case SystemZAddressingMode::Disp20Only128:
356251607Sdim    return isInt<20>(Val) && isInt<20>(Val + 8);
357251607Sdim  }
358251607Sdim  llvm_unreachable("Unhandled displacement range");
359251607Sdim}
360251607Sdim
361251607Sdim// Change the base or index in AM to Value, where IsBase selects
362251607Sdim// between the base and index.
363251607Sdimstatic void changeComponent(SystemZAddressingMode &AM, bool IsBase,
364251607Sdim                            SDValue Value) {
365251607Sdim  if (IsBase)
366251607Sdim    AM.Base = Value;
367251607Sdim  else
368251607Sdim    AM.Index = Value;
369251607Sdim}
370251607Sdim
371251607Sdim// The base or index of AM is equivalent to Value + ADJDYNALLOC,
372251607Sdim// where IsBase selects between the base and index.  Try to fold the
373251607Sdim// ADJDYNALLOC into AM.
374251607Sdimstatic bool expandAdjDynAlloc(SystemZAddressingMode &AM, bool IsBase,
375251607Sdim                              SDValue Value) {
376251607Sdim  if (AM.isDynAlloc() && !AM.IncludesDynAlloc) {
377251607Sdim    changeComponent(AM, IsBase, Value);
378251607Sdim    AM.IncludesDynAlloc = true;
379251607Sdim    return true;
380251607Sdim  }
381251607Sdim  return false;
382251607Sdim}
383251607Sdim
384251607Sdim// The base of AM is equivalent to Base + Index.  Try to use Index as
385251607Sdim// the index register.
386251607Sdimstatic bool expandIndex(SystemZAddressingMode &AM, SDValue Base,
387251607Sdim                        SDValue Index) {
388251607Sdim  if (AM.hasIndexField() && !AM.Index.getNode()) {
389251607Sdim    AM.Base = Base;
390251607Sdim    AM.Index = Index;
391251607Sdim    return true;
392251607Sdim  }
393251607Sdim  return false;
394251607Sdim}
395251607Sdim
396251607Sdim// The base or index of AM is equivalent to Op0 + Op1, where IsBase selects
397251607Sdim// between the base and index.  Try to fold Op1 into AM's displacement.
398251607Sdimstatic bool expandDisp(SystemZAddressingMode &AM, bool IsBase,
399261991Sdim                       SDValue Op0, uint64_t Op1) {
400251607Sdim  // First try adjusting the displacement.
401261991Sdim  int64_t TestDisp = AM.Disp + Op1;
402251607Sdim  if (selectDisp(AM.DR, TestDisp)) {
403251607Sdim    changeComponent(AM, IsBase, Op0);
404251607Sdim    AM.Disp = TestDisp;
405251607Sdim    return true;
406251607Sdim  }
407251607Sdim
408251607Sdim  // We could consider forcing the displacement into a register and
409251607Sdim  // using it as an index, but it would need to be carefully tuned.
410251607Sdim  return false;
411251607Sdim}
412251607Sdim
413251607Sdimbool SystemZDAGToDAGISel::expandAddress(SystemZAddressingMode &AM,
414261991Sdim                                        bool IsBase) const {
415251607Sdim  SDValue N = IsBase ? AM.Base : AM.Index;
416251607Sdim  unsigned Opcode = N.getOpcode();
417251607Sdim  if (Opcode == ISD::TRUNCATE) {
418251607Sdim    N = N.getOperand(0);
419251607Sdim    Opcode = N.getOpcode();
420251607Sdim  }
421251607Sdim  if (Opcode == ISD::ADD || CurDAG->isBaseWithConstantOffset(N)) {
422251607Sdim    SDValue Op0 = N.getOperand(0);
423251607Sdim    SDValue Op1 = N.getOperand(1);
424251607Sdim
425251607Sdim    unsigned Op0Code = Op0->getOpcode();
426251607Sdim    unsigned Op1Code = Op1->getOpcode();
427251607Sdim
428251607Sdim    if (Op0Code == SystemZISD::ADJDYNALLOC)
429251607Sdim      return expandAdjDynAlloc(AM, IsBase, Op1);
430251607Sdim    if (Op1Code == SystemZISD::ADJDYNALLOC)
431251607Sdim      return expandAdjDynAlloc(AM, IsBase, Op0);
432251607Sdim
433251607Sdim    if (Op0Code == ISD::Constant)
434261991Sdim      return expandDisp(AM, IsBase, Op1,
435261991Sdim                        cast<ConstantSDNode>(Op0)->getSExtValue());
436251607Sdim    if (Op1Code == ISD::Constant)
437261991Sdim      return expandDisp(AM, IsBase, Op0,
438261991Sdim                        cast<ConstantSDNode>(Op1)->getSExtValue());
439251607Sdim
440251607Sdim    if (IsBase && expandIndex(AM, Op0, Op1))
441251607Sdim      return true;
442251607Sdim  }
443261991Sdim  if (Opcode == SystemZISD::PCREL_OFFSET) {
444261991Sdim    SDValue Full = N.getOperand(0);
445261991Sdim    SDValue Base = N.getOperand(1);
446261991Sdim    SDValue Anchor = Base.getOperand(0);
447261991Sdim    uint64_t Offset = (cast<GlobalAddressSDNode>(Full)->getOffset() -
448261991Sdim                       cast<GlobalAddressSDNode>(Anchor)->getOffset());
449261991Sdim    return expandDisp(AM, IsBase, Base, Offset);
450261991Sdim  }
451251607Sdim  return false;
452251607Sdim}
453251607Sdim
454251607Sdim// Return true if an instruction with displacement range DR should be
455251607Sdim// used for displacement value Val.  selectDisp(DR, Val) must already hold.
456251607Sdimstatic bool isValidDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
457251607Sdim  assert(selectDisp(DR, Val) && "Invalid displacement");
458251607Sdim  switch (DR) {
459251607Sdim  case SystemZAddressingMode::Disp12Only:
460251607Sdim  case SystemZAddressingMode::Disp20Only:
461251607Sdim  case SystemZAddressingMode::Disp20Only128:
462251607Sdim    return true;
463251607Sdim
464251607Sdim  case SystemZAddressingMode::Disp12Pair:
465251607Sdim    // Use the other instruction if the displacement is too large.
466251607Sdim    return isUInt<12>(Val);
467251607Sdim
468251607Sdim  case SystemZAddressingMode::Disp20Pair:
469251607Sdim    // Use the other instruction if the displacement is small enough.
470251607Sdim    return !isUInt<12>(Val);
471251607Sdim  }
472251607Sdim  llvm_unreachable("Unhandled displacement range");
473251607Sdim}
474251607Sdim
475251607Sdim// Return true if Base + Disp + Index should be performed by LA(Y).
476251607Sdimstatic bool shouldUseLA(SDNode *Base, int64_t Disp, SDNode *Index) {
477251607Sdim  // Don't use LA(Y) for constants.
478251607Sdim  if (!Base)
479251607Sdim    return false;
480251607Sdim
481251607Sdim  // Always use LA(Y) for frame addresses, since we know that the destination
482251607Sdim  // register is almost always (perhaps always) going to be different from
483251607Sdim  // the frame register.
484251607Sdim  if (Base->getOpcode() == ISD::FrameIndex)
485251607Sdim    return true;
486251607Sdim
487251607Sdim  if (Disp) {
488251607Sdim    // Always use LA(Y) if there is a base, displacement and index.
489251607Sdim    if (Index)
490251607Sdim      return true;
491251607Sdim
492251607Sdim    // Always use LA if the displacement is small enough.  It should always
493251607Sdim    // be no worse than AGHI (and better if it avoids a move).
494251607Sdim    if (isUInt<12>(Disp))
495251607Sdim      return true;
496251607Sdim
497251607Sdim    // For similar reasons, always use LAY if the constant is too big for AGHI.
498251607Sdim    // LAY should be no worse than AGFI.
499251607Sdim    if (!isInt<16>(Disp))
500251607Sdim      return true;
501251607Sdim  } else {
502251607Sdim    // Don't use LA for plain registers.
503251607Sdim    if (!Index)
504251607Sdim      return false;
505251607Sdim
506251607Sdim    // Don't use LA for plain addition if the index operand is only used
507251607Sdim    // once.  It should be a natural two-operand addition in that case.
508251607Sdim    if (Index->hasOneUse())
509251607Sdim      return false;
510251607Sdim
511251607Sdim    // Prefer addition if the second operation is sign-extended, in the
512251607Sdim    // hope of using AGF.
513251607Sdim    unsigned IndexOpcode = Index->getOpcode();
514251607Sdim    if (IndexOpcode == ISD::SIGN_EXTEND ||
515251607Sdim        IndexOpcode == ISD::SIGN_EXTEND_INREG)
516251607Sdim      return false;
517251607Sdim  }
518251607Sdim
519251607Sdim  // Don't use LA for two-operand addition if either operand is only
520251607Sdim  // used once.  The addition instructions are better in that case.
521251607Sdim  if (Base->hasOneUse())
522251607Sdim    return false;
523251607Sdim
524251607Sdim  return true;
525251607Sdim}
526251607Sdim
527251607Sdim// Return true if Addr is suitable for AM, updating AM if so.
528251607Sdimbool SystemZDAGToDAGISel::selectAddress(SDValue Addr,
529261991Sdim                                        SystemZAddressingMode &AM) const {
530251607Sdim  // Start out assuming that the address will need to be loaded separately,
531251607Sdim  // then try to extend it as much as we can.
532251607Sdim  AM.Base = Addr;
533251607Sdim
534251607Sdim  // First try treating the address as a constant.
535251607Sdim  if (Addr.getOpcode() == ISD::Constant &&
536261991Sdim      expandDisp(AM, true, SDValue(),
537261991Sdim                 cast<ConstantSDNode>(Addr)->getSExtValue()))
538251607Sdim    ;
539251607Sdim  else
540251607Sdim    // Otherwise try expanding each component.
541251607Sdim    while (expandAddress(AM, true) ||
542251607Sdim           (AM.Index.getNode() && expandAddress(AM, false)))
543251607Sdim      continue;
544251607Sdim
545251607Sdim  // Reject cases where it isn't profitable to use LA(Y).
546251607Sdim  if (AM.Form == SystemZAddressingMode::FormBDXLA &&
547251607Sdim      !shouldUseLA(AM.Base.getNode(), AM.Disp, AM.Index.getNode()))
548251607Sdim    return false;
549251607Sdim
550251607Sdim  // Reject cases where the other instruction in a pair should be used.
551251607Sdim  if (!isValidDisp(AM.DR, AM.Disp))
552251607Sdim    return false;
553251607Sdim
554251607Sdim  // Make sure that ADJDYNALLOC is included where necessary.
555251607Sdim  if (AM.isDynAlloc() && !AM.IncludesDynAlloc)
556251607Sdim    return false;
557251607Sdim
558251607Sdim  DEBUG(AM.dump());
559251607Sdim  return true;
560251607Sdim}
561251607Sdim
562251607Sdim// Insert a node into the DAG at least before Pos.  This will reposition
563251607Sdim// the node as needed, and will assign it a node ID that is <= Pos's ID.
564251607Sdim// Note that this does *not* preserve the uniqueness of node IDs!
565251607Sdim// The selection DAG must no longer depend on their uniqueness when this
566251607Sdim// function is used.
567251607Sdimstatic void insertDAGNode(SelectionDAG *DAG, SDNode *Pos, SDValue N) {
568251607Sdim  if (N.getNode()->getNodeId() == -1 ||
569251607Sdim      N.getNode()->getNodeId() > Pos->getNodeId()) {
570251607Sdim    DAG->RepositionNode(Pos, N.getNode());
571251607Sdim    N.getNode()->setNodeId(Pos->getNodeId());
572251607Sdim  }
573251607Sdim}
574251607Sdim
575251607Sdimvoid SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
576251607Sdim                                             EVT VT, SDValue &Base,
577261991Sdim                                             SDValue &Disp) const {
578251607Sdim  Base = AM.Base;
579251607Sdim  if (!Base.getNode())
580251607Sdim    // Register 0 means "no base".  This is mostly useful for shifts.
581251607Sdim    Base = CurDAG->getRegister(0, VT);
582251607Sdim  else if (Base.getOpcode() == ISD::FrameIndex) {
583251607Sdim    // Lower a FrameIndex to a TargetFrameIndex.
584251607Sdim    int64_t FrameIndex = cast<FrameIndexSDNode>(Base)->getIndex();
585251607Sdim    Base = CurDAG->getTargetFrameIndex(FrameIndex, VT);
586251607Sdim  } else if (Base.getValueType() != VT) {
587251607Sdim    // Truncate values from i64 to i32, for shifts.
588251607Sdim    assert(VT == MVT::i32 && Base.getValueType() == MVT::i64 &&
589251607Sdim           "Unexpected truncation");
590261991Sdim    SDLoc DL(Base);
591251607Sdim    SDValue Trunc = CurDAG->getNode(ISD::TRUNCATE, DL, VT, Base);
592251607Sdim    insertDAGNode(CurDAG, Base.getNode(), Trunc);
593251607Sdim    Base = Trunc;
594251607Sdim  }
595251607Sdim
596251607Sdim  // Lower the displacement to a TargetConstant.
597251607Sdim  Disp = CurDAG->getTargetConstant(AM.Disp, VT);
598251607Sdim}
599251607Sdim
600251607Sdimvoid SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
601251607Sdim                                             EVT VT, SDValue &Base,
602261991Sdim                                             SDValue &Disp,
603261991Sdim                                             SDValue &Index) const {
604251607Sdim  getAddressOperands(AM, VT, Base, Disp);
605251607Sdim
606251607Sdim  Index = AM.Index;
607251607Sdim  if (!Index.getNode())
608251607Sdim    // Register 0 means "no index".
609251607Sdim    Index = CurDAG->getRegister(0, VT);
610251607Sdim}
611251607Sdim
612251607Sdimbool SystemZDAGToDAGISel::selectBDAddr(SystemZAddressingMode::DispRange DR,
613251607Sdim                                       SDValue Addr, SDValue &Base,
614261991Sdim                                       SDValue &Disp) const {
615251607Sdim  SystemZAddressingMode AM(SystemZAddressingMode::FormBD, DR);
616251607Sdim  if (!selectAddress(Addr, AM))
617251607Sdim    return false;
618251607Sdim
619251607Sdim  getAddressOperands(AM, Addr.getValueType(), Base, Disp);
620251607Sdim  return true;
621251607Sdim}
622251607Sdim
623261991Sdimbool SystemZDAGToDAGISel::selectMVIAddr(SystemZAddressingMode::DispRange DR,
624261991Sdim                                        SDValue Addr, SDValue &Base,
625261991Sdim                                        SDValue &Disp) const {
626261991Sdim  SystemZAddressingMode AM(SystemZAddressingMode::FormBDXNormal, DR);
627261991Sdim  if (!selectAddress(Addr, AM) || AM.Index.getNode())
628261991Sdim    return false;
629261991Sdim
630261991Sdim  getAddressOperands(AM, Addr.getValueType(), Base, Disp);
631261991Sdim  return true;
632261991Sdim}
633261991Sdim
634251607Sdimbool SystemZDAGToDAGISel::selectBDXAddr(SystemZAddressingMode::AddrForm Form,
635251607Sdim                                        SystemZAddressingMode::DispRange DR,
636251607Sdim                                        SDValue Addr, SDValue &Base,
637261991Sdim                                        SDValue &Disp, SDValue &Index) const {
638251607Sdim  SystemZAddressingMode AM(Form, DR);
639251607Sdim  if (!selectAddress(Addr, AM))
640251607Sdim    return false;
641251607Sdim
642251607Sdim  getAddressOperands(AM, Addr.getValueType(), Base, Disp, Index);
643251607Sdim  return true;
644251607Sdim}
645251607Sdim
646261991Sdimbool SystemZDAGToDAGISel::detectOrAndInsertion(SDValue &Op,
647261991Sdim                                               uint64_t InsertMask) const {
648261991Sdim  // We're only interested in cases where the insertion is into some operand
649261991Sdim  // of Op, rather than into Op itself.  The only useful case is an AND.
650261991Sdim  if (Op.getOpcode() != ISD::AND)
651261991Sdim    return false;
652261991Sdim
653261991Sdim  // We need a constant mask.
654276479Sdim  auto *MaskNode = dyn_cast<ConstantSDNode>(Op.getOperand(1).getNode());
655261991Sdim  if (!MaskNode)
656261991Sdim    return false;
657261991Sdim
658261991Sdim  // It's not an insertion of Op.getOperand(0) if the two masks overlap.
659261991Sdim  uint64_t AndMask = MaskNode->getZExtValue();
660261991Sdim  if (InsertMask & AndMask)
661261991Sdim    return false;
662261991Sdim
663261991Sdim  // It's only an insertion if all bits are covered or are known to be zero.
664261991Sdim  // The inner check covers all cases but is more expensive.
665261991Sdim  uint64_t Used = allOnes(Op.getValueType().getSizeInBits());
666261991Sdim  if (Used != (AndMask | InsertMask)) {
667261991Sdim    APInt KnownZero, KnownOne;
668276479Sdim    CurDAG->computeKnownBits(Op.getOperand(0), KnownZero, KnownOne);
669261991Sdim    if (Used != (AndMask | InsertMask | KnownZero.getZExtValue()))
670261991Sdim      return false;
671261991Sdim  }
672261991Sdim
673261991Sdim  Op = Op.getOperand(0);
674261991Sdim  return true;
675261991Sdim}
676261991Sdim
677261991Sdimbool SystemZDAGToDAGISel::refineRxSBGMask(RxSBGOperands &RxSBG,
678261991Sdim                                          uint64_t Mask) const {
679261991Sdim  const SystemZInstrInfo *TII = getInstrInfo();
680261991Sdim  if (RxSBG.Rotate != 0)
681261991Sdim    Mask = (Mask << RxSBG.Rotate) | (Mask >> (64 - RxSBG.Rotate));
682261991Sdim  Mask &= RxSBG.Mask;
683261991Sdim  if (TII->isRxSBGMask(Mask, RxSBG.BitSize, RxSBG.Start, RxSBG.End)) {
684261991Sdim    RxSBG.Mask = Mask;
685261991Sdim    return true;
686261991Sdim  }
687261991Sdim  return false;
688261991Sdim}
689261991Sdim
690261991Sdim// Return true if any bits of (RxSBG.Input & Mask) are significant.
691261991Sdimstatic bool maskMatters(RxSBGOperands &RxSBG, uint64_t Mask) {
692261991Sdim  // Rotate the mask in the same way as RxSBG.Input is rotated.
693261991Sdim  if (RxSBG.Rotate != 0)
694261991Sdim    Mask = ((Mask << RxSBG.Rotate) | (Mask >> (64 - RxSBG.Rotate)));
695261991Sdim  return (Mask & RxSBG.Mask) != 0;
696261991Sdim}
697261991Sdim
698261991Sdimbool SystemZDAGToDAGISel::expandRxSBG(RxSBGOperands &RxSBG) const {
699261991Sdim  SDValue N = RxSBG.Input;
700261991Sdim  unsigned Opcode = N.getOpcode();
701261991Sdim  switch (Opcode) {
702261991Sdim  case ISD::AND: {
703261991Sdim    if (RxSBG.Opcode == SystemZ::RNSBG)
704261991Sdim      return false;
705261991Sdim
706276479Sdim    auto *MaskNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
707261991Sdim    if (!MaskNode)
708261991Sdim      return false;
709261991Sdim
710261991Sdim    SDValue Input = N.getOperand(0);
711261991Sdim    uint64_t Mask = MaskNode->getZExtValue();
712261991Sdim    if (!refineRxSBGMask(RxSBG, Mask)) {
713261991Sdim      // If some bits of Input are already known zeros, those bits will have
714261991Sdim      // been removed from the mask.  See if adding them back in makes the
715261991Sdim      // mask suitable.
716261991Sdim      APInt KnownZero, KnownOne;
717276479Sdim      CurDAG->computeKnownBits(Input, KnownZero, KnownOne);
718261991Sdim      Mask |= KnownZero.getZExtValue();
719261991Sdim      if (!refineRxSBGMask(RxSBG, Mask))
720261991Sdim        return false;
721261991Sdim    }
722261991Sdim    RxSBG.Input = Input;
723261991Sdim    return true;
724261991Sdim  }
725261991Sdim
726261991Sdim  case ISD::OR: {
727261991Sdim    if (RxSBG.Opcode != SystemZ::RNSBG)
728261991Sdim      return false;
729261991Sdim
730276479Sdim    auto *MaskNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
731261991Sdim    if (!MaskNode)
732261991Sdim      return false;
733261991Sdim
734261991Sdim    SDValue Input = N.getOperand(0);
735261991Sdim    uint64_t Mask = ~MaskNode->getZExtValue();
736261991Sdim    if (!refineRxSBGMask(RxSBG, Mask)) {
737261991Sdim      // If some bits of Input are already known ones, those bits will have
738261991Sdim      // been removed from the mask.  See if adding them back in makes the
739261991Sdim      // mask suitable.
740261991Sdim      APInt KnownZero, KnownOne;
741276479Sdim      CurDAG->computeKnownBits(Input, KnownZero, KnownOne);
742261991Sdim      Mask &= ~KnownOne.getZExtValue();
743261991Sdim      if (!refineRxSBGMask(RxSBG, Mask))
744261991Sdim        return false;
745261991Sdim    }
746261991Sdim    RxSBG.Input = Input;
747261991Sdim    return true;
748261991Sdim  }
749261991Sdim
750261991Sdim  case ISD::ROTL: {
751261991Sdim    // Any 64-bit rotate left can be merged into the RxSBG.
752261991Sdim    if (RxSBG.BitSize != 64 || N.getValueType() != MVT::i64)
753261991Sdim      return false;
754276479Sdim    auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
755261991Sdim    if (!CountNode)
756261991Sdim      return false;
757261991Sdim
758261991Sdim    RxSBG.Rotate = (RxSBG.Rotate + CountNode->getZExtValue()) & 63;
759261991Sdim    RxSBG.Input = N.getOperand(0);
760261991Sdim    return true;
761261991Sdim  }
762261991Sdim
763276479Sdim  case ISD::ANY_EXTEND:
764276479Sdim    // Bits above the extended operand are don't-care.
765276479Sdim    RxSBG.Input = N.getOperand(0);
766276479Sdim    return true;
767276479Sdim
768261991Sdim  case ISD::ZERO_EXTEND:
769276479Sdim    if (RxSBG.Opcode != SystemZ::RNSBG) {
770276479Sdim      // Restrict the mask to the extended operand.
771276479Sdim      unsigned InnerBitSize = N.getOperand(0).getValueType().getSizeInBits();
772276479Sdim      if (!refineRxSBGMask(RxSBG, allOnes(InnerBitSize)))
773276479Sdim        return false;
774276479Sdim
775276479Sdim      RxSBG.Input = N.getOperand(0);
776276479Sdim      return true;
777276479Sdim    }
778276479Sdim    // Fall through.
779276479Sdim
780276479Sdim  case ISD::SIGN_EXTEND: {
781261991Sdim    // Check that the extension bits are don't-care (i.e. are masked out
782261991Sdim    // by the final mask).
783261991Sdim    unsigned InnerBitSize = N.getOperand(0).getValueType().getSizeInBits();
784261991Sdim    if (maskMatters(RxSBG, allOnes(RxSBG.BitSize) - allOnes(InnerBitSize)))
785261991Sdim      return false;
786261991Sdim
787261991Sdim    RxSBG.Input = N.getOperand(0);
788261991Sdim    return true;
789261991Sdim  }
790261991Sdim
791261991Sdim  case ISD::SHL: {
792276479Sdim    auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
793261991Sdim    if (!CountNode)
794261991Sdim      return false;
795261991Sdim
796261991Sdim    uint64_t Count = CountNode->getZExtValue();
797261991Sdim    unsigned BitSize = N.getValueType().getSizeInBits();
798261991Sdim    if (Count < 1 || Count >= BitSize)
799261991Sdim      return false;
800261991Sdim
801261991Sdim    if (RxSBG.Opcode == SystemZ::RNSBG) {
802261991Sdim      // Treat (shl X, count) as (rotl X, size-count) as long as the bottom
803261991Sdim      // count bits from RxSBG.Input are ignored.
804261991Sdim      if (maskMatters(RxSBG, allOnes(Count)))
805261991Sdim        return false;
806261991Sdim    } else {
807261991Sdim      // Treat (shl X, count) as (and (rotl X, count), ~0<<count).
808261991Sdim      if (!refineRxSBGMask(RxSBG, allOnes(BitSize - Count) << Count))
809261991Sdim        return false;
810261991Sdim    }
811261991Sdim
812261991Sdim    RxSBG.Rotate = (RxSBG.Rotate + Count) & 63;
813261991Sdim    RxSBG.Input = N.getOperand(0);
814261991Sdim    return true;
815261991Sdim  }
816261991Sdim
817261991Sdim  case ISD::SRL:
818261991Sdim  case ISD::SRA: {
819276479Sdim    auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
820261991Sdim    if (!CountNode)
821261991Sdim      return false;
822261991Sdim
823261991Sdim    uint64_t Count = CountNode->getZExtValue();
824261991Sdim    unsigned BitSize = N.getValueType().getSizeInBits();
825261991Sdim    if (Count < 1 || Count >= BitSize)
826261991Sdim      return false;
827261991Sdim
828261991Sdim    if (RxSBG.Opcode == SystemZ::RNSBG || Opcode == ISD::SRA) {
829261991Sdim      // Treat (srl|sra X, count) as (rotl X, size-count) as long as the top
830261991Sdim      // count bits from RxSBG.Input are ignored.
831261991Sdim      if (maskMatters(RxSBG, allOnes(Count) << (BitSize - Count)))
832261991Sdim        return false;
833261991Sdim    } else {
834261991Sdim      // Treat (srl X, count), mask) as (and (rotl X, size-count), ~0>>count),
835261991Sdim      // which is similar to SLL above.
836261991Sdim      if (!refineRxSBGMask(RxSBG, allOnes(BitSize - Count)))
837261991Sdim        return false;
838261991Sdim    }
839261991Sdim
840261991Sdim    RxSBG.Rotate = (RxSBG.Rotate - Count) & 63;
841261991Sdim    RxSBG.Input = N.getOperand(0);
842261991Sdim    return true;
843261991Sdim  }
844261991Sdim  default:
845261991Sdim    return false;
846261991Sdim  }
847261991Sdim}
848261991Sdim
849261991SdimSDValue SystemZDAGToDAGISel::getUNDEF(SDLoc DL, EVT VT) const {
850261991Sdim  SDNode *N = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, VT);
851261991Sdim  return SDValue(N, 0);
852261991Sdim}
853261991Sdim
854261991SdimSDValue SystemZDAGToDAGISel::convertTo(SDLoc DL, EVT VT, SDValue N) const {
855261991Sdim  if (N.getValueType() == MVT::i32 && VT == MVT::i64)
856261991Sdim    return CurDAG->getTargetInsertSubreg(SystemZ::subreg_l32,
857261991Sdim                                         DL, VT, getUNDEF(DL, MVT::i64), N);
858261991Sdim  if (N.getValueType() == MVT::i64 && VT == MVT::i32)
859261991Sdim    return CurDAG->getTargetExtractSubreg(SystemZ::subreg_l32, DL, VT, N);
860261991Sdim  assert(N.getValueType() == VT && "Unexpected value types");
861261991Sdim  return N;
862261991Sdim}
863261991Sdim
864261991SdimSDNode *SystemZDAGToDAGISel::tryRISBGZero(SDNode *N) {
865261991Sdim  EVT VT = N->getValueType(0);
866261991Sdim  RxSBGOperands RISBG(SystemZ::RISBG, SDValue(N, 0));
867261991Sdim  unsigned Count = 0;
868261991Sdim  while (expandRxSBG(RISBG))
869261991Sdim    if (RISBG.Input.getOpcode() != ISD::ANY_EXTEND)
870261991Sdim      Count += 1;
871261991Sdim  if (Count == 0)
872276479Sdim    return nullptr;
873261991Sdim  if (Count == 1) {
874261991Sdim    // Prefer to use normal shift instructions over RISBG, since they can handle
875261991Sdim    // all cases and are sometimes shorter.
876261991Sdim    if (N->getOpcode() != ISD::AND)
877276479Sdim      return nullptr;
878261991Sdim
879261991Sdim    // Prefer register extensions like LLC over RISBG.  Also prefer to start
880261991Sdim    // out with normal ANDs if one instruction would be enough.  We can convert
881261991Sdim    // these ANDs into an RISBG later if a three-address instruction is useful.
882261991Sdim    if (VT == MVT::i32 ||
883261991Sdim        RISBG.Mask == 0xff ||
884261991Sdim        RISBG.Mask == 0xffff ||
885261991Sdim        SystemZ::isImmLF(~RISBG.Mask) ||
886261991Sdim        SystemZ::isImmHF(~RISBG.Mask)) {
887261991Sdim      // Force the new mask into the DAG, since it may include known-one bits.
888276479Sdim      auto *MaskN = cast<ConstantSDNode>(N->getOperand(1).getNode());
889261991Sdim      if (MaskN->getZExtValue() != RISBG.Mask) {
890261991Sdim        SDValue NewMask = CurDAG->getConstant(RISBG.Mask, VT);
891261991Sdim        N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), NewMask);
892261991Sdim        return SelectCode(N);
893261991Sdim      }
894276479Sdim      return nullptr;
895261991Sdim    }
896261991Sdim  }
897261991Sdim
898261991Sdim  unsigned Opcode = SystemZ::RISBG;
899261991Sdim  EVT OpcodeVT = MVT::i64;
900261991Sdim  if (VT == MVT::i32 && Subtarget.hasHighWord()) {
901261991Sdim    Opcode = SystemZ::RISBMux;
902261991Sdim    OpcodeVT = MVT::i32;
903261991Sdim    RISBG.Start &= 31;
904261991Sdim    RISBG.End &= 31;
905261991Sdim  }
906261991Sdim  SDValue Ops[5] = {
907261991Sdim    getUNDEF(SDLoc(N), OpcodeVT),
908261991Sdim    convertTo(SDLoc(N), OpcodeVT, RISBG.Input),
909261991Sdim    CurDAG->getTargetConstant(RISBG.Start, MVT::i32),
910261991Sdim    CurDAG->getTargetConstant(RISBG.End | 128, MVT::i32),
911261991Sdim    CurDAG->getTargetConstant(RISBG.Rotate, MVT::i32)
912261991Sdim  };
913261991Sdim  N = CurDAG->getMachineNode(Opcode, SDLoc(N), OpcodeVT, Ops);
914261991Sdim  return convertTo(SDLoc(N), VT, SDValue(N, 0)).getNode();
915261991Sdim}
916261991Sdim
917261991SdimSDNode *SystemZDAGToDAGISel::tryRxSBG(SDNode *N, unsigned Opcode) {
918261991Sdim  // Try treating each operand of N as the second operand of the RxSBG
919261991Sdim  // and see which goes deepest.
920261991Sdim  RxSBGOperands RxSBG[] = {
921261991Sdim    RxSBGOperands(Opcode, N->getOperand(0)),
922261991Sdim    RxSBGOperands(Opcode, N->getOperand(1))
923261991Sdim  };
924261991Sdim  unsigned Count[] = { 0, 0 };
925261991Sdim  for (unsigned I = 0; I < 2; ++I)
926261991Sdim    while (expandRxSBG(RxSBG[I]))
927261991Sdim      if (RxSBG[I].Input.getOpcode() != ISD::ANY_EXTEND)
928261991Sdim        Count[I] += 1;
929261991Sdim
930261991Sdim  // Do nothing if neither operand is suitable.
931261991Sdim  if (Count[0] == 0 && Count[1] == 0)
932276479Sdim    return nullptr;
933261991Sdim
934261991Sdim  // Pick the deepest second operand.
935261991Sdim  unsigned I = Count[0] > Count[1] ? 0 : 1;
936261991Sdim  SDValue Op0 = N->getOperand(I ^ 1);
937261991Sdim
938261991Sdim  // Prefer IC for character insertions from memory.
939261991Sdim  if (Opcode == SystemZ::ROSBG && (RxSBG[I].Mask & 0xff) == 0)
940276479Sdim    if (auto *Load = dyn_cast<LoadSDNode>(Op0.getNode()))
941261991Sdim      if (Load->getMemoryVT() == MVT::i8)
942276479Sdim        return nullptr;
943261991Sdim
944261991Sdim  // See whether we can avoid an AND in the first operand by converting
945261991Sdim  // ROSBG to RISBG.
946261991Sdim  if (Opcode == SystemZ::ROSBG && detectOrAndInsertion(Op0, RxSBG[I].Mask))
947261991Sdim    Opcode = SystemZ::RISBG;
948261991Sdim
949261991Sdim  EVT VT = N->getValueType(0);
950261991Sdim  SDValue Ops[5] = {
951261991Sdim    convertTo(SDLoc(N), MVT::i64, Op0),
952261991Sdim    convertTo(SDLoc(N), MVT::i64, RxSBG[I].Input),
953261991Sdim    CurDAG->getTargetConstant(RxSBG[I].Start, MVT::i32),
954261991Sdim    CurDAG->getTargetConstant(RxSBG[I].End, MVT::i32),
955261991Sdim    CurDAG->getTargetConstant(RxSBG[I].Rotate, MVT::i32)
956261991Sdim  };
957261991Sdim  N = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i64, Ops);
958261991Sdim  return convertTo(SDLoc(N), VT, SDValue(N, 0)).getNode();
959261991Sdim}
960261991Sdim
961251607SdimSDNode *SystemZDAGToDAGISel::splitLargeImmediate(unsigned Opcode, SDNode *Node,
962251607Sdim                                                 SDValue Op0, uint64_t UpperVal,
963251607Sdim                                                 uint64_t LowerVal) {
964251607Sdim  EVT VT = Node->getValueType(0);
965261991Sdim  SDLoc DL(Node);
966251607Sdim  SDValue Upper = CurDAG->getConstant(UpperVal, VT);
967251607Sdim  if (Op0.getNode())
968251607Sdim    Upper = CurDAG->getNode(Opcode, DL, VT, Op0, Upper);
969251607Sdim  Upper = SDValue(Select(Upper.getNode()), 0);
970251607Sdim
971251607Sdim  SDValue Lower = CurDAG->getConstant(LowerVal, VT);
972251607Sdim  SDValue Or = CurDAG->getNode(Opcode, DL, VT, Upper, Lower);
973251607Sdim  return Or.getNode();
974251607Sdim}
975251607Sdim
976261991Sdimbool SystemZDAGToDAGISel::canUseBlockOperation(StoreSDNode *Store,
977261991Sdim                                               LoadSDNode *Load) const {
978261991Sdim  // Check that the two memory operands have the same size.
979261991Sdim  if (Load->getMemoryVT() != Store->getMemoryVT())
980261991Sdim    return false;
981261991Sdim
982261991Sdim  // Volatility stops an access from being decomposed.
983261991Sdim  if (Load->isVolatile() || Store->isVolatile())
984261991Sdim    return false;
985261991Sdim
986261991Sdim  // There's no chance of overlap if the load is invariant.
987261991Sdim  if (Load->isInvariant())
988261991Sdim    return true;
989261991Sdim
990261991Sdim  // Otherwise we need to check whether there's an alias.
991276479Sdim  const Value *V1 = Load->getMemOperand()->getValue();
992276479Sdim  const Value *V2 = Store->getMemOperand()->getValue();
993261991Sdim  if (!V1 || !V2)
994261991Sdim    return false;
995261991Sdim
996261991Sdim  // Reject equality.
997261991Sdim  uint64_t Size = Load->getMemoryVT().getStoreSize();
998261991Sdim  int64_t End1 = Load->getSrcValueOffset() + Size;
999261991Sdim  int64_t End2 = Store->getSrcValueOffset() + Size;
1000261991Sdim  if (V1 == V2 && End1 == End2)
1001261991Sdim    return false;
1002261991Sdim
1003261991Sdim  return !AA->alias(AliasAnalysis::Location(V1, End1, Load->getTBAAInfo()),
1004261991Sdim                    AliasAnalysis::Location(V2, End2, Store->getTBAAInfo()));
1005261991Sdim}
1006261991Sdim
1007261991Sdimbool SystemZDAGToDAGISel::storeLoadCanUseMVC(SDNode *N) const {
1008276479Sdim  auto *Store = cast<StoreSDNode>(N);
1009276479Sdim  auto *Load = cast<LoadSDNode>(Store->getValue());
1010261991Sdim
1011261991Sdim  // Prefer not to use MVC if either address can use ... RELATIVE LONG
1012261991Sdim  // instructions.
1013261991Sdim  uint64_t Size = Load->getMemoryVT().getStoreSize();
1014261991Sdim  if (Size > 1 && Size <= 8) {
1015261991Sdim    // Prefer LHRL, LRL and LGRL.
1016261991Sdim    if (SystemZISD::isPCREL(Load->getBasePtr().getOpcode()))
1017261991Sdim      return false;
1018261991Sdim    // Prefer STHRL, STRL and STGRL.
1019261991Sdim    if (SystemZISD::isPCREL(Store->getBasePtr().getOpcode()))
1020261991Sdim      return false;
1021261991Sdim  }
1022261991Sdim
1023261991Sdim  return canUseBlockOperation(Store, Load);
1024261991Sdim}
1025261991Sdim
1026261991Sdimbool SystemZDAGToDAGISel::storeLoadCanUseBlockBinary(SDNode *N,
1027261991Sdim                                                     unsigned I) const {
1028276479Sdim  auto *StoreA = cast<StoreSDNode>(N);
1029276479Sdim  auto *LoadA = cast<LoadSDNode>(StoreA->getValue().getOperand(1 - I));
1030276479Sdim  auto *LoadB = cast<LoadSDNode>(StoreA->getValue().getOperand(I));
1031261991Sdim  return !LoadA->isVolatile() && canUseBlockOperation(StoreA, LoadB);
1032261991Sdim}
1033261991Sdim
1034251607SdimSDNode *SystemZDAGToDAGISel::Select(SDNode *Node) {
1035251607Sdim  // Dump information about the Node being selected
1036251607Sdim  DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
1037251607Sdim
1038251607Sdim  // If we have a custom node, we already have selected!
1039251607Sdim  if (Node->isMachineOpcode()) {
1040251607Sdim    DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
1041255804Sdim    Node->setNodeId(-1);
1042276479Sdim    return nullptr;
1043251607Sdim  }
1044251607Sdim
1045251607Sdim  unsigned Opcode = Node->getOpcode();
1046276479Sdim  SDNode *ResNode = nullptr;
1047251607Sdim  switch (Opcode) {
1048251607Sdim  case ISD::OR:
1049261991Sdim    if (Node->getOperand(1).getOpcode() != ISD::Constant)
1050261991Sdim      ResNode = tryRxSBG(Node, SystemZ::ROSBG);
1051261991Sdim    goto or_xor;
1052261991Sdim
1053251607Sdim  case ISD::XOR:
1054261991Sdim    if (Node->getOperand(1).getOpcode() != ISD::Constant)
1055261991Sdim      ResNode = tryRxSBG(Node, SystemZ::RXSBG);
1056261991Sdim    // Fall through.
1057261991Sdim  or_xor:
1058251607Sdim    // If this is a 64-bit operation in which both 32-bit halves are nonzero,
1059251607Sdim    // split the operation into two.
1060261991Sdim    if (!ResNode && Node->getValueType(0) == MVT::i64)
1061276479Sdim      if (auto *Op1 = dyn_cast<ConstantSDNode>(Node->getOperand(1))) {
1062251607Sdim        uint64_t Val = Op1->getZExtValue();
1063251607Sdim        if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val))
1064251607Sdim          Node = splitLargeImmediate(Opcode, Node, Node->getOperand(0),
1065251607Sdim                                     Val - uint32_t(Val), uint32_t(Val));
1066251607Sdim      }
1067251607Sdim    break;
1068251607Sdim
1069261991Sdim  case ISD::AND:
1070261991Sdim    if (Node->getOperand(1).getOpcode() != ISD::Constant)
1071261991Sdim      ResNode = tryRxSBG(Node, SystemZ::RNSBG);
1072261991Sdim    // Fall through.
1073261991Sdim  case ISD::ROTL:
1074261991Sdim  case ISD::SHL:
1075261991Sdim  case ISD::SRL:
1076276479Sdim  case ISD::ZERO_EXTEND:
1077261991Sdim    if (!ResNode)
1078261991Sdim      ResNode = tryRISBGZero(Node);
1079261991Sdim    break;
1080261991Sdim
1081251607Sdim  case ISD::Constant:
1082251607Sdim    // If this is a 64-bit constant that is out of the range of LLILF,
1083251607Sdim    // LLIHF and LGFI, split it into two 32-bit pieces.
1084251607Sdim    if (Node->getValueType(0) == MVT::i64) {
1085251607Sdim      uint64_t Val = cast<ConstantSDNode>(Node)->getZExtValue();
1086251607Sdim      if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val) && !isInt<32>(Val))
1087251607Sdim        Node = splitLargeImmediate(ISD::OR, Node, SDValue(),
1088251607Sdim                                   Val - uint32_t(Val), uint32_t(Val));
1089251607Sdim    }
1090251607Sdim    break;
1091251607Sdim
1092261991Sdim  case SystemZISD::SELECT_CCMASK: {
1093261991Sdim    SDValue Op0 = Node->getOperand(0);
1094261991Sdim    SDValue Op1 = Node->getOperand(1);
1095261991Sdim    // Prefer to put any load first, so that it can be matched as a
1096261991Sdim    // conditional load.
1097261991Sdim    if (Op1.getOpcode() == ISD::LOAD && Op0.getOpcode() != ISD::LOAD) {
1098261991Sdim      SDValue CCValid = Node->getOperand(2);
1099261991Sdim      SDValue CCMask = Node->getOperand(3);
1100261991Sdim      uint64_t ConstCCValid =
1101261991Sdim        cast<ConstantSDNode>(CCValid.getNode())->getZExtValue();
1102261991Sdim      uint64_t ConstCCMask =
1103261991Sdim        cast<ConstantSDNode>(CCMask.getNode())->getZExtValue();
1104261991Sdim      // Invert the condition.
1105261991Sdim      CCMask = CurDAG->getConstant(ConstCCValid ^ ConstCCMask,
1106261991Sdim                                   CCMask.getValueType());
1107261991Sdim      SDValue Op4 = Node->getOperand(4);
1108261991Sdim      Node = CurDAG->UpdateNodeOperands(Node, Op1, Op0, CCValid, CCMask, Op4);
1109261991Sdim    }
1110261991Sdim    break;
1111251607Sdim  }
1112261991Sdim  }
1113251607Sdim
1114251607Sdim  // Select the default instruction
1115261991Sdim  if (!ResNode)
1116261991Sdim    ResNode = SelectCode(Node);
1117251607Sdim
1118251607Sdim  DEBUG(errs() << "=> ";
1119276479Sdim        if (ResNode == nullptr || ResNode == Node)
1120251607Sdim          Node->dump(CurDAG);
1121251607Sdim        else
1122251607Sdim          ResNode->dump(CurDAG);
1123251607Sdim        errs() << "\n";
1124251607Sdim        );
1125251607Sdim  return ResNode;
1126251607Sdim}
1127251607Sdim
1128251607Sdimbool SystemZDAGToDAGISel::
1129251607SdimSelectInlineAsmMemoryOperand(const SDValue &Op,
1130251607Sdim                             char ConstraintCode,
1131251607Sdim                             std::vector<SDValue> &OutOps) {
1132251607Sdim  assert(ConstraintCode == 'm' && "Unexpected constraint code");
1133251607Sdim  // Accept addresses with short displacements, which are compatible
1134251607Sdim  // with Q, R, S and T.  But keep the index operand for future expansion.
1135251607Sdim  SDValue Base, Disp, Index;
1136251607Sdim  if (!selectBDXAddr(SystemZAddressingMode::FormBD,
1137251607Sdim                     SystemZAddressingMode::Disp12Only,
1138251607Sdim                     Op, Base, Disp, Index))
1139251607Sdim    return true;
1140251607Sdim  OutOps.push_back(Base);
1141251607Sdim  OutOps.push_back(Disp);
1142251607Sdim  OutOps.push_back(Index);
1143251607Sdim  return false;
1144251607Sdim}
1145