[SystemZ] Use RNSBG
[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 namespace {
23 // Used to build addressing modes.
24 struct SystemZAddressingMode {
25   // The shape of the address.
26   enum AddrForm {
27     // base+displacement
28     FormBD,
29
30     // base+displacement+index for load and store operands
31     FormBDXNormal,
32
33     // base+displacement+index for load address operands
34     FormBDXLA,
35
36     // base+displacement+index+ADJDYNALLOC
37     FormBDXDynAlloc
38   };
39   AddrForm Form;
40
41   // The type of displacement.  The enum names here correspond directly
42   // to the definitions in SystemZOperand.td.  We could split them into
43   // flags -- single/pair, 128-bit, etc. -- but it hardly seems worth it.
44   enum DispRange {
45     Disp12Only,
46     Disp12Pair,
47     Disp20Only,
48     Disp20Only128,
49     Disp20Pair
50   };
51   DispRange DR;
52
53   // The parts of the address.  The address is equivalent to:
54   //
55   //     Base + Disp + Index + (IncludesDynAlloc ? ADJDYNALLOC : 0)
56   SDValue Base;
57   int64_t Disp;
58   SDValue Index;
59   bool IncludesDynAlloc;
60
61   SystemZAddressingMode(AddrForm form, DispRange dr)
62     : Form(form), DR(dr), Base(), Disp(0), Index(),
63       IncludesDynAlloc(false) {}
64
65   // True if the address can have an index register.
66   bool hasIndexField() { return Form != FormBD; }
67
68   // True if the address can (and must) include ADJDYNALLOC.
69   bool isDynAlloc() { return Form == FormBDXDynAlloc; }
70
71   void dump() {
72     errs() << "SystemZAddressingMode " << this << '\n';
73
74     errs() << " Base ";
75     if (Base.getNode() != 0)
76       Base.getNode()->dump();
77     else
78       errs() << "null\n";
79
80     if (hasIndexField()) {
81       errs() << " Index ";
82       if (Index.getNode() != 0)
83         Index.getNode()->dump();
84       else
85         errs() << "null\n";
86     }
87
88     errs() << " Disp " << Disp;
89     if (IncludesDynAlloc)
90       errs() << " + ADJDYNALLOC";
91     errs() << '\n';
92   }
93 };
94
95 // Return a mask with Count low bits set.
96 static uint64_t allOnes(unsigned int Count) {
97   return Count == 0 ? 0 : (uint64_t(1) << (Count - 1) << 1) - 1;
98 }
99
100 // Represents operands 2 to 5 of the ROTATE AND ... SELECTED BITS operation
101 // given by Opcode.  The operands are: Input (R2), Start (I3), End (I4) and
102 // Rotate (I5).  The combined operand value is effectively:
103 //
104 //   (or (rotl Input, Rotate), ~Mask)
105 //
106 // for RNSBG and:
107 //
108 //   (and (rotl Input, Rotate), Mask)
109 //
110 // otherwise.  The value has BitSize bits.
111 struct RxSBGOperands {
112   RxSBGOperands(unsigned Op, SDValue N)
113     : Opcode(Op), BitSize(N.getValueType().getSizeInBits()),
114       Mask(allOnes(BitSize)), Input(N), Start(64 - BitSize), End(63),
115       Rotate(0) {}
116
117   unsigned Opcode;
118   unsigned BitSize;
119   uint64_t Mask;
120   SDValue Input;
121   unsigned Start;
122   unsigned End;
123   unsigned Rotate;
124 };
125
126 class SystemZDAGToDAGISel : public SelectionDAGISel {
127   const SystemZTargetLowering &Lowering;
128   const SystemZSubtarget &Subtarget;
129
130   // Used by SystemZOperands.td to create integer constants.
131   inline SDValue getImm(const SDNode *Node, uint64_t Imm) {
132     return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
133   }
134
135   // Try to fold more of the base or index of AM into AM, where IsBase
136   // selects between the base and index.
137   bool expandAddress(SystemZAddressingMode &AM, bool IsBase);
138
139   // Try to describe N in AM, returning true on success.
140   bool selectAddress(SDValue N, SystemZAddressingMode &AM);
141
142   // Extract individual target operands from matched address AM.
143   void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
144                           SDValue &Base, SDValue &Disp);
145   void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
146                           SDValue &Base, SDValue &Disp, SDValue &Index);
147
148   // Try to match Addr as a FormBD address with displacement type DR.
149   // Return true on success, storing the base and displacement in
150   // Base and Disp respectively.
151   bool selectBDAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
152                     SDValue &Base, SDValue &Disp);
153
154   // Try to match Addr as a FormBDX* address of form Form with
155   // displacement type DR.  Return true on success, storing the base,
156   // displacement and index in Base, Disp and Index respectively.
157   bool selectBDXAddr(SystemZAddressingMode::AddrForm Form,
158                      SystemZAddressingMode::DispRange DR, SDValue Addr,
159                      SDValue &Base, SDValue &Disp, SDValue &Index);
160
161   // PC-relative address matching routines used by SystemZOperands.td.
162   bool selectPCRelAddress(SDValue Addr, SDValue &Target) {
163     if (Addr.getOpcode() == SystemZISD::PCREL_WRAPPER) {
164       Target = Addr.getOperand(0);
165       return true;
166     }
167     return false;
168   }
169
170   // BD matching routines used by SystemZOperands.td.
171   bool selectBDAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp) {
172     return selectBDAddr(SystemZAddressingMode::Disp12Only, Addr, Base, Disp);
173   }
174   bool selectBDAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) {
175     return selectBDAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
176   }
177   bool selectBDAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp) {
178     return selectBDAddr(SystemZAddressingMode::Disp20Only, Addr, Base, Disp);
179   }
180   bool selectBDAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) {
181     return selectBDAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
182   }
183
184   // BDX matching routines used by SystemZOperands.td.
185   bool selectBDXAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
186                            SDValue &Index) {
187     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
188                          SystemZAddressingMode::Disp12Only,
189                          Addr, Base, Disp, Index);
190   }
191   bool selectBDXAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
192                            SDValue &Index) {
193     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
194                          SystemZAddressingMode::Disp12Pair,
195                          Addr, Base, Disp, Index);
196   }
197   bool selectDynAlloc12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
198                             SDValue &Index) {
199     return selectBDXAddr(SystemZAddressingMode::FormBDXDynAlloc,
200                          SystemZAddressingMode::Disp12Only,
201                          Addr, Base, Disp, Index);
202   }
203   bool selectBDXAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp,
204                            SDValue &Index) {
205     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
206                          SystemZAddressingMode::Disp20Only,
207                          Addr, Base, Disp, Index);
208   }
209   bool selectBDXAddr20Only128(SDValue Addr, SDValue &Base, SDValue &Disp,
210                               SDValue &Index) {
211     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
212                          SystemZAddressingMode::Disp20Only128,
213                          Addr, Base, Disp, Index);
214   }
215   bool selectBDXAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
216                            SDValue &Index) {
217     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
218                          SystemZAddressingMode::Disp20Pair,
219                          Addr, Base, Disp, Index);
220   }
221   bool selectLAAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
222                           SDValue &Index) {
223     return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
224                          SystemZAddressingMode::Disp12Pair,
225                          Addr, Base, Disp, Index);
226   }
227   bool selectLAAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
228                           SDValue &Index) {
229     return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
230                          SystemZAddressingMode::Disp20Pair,
231                          Addr, Base, Disp, Index);
232   }
233
234   // Check whether (or Op (and X InsertMask)) is effectively an insertion
235   // of X into bits InsertMask of some Y != Op.  Return true if so and
236   // set Op to that Y.
237   bool detectOrAndInsertion(SDValue &Op, uint64_t InsertMask);
238
239   // Try to fold some of RxSBG.Input into other fields of RxSBG.
240   // Return true on success.
241   bool expandRxSBG(RxSBGOperands &RxSBG);
242
243   // Return an undefined i64 value.
244   SDValue getUNDEF64(SDLoc DL);
245
246   // Convert N to VT, if it isn't already.
247   SDValue convertTo(SDLoc DL, EVT VT, SDValue N);
248
249   // Try to implement AND or shift node N using RISBG with the zero flag set.
250   // Return the selected node on success, otherwise return null.
251   SDNode *tryRISBGZero(SDNode *N);
252
253   // Try to use RISBG or Opcode to implement OR or XOR node N.
254   // Return the selected node on success, otherwise return null.
255   SDNode *tryRxSBG(SDNode *N, unsigned Opcode);
256
257   // If Op0 is null, then Node is a constant that can be loaded using:
258   //
259   //   (Opcode UpperVal LowerVal)
260   //
261   // If Op0 is nonnull, then Node can be implemented using:
262   //
263   //   (Opcode (Opcode Op0 UpperVal) LowerVal)
264   SDNode *splitLargeImmediate(unsigned Opcode, SDNode *Node, SDValue Op0,
265                               uint64_t UpperVal, uint64_t LowerVal);
266
267   bool storeLoadCanUseMVC(SDNode *N) const;
268
269 public:
270   SystemZDAGToDAGISel(SystemZTargetMachine &TM, CodeGenOpt::Level OptLevel)
271     : SelectionDAGISel(TM, OptLevel),
272       Lowering(*TM.getTargetLowering()),
273       Subtarget(*TM.getSubtargetImpl()) { }
274
275   // Override MachineFunctionPass.
276   virtual const char *getPassName() const LLVM_OVERRIDE {
277     return "SystemZ DAG->DAG Pattern Instruction Selection";
278   }
279
280   // Override SelectionDAGISel.
281   virtual SDNode *Select(SDNode *Node) LLVM_OVERRIDE;
282   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
283                                             char ConstraintCode,
284                                             std::vector<SDValue> &OutOps)
285     LLVM_OVERRIDE;
286
287   // Include the pieces autogenerated from the target description.
288   #include "SystemZGenDAGISel.inc"
289 };
290 } // end anonymous namespace
291
292 FunctionPass *llvm::createSystemZISelDag(SystemZTargetMachine &TM,
293                                          CodeGenOpt::Level OptLevel) {
294   return new SystemZDAGToDAGISel(TM, OptLevel);
295 }
296
297 // Return true if Val should be selected as a displacement for an address
298 // with range DR.  Here we're interested in the range of both the instruction
299 // described by DR and of any pairing instruction.
300 static bool selectDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
301   switch (DR) {
302   case SystemZAddressingMode::Disp12Only:
303     return isUInt<12>(Val);
304
305   case SystemZAddressingMode::Disp12Pair:
306   case SystemZAddressingMode::Disp20Only:
307   case SystemZAddressingMode::Disp20Pair:
308     return isInt<20>(Val);
309
310   case SystemZAddressingMode::Disp20Only128:
311     return isInt<20>(Val) && isInt<20>(Val + 8);
312   }
313   llvm_unreachable("Unhandled displacement range");
314 }
315
316 // Change the base or index in AM to Value, where IsBase selects
317 // between the base and index.
318 static void changeComponent(SystemZAddressingMode &AM, bool IsBase,
319                             SDValue Value) {
320   if (IsBase)
321     AM.Base = Value;
322   else
323     AM.Index = Value;
324 }
325
326 // The base or index of AM is equivalent to Value + ADJDYNALLOC,
327 // where IsBase selects between the base and index.  Try to fold the
328 // ADJDYNALLOC into AM.
329 static bool expandAdjDynAlloc(SystemZAddressingMode &AM, bool IsBase,
330                               SDValue Value) {
331   if (AM.isDynAlloc() && !AM.IncludesDynAlloc) {
332     changeComponent(AM, IsBase, Value);
333     AM.IncludesDynAlloc = true;
334     return true;
335   }
336   return false;
337 }
338
339 // The base of AM is equivalent to Base + Index.  Try to use Index as
340 // the index register.
341 static bool expandIndex(SystemZAddressingMode &AM, SDValue Base,
342                         SDValue Index) {
343   if (AM.hasIndexField() && !AM.Index.getNode()) {
344     AM.Base = Base;
345     AM.Index = Index;
346     return true;
347   }
348   return false;
349 }
350
351 // The base or index of AM is equivalent to Op0 + Op1, where IsBase selects
352 // between the base and index.  Try to fold Op1 into AM's displacement.
353 static bool expandDisp(SystemZAddressingMode &AM, bool IsBase,
354                        SDValue Op0, ConstantSDNode *Op1) {
355   // First try adjusting the displacement.
356   int64_t TestDisp = AM.Disp + Op1->getSExtValue();
357   if (selectDisp(AM.DR, TestDisp)) {
358     changeComponent(AM, IsBase, Op0);
359     AM.Disp = TestDisp;
360     return true;
361   }
362
363   // We could consider forcing the displacement into a register and
364   // using it as an index, but it would need to be carefully tuned.
365   return false;
366 }
367
368 bool SystemZDAGToDAGISel::expandAddress(SystemZAddressingMode &AM,
369                                         bool IsBase) {
370   SDValue N = IsBase ? AM.Base : AM.Index;
371   unsigned Opcode = N.getOpcode();
372   if (Opcode == ISD::TRUNCATE) {
373     N = N.getOperand(0);
374     Opcode = N.getOpcode();
375   }
376   if (Opcode == ISD::ADD || CurDAG->isBaseWithConstantOffset(N)) {
377     SDValue Op0 = N.getOperand(0);
378     SDValue Op1 = N.getOperand(1);
379
380     unsigned Op0Code = Op0->getOpcode();
381     unsigned Op1Code = Op1->getOpcode();
382
383     if (Op0Code == SystemZISD::ADJDYNALLOC)
384       return expandAdjDynAlloc(AM, IsBase, Op1);
385     if (Op1Code == SystemZISD::ADJDYNALLOC)
386       return expandAdjDynAlloc(AM, IsBase, Op0);
387
388     if (Op0Code == ISD::Constant)
389       return expandDisp(AM, IsBase, Op1, cast<ConstantSDNode>(Op0));
390     if (Op1Code == ISD::Constant)
391       return expandDisp(AM, IsBase, Op0, cast<ConstantSDNode>(Op1));
392
393     if (IsBase && expandIndex(AM, Op0, Op1))
394       return true;
395   }
396   return false;
397 }
398
399 // Return true if an instruction with displacement range DR should be
400 // used for displacement value Val.  selectDisp(DR, Val) must already hold.
401 static bool isValidDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
402   assert(selectDisp(DR, Val) && "Invalid displacement");
403   switch (DR) {
404   case SystemZAddressingMode::Disp12Only:
405   case SystemZAddressingMode::Disp20Only:
406   case SystemZAddressingMode::Disp20Only128:
407     return true;
408
409   case SystemZAddressingMode::Disp12Pair:
410     // Use the other instruction if the displacement is too large.
411     return isUInt<12>(Val);
412
413   case SystemZAddressingMode::Disp20Pair:
414     // Use the other instruction if the displacement is small enough.
415     return !isUInt<12>(Val);
416   }
417   llvm_unreachable("Unhandled displacement range");
418 }
419
420 // Return true if Base + Disp + Index should be performed by LA(Y).
421 static bool shouldUseLA(SDNode *Base, int64_t Disp, SDNode *Index) {
422   // Don't use LA(Y) for constants.
423   if (!Base)
424     return false;
425
426   // Always use LA(Y) for frame addresses, since we know that the destination
427   // register is almost always (perhaps always) going to be different from
428   // the frame register.
429   if (Base->getOpcode() == ISD::FrameIndex)
430     return true;
431
432   if (Disp) {
433     // Always use LA(Y) if there is a base, displacement and index.
434     if (Index)
435       return true;
436
437     // Always use LA if the displacement is small enough.  It should always
438     // be no worse than AGHI (and better if it avoids a move).
439     if (isUInt<12>(Disp))
440       return true;
441
442     // For similar reasons, always use LAY if the constant is too big for AGHI.
443     // LAY should be no worse than AGFI.
444     if (!isInt<16>(Disp))
445       return true;
446   } else {
447     // Don't use LA for plain registers.
448     if (!Index)
449       return false;
450
451     // Don't use LA for plain addition if the index operand is only used
452     // once.  It should be a natural two-operand addition in that case.
453     if (Index->hasOneUse())
454       return false;
455
456     // Prefer addition if the second operation is sign-extended, in the
457     // hope of using AGF.
458     unsigned IndexOpcode = Index->getOpcode();
459     if (IndexOpcode == ISD::SIGN_EXTEND ||
460         IndexOpcode == ISD::SIGN_EXTEND_INREG)
461       return false;
462   }
463
464   // Don't use LA for two-operand addition if either operand is only
465   // used once.  The addition instructions are better in that case.
466   if (Base->hasOneUse())
467     return false;
468
469   return true;
470 }
471
472 // Return true if Addr is suitable for AM, updating AM if so.
473 bool SystemZDAGToDAGISel::selectAddress(SDValue Addr,
474                                         SystemZAddressingMode &AM) {
475   // Start out assuming that the address will need to be loaded separately,
476   // then try to extend it as much as we can.
477   AM.Base = Addr;
478
479   // First try treating the address as a constant.
480   if (Addr.getOpcode() == ISD::Constant &&
481       expandDisp(AM, true, SDValue(), cast<ConstantSDNode>(Addr)))
482     ;
483   else
484     // Otherwise try expanding each component.
485     while (expandAddress(AM, true) ||
486            (AM.Index.getNode() && expandAddress(AM, false)))
487       continue;
488
489   // Reject cases where it isn't profitable to use LA(Y).
490   if (AM.Form == SystemZAddressingMode::FormBDXLA &&
491       !shouldUseLA(AM.Base.getNode(), AM.Disp, AM.Index.getNode()))
492     return false;
493
494   // Reject cases where the other instruction in a pair should be used.
495   if (!isValidDisp(AM.DR, AM.Disp))
496     return false;
497
498   // Make sure that ADJDYNALLOC is included where necessary.
499   if (AM.isDynAlloc() && !AM.IncludesDynAlloc)
500     return false;
501
502   DEBUG(AM.dump());
503   return true;
504 }
505
506 // Insert a node into the DAG at least before Pos.  This will reposition
507 // the node as needed, and will assign it a node ID that is <= Pos's ID.
508 // Note that this does *not* preserve the uniqueness of node IDs!
509 // The selection DAG must no longer depend on their uniqueness when this
510 // function is used.
511 static void insertDAGNode(SelectionDAG *DAG, SDNode *Pos, SDValue N) {
512   if (N.getNode()->getNodeId() == -1 ||
513       N.getNode()->getNodeId() > Pos->getNodeId()) {
514     DAG->RepositionNode(Pos, N.getNode());
515     N.getNode()->setNodeId(Pos->getNodeId());
516   }
517 }
518
519 void SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
520                                              EVT VT, SDValue &Base,
521                                              SDValue &Disp) {
522   Base = AM.Base;
523   if (!Base.getNode())
524     // Register 0 means "no base".  This is mostly useful for shifts.
525     Base = CurDAG->getRegister(0, VT);
526   else if (Base.getOpcode() == ISD::FrameIndex) {
527     // Lower a FrameIndex to a TargetFrameIndex.
528     int64_t FrameIndex = cast<FrameIndexSDNode>(Base)->getIndex();
529     Base = CurDAG->getTargetFrameIndex(FrameIndex, VT);
530   } else if (Base.getValueType() != VT) {
531     // Truncate values from i64 to i32, for shifts.
532     assert(VT == MVT::i32 && Base.getValueType() == MVT::i64 &&
533            "Unexpected truncation");
534     SDLoc DL(Base);
535     SDValue Trunc = CurDAG->getNode(ISD::TRUNCATE, DL, VT, Base);
536     insertDAGNode(CurDAG, Base.getNode(), Trunc);
537     Base = Trunc;
538   }
539
540   // Lower the displacement to a TargetConstant.
541   Disp = CurDAG->getTargetConstant(AM.Disp, VT);
542 }
543
544 void SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
545                                              EVT VT, SDValue &Base,
546                                              SDValue &Disp, SDValue &Index) {
547   getAddressOperands(AM, VT, Base, Disp);
548
549   Index = AM.Index;
550   if (!Index.getNode())
551     // Register 0 means "no index".
552     Index = CurDAG->getRegister(0, VT);
553 }
554
555 bool SystemZDAGToDAGISel::selectBDAddr(SystemZAddressingMode::DispRange DR,
556                                        SDValue Addr, SDValue &Base,
557                                        SDValue &Disp) {
558   SystemZAddressingMode AM(SystemZAddressingMode::FormBD, DR);
559   if (!selectAddress(Addr, AM))
560     return false;
561
562   getAddressOperands(AM, Addr.getValueType(), Base, Disp);
563   return true;
564 }
565
566 bool SystemZDAGToDAGISel::selectBDXAddr(SystemZAddressingMode::AddrForm Form,
567                                         SystemZAddressingMode::DispRange DR,
568                                         SDValue Addr, SDValue &Base,
569                                         SDValue &Disp, SDValue &Index) {
570   SystemZAddressingMode AM(Form, DR);
571   if (!selectAddress(Addr, AM))
572     return false;
573
574   getAddressOperands(AM, Addr.getValueType(), Base, Disp, Index);
575   return true;
576 }
577
578 bool SystemZDAGToDAGISel::detectOrAndInsertion(SDValue &Op,
579                                                uint64_t InsertMask) {
580   // We're only interested in cases where the insertion is into some operand
581   // of Op, rather than into Op itself.  The only useful case is an AND.
582   if (Op.getOpcode() != ISD::AND)
583     return false;
584
585   // We need a constant mask.
586   ConstantSDNode *MaskNode =
587     dyn_cast<ConstantSDNode>(Op.getOperand(1).getNode());
588   if (!MaskNode)
589     return false;
590
591   // It's not an insertion of Op.getOperand(0) if the two masks overlap.
592   uint64_t AndMask = MaskNode->getZExtValue();
593   if (InsertMask & AndMask)
594     return false;
595
596   // It's only an insertion if all bits are covered or are known to be zero.
597   // The inner check covers all cases but is more expensive.
598   uint64_t Used = allOnes(Op.getValueType().getSizeInBits());
599   if (Used != (AndMask | InsertMask)) {
600     APInt KnownZero, KnownOne;
601     CurDAG->ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne);
602     if (Used != (AndMask | InsertMask | KnownZero.getZExtValue()))
603       return false;
604   }
605
606   Op = Op.getOperand(0);
607   return true;
608 }
609
610 // Return true if Mask matches the regexp 0*1+0*, given that zero masks
611 // have already been filtered out.  Store the first set bit in LSB and
612 // the number of set bits in Length if so.
613 static bool isStringOfOnes(uint64_t Mask, unsigned &LSB, unsigned &Length) {
614   unsigned First = findFirstSet(Mask);
615   uint64_t Top = (Mask >> First) + 1;
616   if ((Top & -Top) == Top) {
617     LSB = First;
618     Length = findFirstSet(Top);
619     return true;
620   }
621   return false;
622 }
623
624 // Try to update RxSBG so that only the bits of RxSBG.Input in Mask are used.
625 // Return true on success.
626 static bool refineRxSBGMask(RxSBGOperands &RxSBG, uint64_t Mask) {
627   if (RxSBG.Rotate != 0)
628     Mask = (Mask << RxSBG.Rotate) | (Mask >> (64 - RxSBG.Rotate));
629   Mask &= RxSBG.Mask;
630
631   // Reject trivial all-zero masks.
632   if (Mask == 0)
633     return false;
634
635   // Handle the 1+0+ or 0+1+0* cases.  Start then specifies the index of
636   // the msb and End specifies the index of the lsb.
637   unsigned LSB, Length;
638   if (isStringOfOnes(Mask, LSB, Length)) {
639     RxSBG.Mask = Mask;
640     RxSBG.Start = 63 - (LSB + Length - 1);
641     RxSBG.End = 63 - LSB;
642     return true;
643   }
644
645   // Handle the wrap-around 1+0+1+ cases.  Start then specifies the msb
646   // of the low 1s and End specifies the lsb of the high 1s.
647   if (isStringOfOnes(Mask ^ allOnes(RxSBG.BitSize), LSB, Length)) {
648     assert(LSB > 0 && "Bottom bit must be set");
649     assert(LSB + Length < RxSBG.BitSize && "Top bit must be set");
650     RxSBG.Mask = Mask;
651     RxSBG.Start = 63 - (LSB - 1);
652     RxSBG.End = 63 - (LSB + Length);
653     return true;
654   }
655
656   return false;
657 }
658
659 // RxSBG.Input is a shift of Count bits in the direction given by IsLeft.
660 // Return true if the result depends on the signs or zeros that are
661 // shifted in.
662 static bool shiftedInBitsMatter(RxSBGOperands &RxSBG, uint64_t Count,
663                                 bool IsLeft) {
664   // Work out which bits of the shift result are zeros or sign copies.
665   uint64_t ShiftedIn = allOnes(Count);
666   if (!IsLeft)
667     ShiftedIn <<= RxSBG.BitSize - Count;
668
669   // Rotate that mask in the same way as RxSBG.Input is rotated.
670   if (RxSBG.Rotate != 0)
671     ShiftedIn = ((ShiftedIn << RxSBG.Rotate) |
672                  (ShiftedIn >> (64 - RxSBG.Rotate)));
673
674   // Fail if any of the zero or sign bits are used.
675   return (ShiftedIn & RxSBG.Mask) != 0;
676 }
677
678 bool SystemZDAGToDAGISel::expandRxSBG(RxSBGOperands &RxSBG) {
679   SDValue N = RxSBG.Input;
680   unsigned Opcode = N.getOpcode();
681   switch (Opcode) {
682   case ISD::AND: {
683     if (RxSBG.Opcode == SystemZ::RNSBG)
684       return false;
685
686     ConstantSDNode *MaskNode =
687       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
688     if (!MaskNode)
689       return false;
690
691     SDValue Input = N.getOperand(0);
692     uint64_t Mask = MaskNode->getZExtValue();
693     if (!refineRxSBGMask(RxSBG, Mask)) {
694       // If some bits of Input are already known zeros, those bits will have
695       // been removed from the mask.  See if adding them back in makes the
696       // mask suitable.
697       APInt KnownZero, KnownOne;
698       CurDAG->ComputeMaskedBits(Input, KnownZero, KnownOne);
699       Mask |= KnownZero.getZExtValue();
700       if (!refineRxSBGMask(RxSBG, Mask))
701         return false;
702     }
703     RxSBG.Input = Input;
704     return true;
705   }
706
707   case ISD::OR: {
708     if (RxSBG.Opcode != SystemZ::RNSBG)
709       return false;
710
711     ConstantSDNode *MaskNode =
712       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
713     if (!MaskNode)
714       return false;
715
716     SDValue Input = N.getOperand(0);
717     uint64_t Mask = ~MaskNode->getZExtValue();
718     if (!refineRxSBGMask(RxSBG, Mask)) {
719       // If some bits of Input are already known ones, those bits will have
720       // been removed from the mask.  See if adding them back in makes the
721       // mask suitable.
722       APInt KnownZero, KnownOne;
723       CurDAG->ComputeMaskedBits(Input, KnownZero, KnownOne);
724       Mask &= ~KnownOne.getZExtValue();
725       if (!refineRxSBGMask(RxSBG, Mask))
726         return false;
727     }
728     RxSBG.Input = Input;
729     return true;
730   }
731
732   case ISD::ROTL: {
733     // Any 64-bit rotate left can be merged into the RxSBG.
734     if (RxSBG.BitSize != 64)
735       return false;
736     ConstantSDNode *CountNode
737       = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
738     if (!CountNode)
739       return false;
740
741     RxSBG.Rotate = (RxSBG.Rotate + CountNode->getZExtValue()) & 63;
742     RxSBG.Input = N.getOperand(0);
743     return true;
744   }
745       
746   case ISD::SHL: {
747     ConstantSDNode *CountNode =
748       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
749     if (!CountNode)
750       return false;
751
752     uint64_t Count = CountNode->getZExtValue();
753     if (Count < 1 || Count >= RxSBG.BitSize)
754       return false;
755
756     if (RxSBG.Opcode == SystemZ::RNSBG) {
757       // Treat (shl X, count) as (rotl X, size-count) as long as the bottom
758       // count bits from RxSBG.Input are ignored.
759       if (shiftedInBitsMatter(RxSBG, Count, true))
760         return false;
761     } else {
762       // Treat (shl X, count) as (and (rotl X, count), ~0<<count).
763       if (!refineRxSBGMask(RxSBG, allOnes(RxSBG.BitSize - Count) << Count))
764         return false;
765     }
766
767     RxSBG.Rotate = (RxSBG.Rotate + Count) & 63;
768     RxSBG.Input = N.getOperand(0);
769     return true;
770   }
771
772   case ISD::SRL:
773   case ISD::SRA: {
774     ConstantSDNode *CountNode =
775       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
776     if (!CountNode)
777       return false;
778
779     uint64_t Count = CountNode->getZExtValue();
780     if (Count < 1 || Count >= RxSBG.BitSize)
781       return false;
782
783     if (RxSBG.Opcode == SystemZ::RNSBG || Opcode == ISD::SRA) {
784       // Treat (srl|sra X, count) as (rotl X, size-count) as long as the top
785       // count bits from RxSBG.Input are ignored.
786       if (shiftedInBitsMatter(RxSBG, Count, false))
787         return false;
788     } else {
789       // Treat (srl X, count), mask) as (and (rotl X, size-count), ~0>>count),
790       // which is similar to SLL above.
791       if (!refineRxSBGMask(RxSBG, allOnes(RxSBG.BitSize - Count)))
792         return false;
793     }
794
795     RxSBG.Rotate = (RxSBG.Rotate - Count) & 63;
796     RxSBG.Input = N.getOperand(0);
797     return true;
798   }
799   default:
800     return false;
801   }
802 }
803
804 SDValue SystemZDAGToDAGISel::getUNDEF64(SDLoc DL) {
805   SDNode *N = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64);
806   return SDValue(N, 0);
807 }
808
809 SDValue SystemZDAGToDAGISel::convertTo(SDLoc DL, EVT VT, SDValue N) {
810   if (N.getValueType() == MVT::i32 && VT == MVT::i64) {
811     SDValue Index = CurDAG->getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
812     SDNode *Insert = CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG,
813                                             DL, VT, getUNDEF64(DL), N, Index);
814     return SDValue(Insert, 0);
815   }
816   if (N.getValueType() == MVT::i64 && VT == MVT::i32) {
817     SDValue Index = CurDAG->getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
818     SDNode *Extract = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
819                                              DL, VT, N, Index);
820     return SDValue(Extract, 0);
821   }
822   assert(N.getValueType() == VT && "Unexpected value types");
823   return N;
824 }
825
826 SDNode *SystemZDAGToDAGISel::tryRISBGZero(SDNode *N) {
827   RxSBGOperands RISBG(SystemZ::RISBG, SDValue(N, 0));
828   unsigned Count = 0;
829   while (expandRxSBG(RISBG))
830     Count += 1;
831   // Prefer to use normal shift instructions over RISBG, since they can handle
832   // all cases and are sometimes shorter.  Prefer to use RISBG for ANDs though,
833   // since it is effectively a three-operand instruction in this case,
834   // and since it can handle some masks that AND IMMEDIATE can't.
835   if (Count < (N->getOpcode() == ISD::AND ? 1U : 2U))
836     return 0;
837
838   // Prefer register extensions like LLC over RISBG.
839   if (RISBG.Rotate == 0 &&
840       (RISBG.Start == 32 || RISBG.Start == 48 || RISBG.Start == 56) &&
841       RISBG.End == 63)
842     return 0;
843
844   EVT VT = N->getValueType(0);
845   SDValue Ops[5] = {
846     getUNDEF64(SDLoc(N)),
847     convertTo(SDLoc(N), MVT::i64, RISBG.Input),
848     CurDAG->getTargetConstant(RISBG.Start, MVT::i32),
849     CurDAG->getTargetConstant(RISBG.End | 128, MVT::i32),
850     CurDAG->getTargetConstant(RISBG.Rotate, MVT::i32)
851   };
852   N = CurDAG->getMachineNode(SystemZ::RISBG, SDLoc(N), MVT::i64, Ops);
853   return convertTo(SDLoc(N), VT, SDValue(N, 0)).getNode();
854 }
855
856 SDNode *SystemZDAGToDAGISel::tryRxSBG(SDNode *N, unsigned Opcode) {
857   // Try treating each operand of N as the second operand of the RxSBG
858   // and see which goes deepest.
859   RxSBGOperands RxSBG[] = {
860     RxSBGOperands(Opcode, N->getOperand(0)),
861     RxSBGOperands(Opcode, N->getOperand(1))
862   };
863   unsigned Count[] = { 0, 0 };
864   for (unsigned I = 0; I < 2; ++I)
865     while (expandRxSBG(RxSBG[I]))
866       Count[I] += 1;
867
868   // Do nothing if neither operand is suitable.
869   if (Count[0] == 0 && Count[1] == 0)
870     return 0;
871
872   // Pick the deepest second operand.
873   unsigned I = Count[0] > Count[1] ? 0 : 1;
874   SDValue Op0 = N->getOperand(I ^ 1);
875
876   // Prefer IC for character insertions from memory.
877   if (Opcode == SystemZ::ROSBG && (RxSBG[I].Mask & 0xff) == 0)
878     if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Op0.getNode()))
879       if (Load->getMemoryVT() == MVT::i8)
880         return 0;
881
882   // See whether we can avoid an AND in the first operand by converting
883   // ROSBG to RISBG.
884   if (Opcode == SystemZ::ROSBG && detectOrAndInsertion(Op0, RxSBG[I].Mask))
885     Opcode = SystemZ::RISBG;
886            
887   EVT VT = N->getValueType(0);
888   SDValue Ops[5] = {
889     convertTo(SDLoc(N), MVT::i64, Op0),
890     convertTo(SDLoc(N), MVT::i64, RxSBG[I].Input),
891     CurDAG->getTargetConstant(RxSBG[I].Start, MVT::i32),
892     CurDAG->getTargetConstant(RxSBG[I].End, MVT::i32),
893     CurDAG->getTargetConstant(RxSBG[I].Rotate, MVT::i32)
894   };
895   N = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i64, Ops);
896   return convertTo(SDLoc(N), VT, SDValue(N, 0)).getNode();
897 }
898
899 SDNode *SystemZDAGToDAGISel::splitLargeImmediate(unsigned Opcode, SDNode *Node,
900                                                  SDValue Op0, uint64_t UpperVal,
901                                                  uint64_t LowerVal) {
902   EVT VT = Node->getValueType(0);
903   SDLoc DL(Node);
904   SDValue Upper = CurDAG->getConstant(UpperVal, VT);
905   if (Op0.getNode())
906     Upper = CurDAG->getNode(Opcode, DL, VT, Op0, Upper);
907   Upper = SDValue(Select(Upper.getNode()), 0);
908
909   SDValue Lower = CurDAG->getConstant(LowerVal, VT);
910   SDValue Or = CurDAG->getNode(Opcode, DL, VT, Upper, Lower);
911   return Or.getNode();
912 }
913
914 // N is a (store (load ...), ...) pattern.  Return true if it can use MVC.
915 bool SystemZDAGToDAGISel::storeLoadCanUseMVC(SDNode *N) const {
916   StoreSDNode *Store = cast<StoreSDNode>(N);
917   LoadSDNode *Load = cast<LoadSDNode>(Store->getValue().getNode());
918
919   // MVC is logically a bytewise copy, so can't be used for volatile accesses.
920   if (Load->isVolatile() || Store->isVolatile())
921     return false;
922
923   // Prefer not to use MVC if either address can use ... RELATIVE LONG
924   // instructions.
925   assert(Load->getMemoryVT() == Store->getMemoryVT() &&
926          "Should already have checked that the types match");
927   uint64_t Size = Load->getMemoryVT().getStoreSize();
928   if (Size > 1 && Size <= 8) {
929     // Prefer LHRL, LRL and LGRL.
930     if (Load->getBasePtr().getOpcode() == SystemZISD::PCREL_WRAPPER)
931       return false;
932     // Prefer STHRL, STRL and STGRL.
933     if (Store->getBasePtr().getOpcode() == SystemZISD::PCREL_WRAPPER)
934       return false;
935   }
936
937   // There's no chance of overlap if the load is invariant.
938   if (Load->isInvariant())
939     return true;
940
941   // If both operands are aligned, they must be equal or not overlap.
942   if (Load->getAlignment() >= Size && Store->getAlignment() >= Size)
943     return true;
944
945   // Otherwise we need to check whether there's an alias.
946   const Value *V1 = Load->getSrcValue();
947   const Value *V2 = Store->getSrcValue();
948   if (!V1 || !V2)
949     return false;
950
951   int64_t End1 = Load->getSrcValueOffset() + Size;
952   int64_t End2 = Store->getSrcValueOffset() + Size;
953   return !AA->alias(AliasAnalysis::Location(V1, End1, Load->getTBAAInfo()),
954                     AliasAnalysis::Location(V2, End2, Store->getTBAAInfo()));
955 }
956
957 SDNode *SystemZDAGToDAGISel::Select(SDNode *Node) {
958   // Dump information about the Node being selected
959   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
960
961   // If we have a custom node, we already have selected!
962   if (Node->isMachineOpcode()) {
963     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
964     return 0;
965   }
966
967   unsigned Opcode = Node->getOpcode();
968   SDNode *ResNode = 0;
969   switch (Opcode) {
970   case ISD::OR:
971     if (Node->getOperand(1).getOpcode() != ISD::Constant)
972       ResNode = tryRxSBG(Node, SystemZ::ROSBG);
973     goto or_xor;
974
975   case ISD::XOR:
976     if (Node->getOperand(1).getOpcode() != ISD::Constant)
977       ResNode = tryRxSBG(Node, SystemZ::RXSBG);
978     // Fall through.
979   or_xor:
980     // If this is a 64-bit operation in which both 32-bit halves are nonzero,
981     // split the operation into two.
982     if (!ResNode && Node->getValueType(0) == MVT::i64)
983       if (ConstantSDNode *Op1 = dyn_cast<ConstantSDNode>(Node->getOperand(1))) {
984         uint64_t Val = Op1->getZExtValue();
985         if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val))
986           Node = splitLargeImmediate(Opcode, Node, Node->getOperand(0),
987                                      Val - uint32_t(Val), uint32_t(Val));
988       }
989     break;
990
991   case ISD::AND:
992     if (Node->getOperand(1).getOpcode() != ISD::Constant)
993       ResNode = tryRxSBG(Node, SystemZ::RNSBG);
994     // Fall through.
995   case ISD::ROTL:
996   case ISD::SHL:
997   case ISD::SRL:
998     if (!ResNode)
999       ResNode = tryRISBGZero(Node);
1000     break;
1001
1002   case ISD::Constant:
1003     // If this is a 64-bit constant that is out of the range of LLILF,
1004     // LLIHF and LGFI, split it into two 32-bit pieces.
1005     if (Node->getValueType(0) == MVT::i64) {
1006       uint64_t Val = cast<ConstantSDNode>(Node)->getZExtValue();
1007       if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val) && !isInt<32>(Val))
1008         Node = splitLargeImmediate(ISD::OR, Node, SDValue(),
1009                                    Val - uint32_t(Val), uint32_t(Val));
1010     }
1011     break;
1012
1013   case ISD::ATOMIC_LOAD_SUB:
1014     // Try to convert subtractions of constants to additions.
1015     if (ConstantSDNode *Op2 = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
1016       uint64_t Value = -Op2->getZExtValue();
1017       EVT VT = Node->getValueType(0);
1018       if (VT == MVT::i32 || isInt<32>(Value)) {
1019         SDValue Ops[] = { Node->getOperand(0), Node->getOperand(1),
1020                           CurDAG->getConstant(int32_t(Value), VT) };
1021         Node = CurDAG->MorphNodeTo(Node, ISD::ATOMIC_LOAD_ADD,
1022                                    Node->getVTList(), Ops, array_lengthof(Ops));
1023       }
1024     }
1025     break;
1026   }
1027
1028   // Select the default instruction
1029   if (!ResNode)
1030     ResNode = SelectCode(Node);
1031
1032   DEBUG(errs() << "=> ";
1033         if (ResNode == NULL || ResNode == Node)
1034           Node->dump(CurDAG);
1035         else
1036           ResNode->dump(CurDAG);
1037         errs() << "\n";
1038         );
1039   return ResNode;
1040 }
1041
1042 bool SystemZDAGToDAGISel::
1043 SelectInlineAsmMemoryOperand(const SDValue &Op,
1044                              char ConstraintCode,
1045                              std::vector<SDValue> &OutOps) {
1046   assert(ConstraintCode == 'm' && "Unexpected constraint code");
1047   // Accept addresses with short displacements, which are compatible
1048   // with Q, R, S and T.  But keep the index operand for future expansion.
1049   SDValue Base, Disp, Index;
1050   if (!selectBDXAddr(SystemZAddressingMode::FormBD,
1051                      SystemZAddressingMode::Disp12Only,
1052                      Op, Base, Disp, Index))
1053     return true;
1054   OutOps.push_back(Base);
1055   OutOps.push_back(Disp);
1056   OutOps.push_back(Index);
1057   return false;
1058 }