[mips] Split SelectAddr, which was used to match address patterns, into two
[oota-llvm.git] / lib / Target / Mips / MipsISelDAGToDAG.cpp
1 //===-- MipsISelDAGToDAG.cpp - A Dag to Dag Inst Selector for Mips --------===//
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 defines an instruction selector for the MIPS target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "mips-isel"
15 #include "Mips.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsAnalyzeImmediate.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsRegisterInfo.h"
20 #include "MipsSubtarget.h"
21 #include "MipsTargetMachine.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/CodeGen/SelectionDAGNodes.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetMachine.h"
38 using namespace llvm;
39
40 //===----------------------------------------------------------------------===//
41 // Instruction Selector Implementation
42 //===----------------------------------------------------------------------===//
43
44 //===----------------------------------------------------------------------===//
45 // MipsDAGToDAGISel - MIPS specific code to select MIPS machine
46 // instructions for SelectionDAG operations.
47 //===----------------------------------------------------------------------===//
48 namespace {
49
50 class MipsDAGToDAGISel : public SelectionDAGISel {
51
52   /// TM - Keep a reference to MipsTargetMachine.
53   MipsTargetMachine &TM;
54
55   /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
56   /// make the right decision when generating code for different targets.
57   const MipsSubtarget &Subtarget;
58
59 public:
60   explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
61   SelectionDAGISel(tm),
62   TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
63
64   // Pass Name
65   virtual const char *getPassName() const {
66     return "MIPS DAG->DAG Pattern Instruction Selection";
67   }
68
69   virtual bool runOnMachineFunction(MachineFunction &MF);
70
71 private:
72   // Include the pieces autogenerated from the target description.
73   #include "MipsGenDAGISel.inc"
74
75   /// getTargetMachine - Return a reference to the TargetMachine, casted
76   /// to the target-specific type.
77   const MipsTargetMachine &getTargetMachine() {
78     return static_cast<const MipsTargetMachine &>(TM);
79   }
80
81   /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
82   /// to the target-specific type.
83   const MipsInstrInfo *getInstrInfo() {
84     return getTargetMachine().getInstrInfo();
85   }
86
87   SDNode *getGlobalBaseReg();
88
89   SDValue getMips16SPAliasReg();
90
91   void getMips16SPRefReg(SDNode *parent, SDValue &AliasReg);
92
93   std::pair<SDNode*, SDNode*> SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl,
94                                          EVT Ty, bool HasLo, bool HasHi);
95
96   SDNode *Select(SDNode *N);
97
98   // Complex Pattern.
99   /// (reg + imm).
100   bool selectAddrRegImm(SDNode *Parent, SDValue Addr, SDValue &Base,
101                         SDValue &Offset) const;
102
103   /// Fall back on this function if all else fails.
104   bool selectAddrDefault(SDNode *Parent, SDValue Addr, SDValue &Base,
105                          SDValue &Offset) const;
106
107   /// Match integer address pattern.
108   bool selectIntAddr(SDNode *Parent, SDValue Addr, SDValue &Base,
109                      SDValue &Offset) const;
110
111   bool SelectAddr16(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Offset,
112        SDValue &Alias);
113
114   // getImm - Return a target constant with the specified value.
115   inline SDValue getImm(const SDNode *Node, unsigned Imm) {
116     return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
117   }
118
119   void ProcessFunctionAfterISel(MachineFunction &MF);
120   bool ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI, const MachineInstr&);
121   void InitGlobalBaseReg(MachineFunction &MF);
122   void InitMips16SPAliasReg(MachineFunction &MF);
123
124   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
125                                             char ConstraintCode,
126                                             std::vector<SDValue> &OutOps);
127 };
128
129 }
130
131 // Insert instructions to initialize the global base register in the
132 // first MBB of the function. When the ABI is O32 and the relocation model is
133 // PIC, the necessary instructions are emitted later to prevent optimization
134 // passes from moving them.
135 void MipsDAGToDAGISel::InitGlobalBaseReg(MachineFunction &MF) {
136   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
137
138   if (!MipsFI->globalBaseRegSet())
139     return;
140
141   MachineBasicBlock &MBB = MF.front();
142   MachineBasicBlock::iterator I = MBB.begin();
143   MachineRegisterInfo &RegInfo = MF.getRegInfo();
144   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
145   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
146   unsigned V0, V1, V2, GlobalBaseReg = MipsFI->getGlobalBaseReg();
147   const TargetRegisterClass *RC;
148
149   if (Subtarget.isABI_N64())
150     RC = (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
151   else if (Subtarget.inMips16Mode())
152     RC = (const TargetRegisterClass*)&Mips::CPU16RegsRegClass;
153   else
154     RC = (const TargetRegisterClass*)&Mips::CPURegsRegClass;
155
156   V0 = RegInfo.createVirtualRegister(RC);
157   V1 = RegInfo.createVirtualRegister(RC);
158   V2 = RegInfo.createVirtualRegister(RC);
159
160   if (Subtarget.isABI_N64()) {
161     MF.getRegInfo().addLiveIn(Mips::T9_64);
162     MBB.addLiveIn(Mips::T9_64);
163
164     // lui $v0, %hi(%neg(%gp_rel(fname)))
165     // daddu $v1, $v0, $t9
166     // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
167     const GlobalValue *FName = MF.getFunction();
168     BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
169       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
170     BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0)
171       .addReg(Mips::T9_64);
172     BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
173       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
174     return;
175   }
176
177   if (Subtarget.inMips16Mode()) {
178     BuildMI(MBB, I, DL, TII.get(Mips::LiRxImmX16), V0)
179       .addExternalSymbol("_gp_disp", MipsII::MO_ABS_HI);
180     BuildMI(MBB, I, DL, TII.get(Mips::AddiuRxPcImmX16), V1)
181       .addExternalSymbol("_gp_disp", MipsII::MO_ABS_LO);
182     BuildMI(MBB, I, DL, TII.get(Mips::SllX16), V2).addReg(V0).addImm(16);
183     BuildMI(MBB, I, DL, TII.get(Mips::AdduRxRyRz16), GlobalBaseReg)
184       .addReg(V1).addReg(V2);
185     return;
186   }
187
188   if (MF.getTarget().getRelocationModel() == Reloc::Static) {
189     // Set global register to __gnu_local_gp.
190     //
191     // lui   $v0, %hi(__gnu_local_gp)
192     // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
193     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
194       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
195     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
196       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
197     return;
198   }
199
200   MF.getRegInfo().addLiveIn(Mips::T9);
201   MBB.addLiveIn(Mips::T9);
202
203   if (Subtarget.isABI_N32()) {
204     // lui $v0, %hi(%neg(%gp_rel(fname)))
205     // addu $v1, $v0, $t9
206     // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
207     const GlobalValue *FName = MF.getFunction();
208     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
209       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
210     BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
211     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
212       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
213     return;
214   }
215
216   assert(Subtarget.isABI_O32());
217
218   // For O32 ABI, the following instruction sequence is emitted to initialize
219   // the global base register:
220   //
221   //  0. lui   $2, %hi(_gp_disp)
222   //  1. addiu $2, $2, %lo(_gp_disp)
223   //  2. addu  $globalbasereg, $2, $t9
224   //
225   // We emit only the last instruction here.
226   //
227   // GNU linker requires that the first two instructions appear at the beginning
228   // of a function and no instructions be inserted before or between them.
229   // The two instructions are emitted during lowering to MC layer in order to
230   // avoid any reordering.
231   //
232   // Register $2 (Mips::V0) is added to the list of live-in registers to ensure
233   // the value instruction 1 (addiu) defines is valid when instruction 2 (addu)
234   // reads it.
235   MF.getRegInfo().addLiveIn(Mips::V0);
236   MBB.addLiveIn(Mips::V0);
237   BuildMI(MBB, I, DL, TII.get(Mips::ADDu), GlobalBaseReg)
238     .addReg(Mips::V0).addReg(Mips::T9);
239 }
240
241 // Insert instructions to initialize the Mips16 SP Alias register in the
242 // first MBB of the function.
243 //
244 void MipsDAGToDAGISel::InitMips16SPAliasReg(MachineFunction &MF) {
245   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
246
247   if (!MipsFI->mips16SPAliasRegSet())
248     return;
249
250   MachineBasicBlock &MBB = MF.front();
251   MachineBasicBlock::iterator I = MBB.begin();
252   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
253   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
254   unsigned Mips16SPAliasReg = MipsFI->getMips16SPAliasReg();
255
256   BuildMI(MBB, I, DL, TII.get(Mips::MoveR3216), Mips16SPAliasReg)
257     .addReg(Mips::SP);
258 }
259
260
261 bool MipsDAGToDAGISel::ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI,
262                                               const MachineInstr& MI) {
263   unsigned DstReg = 0, ZeroReg = 0;
264
265   // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
266   if ((MI.getOpcode() == Mips::ADDiu) &&
267       (MI.getOperand(1).getReg() == Mips::ZERO) &&
268       (MI.getOperand(2).getImm() == 0)) {
269     DstReg = MI.getOperand(0).getReg();
270     ZeroReg = Mips::ZERO;
271   } else if ((MI.getOpcode() == Mips::DADDiu) &&
272              (MI.getOperand(1).getReg() == Mips::ZERO_64) &&
273              (MI.getOperand(2).getImm() == 0)) {
274     DstReg = MI.getOperand(0).getReg();
275     ZeroReg = Mips::ZERO_64;
276   }
277
278   if (!DstReg)
279     return false;
280
281   // Replace uses with ZeroReg.
282   for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
283        E = MRI->use_end(); U != E;) {
284     MachineOperand &MO = U.getOperand();
285     unsigned OpNo = U.getOperandNo();
286     MachineInstr *MI = MO.getParent();
287     ++U;
288
289     // Do not replace if it is a phi's operand or is tied to def operand.
290     if (MI->isPHI() || MI->isRegTiedToDefOperand(OpNo) || MI->isPseudo())
291       continue;
292
293     MO.setReg(ZeroReg);
294   }
295
296   return true;
297 }
298
299 void MipsDAGToDAGISel::ProcessFunctionAfterISel(MachineFunction &MF) {
300   InitGlobalBaseReg(MF);
301   InitMips16SPAliasReg(MF);
302
303   MachineRegisterInfo *MRI = &MF.getRegInfo();
304
305   for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
306        ++MFI)
307     for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I)
308       ReplaceUsesWithZeroReg(MRI, *I);
309 }
310
311 bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
312   bool Ret = SelectionDAGISel::runOnMachineFunction(MF);
313
314   ProcessFunctionAfterISel(MF);
315
316   return Ret;
317 }
318
319 /// getGlobalBaseReg - Output the instructions required to put the
320 /// GOT address into a register.
321 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
322   unsigned GlobalBaseReg = MF->getInfo<MipsFunctionInfo>()->getGlobalBaseReg();
323   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
324 }
325
326 /// getMips16SPAliasReg - Output the instructions required to put the
327 /// SP into a Mips16 accessible aliased register.
328 SDValue MipsDAGToDAGISel::getMips16SPAliasReg() {
329   unsigned Mips16SPAliasReg =
330     MF->getInfo<MipsFunctionInfo>()->getMips16SPAliasReg();
331   return CurDAG->getRegister(Mips16SPAliasReg, TLI.getPointerTy());
332 }
333
334 /// ComplexPattern used on MipsInstrInfo
335 /// Used on Mips Load/Store instructions
336 bool MipsDAGToDAGISel::selectAddrRegImm(SDNode *Parent, SDValue Addr,
337                                         SDValue &Base, SDValue &Offset) const {
338   EVT ValTy = Addr.getValueType();
339
340   // if Address is FI, get the TargetFrameIndex.
341   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
342     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
343     Offset = CurDAG->getTargetConstant(0, ValTy);
344     return true;
345   }
346
347   // on PIC code Load GA
348   if (Addr.getOpcode() == MipsISD::Wrapper) {
349     Base   = Addr.getOperand(0);
350     Offset = Addr.getOperand(1);
351     return true;
352   }
353
354   if (TM.getRelocationModel() != Reloc::PIC_) {
355     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
356         Addr.getOpcode() == ISD::TargetGlobalAddress))
357       return false;
358   }
359
360   // Addresses of the form FI+const or FI|const
361   if (CurDAG->isBaseWithConstantOffset(Addr)) {
362     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
363     if (isInt<16>(CN->getSExtValue())) {
364
365       // If the first operand is a FI, get the TargetFI Node
366       if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
367                                   (Addr.getOperand(0)))
368         Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
369       else
370         Base = Addr.getOperand(0);
371
372       Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
373       return true;
374     }
375   }
376
377   // Operand is a result from an ADD.
378   if (Addr.getOpcode() == ISD::ADD) {
379     // When loading from constant pools, load the lower address part in
380     // the instruction itself. Example, instead of:
381     //  lui $2, %hi($CPI1_0)
382     //  addiu $2, $2, %lo($CPI1_0)
383     //  lwc1 $f0, 0($2)
384     // Generate:
385     //  lui $2, %hi($CPI1_0)
386     //  lwc1 $f0, %lo($CPI1_0)($2)
387     if (Addr.getOperand(1).getOpcode() == MipsISD::Lo ||
388         Addr.getOperand(1).getOpcode() == MipsISD::GPRel) {
389       SDValue Opnd0 = Addr.getOperand(1).getOperand(0);
390       if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
391           isa<JumpTableSDNode>(Opnd0)) {
392         Base = Addr.getOperand(0);
393         Offset = Opnd0;
394         return true;
395       }
396     }
397   }
398
399   return false;
400 }
401
402 bool MipsDAGToDAGISel::selectAddrDefault(SDNode *Parent, SDValue Addr,
403                                          SDValue &Base, SDValue &Offset) const {
404   Base = Addr;
405   Offset = CurDAG->getTargetConstant(0, Addr.getValueType());
406   return true;
407 }
408
409 bool MipsDAGToDAGISel::selectIntAddr(SDNode *Parent, SDValue Addr,
410                                      SDValue &Base, SDValue &Offset) const {
411   return selectAddrRegImm(Parent, Addr, Base, Offset) ||
412     selectAddrDefault(Parent, Addr, Base, Offset);
413 }
414
415 void MipsDAGToDAGISel::getMips16SPRefReg(SDNode *Parent, SDValue &AliasReg) {
416   SDValue AliasFPReg = CurDAG->getRegister(Mips::S0, TLI.getPointerTy());
417   if (Parent) {
418     switch (Parent->getOpcode()) {
419       case ISD::LOAD: {
420         LoadSDNode *SD = dyn_cast<LoadSDNode>(Parent);
421         switch (SD->getMemoryVT().getSizeInBits()) {
422         case 8:
423         case 16:
424           AliasReg = TM.getFrameLowering()->hasFP(*MF)?
425             AliasFPReg: getMips16SPAliasReg();
426           return;
427         }
428         break;
429       }
430       case ISD::STORE: {
431         StoreSDNode *SD = dyn_cast<StoreSDNode>(Parent);
432         switch (SD->getMemoryVT().getSizeInBits()) {
433         case 8:
434         case 16:
435           AliasReg = TM.getFrameLowering()->hasFP(*MF)?
436             AliasFPReg: getMips16SPAliasReg();
437           return;
438         }
439         break;
440       }
441     }
442   }
443   AliasReg = CurDAG->getRegister(Mips::SP, TLI.getPointerTy());
444   return;
445
446 }
447 bool MipsDAGToDAGISel::SelectAddr16(
448   SDNode *Parent, SDValue Addr, SDValue &Base, SDValue &Offset,
449   SDValue &Alias) {
450   EVT ValTy = Addr.getValueType();
451
452   Alias = CurDAG->getTargetConstant(0, ValTy);
453
454   // if Address is FI, get the TargetFrameIndex.
455   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
456     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
457     Offset = CurDAG->getTargetConstant(0, ValTy);
458     getMips16SPRefReg(Parent, Alias);
459     return true;
460   }
461   // on PIC code Load GA
462   if (Addr.getOpcode() == MipsISD::Wrapper) {
463     Base   = Addr.getOperand(0);
464     Offset = Addr.getOperand(1);
465     return true;
466   }
467   if (TM.getRelocationModel() != Reloc::PIC_) {
468     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
469         Addr.getOpcode() == ISD::TargetGlobalAddress))
470       return false;
471   }
472   // Addresses of the form FI+const or FI|const
473   if (CurDAG->isBaseWithConstantOffset(Addr)) {
474     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
475     if (isInt<16>(CN->getSExtValue())) {
476
477       // If the first operand is a FI, get the TargetFI Node
478       if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
479                                   (Addr.getOperand(0))) {
480         Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
481         getMips16SPRefReg(Parent, Alias);
482       }
483       else
484         Base = Addr.getOperand(0);
485
486       Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
487       return true;
488     }
489   }
490   // Operand is a result from an ADD.
491   if (Addr.getOpcode() == ISD::ADD) {
492     // When loading from constant pools, load the lower address part in
493     // the instruction itself. Example, instead of:
494     //  lui $2, %hi($CPI1_0)
495     //  addiu $2, $2, %lo($CPI1_0)
496     //  lwc1 $f0, 0($2)
497     // Generate:
498     //  lui $2, %hi($CPI1_0)
499     //  lwc1 $f0, %lo($CPI1_0)($2)
500     if (Addr.getOperand(1).getOpcode() == MipsISD::Lo ||
501         Addr.getOperand(1).getOpcode() == MipsISD::GPRel) {
502       SDValue Opnd0 = Addr.getOperand(1).getOperand(0);
503       if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
504           isa<JumpTableSDNode>(Opnd0)) {
505         Base = Addr.getOperand(0);
506         Offset = Opnd0;
507         return true;
508       }
509     }
510
511     // If an indexed floating point load/store can be emitted, return false.
512     const LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(Parent);
513
514     if (LS &&
515         (LS->getMemoryVT() == MVT::f32 || LS->getMemoryVT() == MVT::f64) &&
516         Subtarget.hasFPIdx())
517       return false;
518   }
519   Base   = Addr;
520   Offset = CurDAG->getTargetConstant(0, ValTy);
521   return true;
522 }
523
524 /// Select multiply instructions.
525 std::pair<SDNode*, SDNode*>
526 MipsDAGToDAGISel::SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl, EVT Ty,
527                              bool HasLo, bool HasHi) {
528   SDNode *Lo = 0, *Hi = 0;
529   SDNode *Mul = CurDAG->getMachineNode(Opc, dl, MVT::Glue, N->getOperand(0),
530                                        N->getOperand(1));
531   SDValue InFlag = SDValue(Mul, 0);
532
533   if (HasLo) {
534     unsigned Opcode = Subtarget.inMips16Mode() ? Mips::Mflo16 :
535       (Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64);
536     Lo = CurDAG->getMachineNode(Opcode, dl, Ty, MVT::Glue, InFlag);
537     InFlag = SDValue(Lo, 1);
538   }
539   if (HasHi) {
540     unsigned Opcode = Subtarget.inMips16Mode() ? Mips::Mfhi16 :
541       (Ty == MVT::i32 ? Mips::MFHI : Mips::MFHI64);
542     Hi = CurDAG->getMachineNode(Opcode, dl, Ty, InFlag);
543   }
544   return std::make_pair(Lo, Hi);
545 }
546
547
548 /// Select instructions not customized! Used for
549 /// expanded, promoted and normal instructions
550 SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
551   unsigned Opcode = Node->getOpcode();
552   DebugLoc dl = Node->getDebugLoc();
553
554   // Dump information about the Node being selected
555   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
556
557   // If we have a custom node, we already have selected!
558   if (Node->isMachineOpcode()) {
559     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
560     return NULL;
561   }
562
563   ///
564   // Instruction Selection not handled by the auto-generated
565   // tablegen selection should be handled here.
566   ///
567   EVT NodeTy = Node->getValueType(0);
568   unsigned MultOpc;
569
570   switch(Opcode) {
571   default: break;
572
573   case ISD::SUBE:
574   case ISD::ADDE: {
575     bool inMips16Mode = Subtarget.inMips16Mode();
576     SDValue InFlag = Node->getOperand(2), CmpLHS;
577     unsigned Opc = InFlag.getOpcode(); (void)Opc;
578     assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
579             (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
580            "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
581
582     unsigned MOp;
583     if (Opcode == ISD::ADDE) {
584       CmpLHS = InFlag.getValue(0);
585       if (inMips16Mode)
586         MOp = Mips::AdduRxRyRz16;
587       else
588         MOp = Mips::ADDu;
589     } else {
590       CmpLHS = InFlag.getOperand(0);
591       if (inMips16Mode)
592         MOp = Mips::SubuRxRyRz16;
593       else
594         MOp = Mips::SUBu;
595     }
596
597     SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
598
599     SDValue LHS = Node->getOperand(0);
600     SDValue RHS = Node->getOperand(1);
601
602     EVT VT = LHS.getValueType();
603
604     unsigned Sltu_op = inMips16Mode? Mips::SltuRxRyRz16: Mips::SLTu;
605     SDNode *Carry = CurDAG->getMachineNode(Sltu_op, dl, VT, Ops, 2);
606     unsigned Addu_op = inMips16Mode? Mips::AdduRxRyRz16 : Mips::ADDu;
607     SDNode *AddCarry = CurDAG->getMachineNode(Addu_op, dl, VT,
608                                               SDValue(Carry,0), RHS);
609
610     return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
611                                 LHS, SDValue(AddCarry,0));
612   }
613
614   /// Mul with two results
615   case ISD::SMUL_LOHI:
616   case ISD::UMUL_LOHI: {
617     if (NodeTy == MVT::i32) {
618       if (Subtarget.inMips16Mode())
619         MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MultuRxRy16 :
620                    Mips::MultRxRy16);
621       else
622         MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
623     }
624     else
625       MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMULT);
626
627     std::pair<SDNode*, SDNode*> LoHi = SelectMULT(Node, MultOpc, dl, NodeTy,
628                                                   true, true);
629
630     if (!SDValue(Node, 0).use_empty())
631       ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
632
633     if (!SDValue(Node, 1).use_empty())
634       ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
635
636     return NULL;
637   }
638
639   /// Special Muls
640   case ISD::MUL: {
641     // Mips32 has a 32-bit three operand mul instruction.
642     if (Subtarget.hasMips32() && NodeTy == MVT::i32)
643       break;
644     return SelectMULT(Node, NodeTy == MVT::i32 ? Mips::MULT : Mips::DMULT,
645                       dl, NodeTy, true, false).first;
646   }
647   case ISD::MULHS:
648   case ISD::MULHU: {
649     if (NodeTy == MVT::i32) {
650       if (Subtarget.inMips16Mode())
651         MultOpc = (Opcode == ISD::MULHU ?
652                    Mips::MultuRxRy16 : Mips::MultRxRy16);
653       else
654         MultOpc = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
655     }
656     else
657       MultOpc = (Opcode == ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
658
659     return SelectMULT(Node, MultOpc, dl, NodeTy, false, true).second;
660   }
661
662   // Get target GOT address.
663   case ISD::GLOBAL_OFFSET_TABLE:
664     return getGlobalBaseReg();
665
666   case ISD::ConstantFP: {
667     ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
668     if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
669       if (Subtarget.hasMips64()) {
670         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
671                                               Mips::ZERO_64, MVT::i64);
672         return CurDAG->getMachineNode(Mips::DMTC1, dl, MVT::f64, Zero);
673       }
674
675       SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
676                                             Mips::ZERO, MVT::i32);
677       return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
678                                     Zero);
679     }
680     break;
681   }
682
683   case ISD::Constant: {
684     const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
685     unsigned Size = CN->getValueSizeInBits(0);
686
687     if (Size == 32)
688       break;
689
690     MipsAnalyzeImmediate AnalyzeImm;
691     int64_t Imm = CN->getSExtValue();
692
693     const MipsAnalyzeImmediate::InstSeq &Seq =
694       AnalyzeImm.Analyze(Imm, Size, false);
695
696     MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
697     DebugLoc DL = CN->getDebugLoc();
698     SDNode *RegOpnd;
699     SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
700                                                 MVT::i64);
701
702     // The first instruction can be a LUi which is different from other
703     // instructions (ADDiu, ORI and SLL) in that it does not have a register
704     // operand.
705     if (Inst->Opc == Mips::LUi64)
706       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
707     else
708       RegOpnd =
709         CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
710                                CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
711                                ImmOpnd);
712
713     // The remaining instructions in the sequence are handled here.
714     for (++Inst; Inst != Seq.end(); ++Inst) {
715       ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
716                                           MVT::i64);
717       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
718                                        SDValue(RegOpnd, 0), ImmOpnd);
719     }
720
721     return RegOpnd;
722   }
723
724 #ifndef NDEBUG
725   case ISD::LOAD:
726   case ISD::STORE:
727     assert(cast<MemSDNode>(Node)->getMemoryVT().getSizeInBits() / 8 <=
728            cast<MemSDNode>(Node)->getAlignment() &&
729            "Unexpected unaligned loads/stores.");
730     break;
731 #endif
732
733   case MipsISD::ThreadPointer: {
734     EVT PtrVT = TLI.getPointerTy();
735     unsigned RdhwrOpc, SrcReg, DestReg;
736
737     if (PtrVT == MVT::i32) {
738       RdhwrOpc = Mips::RDHWR;
739       SrcReg = Mips::HWR29;
740       DestReg = Mips::V1;
741     } else {
742       RdhwrOpc = Mips::RDHWR64;
743       SrcReg = Mips::HWR29_64;
744       DestReg = Mips::V1_64;
745     }
746
747     SDNode *Rdhwr =
748       CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
749                              Node->getValueType(0),
750                              CurDAG->getRegister(SrcReg, PtrVT));
751     SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
752                                          SDValue(Rdhwr, 0));
753     SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, PtrVT);
754     ReplaceUses(SDValue(Node, 0), ResNode);
755     return ResNode.getNode();
756   }
757   }
758
759   // Select the default instruction
760   SDNode *ResNode = SelectCode(Node);
761
762   DEBUG(errs() << "=> ");
763   if (ResNode == NULL || ResNode == Node)
764     DEBUG(Node->dump(CurDAG));
765   else
766     DEBUG(ResNode->dump(CurDAG));
767   DEBUG(errs() << "\n");
768   return ResNode;
769 }
770
771 bool MipsDAGToDAGISel::
772 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
773                              std::vector<SDValue> &OutOps) {
774   assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
775   OutOps.push_back(Op);
776   return false;
777 }
778
779 /// createMipsISelDag - This pass converts a legalized DAG into a
780 /// MIPS-specific DAG, ready for instruction scheduling.
781 FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
782   return new MipsDAGToDAGISel(TM);
783 }