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