Add an option to use a virtual register as the global base register instead of
[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 "MipsAnalyzeImmediate.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsRegisterInfo.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MCTargetDesc/MipsBaseInfo.h"
22 #include "llvm/GlobalValue.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Type.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm;
38
39 //===----------------------------------------------------------------------===//
40 // Instruction Selector Implementation
41 //===----------------------------------------------------------------------===//
42
43 //===----------------------------------------------------------------------===//
44 // MipsDAGToDAGISel - MIPS specific code to select MIPS machine
45 // instructions for SelectionDAG operations.
46 //===----------------------------------------------------------------------===//
47 namespace {
48
49 class MipsDAGToDAGISel : public SelectionDAGISel {
50
51   /// TM - Keep a reference to MipsTargetMachine.
52   MipsTargetMachine &TM;
53
54   /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
55   /// make the right decision when generating code for different targets.
56   const MipsSubtarget &Subtarget;
57
58 public:
59   explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
60   SelectionDAGISel(tm),
61   TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
62
63   // Pass Name
64   virtual const char *getPassName() const {
65     return "MIPS DAG->DAG Pattern Instruction Selection";
66   }
67
68   virtual bool runOnMachineFunction(MachineFunction &MF);
69
70 private:
71   // Include the pieces autogenerated from the target description.
72   #include "MipsGenDAGISel.inc"
73
74   /// getTargetMachine - Return a reference to the TargetMachine, casted
75   /// to the target-specific type.
76   const MipsTargetMachine &getTargetMachine() {
77     return static_cast<const MipsTargetMachine &>(TM);
78   }
79
80   /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
81   /// to the target-specific type.
82   const MipsInstrInfo *getInstrInfo() {
83     return getTargetMachine().getInstrInfo();
84   }
85
86   SDNode *getGlobalBaseReg();
87
88   std::pair<SDNode*, SDNode*> SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl,
89                                          EVT Ty, bool HasLo, bool HasHi);
90
91   SDNode *Select(SDNode *N);
92
93   // Complex Pattern.
94   bool SelectAddr(SDValue N, SDValue &Base, SDValue &Offset);
95
96   // getImm - Return a target constant with the specified value.
97   inline SDValue getImm(const SDNode *Node, unsigned Imm) {
98     return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
99   }
100
101   void InitGlobalBaseReg(MachineFunction &MF);
102
103   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
104                                             char ConstraintCode,
105                                             std::vector<SDValue> &OutOps);
106 };
107
108 }
109
110 // Insert instructions to initialize the global base register in the
111 // first MBB of the function. When the ABI is O32 and the relocation model is
112 // PIC, the necessary instructions are emitted later to prevent optimization
113 // passes from moving them.
114 void MipsDAGToDAGISel::InitGlobalBaseReg(MachineFunction &MF) {
115   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
116   
117   if (!MipsFI->globalBaseRegSet())
118     return;
119
120   MachineBasicBlock &MBB = MF.front();
121   MachineBasicBlock::iterator I = MBB.begin();
122   MachineRegisterInfo &RegInfo = MF.getRegInfo();
123   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
124   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
125   unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
126   bool FixGlobalBaseReg = MipsFI->globalBaseRegFixed();
127
128   if (FixGlobalBaseReg) // $gp is the global base register.
129     V0 = V1 = GlobalBaseReg;
130   else {
131     const TargetRegisterClass *RC;
132     RC = Subtarget.isABI_N64() ?
133       Mips::CPU64RegsRegisterClass : Mips::CPURegsRegisterClass;
134     
135     V0 = RegInfo.createVirtualRegister(RC);
136     V1 = RegInfo.createVirtualRegister(RC);
137   }
138
139   if (Subtarget.isABI_N64()) {
140     MF.getRegInfo().addLiveIn(Mips::T9_64);
141
142     // lui $v0, %hi(%neg(%gp_rel(fname)))
143     // daddu $v1, $v0, $t9
144     // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
145     const GlobalValue *FName = MF.getFunction();
146     BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
147       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
148     BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0).addReg(Mips::T9_64);
149     BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
150       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
151   } else if (MF.getTarget().getRelocationModel() == Reloc::Static) {
152     // Set global register to __gnu_local_gp.
153     //
154     // lui   $v0, %hi(__gnu_local_gp)
155     // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
156     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
157       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
158     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
159       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
160   } else {
161     MF.getRegInfo().addLiveIn(Mips::T9);
162
163     if (Subtarget.isABI_N32()) {
164       // lui $v0, %hi(%neg(%gp_rel(fname)))
165       // addu $v1, $v0, $t9
166       // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
167       const GlobalValue *FName = MF.getFunction();
168       BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
169         .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
170       BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
171       BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
172         .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
173     } else if (!MipsFI->globalBaseRegFixed()) {
174       assert(Subtarget.isABI_O32());
175
176       BuildMI(MBB, I, DL, TII.get(Mips::SETGP2), GlobalBaseReg)
177         .addReg(Mips::T9);
178     }
179   }  
180 }
181
182 bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
183   bool Ret = SelectionDAGISel::runOnMachineFunction(MF);
184  
185   InitGlobalBaseReg(MF);
186
187   return Ret;
188 }
189
190 /// getGlobalBaseReg - Output the instructions required to put the
191 /// GOT address into a register.
192 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
193   unsigned GlobalBaseReg = MF->getInfo<MipsFunctionInfo>()->getGlobalBaseReg();
194   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
195 }
196
197 /// ComplexPattern used on MipsInstrInfo
198 /// Used on Mips Load/Store instructions
199 bool MipsDAGToDAGISel::
200 SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) {
201   EVT ValTy = Addr.getValueType();
202
203   // if Address is FI, get the TargetFrameIndex.
204   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
205     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
206     Offset = CurDAG->getTargetConstant(0, ValTy);
207     return true;
208   }
209
210   // on PIC code Load GA
211   if (Addr.getOpcode() == MipsISD::Wrapper) {
212     Base   = Addr.getOperand(0);
213     Offset = Addr.getOperand(1);
214     return true;
215   }
216
217   if (TM.getRelocationModel() != Reloc::PIC_) {
218     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
219         Addr.getOpcode() == ISD::TargetGlobalAddress))
220       return false;
221   }
222
223   // Addresses of the form FI+const or FI|const
224   if (CurDAG->isBaseWithConstantOffset(Addr)) {
225     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
226     if (isInt<16>(CN->getSExtValue())) {
227
228       // If the first operand is a FI, get the TargetFI Node
229       if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
230                                   (Addr.getOperand(0)))
231         Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
232       else
233         Base = Addr.getOperand(0);
234
235       Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
236       return true;
237     }
238   }
239
240   // Operand is a result from an ADD.
241   if (Addr.getOpcode() == ISD::ADD) {
242     // When loading from constant pools, load the lower address part in
243     // the instruction itself. Example, instead of:
244     //  lui $2, %hi($CPI1_0)
245     //  addiu $2, $2, %lo($CPI1_0)
246     //  lwc1 $f0, 0($2)
247     // Generate:
248     //  lui $2, %hi($CPI1_0)
249     //  lwc1 $f0, %lo($CPI1_0)($2)
250     if (Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
251       SDValue LoVal = Addr.getOperand(1);
252       if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) || 
253           isa<GlobalAddressSDNode>(LoVal.getOperand(0))) {
254         Base = Addr.getOperand(0);
255         Offset = LoVal.getOperand(0);
256         return true;
257       }
258     }
259   }
260
261   Base   = Addr;
262   Offset = CurDAG->getTargetConstant(0, ValTy);
263   return true;
264 }
265
266 /// Select multiply instructions.
267 std::pair<SDNode*, SDNode*>
268 MipsDAGToDAGISel::SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl, EVT Ty, 
269                              bool HasLo, bool HasHi) {
270   SDNode *Lo = 0, *Hi = 0;
271   SDNode *Mul = CurDAG->getMachineNode(Opc, dl, MVT::Glue, N->getOperand(0),
272                                        N->getOperand(1));
273   SDValue InFlag = SDValue(Mul, 0);
274
275   if (HasLo) {
276     Lo = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64, dl,
277                                 Ty, MVT::Glue, InFlag);
278     InFlag = SDValue(Lo, 1);
279   }
280   if (HasHi)
281     Hi = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFHI : Mips::MFHI64, dl,
282                                 Ty, InFlag);
283   
284   return std::make_pair(Lo, Hi);
285 }
286
287
288 /// Select instructions not customized! Used for
289 /// expanded, promoted and normal instructions
290 SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
291   unsigned Opcode = Node->getOpcode();
292   DebugLoc dl = Node->getDebugLoc();
293
294   // Dump information about the Node being selected
295   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
296
297   // If we have a custom node, we already have selected!
298   if (Node->isMachineOpcode()) {
299     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
300     return NULL;
301   }
302
303   ///
304   // Instruction Selection not handled by the auto-generated
305   // tablegen selection should be handled here.
306   ///
307   EVT NodeTy = Node->getValueType(0);
308   unsigned MultOpc;
309
310   switch(Opcode) {
311   default: break;
312
313   case ISD::SUBE:
314   case ISD::ADDE: {
315     SDValue InFlag = Node->getOperand(2), CmpLHS;
316     unsigned Opc = InFlag.getOpcode(); (void)Opc;
317     assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
318             (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
319            "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
320
321     unsigned MOp;
322     if (Opcode == ISD::ADDE) {
323       CmpLHS = InFlag.getValue(0);
324       MOp = Mips::ADDu;
325     } else {
326       CmpLHS = InFlag.getOperand(0);
327       MOp = Mips::SUBu;
328     }
329
330     SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
331
332     SDValue LHS = Node->getOperand(0);
333     SDValue RHS = Node->getOperand(1);
334
335     EVT VT = LHS.getValueType();
336     SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
337     SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT,
338                                               SDValue(Carry,0), RHS);
339
340     return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
341                                 LHS, SDValue(AddCarry,0));
342   }
343
344   /// Mul with two results
345   case ISD::SMUL_LOHI:
346   case ISD::UMUL_LOHI: {
347     if (NodeTy == MVT::i32)
348       MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
349     else
350       MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMULT);
351
352     std::pair<SDNode*, SDNode*> LoHi = SelectMULT(Node, MultOpc, dl, NodeTy,
353                                                   true, true);
354
355     if (!SDValue(Node, 0).use_empty())
356       ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
357
358     if (!SDValue(Node, 1).use_empty())
359       ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
360
361     return NULL;
362   }
363
364   /// Special Muls
365   case ISD::MUL: {
366     // Mips32 has a 32-bit three operand mul instruction.
367     if (Subtarget.hasMips32() && NodeTy == MVT::i32)
368       break;
369     return SelectMULT(Node, NodeTy == MVT::i32 ? Mips::MULT : Mips::DMULT,
370                       dl, NodeTy, true, false).first;
371   }
372   case ISD::MULHS:
373   case ISD::MULHU: {
374     if (NodeTy == MVT::i32)
375       MultOpc = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
376     else
377       MultOpc = (Opcode == ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
378
379     return SelectMULT(Node, MultOpc, dl, NodeTy, false, true).second;
380   }
381
382   // Get target GOT address.
383   case ISD::GLOBAL_OFFSET_TABLE:
384     return getGlobalBaseReg();
385
386   case ISD::ConstantFP: {
387     ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
388     if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
389       if (Subtarget.hasMips64()) {
390         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
391                                               Mips::ZERO_64, MVT::i64);
392         return CurDAG->getMachineNode(Mips::DMTC1, dl, MVT::f64, Zero);
393       }
394
395       SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
396                                             Mips::ZERO, MVT::i32);
397       return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
398                                     Zero);
399     }
400     break;
401   }
402
403   case ISD::Constant: {
404     const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
405     unsigned Size = CN->getValueSizeInBits(0);
406
407     if (Size == 32)
408       break;
409
410     MipsAnalyzeImmediate AnalyzeImm;
411     int64_t Imm = CN->getSExtValue();
412
413     const MipsAnalyzeImmediate::InstSeq &Seq =
414       AnalyzeImm.Analyze(Imm, Size, false);
415     
416     MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
417     DebugLoc DL = CN->getDebugLoc();
418     SDNode *RegOpnd;
419     SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
420                                                 MVT::i64);
421
422     // The first instruction can be a LUi which is different from other
423     // instructions (ADDiu, ORI and SLL) in that it does not have a register
424     // operand.
425     if (Inst->Opc == Mips::LUi64)
426       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
427     else
428       RegOpnd =
429         CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
430                                CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
431                                ImmOpnd);
432
433     // The remaining instructions in the sequence are handled here.
434     for (++Inst; Inst != Seq.end(); ++Inst) {
435       ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
436                                           MVT::i64);
437       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
438                                        SDValue(RegOpnd, 0), ImmOpnd);
439     }
440
441     return RegOpnd;
442   }
443
444   case MipsISD::ThreadPointer: {
445     EVT PtrVT = TLI.getPointerTy();
446     unsigned RdhwrOpc, SrcReg, DestReg;
447
448     if (PtrVT == MVT::i32) {
449       RdhwrOpc = Mips::RDHWR;
450       SrcReg = Mips::HWR29;
451       DestReg = Mips::V1;
452     } else {
453       RdhwrOpc = Mips::RDHWR64;
454       SrcReg = Mips::HWR29_64;
455       DestReg = Mips::V1_64;
456     }
457   
458     SDNode *Rdhwr =
459       CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
460                              Node->getValueType(0),
461                              CurDAG->getRegister(SrcReg, PtrVT));
462     SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
463                                          SDValue(Rdhwr, 0));
464     SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, PtrVT);
465     ReplaceUses(SDValue(Node, 0), ResNode);
466     return ResNode.getNode();
467   }
468   }
469
470   // Select the default instruction
471   SDNode *ResNode = SelectCode(Node);
472
473   DEBUG(errs() << "=> ");
474   if (ResNode == NULL || ResNode == Node)
475     DEBUG(Node->dump(CurDAG));
476   else
477     DEBUG(ResNode->dump(CurDAG));
478   DEBUG(errs() << "\n");
479   return ResNode;
480 }
481
482 bool MipsDAGToDAGISel::
483 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
484                              std::vector<SDValue> &OutOps) {
485   assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
486   OutOps.push_back(Op);
487   return false;
488 }
489
490 /// createMipsISelDag - This pass converts a legalized DAG into a
491 /// MIPS-specific DAG, ready for instruction scheduling.
492 FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
493   return new MipsDAGToDAGISel(TM);
494 }