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