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