26c9c9b9f67d1d0978130f276ba884cf976ae8a4
[oota-llvm.git] / lib / Target / SystemZ / SystemZISelDAGToDAG.cpp
1 //===-- SystemZISelDAGToDAG.cpp - A dag to dag inst selector for SystemZ --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the SystemZ target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SystemZTargetMachine.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/CodeGen/SelectionDAGISel.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
19
20 using namespace llvm;
21
22 #define DEBUG_TYPE "systemz-isel"
23
24 namespace {
25 // Used to build addressing modes.
26 struct SystemZAddressingMode {
27   // The shape of the address.
28   enum AddrForm {
29     // base+displacement
30     FormBD,
31
32     // base+displacement+index for load and store operands
33     FormBDXNormal,
34
35     // base+displacement+index for load address operands
36     FormBDXLA,
37
38     // base+displacement+index+ADJDYNALLOC
39     FormBDXDynAlloc
40   };
41   AddrForm Form;
42
43   // The type of displacement.  The enum names here correspond directly
44   // to the definitions in SystemZOperand.td.  We could split them into
45   // flags -- single/pair, 128-bit, etc. -- but it hardly seems worth it.
46   enum DispRange {
47     Disp12Only,
48     Disp12Pair,
49     Disp20Only,
50     Disp20Only128,
51     Disp20Pair
52   };
53   DispRange DR;
54
55   // The parts of the address.  The address is equivalent to:
56   //
57   //     Base + Disp + Index + (IncludesDynAlloc ? ADJDYNALLOC : 0)
58   SDValue Base;
59   int64_t Disp;
60   SDValue Index;
61   bool IncludesDynAlloc;
62
63   SystemZAddressingMode(AddrForm form, DispRange dr)
64     : Form(form), DR(dr), Base(), Disp(0), Index(),
65       IncludesDynAlloc(false) {}
66
67   // True if the address can have an index register.
68   bool hasIndexField() { return Form != FormBD; }
69
70   // True if the address can (and must) include ADJDYNALLOC.
71   bool isDynAlloc() { return Form == FormBDXDynAlloc; }
72
73   void dump() {
74     errs() << "SystemZAddressingMode " << this << '\n';
75
76     errs() << " Base ";
77     if (Base.getNode())
78       Base.getNode()->dump();
79     else
80       errs() << "null\n";
81
82     if (hasIndexField()) {
83       errs() << " Index ";
84       if (Index.getNode())
85         Index.getNode()->dump();
86       else
87         errs() << "null\n";
88     }
89
90     errs() << " Disp " << Disp;
91     if (IncludesDynAlloc)
92       errs() << " + ADJDYNALLOC";
93     errs() << '\n';
94   }
95 };
96
97 // Return a mask with Count low bits set.
98 static uint64_t allOnes(unsigned int Count) {
99   if (Count > 63)
100     return UINT64_MAX;
101   return (uint64_t(1) << Count) - 1;
102 }
103
104 // Represents operands 2 to 5 of the ROTATE AND ... SELECTED BITS operation
105 // given by Opcode.  The operands are: Input (R2), Start (I3), End (I4) and
106 // Rotate (I5).  The combined operand value is effectively:
107 //
108 //   (or (rotl Input, Rotate), ~Mask)
109 //
110 // for RNSBG and:
111 //
112 //   (and (rotl Input, Rotate), Mask)
113 //
114 // otherwise.  The output value has BitSize bits, although Input may be
115 // narrower (in which case the upper bits are don't care).
116 struct RxSBGOperands {
117   RxSBGOperands(unsigned Op, SDValue N)
118     : Opcode(Op), BitSize(N.getValueType().getSizeInBits()),
119       Mask(allOnes(BitSize)), Input(N), Start(64 - BitSize), End(63),
120       Rotate(0) {}
121
122   unsigned Opcode;
123   unsigned BitSize;
124   uint64_t Mask;
125   SDValue Input;
126   unsigned Start;
127   unsigned End;
128   unsigned Rotate;
129 };
130
131 class SystemZDAGToDAGISel : public SelectionDAGISel {
132   const SystemZSubtarget *Subtarget;
133
134   // Used by SystemZOperands.td to create integer constants.
135   inline SDValue getImm(const SDNode *Node, uint64_t Imm) const {
136     return CurDAG->getTargetConstant(Imm, SDLoc(Node), Node->getValueType(0));
137   }
138
139   const SystemZTargetMachine &getTargetMachine() const {
140     return static_cast<const SystemZTargetMachine &>(TM);
141   }
142
143   const SystemZInstrInfo *getInstrInfo() const {
144     return Subtarget->getInstrInfo();
145   }
146
147   // Try to fold more of the base or index of AM into AM, where IsBase
148   // selects between the base and index.
149   bool expandAddress(SystemZAddressingMode &AM, bool IsBase) const;
150
151   // Try to describe N in AM, returning true on success.
152   bool selectAddress(SDValue N, SystemZAddressingMode &AM) const;
153
154   // Extract individual target operands from matched address AM.
155   void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
156                           SDValue &Base, SDValue &Disp) const;
157   void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
158                           SDValue &Base, SDValue &Disp, SDValue &Index) const;
159
160   // Try to match Addr as a FormBD address with displacement type DR.
161   // Return true on success, storing the base and displacement in
162   // Base and Disp respectively.
163   bool selectBDAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
164                     SDValue &Base, SDValue &Disp) const;
165
166   // Try to match Addr as a FormBDX address with displacement type DR.
167   // Return true on success and if the result had no index.  Store the
168   // base and displacement in Base and Disp respectively.
169   bool selectMVIAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
170                      SDValue &Base, SDValue &Disp) const;
171
172   // Try to match Addr as a FormBDX* address of form Form with
173   // displacement type DR.  Return true on success, storing the base,
174   // displacement and index in Base, Disp and Index respectively.
175   bool selectBDXAddr(SystemZAddressingMode::AddrForm Form,
176                      SystemZAddressingMode::DispRange DR, SDValue Addr,
177                      SDValue &Base, SDValue &Disp, SDValue &Index) const;
178
179   // PC-relative address matching routines used by SystemZOperands.td.
180   bool selectPCRelAddress(SDValue Addr, SDValue &Target) const {
181     if (SystemZISD::isPCREL(Addr.getOpcode())) {
182       Target = Addr.getOperand(0);
183       return true;
184     }
185     return false;
186   }
187
188   // BD matching routines used by SystemZOperands.td.
189   bool selectBDAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp) const {
190     return selectBDAddr(SystemZAddressingMode::Disp12Only, Addr, Base, Disp);
191   }
192   bool selectBDAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
193     return selectBDAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
194   }
195   bool selectBDAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp) const {
196     return selectBDAddr(SystemZAddressingMode::Disp20Only, Addr, Base, Disp);
197   }
198   bool selectBDAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
199     return selectBDAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
200   }
201
202   // MVI matching routines used by SystemZOperands.td.
203   bool selectMVIAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
204     return selectMVIAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
205   }
206   bool selectMVIAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
207     return selectMVIAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
208   }
209
210   // BDX matching routines used by SystemZOperands.td.
211   bool selectBDXAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
212                            SDValue &Index) const {
213     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
214                          SystemZAddressingMode::Disp12Only,
215                          Addr, Base, Disp, Index);
216   }
217   bool selectBDXAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
218                            SDValue &Index) const {
219     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
220                          SystemZAddressingMode::Disp12Pair,
221                          Addr, Base, Disp, Index);
222   }
223   bool selectDynAlloc12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
224                             SDValue &Index) const {
225     return selectBDXAddr(SystemZAddressingMode::FormBDXDynAlloc,
226                          SystemZAddressingMode::Disp12Only,
227                          Addr, Base, Disp, Index);
228   }
229   bool selectBDXAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp,
230                            SDValue &Index) const {
231     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
232                          SystemZAddressingMode::Disp20Only,
233                          Addr, Base, Disp, Index);
234   }
235   bool selectBDXAddr20Only128(SDValue Addr, SDValue &Base, SDValue &Disp,
236                               SDValue &Index) const {
237     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
238                          SystemZAddressingMode::Disp20Only128,
239                          Addr, Base, Disp, Index);
240   }
241   bool selectBDXAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
242                            SDValue &Index) const {
243     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
244                          SystemZAddressingMode::Disp20Pair,
245                          Addr, Base, Disp, Index);
246   }
247   bool selectLAAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
248                           SDValue &Index) const {
249     return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
250                          SystemZAddressingMode::Disp12Pair,
251                          Addr, Base, Disp, Index);
252   }
253   bool selectLAAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
254                           SDValue &Index) const {
255     return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
256                          SystemZAddressingMode::Disp20Pair,
257                          Addr, Base, Disp, Index);
258   }
259
260   // Try to match Addr as an address with a base, 12-bit displacement
261   // and index, where the index is element Elem of a vector.
262   // Return true on success, storing the base, displacement and vector
263   // in Base, Disp and Index respectively.
264   bool selectBDVAddr12Only(SDValue Addr, SDValue Elem, SDValue &Base,
265                            SDValue &Disp, SDValue &Index) const;
266
267   // Check whether (or Op (and X InsertMask)) is effectively an insertion
268   // of X into bits InsertMask of some Y != Op.  Return true if so and
269   // set Op to that Y.
270   bool detectOrAndInsertion(SDValue &Op, uint64_t InsertMask) const;
271
272   // Try to update RxSBG so that only the bits of RxSBG.Input in Mask are used.
273   // Return true on success.
274   bool refineRxSBGMask(RxSBGOperands &RxSBG, uint64_t Mask) const;
275
276   // Try to fold some of RxSBG.Input into other fields of RxSBG.
277   // Return true on success.
278   bool expandRxSBG(RxSBGOperands &RxSBG) const;
279
280   // Return an undefined value of type VT.
281   SDValue getUNDEF(SDLoc DL, EVT VT) const;
282
283   // Convert N to VT, if it isn't already.
284   SDValue convertTo(SDLoc DL, EVT VT, SDValue N) const;
285
286   // Try to implement AND or shift node N using RISBG with the zero flag set.
287   // Return the selected node on success, otherwise return null.
288   SDNode *tryRISBGZero(SDNode *N);
289
290   // Try to use RISBG or Opcode to implement OR or XOR node N.
291   // Return the selected node on success, otherwise return null.
292   SDNode *tryRxSBG(SDNode *N, unsigned Opcode);
293
294   // If Op0 is null, then Node is a constant that can be loaded using:
295   //
296   //   (Opcode UpperVal LowerVal)
297   //
298   // If Op0 is nonnull, then Node can be implemented using:
299   //
300   //   (Opcode (Opcode Op0 UpperVal) LowerVal)
301   SDNode *splitLargeImmediate(unsigned Opcode, SDNode *Node, SDValue Op0,
302                               uint64_t UpperVal, uint64_t LowerVal);
303
304   // Try to use gather instruction Opcode to implement vector insertion N.
305   SDNode *tryGather(SDNode *N, unsigned Opcode);
306
307   // Try to use scatter instruction Opcode to implement store Store.
308   SDNode *tryScatter(StoreSDNode *Store, unsigned Opcode);
309
310   // Return true if Load and Store are loads and stores of the same size
311   // and are guaranteed not to overlap.  Such operations can be implemented
312   // using block (SS-format) instructions.
313   //
314   // Partial overlap would lead to incorrect code, since the block operations
315   // are logically bytewise, even though they have a fast path for the
316   // non-overlapping case.  We also need to avoid full overlap (i.e. two
317   // addresses that might be equal at run time) because although that case
318   // would be handled correctly, it might be implemented by millicode.
319   bool canUseBlockOperation(StoreSDNode *Store, LoadSDNode *Load) const;
320
321   // N is a (store (load Y), X) pattern.  Return true if it can use an MVC
322   // from Y to X.
323   bool storeLoadCanUseMVC(SDNode *N) const;
324
325   // N is a (store (op (load A[0]), (load A[1])), X) pattern.  Return true
326   // if A[1 - I] == X and if N can use a block operation like NC from A[I]
327   // to X.
328   bool storeLoadCanUseBlockBinary(SDNode *N, unsigned I) const;
329
330 public:
331   SystemZDAGToDAGISel(SystemZTargetMachine &TM, CodeGenOpt::Level OptLevel)
332       : SelectionDAGISel(TM, OptLevel) {}
333
334   bool runOnMachineFunction(MachineFunction &MF) override {
335     Subtarget = &MF.getSubtarget<SystemZSubtarget>();
336     return SelectionDAGISel::runOnMachineFunction(MF);
337   }
338
339   // Override MachineFunctionPass.
340   const char *getPassName() const override {
341     return "SystemZ DAG->DAG Pattern Instruction Selection";
342   }
343
344   // Override SelectionDAGISel.
345   SDNode *Select(SDNode *Node) override;
346   bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
347                                     std::vector<SDValue> &OutOps) override;
348
349   // Include the pieces autogenerated from the target description.
350   #include "SystemZGenDAGISel.inc"
351 };
352 } // end anonymous namespace
353
354 FunctionPass *llvm::createSystemZISelDag(SystemZTargetMachine &TM,
355                                          CodeGenOpt::Level OptLevel) {
356   return new SystemZDAGToDAGISel(TM, OptLevel);
357 }
358
359 // Return true if Val should be selected as a displacement for an address
360 // with range DR.  Here we're interested in the range of both the instruction
361 // described by DR and of any pairing instruction.
362 static bool selectDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
363   switch (DR) {
364   case SystemZAddressingMode::Disp12Only:
365     return isUInt<12>(Val);
366
367   case SystemZAddressingMode::Disp12Pair:
368   case SystemZAddressingMode::Disp20Only:
369   case SystemZAddressingMode::Disp20Pair:
370     return isInt<20>(Val);
371
372   case SystemZAddressingMode::Disp20Only128:
373     return isInt<20>(Val) && isInt<20>(Val + 8);
374   }
375   llvm_unreachable("Unhandled displacement range");
376 }
377
378 // Change the base or index in AM to Value, where IsBase selects
379 // between the base and index.
380 static void changeComponent(SystemZAddressingMode &AM, bool IsBase,
381                             SDValue Value) {
382   if (IsBase)
383     AM.Base = Value;
384   else
385     AM.Index = Value;
386 }
387
388 // The base or index of AM is equivalent to Value + ADJDYNALLOC,
389 // where IsBase selects between the base and index.  Try to fold the
390 // ADJDYNALLOC into AM.
391 static bool expandAdjDynAlloc(SystemZAddressingMode &AM, bool IsBase,
392                               SDValue Value) {
393   if (AM.isDynAlloc() && !AM.IncludesDynAlloc) {
394     changeComponent(AM, IsBase, Value);
395     AM.IncludesDynAlloc = true;
396     return true;
397   }
398   return false;
399 }
400
401 // The base of AM is equivalent to Base + Index.  Try to use Index as
402 // the index register.
403 static bool expandIndex(SystemZAddressingMode &AM, SDValue Base,
404                         SDValue Index) {
405   if (AM.hasIndexField() && !AM.Index.getNode()) {
406     AM.Base = Base;
407     AM.Index = Index;
408     return true;
409   }
410   return false;
411 }
412
413 // The base or index of AM is equivalent to Op0 + Op1, where IsBase selects
414 // between the base and index.  Try to fold Op1 into AM's displacement.
415 static bool expandDisp(SystemZAddressingMode &AM, bool IsBase,
416                        SDValue Op0, uint64_t Op1) {
417   // First try adjusting the displacement.
418   int64_t TestDisp = AM.Disp + Op1;
419   if (selectDisp(AM.DR, TestDisp)) {
420     changeComponent(AM, IsBase, Op0);
421     AM.Disp = TestDisp;
422     return true;
423   }
424
425   // We could consider forcing the displacement into a register and
426   // using it as an index, but it would need to be carefully tuned.
427   return false;
428 }
429
430 bool SystemZDAGToDAGISel::expandAddress(SystemZAddressingMode &AM,
431                                         bool IsBase) const {
432   SDValue N = IsBase ? AM.Base : AM.Index;
433   unsigned Opcode = N.getOpcode();
434   if (Opcode == ISD::TRUNCATE) {
435     N = N.getOperand(0);
436     Opcode = N.getOpcode();
437   }
438   if (Opcode == ISD::ADD || CurDAG->isBaseWithConstantOffset(N)) {
439     SDValue Op0 = N.getOperand(0);
440     SDValue Op1 = N.getOperand(1);
441
442     unsigned Op0Code = Op0->getOpcode();
443     unsigned Op1Code = Op1->getOpcode();
444
445     if (Op0Code == SystemZISD::ADJDYNALLOC)
446       return expandAdjDynAlloc(AM, IsBase, Op1);
447     if (Op1Code == SystemZISD::ADJDYNALLOC)
448       return expandAdjDynAlloc(AM, IsBase, Op0);
449
450     if (Op0Code == ISD::Constant)
451       return expandDisp(AM, IsBase, Op1,
452                         cast<ConstantSDNode>(Op0)->getSExtValue());
453     if (Op1Code == ISD::Constant)
454       return expandDisp(AM, IsBase, Op0,
455                         cast<ConstantSDNode>(Op1)->getSExtValue());
456
457     if (IsBase && expandIndex(AM, Op0, Op1))
458       return true;
459   }
460   if (Opcode == SystemZISD::PCREL_OFFSET) {
461     SDValue Full = N.getOperand(0);
462     SDValue Base = N.getOperand(1);
463     SDValue Anchor = Base.getOperand(0);
464     uint64_t Offset = (cast<GlobalAddressSDNode>(Full)->getOffset() -
465                        cast<GlobalAddressSDNode>(Anchor)->getOffset());
466     return expandDisp(AM, IsBase, Base, Offset);
467   }
468   return false;
469 }
470
471 // Return true if an instruction with displacement range DR should be
472 // used for displacement value Val.  selectDisp(DR, Val) must already hold.
473 static bool isValidDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
474   assert(selectDisp(DR, Val) && "Invalid displacement");
475   switch (DR) {
476   case SystemZAddressingMode::Disp12Only:
477   case SystemZAddressingMode::Disp20Only:
478   case SystemZAddressingMode::Disp20Only128:
479     return true;
480
481   case SystemZAddressingMode::Disp12Pair:
482     // Use the other instruction if the displacement is too large.
483     return isUInt<12>(Val);
484
485   case SystemZAddressingMode::Disp20Pair:
486     // Use the other instruction if the displacement is small enough.
487     return !isUInt<12>(Val);
488   }
489   llvm_unreachable("Unhandled displacement range");
490 }
491
492 // Return true if Base + Disp + Index should be performed by LA(Y).
493 static bool shouldUseLA(SDNode *Base, int64_t Disp, SDNode *Index) {
494   // Don't use LA(Y) for constants.
495   if (!Base)
496     return false;
497
498   // Always use LA(Y) for frame addresses, since we know that the destination
499   // register is almost always (perhaps always) going to be different from
500   // the frame register.
501   if (Base->getOpcode() == ISD::FrameIndex)
502     return true;
503
504   if (Disp) {
505     // Always use LA(Y) if there is a base, displacement and index.
506     if (Index)
507       return true;
508
509     // Always use LA if the displacement is small enough.  It should always
510     // be no worse than AGHI (and better if it avoids a move).
511     if (isUInt<12>(Disp))
512       return true;
513
514     // For similar reasons, always use LAY if the constant is too big for AGHI.
515     // LAY should be no worse than AGFI.
516     if (!isInt<16>(Disp))
517       return true;
518   } else {
519     // Don't use LA for plain registers.
520     if (!Index)
521       return false;
522
523     // Don't use LA for plain addition if the index operand is only used
524     // once.  It should be a natural two-operand addition in that case.
525     if (Index->hasOneUse())
526       return false;
527
528     // Prefer addition if the second operation is sign-extended, in the
529     // hope of using AGF.
530     unsigned IndexOpcode = Index->getOpcode();
531     if (IndexOpcode == ISD::SIGN_EXTEND ||
532         IndexOpcode == ISD::SIGN_EXTEND_INREG)
533       return false;
534   }
535
536   // Don't use LA for two-operand addition if either operand is only
537   // used once.  The addition instructions are better in that case.
538   if (Base->hasOneUse())
539     return false;
540
541   return true;
542 }
543
544 // Return true if Addr is suitable for AM, updating AM if so.
545 bool SystemZDAGToDAGISel::selectAddress(SDValue Addr,
546                                         SystemZAddressingMode &AM) const {
547   // Start out assuming that the address will need to be loaded separately,
548   // then try to extend it as much as we can.
549   AM.Base = Addr;
550
551   // First try treating the address as a constant.
552   if (Addr.getOpcode() == ISD::Constant &&
553       expandDisp(AM, true, SDValue(),
554                  cast<ConstantSDNode>(Addr)->getSExtValue()))
555     ;
556   else
557     // Otherwise try expanding each component.
558     while (expandAddress(AM, true) ||
559            (AM.Index.getNode() && expandAddress(AM, false)))
560       continue;
561
562   // Reject cases where it isn't profitable to use LA(Y).
563   if (AM.Form == SystemZAddressingMode::FormBDXLA &&
564       !shouldUseLA(AM.Base.getNode(), AM.Disp, AM.Index.getNode()))
565     return false;
566
567   // Reject cases where the other instruction in a pair should be used.
568   if (!isValidDisp(AM.DR, AM.Disp))
569     return false;
570
571   // Make sure that ADJDYNALLOC is included where necessary.
572   if (AM.isDynAlloc() && !AM.IncludesDynAlloc)
573     return false;
574
575   DEBUG(AM.dump());
576   return true;
577 }
578
579 // Insert a node into the DAG at least before Pos.  This will reposition
580 // the node as needed, and will assign it a node ID that is <= Pos's ID.
581 // Note that this does *not* preserve the uniqueness of node IDs!
582 // The selection DAG must no longer depend on their uniqueness when this
583 // function is used.
584 static void insertDAGNode(SelectionDAG *DAG, SDNode *Pos, SDValue N) {
585   if (N.getNode()->getNodeId() == -1 ||
586       N.getNode()->getNodeId() > Pos->getNodeId()) {
587     DAG->RepositionNode(Pos, N.getNode());
588     N.getNode()->setNodeId(Pos->getNodeId());
589   }
590 }
591
592 void SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
593                                              EVT VT, SDValue &Base,
594                                              SDValue &Disp) const {
595   Base = AM.Base;
596   if (!Base.getNode())
597     // Register 0 means "no base".  This is mostly useful for shifts.
598     Base = CurDAG->getRegister(0, VT);
599   else if (Base.getOpcode() == ISD::FrameIndex) {
600     // Lower a FrameIndex to a TargetFrameIndex.
601     int64_t FrameIndex = cast<FrameIndexSDNode>(Base)->getIndex();
602     Base = CurDAG->getTargetFrameIndex(FrameIndex, VT);
603   } else if (Base.getValueType() != VT) {
604     // Truncate values from i64 to i32, for shifts.
605     assert(VT == MVT::i32 && Base.getValueType() == MVT::i64 &&
606            "Unexpected truncation");
607     SDLoc DL(Base);
608     SDValue Trunc = CurDAG->getNode(ISD::TRUNCATE, DL, VT, Base);
609     insertDAGNode(CurDAG, Base.getNode(), Trunc);
610     Base = Trunc;
611   }
612
613   // Lower the displacement to a TargetConstant.
614   Disp = CurDAG->getTargetConstant(AM.Disp, SDLoc(Base), VT);
615 }
616
617 void SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
618                                              EVT VT, SDValue &Base,
619                                              SDValue &Disp,
620                                              SDValue &Index) const {
621   getAddressOperands(AM, VT, Base, Disp);
622
623   Index = AM.Index;
624   if (!Index.getNode())
625     // Register 0 means "no index".
626     Index = CurDAG->getRegister(0, VT);
627 }
628
629 bool SystemZDAGToDAGISel::selectBDAddr(SystemZAddressingMode::DispRange DR,
630                                        SDValue Addr, SDValue &Base,
631                                        SDValue &Disp) const {
632   SystemZAddressingMode AM(SystemZAddressingMode::FormBD, DR);
633   if (!selectAddress(Addr, AM))
634     return false;
635
636   getAddressOperands(AM, Addr.getValueType(), Base, Disp);
637   return true;
638 }
639
640 bool SystemZDAGToDAGISel::selectMVIAddr(SystemZAddressingMode::DispRange DR,
641                                         SDValue Addr, SDValue &Base,
642                                         SDValue &Disp) const {
643   SystemZAddressingMode AM(SystemZAddressingMode::FormBDXNormal, DR);
644   if (!selectAddress(Addr, AM) || AM.Index.getNode())
645     return false;
646
647   getAddressOperands(AM, Addr.getValueType(), Base, Disp);
648   return true;
649 }
650
651 bool SystemZDAGToDAGISel::selectBDXAddr(SystemZAddressingMode::AddrForm Form,
652                                         SystemZAddressingMode::DispRange DR,
653                                         SDValue Addr, SDValue &Base,
654                                         SDValue &Disp, SDValue &Index) const {
655   SystemZAddressingMode AM(Form, DR);
656   if (!selectAddress(Addr, AM))
657     return false;
658
659   getAddressOperands(AM, Addr.getValueType(), Base, Disp, Index);
660   return true;
661 }
662
663 bool SystemZDAGToDAGISel::selectBDVAddr12Only(SDValue Addr, SDValue Elem,
664                                               SDValue &Base,
665                                               SDValue &Disp,
666                                               SDValue &Index) const {
667   SDValue Regs[2];
668   if (selectBDXAddr12Only(Addr, Regs[0], Disp, Regs[1]) &&
669       Regs[0].getNode() && Regs[1].getNode()) {
670     for (unsigned int I = 0; I < 2; ++I) {
671       Base = Regs[I];
672       Index = Regs[1 - I];
673       // We can't tell here whether the index vector has the right type
674       // for the access; the caller needs to do that instead.
675       if (Index.getOpcode() == ISD::ZERO_EXTEND)
676         Index = Index.getOperand(0);
677       if (Index.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
678           Index.getOperand(1) == Elem) {
679         Index = Index.getOperand(0);
680         return true;
681       }
682     }
683   }
684   return false;
685 }
686
687 bool SystemZDAGToDAGISel::detectOrAndInsertion(SDValue &Op,
688                                                uint64_t InsertMask) const {
689   // We're only interested in cases where the insertion is into some operand
690   // of Op, rather than into Op itself.  The only useful case is an AND.
691   if (Op.getOpcode() != ISD::AND)
692     return false;
693
694   // We need a constant mask.
695   auto *MaskNode = dyn_cast<ConstantSDNode>(Op.getOperand(1).getNode());
696   if (!MaskNode)
697     return false;
698
699   // It's not an insertion of Op.getOperand(0) if the two masks overlap.
700   uint64_t AndMask = MaskNode->getZExtValue();
701   if (InsertMask & AndMask)
702     return false;
703
704   // It's only an insertion if all bits are covered or are known to be zero.
705   // The inner check covers all cases but is more expensive.
706   uint64_t Used = allOnes(Op.getValueType().getSizeInBits());
707   if (Used != (AndMask | InsertMask)) {
708     APInt KnownZero, KnownOne;
709     CurDAG->computeKnownBits(Op.getOperand(0), KnownZero, KnownOne);
710     if (Used != (AndMask | InsertMask | KnownZero.getZExtValue()))
711       return false;
712   }
713
714   Op = Op.getOperand(0);
715   return true;
716 }
717
718 bool SystemZDAGToDAGISel::refineRxSBGMask(RxSBGOperands &RxSBG,
719                                           uint64_t Mask) const {
720   const SystemZInstrInfo *TII = getInstrInfo();
721   if (RxSBG.Rotate != 0)
722     Mask = (Mask << RxSBG.Rotate) | (Mask >> (64 - RxSBG.Rotate));
723   Mask &= RxSBG.Mask;
724   if (TII->isRxSBGMask(Mask, RxSBG.BitSize, RxSBG.Start, RxSBG.End)) {
725     RxSBG.Mask = Mask;
726     return true;
727   }
728   return false;
729 }
730
731 // Return true if any bits of (RxSBG.Input & Mask) are significant.
732 static bool maskMatters(RxSBGOperands &RxSBG, uint64_t Mask) {
733   // Rotate the mask in the same way as RxSBG.Input is rotated.
734   if (RxSBG.Rotate != 0)
735     Mask = ((Mask << RxSBG.Rotate) | (Mask >> (64 - RxSBG.Rotate)));
736   return (Mask & RxSBG.Mask) != 0;
737 }
738
739 bool SystemZDAGToDAGISel::expandRxSBG(RxSBGOperands &RxSBG) const {
740   SDValue N = RxSBG.Input;
741   unsigned Opcode = N.getOpcode();
742   switch (Opcode) {
743   case ISD::AND: {
744     if (RxSBG.Opcode == SystemZ::RNSBG)
745       return false;
746
747     auto *MaskNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
748     if (!MaskNode)
749       return false;
750
751     SDValue Input = N.getOperand(0);
752     uint64_t Mask = MaskNode->getZExtValue();
753     if (!refineRxSBGMask(RxSBG, Mask)) {
754       // If some bits of Input are already known zeros, those bits will have
755       // been removed from the mask.  See if adding them back in makes the
756       // mask suitable.
757       APInt KnownZero, KnownOne;
758       CurDAG->computeKnownBits(Input, KnownZero, KnownOne);
759       Mask |= KnownZero.getZExtValue();
760       if (!refineRxSBGMask(RxSBG, Mask))
761         return false;
762     }
763     RxSBG.Input = Input;
764     return true;
765   }
766
767   case ISD::OR: {
768     if (RxSBG.Opcode != SystemZ::RNSBG)
769       return false;
770
771     auto *MaskNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
772     if (!MaskNode)
773       return false;
774
775     SDValue Input = N.getOperand(0);
776     uint64_t Mask = ~MaskNode->getZExtValue();
777     if (!refineRxSBGMask(RxSBG, Mask)) {
778       // If some bits of Input are already known ones, those bits will have
779       // been removed from the mask.  See if adding them back in makes the
780       // mask suitable.
781       APInt KnownZero, KnownOne;
782       CurDAG->computeKnownBits(Input, KnownZero, KnownOne);
783       Mask &= ~KnownOne.getZExtValue();
784       if (!refineRxSBGMask(RxSBG, Mask))
785         return false;
786     }
787     RxSBG.Input = Input;
788     return true;
789   }
790
791   case ISD::ROTL: {
792     // Any 64-bit rotate left can be merged into the RxSBG.
793     if (RxSBG.BitSize != 64 || N.getValueType() != MVT::i64)
794       return false;
795     auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
796     if (!CountNode)
797       return false;
798
799     RxSBG.Rotate = (RxSBG.Rotate + CountNode->getZExtValue()) & 63;
800     RxSBG.Input = N.getOperand(0);
801     return true;
802   }
803       
804   case ISD::ANY_EXTEND:
805     // Bits above the extended operand are don't-care.
806     RxSBG.Input = N.getOperand(0);
807     return true;
808
809   case ISD::ZERO_EXTEND:
810     if (RxSBG.Opcode != SystemZ::RNSBG) {
811       // Restrict the mask to the extended operand.
812       unsigned InnerBitSize = N.getOperand(0).getValueType().getSizeInBits();
813       if (!refineRxSBGMask(RxSBG, allOnes(InnerBitSize)))
814         return false;
815
816       RxSBG.Input = N.getOperand(0);
817       return true;
818     }
819     // Fall through.
820     
821   case ISD::SIGN_EXTEND: {
822     // Check that the extension bits are don't-care (i.e. are masked out
823     // by the final mask).
824     unsigned InnerBitSize = N.getOperand(0).getValueType().getSizeInBits();
825     if (maskMatters(RxSBG, allOnes(RxSBG.BitSize) - allOnes(InnerBitSize)))
826       return false;
827
828     RxSBG.Input = N.getOperand(0);
829     return true;
830   }
831
832   case ISD::SHL: {
833     auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
834     if (!CountNode)
835       return false;
836
837     uint64_t Count = CountNode->getZExtValue();
838     unsigned BitSize = N.getValueType().getSizeInBits();
839     if (Count < 1 || Count >= BitSize)
840       return false;
841
842     if (RxSBG.Opcode == SystemZ::RNSBG) {
843       // Treat (shl X, count) as (rotl X, size-count) as long as the bottom
844       // count bits from RxSBG.Input are ignored.
845       if (maskMatters(RxSBG, allOnes(Count)))
846         return false;
847     } else {
848       // Treat (shl X, count) as (and (rotl X, count), ~0<<count).
849       if (!refineRxSBGMask(RxSBG, allOnes(BitSize - Count) << Count))
850         return false;
851     }
852
853     RxSBG.Rotate = (RxSBG.Rotate + Count) & 63;
854     RxSBG.Input = N.getOperand(0);
855     return true;
856   }
857
858   case ISD::SRL:
859   case ISD::SRA: {
860     auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
861     if (!CountNode)
862       return false;
863
864     uint64_t Count = CountNode->getZExtValue();
865     unsigned BitSize = N.getValueType().getSizeInBits();
866     if (Count < 1 || Count >= BitSize)
867       return false;
868
869     if (RxSBG.Opcode == SystemZ::RNSBG || Opcode == ISD::SRA) {
870       // Treat (srl|sra X, count) as (rotl X, size-count) as long as the top
871       // count bits from RxSBG.Input are ignored.
872       if (maskMatters(RxSBG, allOnes(Count) << (BitSize - Count)))
873         return false;
874     } else {
875       // Treat (srl X, count), mask) as (and (rotl X, size-count), ~0>>count),
876       // which is similar to SLL above.
877       if (!refineRxSBGMask(RxSBG, allOnes(BitSize - Count)))
878         return false;
879     }
880
881     RxSBG.Rotate = (RxSBG.Rotate - Count) & 63;
882     RxSBG.Input = N.getOperand(0);
883     return true;
884   }
885   default:
886     return false;
887   }
888 }
889
890 SDValue SystemZDAGToDAGISel::getUNDEF(SDLoc DL, EVT VT) const {
891   SDNode *N = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, VT);
892   return SDValue(N, 0);
893 }
894
895 SDValue SystemZDAGToDAGISel::convertTo(SDLoc DL, EVT VT, SDValue N) const {
896   if (N.getValueType() == MVT::i32 && VT == MVT::i64)
897     return CurDAG->getTargetInsertSubreg(SystemZ::subreg_l32,
898                                          DL, VT, getUNDEF(DL, MVT::i64), N);
899   if (N.getValueType() == MVT::i64 && VT == MVT::i32)
900     return CurDAG->getTargetExtractSubreg(SystemZ::subreg_l32, DL, VT, N);
901   assert(N.getValueType() == VT && "Unexpected value types");
902   return N;
903 }
904
905 SDNode *SystemZDAGToDAGISel::tryRISBGZero(SDNode *N) {
906   SDLoc DL(N);
907   EVT VT = N->getValueType(0);
908   RxSBGOperands RISBG(SystemZ::RISBG, SDValue(N, 0));
909   unsigned Count = 0;
910   while (expandRxSBG(RISBG))
911     if (RISBG.Input.getOpcode() != ISD::ANY_EXTEND)
912       Count += 1;
913   if (Count == 0)
914     return nullptr;
915   if (Count == 1) {
916     // Prefer to use normal shift instructions over RISBG, since they can handle
917     // all cases and are sometimes shorter.
918     if (N->getOpcode() != ISD::AND)
919       return nullptr;
920
921     // Prefer register extensions like LLC over RISBG.  Also prefer to start
922     // out with normal ANDs if one instruction would be enough.  We can convert
923     // these ANDs into an RISBG later if a three-address instruction is useful.
924     if (VT == MVT::i32 ||
925         RISBG.Mask == 0xff ||
926         RISBG.Mask == 0xffff ||
927         SystemZ::isImmLF(~RISBG.Mask) ||
928         SystemZ::isImmHF(~RISBG.Mask)) {
929       // Force the new mask into the DAG, since it may include known-one bits.
930       auto *MaskN = cast<ConstantSDNode>(N->getOperand(1).getNode());
931       if (MaskN->getZExtValue() != RISBG.Mask) {
932         SDValue NewMask = CurDAG->getConstant(RISBG.Mask, DL, VT);
933         N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), NewMask);
934         return SelectCode(N);
935       }
936       return nullptr;
937     }
938   }  
939
940   unsigned Opcode = SystemZ::RISBG;
941   // Prefer RISBGN if available, since it does not clobber CC.
942   if (Subtarget->hasMiscellaneousExtensions())
943     Opcode = SystemZ::RISBGN;
944   EVT OpcodeVT = MVT::i64;
945   if (VT == MVT::i32 && Subtarget->hasHighWord()) {
946     Opcode = SystemZ::RISBMux;
947     OpcodeVT = MVT::i32;
948     RISBG.Start &= 31;
949     RISBG.End &= 31;
950   }
951   SDValue Ops[5] = {
952     getUNDEF(DL, OpcodeVT),
953     convertTo(DL, OpcodeVT, RISBG.Input),
954     CurDAG->getTargetConstant(RISBG.Start, DL, MVT::i32),
955     CurDAG->getTargetConstant(RISBG.End | 128, DL, MVT::i32),
956     CurDAG->getTargetConstant(RISBG.Rotate, DL, MVT::i32)
957   };
958   N = CurDAG->getMachineNode(Opcode, DL, OpcodeVT, Ops);
959   return convertTo(DL, VT, SDValue(N, 0)).getNode();
960 }
961
962 SDNode *SystemZDAGToDAGISel::tryRxSBG(SDNode *N, unsigned Opcode) {
963   // Try treating each operand of N as the second operand of the RxSBG
964   // and see which goes deepest.
965   RxSBGOperands RxSBG[] = {
966     RxSBGOperands(Opcode, N->getOperand(0)),
967     RxSBGOperands(Opcode, N->getOperand(1))
968   };
969   unsigned Count[] = { 0, 0 };
970   for (unsigned I = 0; I < 2; ++I)
971     while (expandRxSBG(RxSBG[I]))
972       if (RxSBG[I].Input.getOpcode() != ISD::ANY_EXTEND)
973         Count[I] += 1;
974
975   // Do nothing if neither operand is suitable.
976   if (Count[0] == 0 && Count[1] == 0)
977     return nullptr;
978
979   // Pick the deepest second operand.
980   unsigned I = Count[0] > Count[1] ? 0 : 1;
981   SDValue Op0 = N->getOperand(I ^ 1);
982
983   // Prefer IC for character insertions from memory.
984   if (Opcode == SystemZ::ROSBG && (RxSBG[I].Mask & 0xff) == 0)
985     if (auto *Load = dyn_cast<LoadSDNode>(Op0.getNode()))
986       if (Load->getMemoryVT() == MVT::i8)
987         return nullptr;
988
989   // See whether we can avoid an AND in the first operand by converting
990   // ROSBG to RISBG.
991   if (Opcode == SystemZ::ROSBG && detectOrAndInsertion(Op0, RxSBG[I].Mask)) {
992     Opcode = SystemZ::RISBG;
993     // Prefer RISBGN if available, since it does not clobber CC.
994     if (Subtarget->hasMiscellaneousExtensions())
995       Opcode = SystemZ::RISBGN;
996   }
997
998   SDLoc DL(N);
999   EVT VT = N->getValueType(0);
1000   SDValue Ops[5] = {
1001     convertTo(DL, MVT::i64, Op0),
1002     convertTo(DL, MVT::i64, RxSBG[I].Input),
1003     CurDAG->getTargetConstant(RxSBG[I].Start, DL, MVT::i32),
1004     CurDAG->getTargetConstant(RxSBG[I].End, DL, MVT::i32),
1005     CurDAG->getTargetConstant(RxSBG[I].Rotate, DL, MVT::i32)
1006   };
1007   N = CurDAG->getMachineNode(Opcode, DL, MVT::i64, Ops);
1008   return convertTo(DL, VT, SDValue(N, 0)).getNode();
1009 }
1010
1011 SDNode *SystemZDAGToDAGISel::splitLargeImmediate(unsigned Opcode, SDNode *Node,
1012                                                  SDValue Op0, uint64_t UpperVal,
1013                                                  uint64_t LowerVal) {
1014   EVT VT = Node->getValueType(0);
1015   SDLoc DL(Node);
1016   SDValue Upper = CurDAG->getConstant(UpperVal, DL, VT);
1017   if (Op0.getNode())
1018     Upper = CurDAG->getNode(Opcode, DL, VT, Op0, Upper);
1019   Upper = SDValue(Select(Upper.getNode()), 0);
1020
1021   SDValue Lower = CurDAG->getConstant(LowerVal, DL, VT);
1022   SDValue Or = CurDAG->getNode(Opcode, DL, VT, Upper, Lower);
1023   return Or.getNode();
1024 }
1025
1026 SDNode *SystemZDAGToDAGISel::tryGather(SDNode *N, unsigned Opcode) {
1027   SDValue ElemV = N->getOperand(2);
1028   auto *ElemN = dyn_cast<ConstantSDNode>(ElemV);
1029   if (!ElemN)
1030     return 0;
1031
1032   unsigned Elem = ElemN->getZExtValue();
1033   EVT VT = N->getValueType(0);
1034   if (Elem >= VT.getVectorNumElements())
1035     return 0;
1036
1037   auto *Load = dyn_cast<LoadSDNode>(N->getOperand(1));
1038   if (!Load || !Load->hasOneUse())
1039     return 0;
1040   if (Load->getMemoryVT().getSizeInBits() !=
1041       Load->getValueType(0).getSizeInBits())
1042     return 0;
1043
1044   SDValue Base, Disp, Index;
1045   if (!selectBDVAddr12Only(Load->getBasePtr(), ElemV, Base, Disp, Index) ||
1046       Index.getValueType() != VT.changeVectorElementTypeToInteger())
1047     return 0;
1048
1049   SDLoc DL(Load);
1050   SDValue Ops[] = {
1051     N->getOperand(0), Base, Disp, Index,
1052     CurDAG->getTargetConstant(Elem, DL, MVT::i32), Load->getChain()
1053   };
1054   SDNode *Res = CurDAG->getMachineNode(Opcode, DL, VT, MVT::Other, Ops);
1055   ReplaceUses(SDValue(Load, 1), SDValue(Res, 1));
1056   return Res;
1057 }
1058
1059 SDNode *SystemZDAGToDAGISel::tryScatter(StoreSDNode *Store, unsigned Opcode) {
1060   SDValue Value = Store->getValue();
1061   if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1062     return 0;
1063   if (Store->getMemoryVT().getSizeInBits() !=
1064       Value.getValueType().getSizeInBits())
1065     return 0;
1066
1067   SDValue ElemV = Value.getOperand(1);
1068   auto *ElemN = dyn_cast<ConstantSDNode>(ElemV);
1069   if (!ElemN)
1070     return 0;
1071
1072   SDValue Vec = Value.getOperand(0);
1073   EVT VT = Vec.getValueType();
1074   unsigned Elem = ElemN->getZExtValue();
1075   if (Elem >= VT.getVectorNumElements())
1076     return 0;
1077
1078   SDValue Base, Disp, Index;
1079   if (!selectBDVAddr12Only(Store->getBasePtr(), ElemV, Base, Disp, Index) ||
1080       Index.getValueType() != VT.changeVectorElementTypeToInteger())
1081     return 0;
1082
1083   SDLoc DL(Store);
1084   SDValue Ops[] = {
1085     Vec, Base, Disp, Index, CurDAG->getTargetConstant(Elem, DL, MVT::i32),
1086     Store->getChain()
1087   };
1088   return CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops);
1089 }
1090
1091 bool SystemZDAGToDAGISel::canUseBlockOperation(StoreSDNode *Store,
1092                                                LoadSDNode *Load) const {
1093   // Check that the two memory operands have the same size.
1094   if (Load->getMemoryVT() != Store->getMemoryVT())
1095     return false;
1096
1097   // Volatility stops an access from being decomposed.
1098   if (Load->isVolatile() || Store->isVolatile())
1099     return false;
1100
1101   // There's no chance of overlap if the load is invariant.
1102   if (Load->isInvariant())
1103     return true;
1104
1105   // Otherwise we need to check whether there's an alias.
1106   const Value *V1 = Load->getMemOperand()->getValue();
1107   const Value *V2 = Store->getMemOperand()->getValue();
1108   if (!V1 || !V2)
1109     return false;
1110
1111   // Reject equality.
1112   uint64_t Size = Load->getMemoryVT().getStoreSize();
1113   int64_t End1 = Load->getSrcValueOffset() + Size;
1114   int64_t End2 = Store->getSrcValueOffset() + Size;
1115   if (V1 == V2 && End1 == End2)
1116     return false;
1117
1118   return !AA->alias(MemoryLocation(V1, End1, Load->getAAInfo()),
1119                     MemoryLocation(V2, End2, Store->getAAInfo()));
1120 }
1121
1122 bool SystemZDAGToDAGISel::storeLoadCanUseMVC(SDNode *N) const {
1123   auto *Store = cast<StoreSDNode>(N);
1124   auto *Load = cast<LoadSDNode>(Store->getValue());
1125
1126   // Prefer not to use MVC if either address can use ... RELATIVE LONG
1127   // instructions.
1128   uint64_t Size = Load->getMemoryVT().getStoreSize();
1129   if (Size > 1 && Size <= 8) {
1130     // Prefer LHRL, LRL and LGRL.
1131     if (SystemZISD::isPCREL(Load->getBasePtr().getOpcode()))
1132       return false;
1133     // Prefer STHRL, STRL and STGRL.
1134     if (SystemZISD::isPCREL(Store->getBasePtr().getOpcode()))
1135       return false;
1136   }
1137
1138   return canUseBlockOperation(Store, Load);
1139 }
1140
1141 bool SystemZDAGToDAGISel::storeLoadCanUseBlockBinary(SDNode *N,
1142                                                      unsigned I) const {
1143   auto *StoreA = cast<StoreSDNode>(N);
1144   auto *LoadA = cast<LoadSDNode>(StoreA->getValue().getOperand(1 - I));
1145   auto *LoadB = cast<LoadSDNode>(StoreA->getValue().getOperand(I));
1146   return !LoadA->isVolatile() && canUseBlockOperation(StoreA, LoadB);
1147 }
1148
1149 SDNode *SystemZDAGToDAGISel::Select(SDNode *Node) {
1150   // Dump information about the Node being selected
1151   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
1152
1153   // If we have a custom node, we already have selected!
1154   if (Node->isMachineOpcode()) {
1155     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
1156     Node->setNodeId(-1);
1157     return nullptr;
1158   }
1159
1160   unsigned Opcode = Node->getOpcode();
1161   SDNode *ResNode = nullptr;
1162   switch (Opcode) {
1163   case ISD::OR:
1164     if (Node->getOperand(1).getOpcode() != ISD::Constant)
1165       ResNode = tryRxSBG(Node, SystemZ::ROSBG);
1166     goto or_xor;
1167
1168   case ISD::XOR:
1169     if (Node->getOperand(1).getOpcode() != ISD::Constant)
1170       ResNode = tryRxSBG(Node, SystemZ::RXSBG);
1171     // Fall through.
1172   or_xor:
1173     // If this is a 64-bit operation in which both 32-bit halves are nonzero,
1174     // split the operation into two.
1175     if (!ResNode && Node->getValueType(0) == MVT::i64)
1176       if (auto *Op1 = dyn_cast<ConstantSDNode>(Node->getOperand(1))) {
1177         uint64_t Val = Op1->getZExtValue();
1178         if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val))
1179           Node = splitLargeImmediate(Opcode, Node, Node->getOperand(0),
1180                                      Val - uint32_t(Val), uint32_t(Val));
1181       }
1182     break;
1183
1184   case ISD::AND:
1185     if (Node->getOperand(1).getOpcode() != ISD::Constant)
1186       ResNode = tryRxSBG(Node, SystemZ::RNSBG);
1187     // Fall through.
1188   case ISD::ROTL:
1189   case ISD::SHL:
1190   case ISD::SRL:
1191   case ISD::ZERO_EXTEND:
1192     if (!ResNode)
1193       ResNode = tryRISBGZero(Node);
1194     break;
1195
1196   case ISD::Constant:
1197     // If this is a 64-bit constant that is out of the range of LLILF,
1198     // LLIHF and LGFI, split it into two 32-bit pieces.
1199     if (Node->getValueType(0) == MVT::i64) {
1200       uint64_t Val = cast<ConstantSDNode>(Node)->getZExtValue();
1201       if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val) && !isInt<32>(Val))
1202         Node = splitLargeImmediate(ISD::OR, Node, SDValue(),
1203                                    Val - uint32_t(Val), uint32_t(Val));
1204     }
1205     break;
1206
1207   case SystemZISD::SELECT_CCMASK: {
1208     SDValue Op0 = Node->getOperand(0);
1209     SDValue Op1 = Node->getOperand(1);
1210     // Prefer to put any load first, so that it can be matched as a
1211     // conditional load.
1212     if (Op1.getOpcode() == ISD::LOAD && Op0.getOpcode() != ISD::LOAD) {
1213       SDValue CCValid = Node->getOperand(2);
1214       SDValue CCMask = Node->getOperand(3);
1215       uint64_t ConstCCValid =
1216         cast<ConstantSDNode>(CCValid.getNode())->getZExtValue();
1217       uint64_t ConstCCMask =
1218         cast<ConstantSDNode>(CCMask.getNode())->getZExtValue();
1219       // Invert the condition.
1220       CCMask = CurDAG->getConstant(ConstCCValid ^ ConstCCMask, SDLoc(Node),
1221                                    CCMask.getValueType());
1222       SDValue Op4 = Node->getOperand(4);
1223       Node = CurDAG->UpdateNodeOperands(Node, Op1, Op0, CCValid, CCMask, Op4);
1224     }
1225     break;
1226   }
1227
1228   case ISD::INSERT_VECTOR_ELT: {
1229     EVT VT = Node->getValueType(0);
1230     unsigned ElemBitSize = VT.getVectorElementType().getSizeInBits();
1231     if (ElemBitSize == 32)
1232       ResNode = tryGather(Node, SystemZ::VGEF);
1233     else if (ElemBitSize == 64)
1234       ResNode = tryGather(Node, SystemZ::VGEG);
1235     break;
1236   }
1237
1238   case ISD::STORE: {
1239     auto *Store = cast<StoreSDNode>(Node);
1240     unsigned ElemBitSize = Store->getValue().getValueType().getSizeInBits();
1241     if (ElemBitSize == 32)
1242       ResNode = tryScatter(Store, SystemZ::VSCEF);
1243     else if (ElemBitSize == 64)
1244       ResNode = tryScatter(Store, SystemZ::VSCEG);
1245     break;
1246   }
1247   }
1248
1249   // Select the default instruction
1250   if (!ResNode)
1251     ResNode = SelectCode(Node);
1252
1253   DEBUG(errs() << "=> ";
1254         if (ResNode == nullptr || ResNode == Node)
1255           Node->dump(CurDAG);
1256         else
1257           ResNode->dump(CurDAG);
1258         errs() << "\n";
1259         );
1260   return ResNode;
1261 }
1262
1263 bool SystemZDAGToDAGISel::
1264 SelectInlineAsmMemoryOperand(const SDValue &Op,
1265                              unsigned ConstraintID,
1266                              std::vector<SDValue> &OutOps) {
1267   switch(ConstraintID) {
1268   default:
1269     llvm_unreachable("Unexpected asm memory constraint");
1270   case InlineAsm::Constraint_i:
1271   case InlineAsm::Constraint_m:
1272   case InlineAsm::Constraint_Q:
1273   case InlineAsm::Constraint_R:
1274   case InlineAsm::Constraint_S:
1275   case InlineAsm::Constraint_T:
1276     // Accept addresses with short displacements, which are compatible
1277     // with Q, R, S and T.  But keep the index operand for future expansion.
1278     SDValue Base, Disp, Index;
1279     if (selectBDXAddr(SystemZAddressingMode::FormBD,
1280                       SystemZAddressingMode::Disp12Only,
1281                       Op, Base, Disp, Index)) {
1282       OutOps.push_back(Base);
1283       OutOps.push_back(Disp);
1284       OutOps.push_back(Index);
1285       return false;
1286     }
1287     break;
1288   }
1289   return true;
1290 }