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   // Clear the kill flags for the base and index registers in the first
73   // instruction.
74   EarlierMI->getOperand(1).setIsKill(false);
75   EarlierMI->getOperand(3).setIsKill(false);
76 
77   // Set the opcodes.
78   unsigned HighOpcode = getOpcodeForOffset(NewOpcode, HighOffsetOp.getImm());
79   unsigned LowOpcode = getOpcodeForOffset(NewOpcode, LowOffsetOp.getImm());
80   assert(HighOpcode && LowOpcode && "Both offsets should be in range");
81 
82   EarlierMI->setDesc(get(HighOpcode));
83   MI->setDesc(get(LowOpcode));
84 }
85 
86 // Split ADJDYNALLOC instruction MI.
87 void SystemZInstrInfo::splitAdjDynAlloc(MachineBasicBlock::iterator MI) const {
88   MachineBasicBlock *MBB = MI->getParent();
89   MachineFunction &MF = *MBB->getParent();
90   MachineFrameInfo *MFFrame = MF.getFrameInfo();
91   MachineOperand &OffsetMO = MI->getOperand(2);
92 
93   uint64_t Offset = (MFFrame->getMaxCallFrameSize() +
94                      SystemZMC::CallFrameSize +
95                      OffsetMO.getImm());
96   unsigned NewOpcode = getOpcodeForOffset(SystemZ::LA, Offset);
97   assert(NewOpcode && "No support for huge argument lists yet");
98   MI->setDesc(get(NewOpcode));
99   OffsetMO.setImm(Offset);
100 }
101 
102 // MI is an RI-style pseudo instruction.  Replace it with LowOpcode
103 // if the first operand is a low GR32 and HighOpcode if the first operand
104 // is a high GR32.  ConvertHigh is true if LowOpcode takes a signed operand
105 // and HighOpcode takes an unsigned 32-bit operand.  In those cases,
106 // MI has the same kind of operand as LowOpcode, so needs to be converted
107 // if HighOpcode is used.
108 void SystemZInstrInfo::expandRIPseudo(MachineInstr *MI, unsigned LowOpcode,
109                                       unsigned HighOpcode,
110                                       bool ConvertHigh) const {
111   unsigned Reg = MI->getOperand(0).getReg();
112   bool IsHigh = isHighReg(Reg);
113   MI->setDesc(get(IsHigh ? HighOpcode : LowOpcode));
114   if (IsHigh && ConvertHigh)
115     MI->getOperand(1).setImm(uint32_t(MI->getOperand(1).getImm()));
116 }
117 
118 // MI is a three-operand RIE-style pseudo instruction.  Replace it with
119 // LowOpcodeK if the registers are both low GR32s, otherwise use a move
120 // followed by HighOpcode or LowOpcode, depending on whether the target
121 // is a high or low GR32.
122 void SystemZInstrInfo::expandRIEPseudo(MachineInstr *MI, unsigned LowOpcode,
123                                        unsigned LowOpcodeK,
124                                        unsigned HighOpcode) const {
125   unsigned DestReg = MI->getOperand(0).getReg();
126   unsigned SrcReg = MI->getOperand(1).getReg();
127   bool DestIsHigh = isHighReg(DestReg);
128   bool SrcIsHigh = isHighReg(SrcReg);
129   if (!DestIsHigh && !SrcIsHigh)
130     MI->setDesc(get(LowOpcodeK));
131   else {
132     emitGRX32Move(*MI->getParent(), MI, MI->getDebugLoc(),
133                   DestReg, SrcReg, SystemZ::LR, 32,
134                   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(),
159                 LowOpcode, 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).addImm(0);
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).addImm(1);
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                                      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) &&
234       MI->getOperand(1).isFI() &&
235       MI->getOperand(2).getImm() == 0 &&
236       MI->getOperand(3).getReg() == 0) {
237     FrameIndex = MI->getOperand(1).getIndex();
238     return MI->getOperand(0).getReg();
239   }
240   return 0;
241 }
242 
243 unsigned SystemZInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
244                                                int &FrameIndex) const {
245   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXLoad);
246 }
247 
248 unsigned SystemZInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
249                                               int &FrameIndex) const {
250   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXStore);
251 }
252 
253 bool SystemZInstrInfo::isStackSlotCopy(const MachineInstr *MI,
254                                        int &DestFrameIndex,
255                                        int &SrcFrameIndex) const {
256   // Check for MVC 0(Length,FI1),0(FI2)
257   const MachineFrameInfo *MFI = MI->getParent()->getParent()->getFrameInfo();
258   if (MI->getOpcode() != SystemZ::MVC ||
259       !MI->getOperand(0).isFI() ||
260       MI->getOperand(1).getImm() != 0 ||
261       !MI->getOperand(3).isFI() ||
262       MI->getOperand(4).getImm() != 0)
263     return false;
264 
265   // Check that Length covers the full slots.
266   int64_t Length = MI->getOperand(2).getImm();
267   unsigned FI1 = MI->getOperand(0).getIndex();
268   unsigned FI2 = MI->getOperand(3).getIndex();
269   if (MFI->getObjectSize(FI1) != Length ||
270       MFI->getObjectSize(FI2) != Length)
271     return false;
272 
273   DestFrameIndex = FI1;
274   SrcFrameIndex = FI2;
275   return true;
276 }
277 
278 bool SystemZInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
279                                      MachineBasicBlock *&TBB,
280                                      MachineBasicBlock *&FBB,
281                                      SmallVectorImpl<MachineOperand> &Cond,
282                                      bool AllowModify) const {
283   // Most of the code and comments here are boilerplate.
284 
285   // Start from the bottom of the block and work up, examining the
286   // terminator instructions.
287   MachineBasicBlock::iterator I = MBB.end();
288   while (I != MBB.begin()) {
289     --I;
290     if (I->isDebugValue())
291       continue;
292 
293     // Working from the bottom, when we see a non-terminator instruction, we're
294     // done.
295     if (!isUnpredicatedTerminator(*I))
296       break;
297 
298     // A terminator that isn't a branch can't easily be handled by this
299     // analysis.
300     if (!I->isBranch())
301       return true;
302 
303     // Can't handle indirect branches.
304     SystemZII::Branch Branch(getBranchInfo(I));
305     if (!Branch.Target->isMBB())
306       return true;
307 
308     // Punt on compound branches.
309     if (Branch.Type != SystemZII::BranchNormal)
310       return true;
311 
312     if (Branch.CCMask == SystemZ::CCMASK_ANY) {
313       // Handle unconditional branches.
314       if (!AllowModify) {
315         TBB = Branch.Target->getMBB();
316         continue;
317       }
318 
319       // If the block has any instructions after a JMP, delete them.
320       while (std::next(I) != MBB.end())
321         std::next(I)->eraseFromParent();
322 
323       Cond.clear();
324       FBB = nullptr;
325 
326       // Delete the JMP if it's equivalent to a fall-through.
327       if (MBB.isLayoutSuccessor(Branch.Target->getMBB())) {
328         TBB = nullptr;
329         I->eraseFromParent();
330         I = MBB.end();
331         continue;
332       }
333 
334       // TBB is used to indicate the unconditinal destination.
335       TBB = Branch.Target->getMBB();
336       continue;
337     }
338 
339     // Working from the bottom, handle the first conditional branch.
340     if (Cond.empty()) {
341       // FIXME: add X86-style branch swap
342       FBB = TBB;
343       TBB = Branch.Target->getMBB();
344       Cond.push_back(MachineOperand::CreateImm(Branch.CCValid));
345       Cond.push_back(MachineOperand::CreateImm(Branch.CCMask));
346       continue;
347     }
348 
349     // Handle subsequent conditional branches.
350     assert(Cond.size() == 2 && TBB && "Should have seen a conditional branch");
351 
352     // Only handle the case where all conditional branches branch to the same
353     // destination.
354     if (TBB != Branch.Target->getMBB())
355       return true;
356 
357     // If the conditions are the same, we can leave them alone.
358     unsigned OldCCValid = Cond[0].getImm();
359     unsigned OldCCMask = Cond[1].getImm();
360     if (OldCCValid == Branch.CCValid && OldCCMask == Branch.CCMask)
361       continue;
362 
363     // FIXME: Try combining conditions like X86 does.  Should be easy on Z!
364     return false;
365   }
366 
367   return false;
368 }
369 
370 unsigned SystemZInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
371   // Most of the code and comments here are boilerplate.
372   MachineBasicBlock::iterator I = MBB.end();
373   unsigned Count = 0;
374 
375   while (I != MBB.begin()) {
376     --I;
377     if (I->isDebugValue())
378       continue;
379     if (!I->isBranch())
380       break;
381     if (!getBranchInfo(I).Target->isMBB())
382       break;
383     // Remove the branch.
384     I->eraseFromParent();
385     I = MBB.end();
386     ++Count;
387   }
388 
389   return Count;
390 }
391 
392 bool SystemZInstrInfo::
393 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
394   assert(Cond.size() == 2 && "Invalid condition");
395   Cond[1].setImm(Cond[1].getImm() ^ Cond[0].getImm());
396   return false;
397 }
398 
399 unsigned
400 SystemZInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
401                                MachineBasicBlock *FBB,
402                                ArrayRef<MachineOperand> Cond,
403                                DebugLoc DL) 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 
413   if (Cond.empty()) {
414     // Unconditional branch?
415     assert(!FBB && "Unconditional branch with multiple successors!");
416     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(TBB);
417     return 1;
418   }
419 
420   // Conditional branch.
421   unsigned Count = 0;
422   unsigned CCValid = Cond[0].getImm();
423   unsigned CCMask = Cond[1].getImm();
424   BuildMI(&MBB, DL, get(SystemZ::BRC))
425     .addImm(CCValid).addImm(CCMask).addMBB(TBB);
426   ++Count;
427 
428   if (FBB) {
429     // Two-way Conditional branch. Insert the second branch.
430     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(FBB);
431     ++Count;
432   }
433   return Count;
434 }
435 
436 bool SystemZInstrInfo::analyzeCompare(const MachineInstr *MI,
437                                       unsigned &SrcReg, unsigned &SrcReg2,
438                                       int &Mask, int &Value) const {
439   assert(MI->isCompare() && "Caller should have checked for a comparison");
440 
441   if (MI->getNumExplicitOperands() == 2 &&
442       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;
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
520 SystemZInstrInfo::optimizeCompareInstr(MachineInstr *Compare,
521                                        unsigned SrcReg, unsigned SrcReg2,
522                                        int Mask, int Value,
523                                        const MachineRegisterInfo *MRI) const {
524   assert(!SrcReg2 && "Only optimizing constant comparisons so far");
525   bool IsLogical = (Compare->getDesc().TSFlags & SystemZII::IsLogical) != 0;
526   return Value == 0 && !IsLogical &&
527          removeIPMBasedCompare(Compare, SrcReg, MRI, &RI);
528 }
529 
530 // If Opcode is a move that has a conditional variant, return that variant,
531 // otherwise return 0.
532 static unsigned getConditionalMove(unsigned Opcode) {
533   switch (Opcode) {
534   case SystemZ::LR:  return SystemZ::LOCR;
535   case SystemZ::LGR: return SystemZ::LOCGR;
536   default:           return 0;
537   }
538 }
539 
540 bool SystemZInstrInfo::isPredicable(MachineInstr &MI) const {
541   unsigned Opcode = MI.getOpcode();
542   if (STI.hasLoadStoreOnCond() && getConditionalMove(Opcode))
543     return true;
544   if (Opcode == SystemZ::Return ||
545       Opcode == SystemZ::CallJG ||
546       Opcode == SystemZ::CallBR)
547     return true;
548   return false;
549 }
550 
551 bool SystemZInstrInfo::
552 isProfitableToIfCvt(MachineBasicBlock &MBB,
553                     unsigned NumCycles, unsigned ExtraPredCycles,
554                     BranchProbability Probability) const {
555   // Avoid using conditional returns at the end of a loop (since then
556   // we'd need to emit an unconditional branch to the beginning anyway,
557   // making the loop body longer).  This doesn't apply for low-probability
558   // loops (eg. compare-and-swap retry), so just decide based on branch
559   // probability instead of looping structure.
560   if (MBB.succ_empty() && Probability < BranchProbability(1, 8))
561     return false;
562   // For now only convert single instructions.
563   return NumCycles == 1;
564 }
565 
566 bool SystemZInstrInfo::
567 isProfitableToIfCvt(MachineBasicBlock &TMBB,
568                     unsigned NumCyclesT, unsigned ExtraPredCyclesT,
569                     MachineBasicBlock &FMBB,
570                     unsigned NumCyclesF, unsigned ExtraPredCyclesF,
571                     BranchProbability Probability) const {
572   // For now avoid converting mutually-exclusive cases.
573   return false;
574 }
575 
576 bool SystemZInstrInfo::
577 isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
578                           BranchProbability Probability) const {
579   // For now only duplicate single instructions.
580   return NumCycles == 1;
581 }
582 
583 bool SystemZInstrInfo::PredicateInstruction(
584     MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
585   assert(Pred.size() == 2 && "Invalid condition");
586   unsigned CCValid = Pred[0].getImm();
587   unsigned CCMask = Pred[1].getImm();
588   assert(CCMask > 0 && CCMask < 15 && "Invalid predicate");
589   unsigned Opcode = MI.getOpcode();
590   if (STI.hasLoadStoreOnCond()) {
591     if (unsigned CondOpcode = getConditionalMove(Opcode)) {
592       MI.setDesc(get(CondOpcode));
593       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
594           .addImm(CCValid)
595           .addImm(CCMask)
596           .addReg(SystemZ::CC, RegState::Implicit);
597       return true;
598     }
599   }
600   if (Opcode == SystemZ::Return) {
601     MI.setDesc(get(SystemZ::CondReturn));
602     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
603       .addImm(CCValid).addImm(CCMask)
604       .addReg(SystemZ::CC, RegState::Implicit);
605     return true;
606   }
607   if (Opcode == SystemZ::CallJG) {
608     const GlobalValue *Global = MI.getOperand(0).getGlobal();
609     const uint32_t *RegMask = MI.getOperand(1).getRegMask();
610     MI.RemoveOperand(1);
611     MI.RemoveOperand(0);
612     MI.setDesc(get(SystemZ::CallBRCL));
613     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
614       .addImm(CCValid).addImm(CCMask)
615       .addGlobalAddress(Global)
616       .addRegMask(RegMask)
617       .addReg(SystemZ::CC, RegState::Implicit);
618     return true;
619   }
620   if (Opcode == SystemZ::CallBR) {
621     const uint32_t *RegMask = MI.getOperand(0).getRegMask();
622     MI.RemoveOperand(0);
623     MI.setDesc(get(SystemZ::CallBCR));
624     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
625       .addImm(CCValid).addImm(CCMask)
626       .addRegMask(RegMask)
627       .addReg(SystemZ::CC, RegState::Implicit);
628     return true;
629   }
630   return false;
631 }
632 
633 void SystemZInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
634                                    MachineBasicBlock::iterator MBBI,
635                                    DebugLoc DL, unsigned DestReg,
636                                    unsigned SrcReg, bool KillSrc) const {
637   // Split 128-bit GPR moves into two 64-bit moves.  This handles ADDR128 too.
638   if (SystemZ::GR128BitRegClass.contains(DestReg, SrcReg)) {
639     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_h64),
640                 RI.getSubReg(SrcReg, SystemZ::subreg_h64), KillSrc);
641     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_l64),
642                 RI.getSubReg(SrcReg, SystemZ::subreg_l64), KillSrc);
643     return;
644   }
645 
646   if (SystemZ::GRX32BitRegClass.contains(DestReg, SrcReg)) {
647     emitGRX32Move(MBB, MBBI, DL, DestReg, SrcReg, SystemZ::LR, 32, KillSrc);
648     return;
649   }
650 
651   // Everything else needs only one instruction.
652   unsigned Opcode;
653   if (SystemZ::GR64BitRegClass.contains(DestReg, SrcReg))
654     Opcode = SystemZ::LGR;
655   else if (SystemZ::FP32BitRegClass.contains(DestReg, SrcReg))
656     // For z13 we prefer LDR over LER to avoid partial register dependencies.
657     Opcode = STI.hasVector() ? SystemZ::LDR32 : SystemZ::LER;
658   else if (SystemZ::FP64BitRegClass.contains(DestReg, SrcReg))
659     Opcode = SystemZ::LDR;
660   else if (SystemZ::FP128BitRegClass.contains(DestReg, SrcReg))
661     Opcode = SystemZ::LXR;
662   else if (SystemZ::VR32BitRegClass.contains(DestReg, SrcReg))
663     Opcode = SystemZ::VLR32;
664   else if (SystemZ::VR64BitRegClass.contains(DestReg, SrcReg))
665     Opcode = SystemZ::VLR64;
666   else if (SystemZ::VR128BitRegClass.contains(DestReg, SrcReg))
667     Opcode = SystemZ::VLR;
668   else
669     llvm_unreachable("Impossible reg-to-reg copy");
670 
671   BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
672     .addReg(SrcReg, getKillRegState(KillSrc));
673 }
674 
675 void SystemZInstrInfo::storeRegToStackSlot(
676     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg,
677     bool isKill, int FrameIdx, const TargetRegisterClass *RC,
678     const TargetRegisterInfo *TRI) const {
679   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
680 
681   // Callers may expect a single instruction, so keep 128-bit moves
682   // together for now and lower them after register allocation.
683   unsigned LoadOpcode, StoreOpcode;
684   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
685   addFrameReference(BuildMI(MBB, MBBI, DL, get(StoreOpcode))
686                         .addReg(SrcReg, getKillRegState(isKill)),
687                     FrameIdx);
688 }
689 
690 void SystemZInstrInfo::loadRegFromStackSlot(
691     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DestReg,
692     int FrameIdx, const TargetRegisterClass *RC,
693     const TargetRegisterInfo *TRI) const {
694   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
695 
696   // Callers may expect a single instruction, so keep 128-bit moves
697   // together for now and lower them after register allocation.
698   unsigned LoadOpcode, StoreOpcode;
699   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
700   addFrameReference(BuildMI(MBB, MBBI, DL, get(LoadOpcode), DestReg),
701                     FrameIdx);
702 }
703 
704 // Return true if MI is a simple load or store with a 12-bit displacement
705 // and no index.  Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
706 static bool isSimpleBD12Move(const MachineInstr *MI, unsigned Flag) {
707   const MCInstrDesc &MCID = MI->getDesc();
708   return ((MCID.TSFlags & Flag) &&
709           isUInt<12>(MI->getOperand(2).getImm()) &&
710           MI->getOperand(3).getReg() == 0);
711 }
712 
713 namespace {
714 struct LogicOp {
715   LogicOp() : RegSize(0), ImmLSB(0), ImmSize(0) {}
716   LogicOp(unsigned regSize, unsigned immLSB, unsigned immSize)
717     : RegSize(regSize), ImmLSB(immLSB), ImmSize(immSize) {}
718 
719   explicit operator bool() const { return RegSize; }
720 
721   unsigned RegSize, ImmLSB, ImmSize;
722 };
723 } // end anonymous namespace
724 
725 static LogicOp interpretAndImmediate(unsigned Opcode) {
726   switch (Opcode) {
727   case SystemZ::NILMux: return LogicOp(32,  0, 16);
728   case SystemZ::NIHMux: return LogicOp(32, 16, 16);
729   case SystemZ::NILL64: return LogicOp(64,  0, 16);
730   case SystemZ::NILH64: return LogicOp(64, 16, 16);
731   case SystemZ::NIHL64: return LogicOp(64, 32, 16);
732   case SystemZ::NIHH64: return LogicOp(64, 48, 16);
733   case SystemZ::NIFMux: return LogicOp(32,  0, 32);
734   case SystemZ::NILF64: return LogicOp(64,  0, 32);
735   case SystemZ::NIHF64: return LogicOp(64, 32, 32);
736   default:              return LogicOp();
737   }
738 }
739 
740 static void transferDeadCC(MachineInstr *OldMI, MachineInstr *NewMI) {
741   if (OldMI->registerDefIsDead(SystemZ::CC)) {
742     MachineOperand *CCDef = NewMI->findRegisterDefOperand(SystemZ::CC);
743     if (CCDef != nullptr)
744       CCDef->setIsDead(true);
745   }
746 }
747 
748 // Used to return from convertToThreeAddress after replacing two-address
749 // instruction OldMI with three-address instruction NewMI.
750 static MachineInstr *finishConvertToThreeAddress(MachineInstr *OldMI,
751                                                  MachineInstr *NewMI,
752                                                  LiveVariables *LV) {
753   if (LV) {
754     unsigned NumOps = OldMI->getNumOperands();
755     for (unsigned I = 1; I < NumOps; ++I) {
756       MachineOperand &Op = OldMI->getOperand(I);
757       if (Op.isReg() && Op.isKill())
758         LV->replaceKillInstruction(Op.getReg(), OldMI, NewMI);
759     }
760   }
761   transferDeadCC(OldMI, NewMI);
762   return NewMI;
763 }
764 
765 MachineInstr *
766 SystemZInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
767                                         MachineBasicBlock::iterator &MBBI,
768                                         LiveVariables *LV) const {
769   MachineInstr *MI = MBBI;
770   MachineBasicBlock *MBB = MI->getParent();
771   MachineFunction *MF = MBB->getParent();
772   MachineRegisterInfo &MRI = MF->getRegInfo();
773 
774   unsigned Opcode = MI->getOpcode();
775   unsigned NumOps = MI->getNumOperands();
776 
777   // Try to convert something like SLL into SLLK, if supported.
778   // We prefer to keep the two-operand form where possible both
779   // because it tends to be shorter and because some instructions
780   // have memory forms that can be used during spilling.
781   if (STI.hasDistinctOps()) {
782     MachineOperand &Dest = MI->getOperand(0);
783     MachineOperand &Src = MI->getOperand(1);
784     unsigned DestReg = Dest.getReg();
785     unsigned SrcReg = Src.getReg();
786     // AHIMux is only really a three-operand instruction when both operands
787     // are low registers.  Try to constrain both operands to be low if
788     // possible.
789     if (Opcode == SystemZ::AHIMux &&
790         TargetRegisterInfo::isVirtualRegister(DestReg) &&
791         TargetRegisterInfo::isVirtualRegister(SrcReg) &&
792         MRI.getRegClass(DestReg)->contains(SystemZ::R1L) &&
793         MRI.getRegClass(SrcReg)->contains(SystemZ::R1L)) {
794       MRI.constrainRegClass(DestReg, &SystemZ::GR32BitRegClass);
795       MRI.constrainRegClass(SrcReg, &SystemZ::GR32BitRegClass);
796     }
797     int ThreeOperandOpcode = SystemZ::getThreeOperandOpcode(Opcode);
798     if (ThreeOperandOpcode >= 0) {
799       // Create three address instruction without adding the implicit
800       // operands. Those will instead be copied over from the original
801       // instruction by the loop below.
802       MachineInstrBuilder MIB(*MF,
803                               MF->CreateMachineInstr(get(ThreeOperandOpcode),
804                                     MI->getDebugLoc(), /*NoImplicit=*/true));
805       MIB.addOperand(Dest);
806       // Keep the kill state, but drop the tied flag.
807       MIB.addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg());
808       // Keep the remaining operands as-is.
809       for (unsigned I = 2; I < NumOps; ++I)
810         MIB.addOperand(MI->getOperand(I));
811       MBB->insert(MI, MIB);
812       return finishConvertToThreeAddress(MI, MIB, LV);
813     }
814   }
815 
816   // Try to convert an AND into an RISBG-type instruction.
817   if (LogicOp And = interpretAndImmediate(Opcode)) {
818     uint64_t Imm = MI->getOperand(2).getImm() << And.ImmLSB;
819     // AND IMMEDIATE leaves the other bits of the register unchanged.
820     Imm |= allOnes(And.RegSize) & ~(allOnes(And.ImmSize) << And.ImmLSB);
821     unsigned Start, End;
822     if (isRxSBGMask(Imm, And.RegSize, Start, End)) {
823       unsigned NewOpcode;
824       if (And.RegSize == 64) {
825         NewOpcode = SystemZ::RISBG;
826         // Prefer RISBGN if available, since it does not clobber CC.
827         if (STI.hasMiscellaneousExtensions())
828           NewOpcode = SystemZ::RISBGN;
829       } else {
830         NewOpcode = SystemZ::RISBMux;
831         Start &= 31;
832         End &= 31;
833       }
834       MachineOperand &Dest = MI->getOperand(0);
835       MachineOperand &Src = MI->getOperand(1);
836       MachineInstrBuilder MIB =
837         BuildMI(*MBB, MI, MI->getDebugLoc(), get(NewOpcode))
838         .addOperand(Dest).addReg(0)
839         .addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg())
840         .addImm(Start).addImm(End + 128).addImm(0);
841       return finishConvertToThreeAddress(MI, MIB, LV);
842     }
843   }
844   return nullptr;
845 }
846 
847 MachineInstr *SystemZInstrInfo::foldMemoryOperandImpl(
848     MachineFunction &MF, MachineInstr *MI, ArrayRef<unsigned> Ops,
849     MachineBasicBlock::iterator InsertPt, int FrameIndex) const {
850   const MachineFrameInfo *MFI = MF.getFrameInfo();
851   unsigned Size = MFI->getObjectSize(FrameIndex);
852   unsigned Opcode = MI->getOpcode();
853 
854 // XXX This is an introduction of a CC def and is illegal! Reactivate
855 // with a check of liveness of CC reg.
856 #if 0
857   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
858     if ((Opcode == SystemZ::LA || Opcode == SystemZ::LAY) &&
859         isInt<8>(MI->getOperand(2).getImm()) &&
860         !MI->getOperand(3).getReg()) {
861       // LA(Y) %reg, CONST(%reg) -> AGSI %mem, CONST
862       MachineInstr *BuiltMI =
863         BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
864                      get(SystemZ::AGSI))
865           .addFrameIndex(FrameIndex)
866           .addImm(0)
867           .addImm(MI->getOperand(2).getImm());
868       BuiltMI->findRegisterDefOperand(SystemZ::CC)->setIsDead(true);
869       return BuiltMI;
870     }
871     return nullptr;
872   }
873 #endif
874 
875   // All other cases require a single operand.
876   if (Ops.size() != 1)
877     return nullptr;
878 
879   unsigned OpNum = Ops[0];
880   assert(Size == MF.getRegInfo()
881          .getRegClass(MI->getOperand(OpNum).getReg())->getSize() &&
882          "Invalid size combination");
883 
884   if ((Opcode == SystemZ::AHI || Opcode == SystemZ::AGHI) &&
885       OpNum == 0 &&
886       isInt<8>(MI->getOperand(2).getImm())) {
887     // A(G)HI %reg, CONST -> A(G)SI %mem, CONST
888     Opcode = (Opcode == SystemZ::AHI ? SystemZ::ASI : SystemZ::AGSI);
889     MachineInstr *BuiltMI =
890       BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
891                    get(Opcode))
892         .addFrameIndex(FrameIndex)
893         .addImm(0)
894         .addImm(MI->getOperand(2).getImm());
895     transferDeadCC(MI, BuiltMI);
896     return BuiltMI;
897   }
898 
899   if (Opcode == SystemZ::LGDR || Opcode == SystemZ::LDGR) {
900     bool Op0IsGPR = (Opcode == SystemZ::LGDR);
901     bool Op1IsGPR = (Opcode == SystemZ::LDGR);
902     // If we're spilling the destination of an LDGR or LGDR, store the
903     // source register instead.
904     if (OpNum == 0) {
905       unsigned StoreOpcode = Op1IsGPR ? SystemZ::STG : SystemZ::STD;
906       return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
907                      get(StoreOpcode))
908           .addOperand(MI->getOperand(1))
909           .addFrameIndex(FrameIndex)
910           .addImm(0)
911           .addReg(0);
912     }
913     // If we're spilling the source of an LDGR or LGDR, load the
914     // destination register instead.
915     if (OpNum == 1) {
916       unsigned LoadOpcode = Op0IsGPR ? SystemZ::LG : SystemZ::LD;
917       unsigned Dest = MI->getOperand(0).getReg();
918       return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
919                      get(LoadOpcode), Dest)
920           .addFrameIndex(FrameIndex)
921           .addImm(0)
922           .addReg(0);
923     }
924   }
925 
926   // Look for cases where the source of a simple store or the destination
927   // of a simple load is being spilled.  Try to use MVC instead.
928   //
929   // Although MVC is in practice a fast choice in these cases, it is still
930   // logically a bytewise copy.  This means that we cannot use it if the
931   // load or store is volatile.  We also wouldn't be able to use MVC if
932   // the two memories partially overlap, but that case cannot occur here,
933   // because we know that one of the memories is a full frame index.
934   //
935   // For performance reasons, we also want to avoid using MVC if the addresses
936   // might be equal.  We don't worry about that case here, because spill slot
937   // coloring happens later, and because we have special code to remove
938   // MVCs that turn out to be redundant.
939   if (OpNum == 0 && MI->hasOneMemOperand()) {
940     MachineMemOperand *MMO = *MI->memoperands_begin();
941     if (MMO->getSize() == Size && !MMO->isVolatile()) {
942       // Handle conversion of loads.
943       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXLoad)) {
944         return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
945                        get(SystemZ::MVC))
946             .addFrameIndex(FrameIndex)
947             .addImm(0)
948             .addImm(Size)
949             .addOperand(MI->getOperand(1))
950             .addImm(MI->getOperand(2).getImm())
951             .addMemOperand(MMO);
952       }
953       // Handle conversion of stores.
954       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXStore)) {
955         return BuildMI(*InsertPt->getParent(), InsertPt, MI->getDebugLoc(),
956                        get(SystemZ::MVC))
957             .addOperand(MI->getOperand(1))
958             .addImm(MI->getOperand(2).getImm())
959             .addImm(Size)
960             .addFrameIndex(FrameIndex)
961             .addImm(0)
962             .addMemOperand(MMO);
963       }
964     }
965   }
966 
967   // If the spilled operand is the final one, try to change <INSN>R
968   // into <INSN>.
969   int MemOpcode = SystemZ::getMemOpcode(Opcode);
970   if (MemOpcode >= 0) {
971     unsigned NumOps = MI->getNumExplicitOperands();
972     if (OpNum == NumOps - 1) {
973       const MCInstrDesc &MemDesc = get(MemOpcode);
974       uint64_t AccessBytes = SystemZII::getAccessSize(MemDesc.TSFlags);
975       assert(AccessBytes != 0 && "Size of access should be known");
976       assert(AccessBytes <= Size && "Access outside the frame index");
977       uint64_t Offset = Size - AccessBytes;
978       MachineInstrBuilder MIB = BuildMI(*InsertPt->getParent(), InsertPt,
979                                         MI->getDebugLoc(), get(MemOpcode));
980       for (unsigned I = 0; I < OpNum; ++I)
981         MIB.addOperand(MI->getOperand(I));
982       MIB.addFrameIndex(FrameIndex).addImm(Offset);
983       if (MemDesc.TSFlags & SystemZII::HasIndex)
984         MIB.addReg(0);
985       transferDeadCC(MI, MIB);
986       return MIB;
987     }
988   }
989 
990   return nullptr;
991 }
992 
993 MachineInstr *SystemZInstrInfo::foldMemoryOperandImpl(
994     MachineFunction &MF, MachineInstr *MI, ArrayRef<unsigned> Ops,
995     MachineBasicBlock::iterator InsertPt, MachineInstr *LoadMI) const {
996   return nullptr;
997 }
998 
999 bool
1000 SystemZInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
1001   switch (MI->getOpcode()) {
1002   case SystemZ::L128:
1003     splitMove(MI, SystemZ::LG);
1004     return true;
1005 
1006   case SystemZ::ST128:
1007     splitMove(MI, SystemZ::STG);
1008     return true;
1009 
1010   case SystemZ::LX:
1011     splitMove(MI, SystemZ::LD);
1012     return true;
1013 
1014   case SystemZ::STX:
1015     splitMove(MI, SystemZ::STD);
1016     return true;
1017 
1018   case SystemZ::LBMux:
1019     expandRXYPseudo(MI, SystemZ::LB, SystemZ::LBH);
1020     return true;
1021 
1022   case SystemZ::LHMux:
1023     expandRXYPseudo(MI, SystemZ::LH, SystemZ::LHH);
1024     return true;
1025 
1026   case SystemZ::LLCRMux:
1027     expandZExtPseudo(MI, SystemZ::LLCR, 8);
1028     return true;
1029 
1030   case SystemZ::LLHRMux:
1031     expandZExtPseudo(MI, SystemZ::LLHR, 16);
1032     return true;
1033 
1034   case SystemZ::LLCMux:
1035     expandRXYPseudo(MI, SystemZ::LLC, SystemZ::LLCH);
1036     return true;
1037 
1038   case SystemZ::LLHMux:
1039     expandRXYPseudo(MI, SystemZ::LLH, SystemZ::LLHH);
1040     return true;
1041 
1042   case SystemZ::LMux:
1043     expandRXYPseudo(MI, SystemZ::L, SystemZ::LFH);
1044     return true;
1045 
1046   case SystemZ::STCMux:
1047     expandRXYPseudo(MI, SystemZ::STC, SystemZ::STCH);
1048     return true;
1049 
1050   case SystemZ::STHMux:
1051     expandRXYPseudo(MI, SystemZ::STH, SystemZ::STHH);
1052     return true;
1053 
1054   case SystemZ::STMux:
1055     expandRXYPseudo(MI, SystemZ::ST, SystemZ::STFH);
1056     return true;
1057 
1058   case SystemZ::LHIMux:
1059     expandRIPseudo(MI, SystemZ::LHI, SystemZ::IIHF, true);
1060     return true;
1061 
1062   case SystemZ::IIFMux:
1063     expandRIPseudo(MI, SystemZ::IILF, SystemZ::IIHF, false);
1064     return true;
1065 
1066   case SystemZ::IILMux:
1067     expandRIPseudo(MI, SystemZ::IILL, SystemZ::IIHL, false);
1068     return true;
1069 
1070   case SystemZ::IIHMux:
1071     expandRIPseudo(MI, SystemZ::IILH, SystemZ::IIHH, false);
1072     return true;
1073 
1074   case SystemZ::NIFMux:
1075     expandRIPseudo(MI, SystemZ::NILF, SystemZ::NIHF, false);
1076     return true;
1077 
1078   case SystemZ::NILMux:
1079     expandRIPseudo(MI, SystemZ::NILL, SystemZ::NIHL, false);
1080     return true;
1081 
1082   case SystemZ::NIHMux:
1083     expandRIPseudo(MI, SystemZ::NILH, SystemZ::NIHH, false);
1084     return true;
1085 
1086   case SystemZ::OIFMux:
1087     expandRIPseudo(MI, SystemZ::OILF, SystemZ::OIHF, false);
1088     return true;
1089 
1090   case SystemZ::OILMux:
1091     expandRIPseudo(MI, SystemZ::OILL, SystemZ::OIHL, false);
1092     return true;
1093 
1094   case SystemZ::OIHMux:
1095     expandRIPseudo(MI, SystemZ::OILH, SystemZ::OIHH, false);
1096     return true;
1097 
1098   case SystemZ::XIFMux:
1099     expandRIPseudo(MI, SystemZ::XILF, SystemZ::XIHF, false);
1100     return true;
1101 
1102   case SystemZ::TMLMux:
1103     expandRIPseudo(MI, SystemZ::TMLL, SystemZ::TMHL, false);
1104     return true;
1105 
1106   case SystemZ::TMHMux:
1107     expandRIPseudo(MI, SystemZ::TMLH, SystemZ::TMHH, false);
1108     return true;
1109 
1110   case SystemZ::AHIMux:
1111     expandRIPseudo(MI, SystemZ::AHI, SystemZ::AIH, false);
1112     return true;
1113 
1114   case SystemZ::AHIMuxK:
1115     expandRIEPseudo(MI, SystemZ::AHI, SystemZ::AHIK, SystemZ::AIH);
1116     return true;
1117 
1118   case SystemZ::AFIMux:
1119     expandRIPseudo(MI, SystemZ::AFI, SystemZ::AIH, false);
1120     return true;
1121 
1122   case SystemZ::CFIMux:
1123     expandRIPseudo(MI, SystemZ::CFI, SystemZ::CIH, false);
1124     return true;
1125 
1126   case SystemZ::CLFIMux:
1127     expandRIPseudo(MI, SystemZ::CLFI, SystemZ::CLIH, false);
1128     return true;
1129 
1130   case SystemZ::CMux:
1131     expandRXYPseudo(MI, SystemZ::C, SystemZ::CHF);
1132     return true;
1133 
1134   case SystemZ::CLMux:
1135     expandRXYPseudo(MI, SystemZ::CL, SystemZ::CLHF);
1136     return true;
1137 
1138   case SystemZ::RISBMux: {
1139     bool DestIsHigh = isHighReg(MI->getOperand(0).getReg());
1140     bool SrcIsHigh = isHighReg(MI->getOperand(2).getReg());
1141     if (SrcIsHigh == DestIsHigh)
1142       MI->setDesc(get(DestIsHigh ? SystemZ::RISBHH : SystemZ::RISBLL));
1143     else {
1144       MI->setDesc(get(DestIsHigh ? SystemZ::RISBHL : SystemZ::RISBLH));
1145       MI->getOperand(5).setImm(MI->getOperand(5).getImm() ^ 32);
1146     }
1147     return true;
1148   }
1149 
1150   case SystemZ::ADJDYNALLOC:
1151     splitAdjDynAlloc(MI);
1152     return true;
1153 
1154   case TargetOpcode::LOAD_STACK_GUARD:
1155     expandLoadStackGuard(MI);
1156     return true;
1157 
1158   default:
1159     return false;
1160   }
1161 }
1162 
1163 uint64_t SystemZInstrInfo::getInstSizeInBytes(const MachineInstr *MI) const {
1164   if (MI->getOpcode() == TargetOpcode::INLINEASM) {
1165     const MachineFunction *MF = MI->getParent()->getParent();
1166     const char *AsmStr = MI->getOperand(0).getSymbolName();
1167     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1168   }
1169   return MI->getDesc().getSize();
1170 }
1171 
1172 SystemZII::Branch
1173 SystemZInstrInfo::getBranchInfo(const MachineInstr *MI) const {
1174   switch (MI->getOpcode()) {
1175   case SystemZ::BR:
1176   case SystemZ::J:
1177   case SystemZ::JG:
1178     return SystemZII::Branch(SystemZII::BranchNormal, SystemZ::CCMASK_ANY,
1179                              SystemZ::CCMASK_ANY, &MI->getOperand(0));
1180 
1181   case SystemZ::BRC:
1182   case SystemZ::BRCL:
1183     return SystemZII::Branch(SystemZII::BranchNormal,
1184                              MI->getOperand(0).getImm(),
1185                              MI->getOperand(1).getImm(), &MI->getOperand(2));
1186 
1187   case SystemZ::BRCT:
1188     return SystemZII::Branch(SystemZII::BranchCT, SystemZ::CCMASK_ICMP,
1189                              SystemZ::CCMASK_CMP_NE, &MI->getOperand(2));
1190 
1191   case SystemZ::BRCTG:
1192     return SystemZII::Branch(SystemZII::BranchCTG, SystemZ::CCMASK_ICMP,
1193                              SystemZ::CCMASK_CMP_NE, &MI->getOperand(2));
1194 
1195   case SystemZ::CIJ:
1196   case SystemZ::CRJ:
1197     return SystemZII::Branch(SystemZII::BranchC, SystemZ::CCMASK_ICMP,
1198                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1199 
1200   case SystemZ::CLIJ:
1201   case SystemZ::CLRJ:
1202     return SystemZII::Branch(SystemZII::BranchCL, SystemZ::CCMASK_ICMP,
1203                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1204 
1205   case SystemZ::CGIJ:
1206   case SystemZ::CGRJ:
1207     return SystemZII::Branch(SystemZII::BranchCG, SystemZ::CCMASK_ICMP,
1208                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1209 
1210   case SystemZ::CLGIJ:
1211   case SystemZ::CLGRJ:
1212     return SystemZII::Branch(SystemZII::BranchCLG, SystemZ::CCMASK_ICMP,
1213                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1214 
1215   default:
1216     llvm_unreachable("Unrecognized branch opcode");
1217   }
1218 }
1219 
1220 void SystemZInstrInfo::getLoadStoreOpcodes(const TargetRegisterClass *RC,
1221                                            unsigned &LoadOpcode,
1222                                            unsigned &StoreOpcode) const {
1223   if (RC == &SystemZ::GR32BitRegClass || RC == &SystemZ::ADDR32BitRegClass) {
1224     LoadOpcode = SystemZ::L;
1225     StoreOpcode = SystemZ::ST;
1226   } else if (RC == &SystemZ::GRH32BitRegClass) {
1227     LoadOpcode = SystemZ::LFH;
1228     StoreOpcode = SystemZ::STFH;
1229   } else if (RC == &SystemZ::GRX32BitRegClass) {
1230     LoadOpcode = SystemZ::LMux;
1231     StoreOpcode = SystemZ::STMux;
1232   } else if (RC == &SystemZ::GR64BitRegClass ||
1233              RC == &SystemZ::ADDR64BitRegClass) {
1234     LoadOpcode = SystemZ::LG;
1235     StoreOpcode = SystemZ::STG;
1236   } else if (RC == &SystemZ::GR128BitRegClass ||
1237              RC == &SystemZ::ADDR128BitRegClass) {
1238     LoadOpcode = SystemZ::L128;
1239     StoreOpcode = SystemZ::ST128;
1240   } else if (RC == &SystemZ::FP32BitRegClass) {
1241     LoadOpcode = SystemZ::LE;
1242     StoreOpcode = SystemZ::STE;
1243   } else if (RC == &SystemZ::FP64BitRegClass) {
1244     LoadOpcode = SystemZ::LD;
1245     StoreOpcode = SystemZ::STD;
1246   } else if (RC == &SystemZ::FP128BitRegClass) {
1247     LoadOpcode = SystemZ::LX;
1248     StoreOpcode = SystemZ::STX;
1249   } else if (RC == &SystemZ::VR32BitRegClass) {
1250     LoadOpcode = SystemZ::VL32;
1251     StoreOpcode = SystemZ::VST32;
1252   } else if (RC == &SystemZ::VR64BitRegClass) {
1253     LoadOpcode = SystemZ::VL64;
1254     StoreOpcode = SystemZ::VST64;
1255   } else if (RC == &SystemZ::VF128BitRegClass ||
1256              RC == &SystemZ::VR128BitRegClass) {
1257     LoadOpcode = SystemZ::VL;
1258     StoreOpcode = SystemZ::VST;
1259   } else
1260     llvm_unreachable("Unsupported regclass to load or store");
1261 }
1262 
1263 unsigned SystemZInstrInfo::getOpcodeForOffset(unsigned Opcode,
1264                                               int64_t Offset) const {
1265   const MCInstrDesc &MCID = get(Opcode);
1266   int64_t Offset2 = (MCID.TSFlags & SystemZII::Is128Bit ? Offset + 8 : Offset);
1267   if (isUInt<12>(Offset) && isUInt<12>(Offset2)) {
1268     // Get the instruction to use for unsigned 12-bit displacements.
1269     int Disp12Opcode = SystemZ::getDisp12Opcode(Opcode);
1270     if (Disp12Opcode >= 0)
1271       return Disp12Opcode;
1272 
1273     // All address-related instructions can use unsigned 12-bit
1274     // displacements.
1275     return Opcode;
1276   }
1277   if (isInt<20>(Offset) && isInt<20>(Offset2)) {
1278     // Get the instruction to use for signed 20-bit displacements.
1279     int Disp20Opcode = SystemZ::getDisp20Opcode(Opcode);
1280     if (Disp20Opcode >= 0)
1281       return Disp20Opcode;
1282 
1283     // Check whether Opcode allows signed 20-bit displacements.
1284     if (MCID.TSFlags & SystemZII::Has20BitOffset)
1285       return Opcode;
1286   }
1287   return 0;
1288 }
1289 
1290 unsigned SystemZInstrInfo::getLoadAndTest(unsigned Opcode) const {
1291   switch (Opcode) {
1292   case SystemZ::L:      return SystemZ::LT;
1293   case SystemZ::LY:     return SystemZ::LT;
1294   case SystemZ::LG:     return SystemZ::LTG;
1295   case SystemZ::LGF:    return SystemZ::LTGF;
1296   case SystemZ::LR:     return SystemZ::LTR;
1297   case SystemZ::LGFR:   return SystemZ::LTGFR;
1298   case SystemZ::LGR:    return SystemZ::LTGR;
1299   case SystemZ::LER:    return SystemZ::LTEBR;
1300   case SystemZ::LDR:    return SystemZ::LTDBR;
1301   case SystemZ::LXR:    return SystemZ::LTXBR;
1302   case SystemZ::LCDFR:  return SystemZ::LCDBR;
1303   case SystemZ::LPDFR:  return SystemZ::LPDBR;
1304   case SystemZ::LNDFR:  return SystemZ::LNDBR;
1305   case SystemZ::LCDFR_32:  return SystemZ::LCEBR;
1306   case SystemZ::LPDFR_32:  return SystemZ::LPEBR;
1307   case SystemZ::LNDFR_32:  return SystemZ::LNEBR;
1308   // On zEC12 we prefer to use RISBGN.  But if there is a chance to
1309   // actually use the condition code, we may turn it back into RISGB.
1310   // Note that RISBG is not really a "load-and-test" instruction,
1311   // but sets the same condition code values, so is OK to use here.
1312   case SystemZ::RISBGN: return SystemZ::RISBG;
1313   default:              return 0;
1314   }
1315 }
1316 
1317 // Return true if Mask matches the regexp 0*1+0*, given that zero masks
1318 // have already been filtered out.  Store the first set bit in LSB and
1319 // the number of set bits in Length if so.
1320 static bool isStringOfOnes(uint64_t Mask, unsigned &LSB, unsigned &Length) {
1321   unsigned First = findFirstSet(Mask);
1322   uint64_t Top = (Mask >> First) + 1;
1323   if ((Top & -Top) == Top) {
1324     LSB = First;
1325     Length = findFirstSet(Top);
1326     return true;
1327   }
1328   return false;
1329 }
1330 
1331 bool SystemZInstrInfo::isRxSBGMask(uint64_t Mask, unsigned BitSize,
1332                                    unsigned &Start, unsigned &End) const {
1333   // Reject trivial all-zero masks.
1334   Mask &= allOnes(BitSize);
1335   if (Mask == 0)
1336     return false;
1337 
1338   // Handle the 1+0+ or 0+1+0* cases.  Start then specifies the index of
1339   // the msb and End specifies the index of the lsb.
1340   unsigned LSB, Length;
1341   if (isStringOfOnes(Mask, LSB, Length)) {
1342     Start = 63 - (LSB + Length - 1);
1343     End = 63 - LSB;
1344     return true;
1345   }
1346 
1347   // Handle the wrap-around 1+0+1+ cases.  Start then specifies the msb
1348   // of the low 1s and End specifies the lsb of the high 1s.
1349   if (isStringOfOnes(Mask ^ allOnes(BitSize), LSB, Length)) {
1350     assert(LSB > 0 && "Bottom bit must be set");
1351     assert(LSB + Length < BitSize && "Top bit must be set");
1352     Start = 63 - (LSB - 1);
1353     End = 63 - (LSB + Length);
1354     return true;
1355   }
1356 
1357   return false;
1358 }
1359 
1360 unsigned SystemZInstrInfo::getCompareAndBranch(unsigned Opcode,
1361                                                SystemZII::CompareAndBranchType Type,
1362                                                const MachineInstr *MI) const {
1363   switch (Opcode) {
1364   case SystemZ::CHI:
1365   case SystemZ::CGHI:
1366     if (!(MI && isInt<8>(MI->getOperand(1).getImm())))
1367       return 0;
1368     break;
1369   case SystemZ::CLFI:
1370   case SystemZ::CLGFI:
1371     if (!(MI && isUInt<8>(MI->getOperand(1).getImm())))
1372       return 0;
1373   }
1374   switch (Type) {
1375   case SystemZII::CompareAndBranch:
1376     switch (Opcode) {
1377     case SystemZ::CR:
1378       return SystemZ::CRJ;
1379     case SystemZ::CGR:
1380       return SystemZ::CGRJ;
1381     case SystemZ::CHI:
1382       return SystemZ::CIJ;
1383     case SystemZ::CGHI:
1384       return SystemZ::CGIJ;
1385     case SystemZ::CLR:
1386       return SystemZ::CLRJ;
1387     case SystemZ::CLGR:
1388       return SystemZ::CLGRJ;
1389     case SystemZ::CLFI:
1390       return SystemZ::CLIJ;
1391     case SystemZ::CLGFI:
1392       return SystemZ::CLGIJ;
1393     default:
1394       return 0;
1395     }
1396   case SystemZII::CompareAndReturn:
1397     switch (Opcode) {
1398     case SystemZ::CR:
1399       return SystemZ::CRBReturn;
1400     case SystemZ::CGR:
1401       return SystemZ::CGRBReturn;
1402     case SystemZ::CHI:
1403       return SystemZ::CIBReturn;
1404     case SystemZ::CGHI:
1405       return SystemZ::CGIBReturn;
1406     case SystemZ::CLR:
1407       return SystemZ::CLRBReturn;
1408     case SystemZ::CLGR:
1409       return SystemZ::CLGRBReturn;
1410     case SystemZ::CLFI:
1411       return SystemZ::CLIBReturn;
1412     case SystemZ::CLGFI:
1413       return SystemZ::CLGIBReturn;
1414     default:
1415       return 0;
1416     }
1417   case SystemZII::CompareAndSibcall:
1418     switch (Opcode) {
1419     case SystemZ::CR:
1420       return SystemZ::CRBCall;
1421     case SystemZ::CGR:
1422       return SystemZ::CGRBCall;
1423     case SystemZ::CHI:
1424       return SystemZ::CIBCall;
1425     case SystemZ::CGHI:
1426       return SystemZ::CGIBCall;
1427     case SystemZ::CLR:
1428       return SystemZ::CLRBCall;
1429     case SystemZ::CLGR:
1430       return SystemZ::CLGRBCall;
1431     case SystemZ::CLFI:
1432       return SystemZ::CLIBCall;
1433     case SystemZ::CLGFI:
1434       return SystemZ::CLGIBCall;
1435     default:
1436       return 0;
1437     }
1438   }
1439   return 0;
1440 }
1441 
1442 void SystemZInstrInfo::loadImmediate(MachineBasicBlock &MBB,
1443                                      MachineBasicBlock::iterator MBBI,
1444                                      unsigned Reg, uint64_t Value) const {
1445   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1446   unsigned Opcode;
1447   if (isInt<16>(Value))
1448     Opcode = SystemZ::LGHI;
1449   else if (SystemZ::isImmLL(Value))
1450     Opcode = SystemZ::LLILL;
1451   else if (SystemZ::isImmLH(Value)) {
1452     Opcode = SystemZ::LLILH;
1453     Value >>= 16;
1454   } else {
1455     assert(isInt<32>(Value) && "Huge values not handled yet");
1456     Opcode = SystemZ::LGFI;
1457   }
1458   BuildMI(MBB, MBBI, DL, get(Opcode), Reg).addImm(Value);
1459 }
1460