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