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