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