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