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