a319e1c6aa8f7be4f2ba234c81c20f97f57b3ea5
[oota-llvm.git] / lib / Target / SystemZ / SystemZInstrInfo.cpp
1 //===-- SystemZInstrInfo.cpp - SystemZ instruction information ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the SystemZ implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SystemZInstrInfo.h"
15 #include "SystemZInstrBuilder.h"
16 #include "SystemZTargetMachine.h"
17 #include "llvm/CodeGen/LiveVariables.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19
20 using namespace llvm;
21
22 #define GET_INSTRINFO_CTOR_DTOR
23 #define GET_INSTRMAP_INFO
24 #include "SystemZGenInstrInfo.inc"
25
26 // Return a mask with Count low bits set.
27 static uint64_t allOnes(unsigned int Count) {
28   return Count == 0 ? 0 : (uint64_t(1) << (Count - 1) << 1) - 1;
29 }
30
31 // Reg should be a 32-bit GPR.  Return true if it is a high register rather
32 // than a low register.
33 static bool isHighReg(unsigned int Reg) {
34   if (SystemZ::GRH32BitRegClass.contains(Reg))
35     return true;
36   assert(SystemZ::GR32BitRegClass.contains(Reg) && "Invalid GRX32");
37   return false;
38 }
39
40 // Pin the vtable to this file.
41 void SystemZInstrInfo::anchor() {}
42
43 SystemZInstrInfo::SystemZInstrInfo(SystemZSubtarget &sti)
44   : SystemZGenInstrInfo(SystemZ::ADJCALLSTACKDOWN, SystemZ::ADJCALLSTACKUP),
45     RI(), STI(sti) {
46 }
47
48 // MI is a 128-bit load or store.  Split it into two 64-bit loads or stores,
49 // each having the opcode given by NewOpcode.
50 void SystemZInstrInfo::splitMove(MachineBasicBlock::iterator MI,
51                                  unsigned NewOpcode) const {
52   MachineBasicBlock *MBB = MI->getParent();
53   MachineFunction &MF = *MBB->getParent();
54
55   // Get two load or store instructions.  Use the original instruction for one
56   // of them (arbitrarily the second here) and create a clone for the other.
57   MachineInstr *EarlierMI = MF.CloneMachineInstr(MI);
58   MBB->insert(MI, EarlierMI);
59
60   // Set up the two 64-bit registers.
61   MachineOperand &HighRegOp = EarlierMI->getOperand(0);
62   MachineOperand &LowRegOp = MI->getOperand(0);
63   HighRegOp.setReg(RI.getSubReg(HighRegOp.getReg(), SystemZ::subreg_h64));
64   LowRegOp.setReg(RI.getSubReg(LowRegOp.getReg(), SystemZ::subreg_l64));
65
66   // The address in the first (high) instruction is already correct.
67   // Adjust the offset in the second (low) instruction.
68   MachineOperand &HighOffsetOp = EarlierMI->getOperand(2);
69   MachineOperand &LowOffsetOp = MI->getOperand(2);
70   LowOffsetOp.setImm(LowOffsetOp.getImm() + 8);
71
72   // Set the opcodes.
73   unsigned HighOpcode = getOpcodeForOffset(NewOpcode, HighOffsetOp.getImm());
74   unsigned LowOpcode = getOpcodeForOffset(NewOpcode, LowOffsetOp.getImm());
75   assert(HighOpcode && LowOpcode && "Both offsets should be in range");
76
77   EarlierMI->setDesc(get(HighOpcode));
78   MI->setDesc(get(LowOpcode));
79 }
80
81 // Split ADJDYNALLOC instruction MI.
82 void SystemZInstrInfo::splitAdjDynAlloc(MachineBasicBlock::iterator MI) const {
83   MachineBasicBlock *MBB = MI->getParent();
84   MachineFunction &MF = *MBB->getParent();
85   MachineFrameInfo *MFFrame = MF.getFrameInfo();
86   MachineOperand &OffsetMO = MI->getOperand(2);
87
88   uint64_t Offset = (MFFrame->getMaxCallFrameSize() +
89                      SystemZMC::CallFrameSize +
90                      OffsetMO.getImm());
91   unsigned NewOpcode = getOpcodeForOffset(SystemZ::LA, Offset);
92   assert(NewOpcode && "No support for huge argument lists yet");
93   MI->setDesc(get(NewOpcode));
94   OffsetMO.setImm(Offset);
95 }
96
97 // MI is an RI-style pseudo instruction.  Replace it with LowOpcode
98 // if the first operand is a low GR32 and HighOpcode if the first operand
99 // is a high GR32.  ConvertHigh is true if LowOpcode takes a signed operand
100 // and HighOpcode takes an unsigned 32-bit operand.  In those cases,
101 // MI has the same kind of operand as LowOpcode, so needs to be converted
102 // if HighOpcode is used.
103 void SystemZInstrInfo::expandRIPseudo(MachineInstr *MI, unsigned LowOpcode,
104                                       unsigned HighOpcode,
105                                       bool ConvertHigh) const {
106   unsigned Reg = MI->getOperand(0).getReg();
107   bool IsHigh = isHighReg(Reg);
108   MI->setDesc(get(IsHigh ? HighOpcode : LowOpcode));
109   if (IsHigh && ConvertHigh)
110     MI->getOperand(1).setImm(uint32_t(MI->getOperand(1).getImm()));
111 }
112
113 // MI is a three-operand RIE-style pseudo instruction.  Replace it with
114 // LowOpcodeK if the registers are both low GR32s, otherwise use a move
115 // followed by HighOpcode or LowOpcode, depending on whether the target
116 // is a high or low GR32.
117 void SystemZInstrInfo::expandRIEPseudo(MachineInstr *MI, unsigned LowOpcode,
118                                        unsigned LowOpcodeK,
119                                        unsigned HighOpcode) const {
120   unsigned DestReg = MI->getOperand(0).getReg();
121   unsigned SrcReg = MI->getOperand(1).getReg();
122   bool DestIsHigh = isHighReg(DestReg);
123   bool SrcIsHigh = isHighReg(SrcReg);
124   if (!DestIsHigh && !SrcIsHigh)
125     MI->setDesc(get(LowOpcodeK));
126   else {
127     emitGRX32Move(*MI->getParent(), MI, MI->getDebugLoc(),
128                   DestReg, SrcReg, SystemZ::LR, 32,
129                   MI->getOperand(1).isKill());
130     MI->setDesc(get(DestIsHigh ? HighOpcode : LowOpcode));
131     MI->getOperand(1).setReg(DestReg);
132     MI->tieOperands(0, 1);
133   }
134 }
135
136 // MI is an RXY-style pseudo instruction.  Replace it with LowOpcode
137 // if the first operand is a low GR32 and HighOpcode if the first operand
138 // is a high GR32.
139 void SystemZInstrInfo::expandRXYPseudo(MachineInstr *MI, unsigned LowOpcode,
140                                        unsigned HighOpcode) const {
141   unsigned Reg = MI->getOperand(0).getReg();
142   unsigned Opcode = getOpcodeForOffset(isHighReg(Reg) ? HighOpcode : LowOpcode,
143                                        MI->getOperand(2).getImm());
144   MI->setDesc(get(Opcode));
145 }
146
147 // MI is an RR-style pseudo instruction that zero-extends the low Size bits
148 // of one GRX32 into another.  Replace it with LowOpcode if both operands
149 // are low registers, otherwise use RISB[LH]G.
150 void SystemZInstrInfo::expandZExtPseudo(MachineInstr *MI, unsigned LowOpcode,
151                                         unsigned Size) const {
152   emitGRX32Move(*MI->getParent(), MI, MI->getDebugLoc(),
153                 MI->getOperand(0).getReg(), MI->getOperand(1).getReg(),
154                 LowOpcode, Size, MI->getOperand(1).isKill());
155   MI->eraseFromParent();
156 }
157
158 // Emit a zero-extending move from 32-bit GPR SrcReg to 32-bit GPR
159 // DestReg before MBBI in MBB.  Use LowLowOpcode when both DestReg and SrcReg
160 // are low registers, otherwise use RISB[LH]G.  Size is the number of bits
161 // taken from the low end of SrcReg (8 for LLCR, 16 for LLHR and 32 for LR).
162 // KillSrc is true if this move is the last use of SrcReg.
163 void SystemZInstrInfo::emitGRX32Move(MachineBasicBlock &MBB,
164                                      MachineBasicBlock::iterator MBBI,
165                                      DebugLoc DL, unsigned DestReg,
166                                      unsigned SrcReg, unsigned LowLowOpcode,
167                                      unsigned Size, bool KillSrc) const {
168   unsigned Opcode;
169   bool DestIsHigh = isHighReg(DestReg);
170   bool SrcIsHigh = isHighReg(SrcReg);
171   if (DestIsHigh && SrcIsHigh)
172     Opcode = SystemZ::RISBHH;
173   else if (DestIsHigh && !SrcIsHigh)
174     Opcode = SystemZ::RISBHL;
175   else if (!DestIsHigh && SrcIsHigh)
176     Opcode = SystemZ::RISBLH;
177   else {
178     BuildMI(MBB, MBBI, DL, get(LowLowOpcode), DestReg)
179       .addReg(SrcReg, getKillRegState(KillSrc));
180     return;
181   }
182   unsigned Rotate = (DestIsHigh != SrcIsHigh ? 32 : 0);
183   BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
184     .addReg(DestReg, RegState::Undef)
185     .addReg(SrcReg, getKillRegState(KillSrc))
186     .addImm(32 - Size).addImm(128 + 31).addImm(Rotate);
187 }
188
189 // If MI is a simple load or store for a frame object, return the register
190 // it loads or stores and set FrameIndex to the index of the frame object.
191 // Return 0 otherwise.
192 //
193 // Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
194 static int isSimpleMove(const MachineInstr *MI, int &FrameIndex,
195                         unsigned Flag) {
196   const MCInstrDesc &MCID = MI->getDesc();
197   if ((MCID.TSFlags & Flag) &&
198       MI->getOperand(1).isFI() &&
199       MI->getOperand(2).getImm() == 0 &&
200       MI->getOperand(3).getReg() == 0) {
201     FrameIndex = MI->getOperand(1).getIndex();
202     return MI->getOperand(0).getReg();
203   }
204   return 0;
205 }
206
207 unsigned SystemZInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
208                                                int &FrameIndex) const {
209   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXLoad);
210 }
211
212 unsigned SystemZInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
213                                               int &FrameIndex) const {
214   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXStore);
215 }
216
217 bool SystemZInstrInfo::isStackSlotCopy(const MachineInstr *MI,
218                                        int &DestFrameIndex,
219                                        int &SrcFrameIndex) const {
220   // Check for MVC 0(Length,FI1),0(FI2)
221   const MachineFrameInfo *MFI = MI->getParent()->getParent()->getFrameInfo();
222   if (MI->getOpcode() != SystemZ::MVC ||
223       !MI->getOperand(0).isFI() ||
224       MI->getOperand(1).getImm() != 0 ||
225       !MI->getOperand(3).isFI() ||
226       MI->getOperand(4).getImm() != 0)
227     return false;
228
229   // Check that Length covers the full slots.
230   int64_t Length = MI->getOperand(2).getImm();
231   unsigned FI1 = MI->getOperand(0).getIndex();
232   unsigned FI2 = MI->getOperand(3).getIndex();
233   if (MFI->getObjectSize(FI1) != Length ||
234       MFI->getObjectSize(FI2) != Length)
235     return false;
236
237   DestFrameIndex = FI1;
238   SrcFrameIndex = FI2;
239   return true;
240 }
241
242 bool SystemZInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
243                                      MachineBasicBlock *&TBB,
244                                      MachineBasicBlock *&FBB,
245                                      SmallVectorImpl<MachineOperand> &Cond,
246                                      bool AllowModify) const {
247   // Most of the code and comments here are boilerplate.
248
249   // Start from the bottom of the block and work up, examining the
250   // terminator instructions.
251   MachineBasicBlock::iterator I = MBB.end();
252   while (I != MBB.begin()) {
253     --I;
254     if (I->isDebugValue())
255       continue;
256
257     // Working from the bottom, when we see a non-terminator instruction, we're
258     // done.
259     if (!isUnpredicatedTerminator(I))
260       break;
261
262     // A terminator that isn't a branch can't easily be handled by this
263     // analysis.
264     if (!I->isBranch())
265       return true;
266
267     // Can't handle indirect branches.
268     SystemZII::Branch Branch(getBranchInfo(I));
269     if (!Branch.Target->isMBB())
270       return true;
271
272     // Punt on compound branches.
273     if (Branch.Type != SystemZII::BranchNormal)
274       return true;
275
276     if (Branch.CCMask == SystemZ::CCMASK_ANY) {
277       // Handle unconditional branches.
278       if (!AllowModify) {
279         TBB = Branch.Target->getMBB();
280         continue;
281       }
282
283       // If the block has any instructions after a JMP, delete them.
284       while (std::next(I) != MBB.end())
285         std::next(I)->eraseFromParent();
286
287       Cond.clear();
288       FBB = nullptr;
289
290       // Delete the JMP if it's equivalent to a fall-through.
291       if (MBB.isLayoutSuccessor(Branch.Target->getMBB())) {
292         TBB = nullptr;
293         I->eraseFromParent();
294         I = MBB.end();
295         continue;
296       }
297
298       // TBB is used to indicate the unconditinal destination.
299       TBB = Branch.Target->getMBB();
300       continue;
301     }
302
303     // Working from the bottom, handle the first conditional branch.
304     if (Cond.empty()) {
305       // FIXME: add X86-style branch swap
306       FBB = TBB;
307       TBB = Branch.Target->getMBB();
308       Cond.push_back(MachineOperand::CreateImm(Branch.CCValid));
309       Cond.push_back(MachineOperand::CreateImm(Branch.CCMask));
310       continue;
311     }
312
313     // Handle subsequent conditional branches.
314     assert(Cond.size() == 2 && TBB && "Should have seen a conditional branch");
315
316     // Only handle the case where all conditional branches branch to the same
317     // destination.
318     if (TBB != Branch.Target->getMBB())
319       return true;
320
321     // If the conditions are the same, we can leave them alone.
322     unsigned OldCCValid = Cond[0].getImm();
323     unsigned OldCCMask = Cond[1].getImm();
324     if (OldCCValid == Branch.CCValid && OldCCMask == Branch.CCMask)
325       continue;
326
327     // FIXME: Try combining conditions like X86 does.  Should be easy on Z!
328     return false;
329   }
330
331   return false;
332 }
333
334 unsigned SystemZInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
335   // Most of the code and comments here are boilerplate.
336   MachineBasicBlock::iterator I = MBB.end();
337   unsigned Count = 0;
338
339   while (I != MBB.begin()) {
340     --I;
341     if (I->isDebugValue())
342       continue;
343     if (!I->isBranch())
344       break;
345     if (!getBranchInfo(I).Target->isMBB())
346       break;
347     // Remove the branch.
348     I->eraseFromParent();
349     I = MBB.end();
350     ++Count;
351   }
352
353   return Count;
354 }
355
356 bool SystemZInstrInfo::
357 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
358   assert(Cond.size() == 2 && "Invalid condition");
359   Cond[1].setImm(Cond[1].getImm() ^ Cond[0].getImm());
360   return false;
361 }
362
363 unsigned
364 SystemZInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
365                                MachineBasicBlock *FBB,
366                                ArrayRef<MachineOperand> Cond,
367                                DebugLoc DL) const {
368   // In this function we output 32-bit branches, which should always
369   // have enough range.  They can be shortened and relaxed by later code
370   // in the pipeline, if desired.
371
372   // Shouldn't be a fall through.
373   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
374   assert((Cond.size() == 2 || Cond.size() == 0) &&
375          "SystemZ branch conditions have one component!");
376
377   if (Cond.empty()) {
378     // Unconditional branch?
379     assert(!FBB && "Unconditional branch with multiple successors!");
380     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(TBB);
381     return 1;
382   }
383
384   // Conditional branch.
385   unsigned Count = 0;
386   unsigned CCValid = Cond[0].getImm();
387   unsigned CCMask = Cond[1].getImm();
388   BuildMI(&MBB, DL, get(SystemZ::BRC))
389     .addImm(CCValid).addImm(CCMask).addMBB(TBB);
390   ++Count;
391
392   if (FBB) {
393     // Two-way Conditional branch. Insert the second branch.
394     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(FBB);
395     ++Count;
396   }
397   return Count;
398 }
399
400 bool SystemZInstrInfo::analyzeCompare(const MachineInstr *MI,
401                                       unsigned &SrcReg, unsigned &SrcReg2,
402                                       int &Mask, int &Value) const {
403   assert(MI->isCompare() && "Caller should have checked for a comparison");
404
405   if (MI->getNumExplicitOperands() == 2 &&
406       MI->getOperand(0).isReg() &&
407       MI->getOperand(1).isImm()) {
408     SrcReg = MI->getOperand(0).getReg();
409     SrcReg2 = 0;
410     Value = MI->getOperand(1).getImm();
411     Mask = ~0;
412     return true;
413   }
414
415   return false;
416 }
417
418 // If Reg is a virtual register, return its definition, otherwise return null.
419 static MachineInstr *getDef(unsigned Reg,
420                             const MachineRegisterInfo *MRI) {
421   if (TargetRegisterInfo::isPhysicalRegister(Reg))
422     return nullptr;
423   return MRI->getUniqueVRegDef(Reg);
424 }
425
426 // Return true if MI is a shift of type Opcode by Imm bits.
427 static bool isShift(MachineInstr *MI, unsigned Opcode, int64_t Imm) {
428   return (MI->getOpcode() == Opcode &&
429           !MI->getOperand(2).getReg() &&
430           MI->getOperand(3).getImm() == Imm);
431 }
432
433 // If the destination of MI has no uses, delete it as dead.
434 static void eraseIfDead(MachineInstr *MI, const MachineRegisterInfo *MRI) {
435   if (MRI->use_nodbg_empty(MI->getOperand(0).getReg()))
436     MI->eraseFromParent();
437 }
438
439 // Compare compares SrcReg against zero.  Check whether SrcReg contains
440 // the result of an IPM sequence whose input CC survives until Compare,
441 // and whether Compare is therefore redundant.  Delete it and return
442 // true if so.
443 static bool removeIPMBasedCompare(MachineInstr *Compare, unsigned SrcReg,
444                                   const MachineRegisterInfo *MRI,
445                                   const TargetRegisterInfo *TRI) {
446   MachineInstr *LGFR = nullptr;
447   MachineInstr *RLL = getDef(SrcReg, MRI);
448   if (RLL && RLL->getOpcode() == SystemZ::LGFR) {
449     LGFR = RLL;
450     RLL = getDef(LGFR->getOperand(1).getReg(), MRI);
451   }
452   if (!RLL || !isShift(RLL, SystemZ::RLL, 31))
453     return false;
454
455   MachineInstr *SRL = getDef(RLL->getOperand(1).getReg(), MRI);
456   if (!SRL || !isShift(SRL, SystemZ::SRL, SystemZ::IPM_CC))
457     return false;
458
459   MachineInstr *IPM = getDef(SRL->getOperand(1).getReg(), MRI);
460   if (!IPM || IPM->getOpcode() != SystemZ::IPM)
461     return false;
462
463   // Check that there are no assignments to CC between the IPM and Compare,
464   if (IPM->getParent() != Compare->getParent())
465     return false;
466   MachineBasicBlock::iterator MBBI = IPM, MBBE = Compare;
467   for (++MBBI; MBBI != MBBE; ++MBBI) {
468     MachineInstr *MI = MBBI;
469     if (MI->modifiesRegister(SystemZ::CC, TRI))
470       return false;
471   }
472
473   Compare->eraseFromParent();
474   if (LGFR)
475     eraseIfDead(LGFR, MRI);
476   eraseIfDead(RLL, MRI);
477   eraseIfDead(SRL, MRI);
478   eraseIfDead(IPM, MRI);
479
480   return true;
481 }
482
483 bool
484 SystemZInstrInfo::optimizeCompareInstr(MachineInstr *Compare,
485                                        unsigned SrcReg, unsigned SrcReg2,
486                                        int Mask, int Value,
487                                        const MachineRegisterInfo *MRI) const {
488   assert(!SrcReg2 && "Only optimizing constant comparisons so far");
489   bool IsLogical = (Compare->getDesc().TSFlags & SystemZII::IsLogical) != 0;
490   if (Value == 0 &&
491       !IsLogical &&
492       removeIPMBasedCompare(Compare, SrcReg, MRI, &RI))
493     return true;
494   return false;
495 }
496
497 // If Opcode is a move that has a conditional variant, return that variant,
498 // otherwise return 0.
499 static unsigned getConditionalMove(unsigned Opcode) {
500   switch (Opcode) {
501   case SystemZ::LR:  return SystemZ::LOCR;
502   case SystemZ::LGR: return SystemZ::LOCGR;
503   default:           return 0;
504   }
505 }
506
507 bool SystemZInstrInfo::isPredicable(MachineInstr *MI) const {
508   unsigned Opcode = MI->getOpcode();
509   if (STI.hasLoadStoreOnCond() &&
510       getConditionalMove(Opcode))
511     return true;
512   return false;
513 }
514
515 bool SystemZInstrInfo::
516 isProfitableToIfCvt(MachineBasicBlock &MBB,
517                     unsigned NumCycles, unsigned ExtraPredCycles,
518                     BranchProbability Probability) const {
519   // For now only convert single instructions.
520   return NumCycles == 1;
521 }
522
523 bool SystemZInstrInfo::
524 isProfitableToIfCvt(MachineBasicBlock &TMBB,
525                     unsigned NumCyclesT, unsigned ExtraPredCyclesT,
526                     MachineBasicBlock &FMBB,
527                     unsigned NumCyclesF, unsigned ExtraPredCyclesF,
528                     BranchProbability Probability) const {
529   // For now avoid converting mutually-exclusive cases.
530   return false;
531 }
532
533 bool SystemZInstrInfo::
534 PredicateInstruction(MachineInstr *MI, ArrayRef<MachineOperand> Pred) const {
535   assert(Pred.size() == 2 && "Invalid condition");
536   unsigned CCValid = Pred[0].getImm();
537   unsigned CCMask = Pred[1].getImm();
538   assert(CCMask > 0 && CCMask < 15 && "Invalid predicate");
539   unsigned Opcode = MI->getOpcode();
540   if (STI.hasLoadStoreOnCond()) {
541     if (unsigned CondOpcode = getConditionalMove(Opcode)) {
542       MI->setDesc(get(CondOpcode));
543       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
544         .addImm(CCValid).addImm(CCMask)
545         .addReg(SystemZ::CC, RegState::Implicit);
546       return true;
547     }
548   }
549   return false;
550 }
551
552 void SystemZInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
553                                    MachineBasicBlock::iterator MBBI,
554                                    DebugLoc DL, unsigned DestReg,
555                                    unsigned SrcReg, bool KillSrc) const {
556   // Split 128-bit GPR moves into two 64-bit moves.  This handles ADDR128 too.
557   if (SystemZ::GR128BitRegClass.contains(DestReg, SrcReg)) {
558     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_h64),
559                 RI.getSubReg(SrcReg, SystemZ::subreg_h64), KillSrc);
560     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_l64),
561                 RI.getSubReg(SrcReg, SystemZ::subreg_l64), KillSrc);
562     return;
563   }
564
565   if (SystemZ::GRX32BitRegClass.contains(DestReg, SrcReg)) {
566     emitGRX32Move(MBB, MBBI, DL, DestReg, SrcReg, SystemZ::LR, 32, KillSrc);
567     return;
568   }
569
570   // Everything else needs only one instruction.
571   unsigned Opcode;
572   if (SystemZ::GR64BitRegClass.contains(DestReg, SrcReg))
573     Opcode = SystemZ::LGR;
574   else if (SystemZ::FP32BitRegClass.contains(DestReg, SrcReg))
575     Opcode = SystemZ::LER;
576   else if (SystemZ::FP64BitRegClass.contains(DestReg, SrcReg))
577     Opcode = SystemZ::LDR;
578   else if (SystemZ::FP128BitRegClass.contains(DestReg, SrcReg))
579     Opcode = SystemZ::LXR;
580   else if (SystemZ::VR32BitRegClass.contains(DestReg, SrcReg))
581     Opcode = SystemZ::VLR32;
582   else if (SystemZ::VR64BitRegClass.contains(DestReg, SrcReg))
583     Opcode = SystemZ::VLR64;
584   else if (SystemZ::VR128BitRegClass.contains(DestReg, SrcReg))
585     Opcode = SystemZ::VLR;
586   else
587     llvm_unreachable("Impossible reg-to-reg copy");
588
589   BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
590     .addReg(SrcReg, getKillRegState(KillSrc));
591 }
592
593 void SystemZInstrInfo::storeRegToStackSlot(
594     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg,
595     bool isKill, int FrameIdx, const TargetRegisterClass *RC,
596     const TargetRegisterInfo *TRI) const {
597   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
598
599   // Callers may expect a single instruction, so keep 128-bit moves
600   // together for now and lower them after register allocation.
601   unsigned LoadOpcode, StoreOpcode;
602   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
603   addFrameReference(BuildMI(MBB, MBBI, DL, get(StoreOpcode))
604                         .addReg(SrcReg, getKillRegState(isKill)),
605                     FrameIdx);
606 }
607
608 void SystemZInstrInfo::loadRegFromStackSlot(
609     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DestReg,
610     int FrameIdx, const TargetRegisterClass *RC,
611     const TargetRegisterInfo *TRI) const {
612   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
613
614   // Callers may expect a single instruction, so keep 128-bit moves
615   // together for now and lower them after register allocation.
616   unsigned LoadOpcode, StoreOpcode;
617   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
618   addFrameReference(BuildMI(MBB, MBBI, DL, get(LoadOpcode), DestReg),
619                     FrameIdx);
620 }
621
622 // Return true if MI is a simple load or store with a 12-bit displacement
623 // and no index.  Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
624 static bool isSimpleBD12Move(const MachineInstr *MI, unsigned Flag) {
625   const MCInstrDesc &MCID = MI->getDesc();
626   return ((MCID.TSFlags & Flag) &&
627           isUInt<12>(MI->getOperand(2).getImm()) &&
628           MI->getOperand(3).getReg() == 0);
629 }
630
631 namespace {
632 struct LogicOp {
633   LogicOp() : RegSize(0), ImmLSB(0), ImmSize(0) {}
634   LogicOp(unsigned regSize, unsigned immLSB, unsigned immSize)
635     : RegSize(regSize), ImmLSB(immLSB), ImmSize(immSize) {}
636
637   explicit operator bool() const { return RegSize; }
638
639   unsigned RegSize, ImmLSB, ImmSize;
640 };
641 } // end anonymous namespace
642
643 static LogicOp interpretAndImmediate(unsigned Opcode) {
644   switch (Opcode) {
645   case SystemZ::NILMux: return LogicOp(32,  0, 16);
646   case SystemZ::NIHMux: return LogicOp(32, 16, 16);
647   case SystemZ::NILL64: return LogicOp(64,  0, 16);
648   case SystemZ::NILH64: return LogicOp(64, 16, 16);
649   case SystemZ::NIHL64: return LogicOp(64, 32, 16);
650   case SystemZ::NIHH64: return LogicOp(64, 48, 16);
651   case SystemZ::NIFMux: return LogicOp(32,  0, 32);
652   case SystemZ::NILF64: return LogicOp(64,  0, 32);
653   case SystemZ::NIHF64: return LogicOp(64, 32, 32);
654   default:              return LogicOp();
655   }
656 }
657
658 // Used to return from convertToThreeAddress after replacing two-address
659 // instruction OldMI with three-address instruction NewMI.
660 static MachineInstr *finishConvertToThreeAddress(MachineInstr *OldMI,
661                                                  MachineInstr *NewMI,
662                                                  LiveVariables *LV) {
663   if (LV) {
664     unsigned NumOps = OldMI->getNumOperands();
665     for (unsigned I = 1; I < NumOps; ++I) {
666       MachineOperand &Op = OldMI->getOperand(I);
667       if (Op.isReg() && Op.isKill())
668         LV->replaceKillInstruction(Op.getReg(), OldMI, NewMI);
669     }
670   }
671   return NewMI;
672 }
673
674 MachineInstr *
675 SystemZInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
676                                         MachineBasicBlock::iterator &MBBI,
677                                         LiveVariables *LV) const {
678   MachineInstr *MI = MBBI;
679   MachineBasicBlock *MBB = MI->getParent();
680   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
681
682   unsigned Opcode = MI->getOpcode();
683   unsigned NumOps = MI->getNumOperands();
684
685   // Try to convert something like SLL into SLLK, if supported.
686   // We prefer to keep the two-operand form where possible both
687   // because it tends to be shorter and because some instructions
688   // have memory forms that can be used during spilling.
689   if (STI.hasDistinctOps()) {
690     MachineOperand &Dest = MI->getOperand(0);
691     MachineOperand &Src = MI->getOperand(1);
692     unsigned DestReg = Dest.getReg();
693     unsigned SrcReg = Src.getReg();
694     // AHIMux is only really a three-operand instruction when both operands
695     // are low registers.  Try to constrain both operands to be low if
696     // possible.
697     if (Opcode == SystemZ::AHIMux &&
698         TargetRegisterInfo::isVirtualRegister(DestReg) &&
699         TargetRegisterInfo::isVirtualRegister(SrcReg) &&
700         MRI.getRegClass(DestReg)->contains(SystemZ::R1L) &&
701         MRI.getRegClass(SrcReg)->contains(SystemZ::R1L)) {
702       MRI.constrainRegClass(DestReg, &SystemZ::GR32BitRegClass);
703       MRI.constrainRegClass(SrcReg, &SystemZ::GR32BitRegClass);
704     }
705     int ThreeOperandOpcode = SystemZ::getThreeOperandOpcode(Opcode);
706     if (ThreeOperandOpcode >= 0) {
707       MachineInstrBuilder MIB =
708         BuildMI(*MBB, MBBI, MI->getDebugLoc(), get(ThreeOperandOpcode))
709         .addOperand(Dest);
710       // Keep the kill state, but drop the tied flag.
711       MIB.addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg());
712       // Keep the remaining operands as-is.
713       for (unsigned I = 2; I < NumOps; ++I)
714         MIB.addOperand(MI->getOperand(I));
715       return finishConvertToThreeAddress(MI, MIB, LV);
716     }
717   }
718
719   // Try to convert an AND into an RISBG-type instruction.
720   if (LogicOp And = interpretAndImmediate(Opcode)) {
721     uint64_t Imm = MI->getOperand(2).getImm() << And.ImmLSB;
722     // AND IMMEDIATE leaves the other bits of the register unchanged.
723     Imm |= allOnes(And.RegSize) & ~(allOnes(And.ImmSize) << And.ImmLSB);
724     unsigned Start, End;
725     if (isRxSBGMask(Imm, And.RegSize, Start, End)) {
726       unsigned NewOpcode;
727       if (And.RegSize == 64) {
728         NewOpcode = SystemZ::RISBG;
729         // Prefer RISBGN if available, since it does not clobber CC.
730         if (STI.hasMiscellaneousExtensions())
731           NewOpcode = SystemZ::RISBGN;
732       } else {
733         NewOpcode = SystemZ::RISBMux;
734         Start &= 31;
735         End &= 31;
736       }
737       MachineOperand &Dest = MI->getOperand(0);
738       MachineOperand &Src = MI->getOperand(1);
739       MachineInstrBuilder MIB =
740         BuildMI(*MBB, MI, MI->getDebugLoc(), get(NewOpcode))
741         .addOperand(Dest).addReg(0)
742         .addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg())
743         .addImm(Start).addImm(End + 128).addImm(0);
744       return finishConvertToThreeAddress(MI, MIB, LV);
745     }
746   }
747   return nullptr;
748 }
749
750 MachineInstr *SystemZInstrInfo::foldMemoryOperandImpl(
751     MachineFunction &MF, MachineInstr *MI, ArrayRef<unsigned> Ops,
752     MachineBasicBlock::iterator InsertPt, int FrameIndex) const {
753   const MachineFrameInfo *MFI = MF.getFrameInfo();
754   unsigned Size = MFI->getObjectSize(FrameIndex);
755   unsigned Opcode = MI->getOpcode();
756
757   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
758     if ((Opcode == SystemZ::LA || Opcode == SystemZ::LAY) &&
759         isInt<8>(MI->getOperand(2).getImm()) &&
760         !MI->getOperand(3).getReg()) {
761       // LA(Y) %reg, CONST(%reg) -> AGSI %mem, CONST
762       return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
763                      get(SystemZ::AGSI))
764           .addFrameIndex(FrameIndex)
765           .addImm(0)
766           .addImm(MI->getOperand(2).getImm());
767     }
768     return nullptr;
769   }
770
771   // All other cases require a single operand.
772   if (Ops.size() != 1)
773     return nullptr;
774
775   unsigned OpNum = Ops[0];
776   assert(Size == MF.getRegInfo()
777          .getRegClass(MI->getOperand(OpNum).getReg())->getSize() &&
778          "Invalid size combination");
779
780   if ((Opcode == SystemZ::AHI || Opcode == SystemZ::AGHI) &&
781       OpNum == 0 &&
782       isInt<8>(MI->getOperand(2).getImm())) {
783     // A(G)HI %reg, CONST -> A(G)SI %mem, CONST
784     Opcode = (Opcode == SystemZ::AHI ? SystemZ::ASI : SystemZ::AGSI);
785     return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
786                    get(Opcode))
787         .addFrameIndex(FrameIndex)
788         .addImm(0)
789         .addImm(MI->getOperand(2).getImm());
790   }
791
792   if (Opcode == SystemZ::LGDR || Opcode == SystemZ::LDGR) {
793     bool Op0IsGPR = (Opcode == SystemZ::LGDR);
794     bool Op1IsGPR = (Opcode == SystemZ::LDGR);
795     // If we're spilling the destination of an LDGR or LGDR, store the
796     // source register instead.
797     if (OpNum == 0) {
798       unsigned StoreOpcode = Op1IsGPR ? SystemZ::STG : SystemZ::STD;
799       return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
800                      get(StoreOpcode))
801           .addOperand(MI->getOperand(1))
802           .addFrameIndex(FrameIndex)
803           .addImm(0)
804           .addReg(0);
805     }
806     // If we're spilling the source of an LDGR or LGDR, load the
807     // destination register instead.
808     if (OpNum == 1) {
809       unsigned LoadOpcode = Op0IsGPR ? SystemZ::LG : SystemZ::LD;
810       unsigned Dest = MI->getOperand(0).getReg();
811       return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
812                      get(LoadOpcode), Dest)
813           .addFrameIndex(FrameIndex)
814           .addImm(0)
815           .addReg(0);
816     }
817   }
818
819   // Look for cases where the source of a simple store or the destination
820   // of a simple load is being spilled.  Try to use MVC instead.
821   //
822   // Although MVC is in practice a fast choice in these cases, it is still
823   // logically a bytewise copy.  This means that we cannot use it if the
824   // load or store is volatile.  We also wouldn't be able to use MVC if
825   // the two memories partially overlap, but that case cannot occur here,
826   // because we know that one of the memories is a full frame index.
827   //
828   // For performance reasons, we also want to avoid using MVC if the addresses
829   // might be equal.  We don't worry about that case here, because spill slot
830   // coloring happens later, and because we have special code to remove
831   // MVCs that turn out to be redundant.
832   if (OpNum == 0 && MI->hasOneMemOperand()) {
833     MachineMemOperand *MMO = *MI->memoperands_begin();
834     if (MMO->getSize() == Size && !MMO->isVolatile()) {
835       // Handle conversion of loads.
836       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXLoad)) {
837         return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
838                        get(SystemZ::MVC))
839             .addFrameIndex(FrameIndex)
840             .addImm(0)
841             .addImm(Size)
842             .addOperand(MI->getOperand(1))
843             .addImm(MI->getOperand(2).getImm())
844             .addMemOperand(MMO);
845       }
846       // Handle conversion of stores.
847       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXStore)) {
848         return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
849                        get(SystemZ::MVC))
850             .addOperand(MI->getOperand(1))
851             .addImm(MI->getOperand(2).getImm())
852             .addImm(Size)
853             .addFrameIndex(FrameIndex)
854             .addImm(0)
855             .addMemOperand(MMO);
856       }
857     }
858   }
859
860   // If the spilled operand is the final one, try to change <INSN>R
861   // into <INSN>.
862   int MemOpcode = SystemZ::getMemOpcode(Opcode);
863   if (MemOpcode >= 0) {
864     unsigned NumOps = MI->getNumExplicitOperands();
865     if (OpNum == NumOps - 1) {
866       const MCInstrDesc &MemDesc = get(MemOpcode);
867       uint64_t AccessBytes = SystemZII::getAccessSize(MemDesc.TSFlags);
868       assert(AccessBytes != 0 && "Size of access should be known");
869       assert(AccessBytes <= Size && "Access outside the frame index");
870       uint64_t Offset = Size - AccessBytes;
871       MachineInstrBuilder MIB = BuildMI(*InsertPt->getParent(), InsertPt,
872                                         MI->getDebugLoc(), get(MemOpcode));
873       for (unsigned I = 0; I < OpNum; ++I)
874         MIB.addOperand(MI->getOperand(I));
875       MIB.addFrameIndex(FrameIndex).addImm(Offset);
876       if (MemDesc.TSFlags & SystemZII::HasIndex)
877         MIB.addReg(0);
878       return MIB;
879     }
880   }
881
882   return nullptr;
883 }
884
885 MachineInstr *SystemZInstrInfo::foldMemoryOperandImpl(
886     MachineFunction &MF, MachineInstr *MI, ArrayRef<unsigned> Ops,
887     MachineBasicBlock::iterator InsertPt, MachineInstr *LoadMI) const {
888   return nullptr;
889 }
890
891 bool
892 SystemZInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
893   switch (MI->getOpcode()) {
894   case SystemZ::L128:
895     splitMove(MI, SystemZ::LG);
896     return true;
897
898   case SystemZ::ST128:
899     splitMove(MI, SystemZ::STG);
900     return true;
901
902   case SystemZ::LX:
903     splitMove(MI, SystemZ::LD);
904     return true;
905
906   case SystemZ::STX:
907     splitMove(MI, SystemZ::STD);
908     return true;
909
910   case SystemZ::LBMux:
911     expandRXYPseudo(MI, SystemZ::LB, SystemZ::LBH);
912     return true;
913
914   case SystemZ::LHMux:
915     expandRXYPseudo(MI, SystemZ::LH, SystemZ::LHH);
916     return true;
917
918   case SystemZ::LLCRMux:
919     expandZExtPseudo(MI, SystemZ::LLCR, 8);
920     return true;
921
922   case SystemZ::LLHRMux:
923     expandZExtPseudo(MI, SystemZ::LLHR, 16);
924     return true;
925
926   case SystemZ::LLCMux:
927     expandRXYPseudo(MI, SystemZ::LLC, SystemZ::LLCH);
928     return true;
929
930   case SystemZ::LLHMux:
931     expandRXYPseudo(MI, SystemZ::LLH, SystemZ::LLHH);
932     return true;
933
934   case SystemZ::LMux:
935     expandRXYPseudo(MI, SystemZ::L, SystemZ::LFH);
936     return true;
937
938   case SystemZ::STCMux:
939     expandRXYPseudo(MI, SystemZ::STC, SystemZ::STCH);
940     return true;
941
942   case SystemZ::STHMux:
943     expandRXYPseudo(MI, SystemZ::STH, SystemZ::STHH);
944     return true;
945
946   case SystemZ::STMux:
947     expandRXYPseudo(MI, SystemZ::ST, SystemZ::STFH);
948     return true;
949
950   case SystemZ::LHIMux:
951     expandRIPseudo(MI, SystemZ::LHI, SystemZ::IIHF, true);
952     return true;
953
954   case SystemZ::IIFMux:
955     expandRIPseudo(MI, SystemZ::IILF, SystemZ::IIHF, false);
956     return true;
957
958   case SystemZ::IILMux:
959     expandRIPseudo(MI, SystemZ::IILL, SystemZ::IIHL, false);
960     return true;
961
962   case SystemZ::IIHMux:
963     expandRIPseudo(MI, SystemZ::IILH, SystemZ::IIHH, false);
964     return true;
965
966   case SystemZ::NIFMux:
967     expandRIPseudo(MI, SystemZ::NILF, SystemZ::NIHF, false);
968     return true;
969
970   case SystemZ::NILMux:
971     expandRIPseudo(MI, SystemZ::NILL, SystemZ::NIHL, false);
972     return true;
973
974   case SystemZ::NIHMux:
975     expandRIPseudo(MI, SystemZ::NILH, SystemZ::NIHH, false);
976     return true;
977
978   case SystemZ::OIFMux:
979     expandRIPseudo(MI, SystemZ::OILF, SystemZ::OIHF, false);
980     return true;
981
982   case SystemZ::OILMux:
983     expandRIPseudo(MI, SystemZ::OILL, SystemZ::OIHL, false);
984     return true;
985
986   case SystemZ::OIHMux:
987     expandRIPseudo(MI, SystemZ::OILH, SystemZ::OIHH, false);
988     return true;
989
990   case SystemZ::XIFMux:
991     expandRIPseudo(MI, SystemZ::XILF, SystemZ::XIHF, false);
992     return true;
993
994   case SystemZ::TMLMux:
995     expandRIPseudo(MI, SystemZ::TMLL, SystemZ::TMHL, false);
996     return true;
997
998   case SystemZ::TMHMux:
999     expandRIPseudo(MI, SystemZ::TMLH, SystemZ::TMHH, false);
1000     return true;
1001
1002   case SystemZ::AHIMux:
1003     expandRIPseudo(MI, SystemZ::AHI, SystemZ::AIH, false);
1004     return true;
1005
1006   case SystemZ::AHIMuxK:
1007     expandRIEPseudo(MI, SystemZ::AHI, SystemZ::AHIK, SystemZ::AIH);
1008     return true;
1009
1010   case SystemZ::AFIMux:
1011     expandRIPseudo(MI, SystemZ::AFI, SystemZ::AIH, false);
1012     return true;
1013
1014   case SystemZ::CFIMux:
1015     expandRIPseudo(MI, SystemZ::CFI, SystemZ::CIH, false);
1016     return true;
1017
1018   case SystemZ::CLFIMux:
1019     expandRIPseudo(MI, SystemZ::CLFI, SystemZ::CLIH, false);
1020     return true;
1021
1022   case SystemZ::CMux:
1023     expandRXYPseudo(MI, SystemZ::C, SystemZ::CHF);
1024     return true;
1025
1026   case SystemZ::CLMux:
1027     expandRXYPseudo(MI, SystemZ::CL, SystemZ::CLHF);
1028     return true;
1029
1030   case SystemZ::RISBMux: {
1031     bool DestIsHigh = isHighReg(MI->getOperand(0).getReg());
1032     bool SrcIsHigh = isHighReg(MI->getOperand(2).getReg());
1033     if (SrcIsHigh == DestIsHigh)
1034       MI->setDesc(get(DestIsHigh ? SystemZ::RISBHH : SystemZ::RISBLL));
1035     else {
1036       MI->setDesc(get(DestIsHigh ? SystemZ::RISBHL : SystemZ::RISBLH));
1037       MI->getOperand(5).setImm(MI->getOperand(5).getImm() ^ 32);
1038     }
1039     return true;
1040   }
1041
1042   case SystemZ::ADJDYNALLOC:
1043     splitAdjDynAlloc(MI);
1044     return true;
1045
1046   default:
1047     return false;
1048   }
1049 }
1050
1051 uint64_t SystemZInstrInfo::getInstSizeInBytes(const MachineInstr *MI) const {
1052   if (MI->getOpcode() == TargetOpcode::INLINEASM) {
1053     const MachineFunction *MF = MI->getParent()->getParent();
1054     const char *AsmStr = MI->getOperand(0).getSymbolName();
1055     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1056   }
1057   return MI->getDesc().getSize();
1058 }
1059
1060 SystemZII::Branch
1061 SystemZInstrInfo::getBranchInfo(const MachineInstr *MI) const {
1062   switch (MI->getOpcode()) {
1063   case SystemZ::BR:
1064   case SystemZ::J:
1065   case SystemZ::JG:
1066     return SystemZII::Branch(SystemZII::BranchNormal, SystemZ::CCMASK_ANY,
1067                              SystemZ::CCMASK_ANY, &MI->getOperand(0));
1068
1069   case SystemZ::BRC:
1070   case SystemZ::BRCL:
1071     return SystemZII::Branch(SystemZII::BranchNormal,
1072                              MI->getOperand(0).getImm(),
1073                              MI->getOperand(1).getImm(), &MI->getOperand(2));
1074
1075   case SystemZ::BRCT:
1076     return SystemZII::Branch(SystemZII::BranchCT, SystemZ::CCMASK_ICMP,
1077                              SystemZ::CCMASK_CMP_NE, &MI->getOperand(2));
1078
1079   case SystemZ::BRCTG:
1080     return SystemZII::Branch(SystemZII::BranchCTG, SystemZ::CCMASK_ICMP,
1081                              SystemZ::CCMASK_CMP_NE, &MI->getOperand(2));
1082
1083   case SystemZ::CIJ:
1084   case SystemZ::CRJ:
1085     return SystemZII::Branch(SystemZII::BranchC, SystemZ::CCMASK_ICMP,
1086                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1087
1088   case SystemZ::CLIJ:
1089   case SystemZ::CLRJ:
1090     return SystemZII::Branch(SystemZII::BranchCL, SystemZ::CCMASK_ICMP,
1091                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1092
1093   case SystemZ::CGIJ:
1094   case SystemZ::CGRJ:
1095     return SystemZII::Branch(SystemZII::BranchCG, SystemZ::CCMASK_ICMP,
1096                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1097
1098   case SystemZ::CLGIJ:
1099   case SystemZ::CLGRJ:
1100     return SystemZII::Branch(SystemZII::BranchCLG, SystemZ::CCMASK_ICMP,
1101                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1102
1103   default:
1104     llvm_unreachable("Unrecognized branch opcode");
1105   }
1106 }
1107
1108 void SystemZInstrInfo::getLoadStoreOpcodes(const TargetRegisterClass *RC,
1109                                            unsigned &LoadOpcode,
1110                                            unsigned &StoreOpcode) const {
1111   if (RC == &SystemZ::GR32BitRegClass || RC == &SystemZ::ADDR32BitRegClass) {
1112     LoadOpcode = SystemZ::L;
1113     StoreOpcode = SystemZ::ST;
1114   } else if (RC == &SystemZ::GRH32BitRegClass) {
1115     LoadOpcode = SystemZ::LFH;
1116     StoreOpcode = SystemZ::STFH;
1117   } else if (RC == &SystemZ::GRX32BitRegClass) {
1118     LoadOpcode = SystemZ::LMux;
1119     StoreOpcode = SystemZ::STMux;
1120   } else if (RC == &SystemZ::GR64BitRegClass ||
1121              RC == &SystemZ::ADDR64BitRegClass) {
1122     LoadOpcode = SystemZ::LG;
1123     StoreOpcode = SystemZ::STG;
1124   } else if (RC == &SystemZ::GR128BitRegClass ||
1125              RC == &SystemZ::ADDR128BitRegClass) {
1126     LoadOpcode = SystemZ::L128;
1127     StoreOpcode = SystemZ::ST128;
1128   } else if (RC == &SystemZ::FP32BitRegClass) {
1129     LoadOpcode = SystemZ::LE;
1130     StoreOpcode = SystemZ::STE;
1131   } else if (RC == &SystemZ::FP64BitRegClass) {
1132     LoadOpcode = SystemZ::LD;
1133     StoreOpcode = SystemZ::STD;
1134   } else if (RC == &SystemZ::FP128BitRegClass) {
1135     LoadOpcode = SystemZ::LX;
1136     StoreOpcode = SystemZ::STX;
1137   } else if (RC == &SystemZ::VR32BitRegClass) {
1138     LoadOpcode = SystemZ::VL32;
1139     StoreOpcode = SystemZ::VST32;
1140   } else if (RC == &SystemZ::VR64BitRegClass) {
1141     LoadOpcode = SystemZ::VL64;
1142     StoreOpcode = SystemZ::VST64;
1143   } else if (RC == &SystemZ::VF128BitRegClass ||
1144              RC == &SystemZ::VR128BitRegClass) {
1145     LoadOpcode = SystemZ::VL;
1146     StoreOpcode = SystemZ::VST;
1147   } else
1148     llvm_unreachable("Unsupported regclass to load or store");
1149 }
1150
1151 unsigned SystemZInstrInfo::getOpcodeForOffset(unsigned Opcode,
1152                                               int64_t Offset) const {
1153   const MCInstrDesc &MCID = get(Opcode);
1154   int64_t Offset2 = (MCID.TSFlags & SystemZII::Is128Bit ? Offset + 8 : Offset);
1155   if (isUInt<12>(Offset) && isUInt<12>(Offset2)) {
1156     // Get the instruction to use for unsigned 12-bit displacements.
1157     int Disp12Opcode = SystemZ::getDisp12Opcode(Opcode);
1158     if (Disp12Opcode >= 0)
1159       return Disp12Opcode;
1160
1161     // All address-related instructions can use unsigned 12-bit
1162     // displacements.
1163     return Opcode;
1164   }
1165   if (isInt<20>(Offset) && isInt<20>(Offset2)) {
1166     // Get the instruction to use for signed 20-bit displacements.
1167     int Disp20Opcode = SystemZ::getDisp20Opcode(Opcode);
1168     if (Disp20Opcode >= 0)
1169       return Disp20Opcode;
1170
1171     // Check whether Opcode allows signed 20-bit displacements.
1172     if (MCID.TSFlags & SystemZII::Has20BitOffset)
1173       return Opcode;
1174   }
1175   return 0;
1176 }
1177
1178 unsigned SystemZInstrInfo::getLoadAndTest(unsigned Opcode) const {
1179   switch (Opcode) {
1180   case SystemZ::L:      return SystemZ::LT;
1181   case SystemZ::LY:     return SystemZ::LT;
1182   case SystemZ::LG:     return SystemZ::LTG;
1183   case SystemZ::LGF:    return SystemZ::LTGF;
1184   case SystemZ::LR:     return SystemZ::LTR;
1185   case SystemZ::LGFR:   return SystemZ::LTGFR;
1186   case SystemZ::LGR:    return SystemZ::LTGR;
1187   case SystemZ::LER:    return SystemZ::LTEBR;
1188   case SystemZ::LDR:    return SystemZ::LTDBR;
1189   case SystemZ::LXR:    return SystemZ::LTXBR;
1190   case SystemZ::LCDFR:  return SystemZ::LCDBR;
1191   case SystemZ::LPDFR:  return SystemZ::LPDBR;
1192   case SystemZ::LNDFR:  return SystemZ::LNDBR;
1193   case SystemZ::LCDFR_32:  return SystemZ::LCEBR;
1194   case SystemZ::LPDFR_32:  return SystemZ::LPEBR;
1195   case SystemZ::LNDFR_32:  return SystemZ::LNEBR;
1196   // On zEC12 we prefer to use RISBGN.  But if there is a chance to
1197   // actually use the condition code, we may turn it back into RISGB.
1198   // Note that RISBG is not really a "load-and-test" instruction,
1199   // but sets the same condition code values, so is OK to use here.
1200   case SystemZ::RISBGN: return SystemZ::RISBG;
1201   default:              return 0;
1202   }
1203 }
1204
1205 // Return true if Mask matches the regexp 0*1+0*, given that zero masks
1206 // have already been filtered out.  Store the first set bit in LSB and
1207 // the number of set bits in Length if so.
1208 static bool isStringOfOnes(uint64_t Mask, unsigned &LSB, unsigned &Length) {
1209   unsigned First = findFirstSet(Mask);
1210   uint64_t Top = (Mask >> First) + 1;
1211   if ((Top & -Top) == Top) {
1212     LSB = First;
1213     Length = findFirstSet(Top);
1214     return true;
1215   }
1216   return false;
1217 }
1218
1219 bool SystemZInstrInfo::isRxSBGMask(uint64_t Mask, unsigned BitSize,
1220                                    unsigned &Start, unsigned &End) const {
1221   // Reject trivial all-zero masks.
1222   Mask &= allOnes(BitSize);
1223   if (Mask == 0)
1224     return false;
1225
1226   // Handle the 1+0+ or 0+1+0* cases.  Start then specifies the index of
1227   // the msb and End specifies the index of the lsb.
1228   unsigned LSB, Length;
1229   if (isStringOfOnes(Mask, LSB, Length)) {
1230     Start = 63 - (LSB + Length - 1);
1231     End = 63 - LSB;
1232     return true;
1233   }
1234
1235   // Handle the wrap-around 1+0+1+ cases.  Start then specifies the msb
1236   // of the low 1s and End specifies the lsb of the high 1s.
1237   if (isStringOfOnes(Mask ^ allOnes(BitSize), LSB, Length)) {
1238     assert(LSB > 0 && "Bottom bit must be set");
1239     assert(LSB + Length < BitSize && "Top bit must be set");
1240     Start = 63 - (LSB - 1);
1241     End = 63 - (LSB + Length);
1242     return true;
1243   }
1244
1245   return false;
1246 }
1247
1248 unsigned SystemZInstrInfo::getCompareAndBranch(unsigned Opcode,
1249                                                const MachineInstr *MI) const {
1250   switch (Opcode) {
1251   case SystemZ::CR:
1252     return SystemZ::CRJ;
1253   case SystemZ::CGR:
1254     return SystemZ::CGRJ;
1255   case SystemZ::CHI:
1256     return MI && isInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CIJ : 0;
1257   case SystemZ::CGHI:
1258     return MI && isInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CGIJ : 0;
1259   case SystemZ::CLR:
1260     return SystemZ::CLRJ;
1261   case SystemZ::CLGR:
1262     return SystemZ::CLGRJ;
1263   case SystemZ::CLFI:
1264     return MI && isUInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CLIJ : 0;
1265   case SystemZ::CLGFI:
1266     return MI && isUInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CLGIJ : 0;
1267   default:
1268     return 0;
1269   }
1270 }
1271
1272 void SystemZInstrInfo::loadImmediate(MachineBasicBlock &MBB,
1273                                      MachineBasicBlock::iterator MBBI,
1274                                      unsigned Reg, uint64_t Value) const {
1275   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1276   unsigned Opcode;
1277   if (isInt<16>(Value))
1278     Opcode = SystemZ::LGHI;
1279   else if (SystemZ::isImmLL(Value))
1280     Opcode = SystemZ::LLILL;
1281   else if (SystemZ::isImmLH(Value)) {
1282     Opcode = SystemZ::LLILH;
1283     Value >>= 16;
1284   } else {
1285     assert(isInt<32>(Value) && "Huge values not handled yet");
1286     Opcode = SystemZ::LGFI;
1287   }
1288   BuildMI(MBB, MBBI, DL, get(Opcode), Reg).addImm(Value);
1289 }