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