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