2bb16e3cfb57509b50ecc171abfb07aaac4e3a5f
[oota-llvm.git] / lib / Target / Mips / MipsFastISel.cpp
1 //===-- MipsastISel.cpp - Mips FastISel implementation
2 //---------------------===//
3
4 #include "llvm/CodeGen/FunctionLoweringInfo.h"
5 #include "llvm/CodeGen/FastISel.h"
6 #include "llvm/CodeGen/MachineInstrBuilder.h"
7 #include "llvm/IR/GlobalAlias.h"
8 #include "llvm/IR/GlobalVariable.h"
9 #include "llvm/Target/TargetInstrInfo.h"
10 #include "llvm/Target/TargetLibraryInfo.h"
11 #include "MipsCCState.h"
12 #include "MipsRegisterInfo.h"
13 #include "MipsISelLowering.h"
14 #include "MipsMachineFunction.h"
15 #include "MipsSubtarget.h"
16 #include "MipsTargetMachine.h"
17
18 using namespace llvm;
19
20 namespace {
21
22 class MipsFastISel final : public FastISel {
23
24   // All possible address modes.
25   class Address {
26   public:
27     typedef enum { RegBase, FrameIndexBase } BaseKind;
28
29   private:
30     BaseKind Kind;
31     union {
32       unsigned Reg;
33       int FI;
34     } Base;
35
36     int64_t Offset;
37
38     const GlobalValue *GV;
39
40   public:
41     // Innocuous defaults for our address.
42     Address() : Kind(RegBase), Offset(0), GV(0) { Base.Reg = 0; }
43     void setKind(BaseKind K) { Kind = K; }
44     BaseKind getKind() const { return Kind; }
45     bool isRegBase() const { return Kind == RegBase; }
46     void setReg(unsigned Reg) {
47       assert(isRegBase() && "Invalid base register access!");
48       Base.Reg = Reg;
49     }
50     unsigned getReg() const {
51       assert(isRegBase() && "Invalid base register access!");
52       return Base.Reg;
53     }
54     void setOffset(int64_t Offset_) { Offset = Offset_; }
55     int64_t getOffset() const { return Offset; }
56     void setGlobalValue(const GlobalValue *G) { GV = G; }
57     const GlobalValue *getGlobalValue() { return GV; }
58   };
59
60   /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
61   /// make the right decision when generating code for different targets.
62   Module &M;
63   const TargetMachine &TM;
64   const TargetInstrInfo &TII;
65   const TargetLowering &TLI;
66   const MipsSubtarget *Subtarget;
67   MipsFunctionInfo *MFI;
68
69   // Convenience variables to avoid some queries.
70   LLVMContext *Context;
71
72   bool fastLowerCall(CallLoweringInfo &CLI) override;
73
74   bool TargetSupported;
75   bool UnsupportedFPMode; // To allow fast-isel to proceed and just not handle
76   // floating point but not reject doing fast-isel in other
77   // situations
78
79 private:
80   // Selection routines.
81   bool selectLoad(const Instruction *I);
82   bool selectStore(const Instruction *I);
83   bool selectBranch(const Instruction *I);
84   bool selectCmp(const Instruction *I);
85   bool selectFPExt(const Instruction *I);
86   bool selectFPTrunc(const Instruction *I);
87   bool selectFPToInt(const Instruction *I, bool IsSigned);
88   bool selectRet(const Instruction *I);
89   bool selectTrunc(const Instruction *I);
90   bool selectIntExt(const Instruction *I);
91
92   // Utility helper routines.
93   bool isTypeLegal(Type *Ty, MVT &VT);
94   bool isLoadTypeLegal(Type *Ty, MVT &VT);
95   bool computeAddress(const Value *Obj, Address &Addr);
96   bool computeCallAddress(const Value *V, Address &Addr);
97
98   // Emit helper routines.
99   bool emitCmp(unsigned DestReg, const CmpInst *CI);
100   bool emitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
101                 unsigned Alignment = 0);
102   bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
103                  MachineMemOperand *MMO = nullptr);
104   bool emitStore(MVT VT, unsigned SrcReg, Address &Addr,
105                  unsigned Alignment = 0);
106   unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
107   bool emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg,
108
109                   bool IsZExt);
110   bool emitIntZExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg);
111
112   bool emitIntSExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg);
113   bool emitIntSExt32r1(MVT SrcVT, unsigned SrcReg, MVT DestVT,
114                        unsigned DestReg);
115   bool emitIntSExt32r2(MVT SrcVT, unsigned SrcReg, MVT DestVT,
116                        unsigned DestReg);
117
118   unsigned getRegEnsuringSimpleIntegerWidening(const Value *, bool IsUnsigned);
119
120   unsigned materializeFP(const ConstantFP *CFP, MVT VT);
121   unsigned materializeGV(const GlobalValue *GV, MVT VT);
122   unsigned materializeInt(const Constant *C, MVT VT);
123   unsigned materialize32BitInt(int64_t Imm, const TargetRegisterClass *RC);
124
125   MachineInstrBuilder emitInst(unsigned Opc) {
126     return BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
127   }
128   MachineInstrBuilder emitInst(unsigned Opc, unsigned DstReg) {
129     return BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
130                    DstReg);
131   }
132   MachineInstrBuilder emitInstStore(unsigned Opc, unsigned SrcReg,
133                                     unsigned MemReg, int64_t MemOffset) {
134     return emitInst(Opc).addReg(SrcReg).addReg(MemReg).addImm(MemOffset);
135   }
136   MachineInstrBuilder emitInstLoad(unsigned Opc, unsigned DstReg,
137                                    unsigned MemReg, int64_t MemOffset) {
138     return emitInst(Opc, DstReg).addReg(MemReg).addImm(MemOffset);
139   }
140   // for some reason, this default is not generated by tablegen
141   // so we explicitly generate it here.
142   //
143   unsigned fastEmitInst_riir(uint64_t inst, const TargetRegisterClass *RC,
144                              unsigned Op0, bool Op0IsKill, uint64_t imm1,
145                              uint64_t imm2, unsigned Op3, bool Op3IsKill) {
146     return 0;
147   }
148
149   // Call handling routines.
150 private:
151   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
152   bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
153                        unsigned &NumBytes);
154   bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
155
156 public:
157   // Backend specific FastISel code.
158   explicit MipsFastISel(FunctionLoweringInfo &funcInfo,
159                         const TargetLibraryInfo *libInfo)
160       : FastISel(funcInfo, libInfo),
161         M(const_cast<Module &>(*funcInfo.Fn->getParent())),
162         TM(funcInfo.MF->getTarget()),
163         TII(*TM.getSubtargetImpl()->getInstrInfo()),
164         TLI(*TM.getSubtargetImpl()->getTargetLowering()),
165         Subtarget(&TM.getSubtarget<MipsSubtarget>()) {
166     MFI = funcInfo.MF->getInfo<MipsFunctionInfo>();
167     Context = &funcInfo.Fn->getContext();
168     TargetSupported = ((Subtarget->getRelocationModel() == Reloc::PIC_) &&
169                        ((Subtarget->hasMips32r2() || Subtarget->hasMips32()) &&
170                         (Subtarget->isABI_O32())));
171     UnsupportedFPMode = Subtarget->isFP64bit();
172   }
173
174   unsigned fastMaterializeConstant(const Constant *C) override;
175   bool fastSelectInstruction(const Instruction *I) override;
176
177 #include "MipsGenFastISel.inc"
178 };
179 } // end anonymous namespace.
180
181 static bool CC_Mips(unsigned ValNo, MVT ValVT, MVT LocVT,
182                     CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
183                     CCState &State) LLVM_ATTRIBUTE_UNUSED;
184
185 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, MVT LocVT,
186                             CCValAssign::LocInfo LocInfo,
187                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
188   llvm_unreachable("should not be called");
189 }
190
191 bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, MVT LocVT,
192                      CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
193                      CCState &State) {
194   llvm_unreachable("should not be called");
195 }
196
197 #include "MipsGenCallingConv.inc"
198
199 CCAssignFn *MipsFastISel::CCAssignFnForCall(CallingConv::ID CC) const {
200   return CC_MipsO32;
201 }
202
203 unsigned MipsFastISel::materializeInt(const Constant *C, MVT VT) {
204   if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
205     return 0;
206   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
207   const ConstantInt *CI = cast<ConstantInt>(C);
208   int64_t Imm;
209   if ((VT != MVT::i1) && CI->isNegative())
210     Imm = CI->getSExtValue();
211   else
212     Imm = CI->getZExtValue();
213   return materialize32BitInt(Imm, RC);
214 }
215
216 unsigned MipsFastISel::materialize32BitInt(int64_t Imm,
217                                            const TargetRegisterClass *RC) {
218   unsigned ResultReg = createResultReg(RC);
219
220   if (isInt<16>(Imm)) {
221     unsigned Opc = Mips::ADDiu;
222     emitInst(Opc, ResultReg).addReg(Mips::ZERO).addImm(Imm);
223     return ResultReg;
224   } else if (isUInt<16>(Imm)) {
225     emitInst(Mips::ORi, ResultReg).addReg(Mips::ZERO).addImm(Imm);
226     return ResultReg;
227   }
228   unsigned Lo = Imm & 0xFFFF;
229   unsigned Hi = (Imm >> 16) & 0xFFFF;
230   if (Lo) {
231     // Both Lo and Hi have nonzero bits.
232     unsigned TmpReg = createResultReg(RC);
233     emitInst(Mips::LUi, TmpReg).addImm(Hi);
234     emitInst(Mips::ORi, ResultReg).addReg(TmpReg).addImm(Lo);
235   } else {
236     emitInst(Mips::LUi, ResultReg).addImm(Hi);
237   }
238   return ResultReg;
239 }
240
241 unsigned MipsFastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
242   if (UnsupportedFPMode)
243     return 0;
244   int64_t Imm = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
245   if (VT == MVT::f32) {
246     const TargetRegisterClass *RC = &Mips::FGR32RegClass;
247     unsigned DestReg = createResultReg(RC);
248     unsigned TempReg = materialize32BitInt(Imm, &Mips::GPR32RegClass);
249     emitInst(Mips::MTC1, DestReg).addReg(TempReg);
250     return DestReg;
251   } else if (VT == MVT::f64) {
252     const TargetRegisterClass *RC = &Mips::AFGR64RegClass;
253     unsigned DestReg = createResultReg(RC);
254     unsigned TempReg1 = materialize32BitInt(Imm >> 32, &Mips::GPR32RegClass);
255     unsigned TempReg2 =
256         materialize32BitInt(Imm & 0xFFFFFFFF, &Mips::GPR32RegClass);
257     emitInst(Mips::BuildPairF64, DestReg).addReg(TempReg2).addReg(TempReg1);
258     return DestReg;
259   }
260   return 0;
261 }
262
263 unsigned MipsFastISel::materializeGV(const GlobalValue *GV, MVT VT) {
264   // For now 32-bit only.
265   if (VT != MVT::i32)
266     return 0;
267   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
268   unsigned DestReg = createResultReg(RC);
269   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
270   bool IsThreadLocal = GVar && GVar->isThreadLocal();
271   // TLS not supported at this time.
272   if (IsThreadLocal)
273     return 0;
274   emitInst(Mips::LW, DestReg)
275       .addReg(MFI->getGlobalBaseReg())
276       .addGlobalAddress(GV, 0, MipsII::MO_GOT);
277   if ((GV->hasInternalLinkage() ||
278        (GV->hasLocalLinkage() && !isa<Function>(GV)))) {
279     unsigned TempReg = createResultReg(RC);
280     emitInst(Mips::ADDiu, TempReg)
281         .addReg(DestReg)
282         .addGlobalAddress(GV, 0, MipsII::MO_ABS_LO);
283     DestReg = TempReg;
284   }
285   return DestReg;
286 }
287
288 // Materialize a constant into a register, and return the register
289 // number (or zero if we failed to handle it).
290 unsigned MipsFastISel::fastMaterializeConstant(const Constant *C) {
291   EVT CEVT = TLI.getValueType(C->getType(), true);
292
293   // Only handle simple types.
294   if (!CEVT.isSimple())
295     return 0;
296   MVT VT = CEVT.getSimpleVT();
297
298   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
299     return (UnsupportedFPMode) ? 0 : materializeFP(CFP, VT);
300   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
301     return materializeGV(GV, VT);
302   else if (isa<ConstantInt>(C))
303     return materializeInt(C, VT);
304
305   return 0;
306 }
307
308 bool MipsFastISel::computeAddress(const Value *Obj, Address &Addr) {
309   // This construct looks a big awkward but it is how other ports handle this
310   // and as this function is more fully completed, these cases which
311   // return false will have additional code in them.
312   //
313   if (isa<Instruction>(Obj))
314     return false;
315   else if (isa<ConstantExpr>(Obj))
316     return false;
317   Addr.setReg(getRegForValue(Obj));
318   return Addr.getReg() != 0;
319 }
320
321 bool MipsFastISel::computeCallAddress(const Value *V, Address &Addr) {
322   const GlobalValue *GV = dyn_cast<GlobalValue>(V);
323   if (GV && isa<Function>(GV) && dyn_cast<Function>(GV)->isIntrinsic())
324     return false;
325   if (!GV)
326     return false;
327   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
328     Addr.setGlobalValue(GV);
329     return true;
330   }
331   return false;
332 }
333
334 bool MipsFastISel::isTypeLegal(Type *Ty, MVT &VT) {
335   EVT evt = TLI.getValueType(Ty, true);
336   // Only handle simple types.
337   if (evt == MVT::Other || !evt.isSimple())
338     return false;
339   VT = evt.getSimpleVT();
340
341   // Handle all legal types, i.e. a register that will directly hold this
342   // value.
343   return TLI.isTypeLegal(VT);
344 }
345
346 bool MipsFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
347   if (isTypeLegal(Ty, VT))
348     return true;
349   // We will extend this in a later patch:
350   //   If this is a type than can be sign or zero-extended to a basic operation
351   //   go ahead and accept it now.
352   if (VT == MVT::i8 || VT == MVT::i16)
353     return true;
354   return false;
355 }
356 // Because of how EmitCmp is called with fast-isel, you can
357 // end up with redundant "andi" instructions after the sequences emitted below.
358 // We should try and solve this issue in the future.
359 //
360 bool MipsFastISel::emitCmp(unsigned ResultReg, const CmpInst *CI) {
361   const Value *Left = CI->getOperand(0), *Right = CI->getOperand(1);
362   bool IsUnsigned = CI->isUnsigned();
363   unsigned LeftReg = getRegEnsuringSimpleIntegerWidening(Left, IsUnsigned);
364   if (LeftReg == 0)
365     return false;
366   unsigned RightReg = getRegEnsuringSimpleIntegerWidening(Right, IsUnsigned);
367   if (RightReg == 0)
368     return false;
369   CmpInst::Predicate P = CI->getPredicate();
370
371   switch (P) {
372   default:
373     return false;
374   case CmpInst::ICMP_EQ: {
375     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
376     emitInst(Mips::XOR, TempReg).addReg(LeftReg).addReg(RightReg);
377     emitInst(Mips::SLTiu, ResultReg).addReg(TempReg).addImm(1);
378     break;
379   }
380   case CmpInst::ICMP_NE: {
381     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
382     emitInst(Mips::XOR, TempReg).addReg(LeftReg).addReg(RightReg);
383     emitInst(Mips::SLTu, ResultReg).addReg(Mips::ZERO).addReg(TempReg);
384     break;
385   }
386   case CmpInst::ICMP_UGT: {
387     emitInst(Mips::SLTu, ResultReg).addReg(RightReg).addReg(LeftReg);
388     break;
389   }
390   case CmpInst::ICMP_ULT: {
391     emitInst(Mips::SLTu, ResultReg).addReg(LeftReg).addReg(RightReg);
392     break;
393   }
394   case CmpInst::ICMP_UGE: {
395     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
396     emitInst(Mips::SLTu, TempReg).addReg(LeftReg).addReg(RightReg);
397     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
398     break;
399   }
400   case CmpInst::ICMP_ULE: {
401     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
402     emitInst(Mips::SLTu, TempReg).addReg(RightReg).addReg(LeftReg);
403     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
404     break;
405   }
406   case CmpInst::ICMP_SGT: {
407     emitInst(Mips::SLT, ResultReg).addReg(RightReg).addReg(LeftReg);
408     break;
409   }
410   case CmpInst::ICMP_SLT: {
411     emitInst(Mips::SLT, ResultReg).addReg(LeftReg).addReg(RightReg);
412     break;
413   }
414   case CmpInst::ICMP_SGE: {
415     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
416     emitInst(Mips::SLT, TempReg).addReg(LeftReg).addReg(RightReg);
417     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
418     break;
419   }
420   case CmpInst::ICMP_SLE: {
421     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
422     emitInst(Mips::SLT, TempReg).addReg(RightReg).addReg(LeftReg);
423     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
424     break;
425   }
426   case CmpInst::FCMP_OEQ:
427   case CmpInst::FCMP_UNE:
428   case CmpInst::FCMP_OLT:
429   case CmpInst::FCMP_OLE:
430   case CmpInst::FCMP_OGT:
431   case CmpInst::FCMP_OGE: {
432     if (UnsupportedFPMode)
433       return false;
434     bool IsFloat = Left->getType()->isFloatTy();
435     bool IsDouble = Left->getType()->isDoubleTy();
436     if (!IsFloat && !IsDouble)
437       return false;
438     unsigned Opc, CondMovOpc;
439     switch (P) {
440     case CmpInst::FCMP_OEQ:
441       Opc = IsFloat ? Mips::C_EQ_S : Mips::C_EQ_D32;
442       CondMovOpc = Mips::MOVT_I;
443       break;
444     case CmpInst::FCMP_UNE:
445       Opc = IsFloat ? Mips::C_EQ_S : Mips::C_EQ_D32;
446       CondMovOpc = Mips::MOVF_I;
447       break;
448     case CmpInst::FCMP_OLT:
449       Opc = IsFloat ? Mips::C_OLT_S : Mips::C_OLT_D32;
450       CondMovOpc = Mips::MOVT_I;
451       break;
452     case CmpInst::FCMP_OLE:
453       Opc = IsFloat ? Mips::C_OLE_S : Mips::C_OLE_D32;
454       CondMovOpc = Mips::MOVT_I;
455       break;
456     case CmpInst::FCMP_OGT:
457       Opc = IsFloat ? Mips::C_ULE_S : Mips::C_ULE_D32;
458       CondMovOpc = Mips::MOVF_I;
459       break;
460     case CmpInst::FCMP_OGE:
461       Opc = IsFloat ? Mips::C_ULT_S : Mips::C_ULT_D32;
462       CondMovOpc = Mips::MOVF_I;
463       break;
464     default:
465       llvm_unreachable("Only switching of a subset of CCs.");
466     }
467     unsigned RegWithZero = createResultReg(&Mips::GPR32RegClass);
468     unsigned RegWithOne = createResultReg(&Mips::GPR32RegClass);
469     emitInst(Mips::ADDiu, RegWithZero).addReg(Mips::ZERO).addImm(0);
470     emitInst(Mips::ADDiu, RegWithOne).addReg(Mips::ZERO).addImm(1);
471     emitInst(Opc).addReg(LeftReg).addReg(RightReg).addReg(
472         Mips::FCC0, RegState::ImplicitDefine);
473     MachineInstrBuilder MI = emitInst(CondMovOpc, ResultReg)
474                                  .addReg(RegWithOne)
475                                  .addReg(Mips::FCC0)
476                                  .addReg(RegWithZero, RegState::Implicit);
477     MI->tieOperands(0, 3);
478     break;
479   }
480   }
481   return true;
482 }
483 bool MipsFastISel::emitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
484                             unsigned Alignment) {
485   //
486   // more cases will be handled here in following patches.
487   //
488   unsigned Opc;
489   switch (VT.SimpleTy) {
490   case MVT::i32: {
491     ResultReg = createResultReg(&Mips::GPR32RegClass);
492     Opc = Mips::LW;
493     break;
494   }
495   case MVT::i16: {
496     ResultReg = createResultReg(&Mips::GPR32RegClass);
497     Opc = Mips::LHu;
498     break;
499   }
500   case MVT::i8: {
501     ResultReg = createResultReg(&Mips::GPR32RegClass);
502     Opc = Mips::LBu;
503     break;
504   }
505   case MVT::f32: {
506     if (UnsupportedFPMode)
507       return false;
508     ResultReg = createResultReg(&Mips::FGR32RegClass);
509     Opc = Mips::LWC1;
510     break;
511   }
512   case MVT::f64: {
513     if (UnsupportedFPMode)
514       return false;
515     ResultReg = createResultReg(&Mips::AFGR64RegClass);
516     Opc = Mips::LDC1;
517     break;
518   }
519   default:
520     return false;
521   }
522   emitInstLoad(Opc, ResultReg, Addr.getReg(), Addr.getOffset());
523   return true;
524 }
525
526 bool MipsFastISel::emitStore(MVT VT, unsigned SrcReg, Address &Addr,
527                              unsigned Alignment) {
528   //
529   // more cases will be handled here in following patches.
530   //
531   unsigned Opc;
532   switch (VT.SimpleTy) {
533   case MVT::i8:
534     Opc = Mips::SB;
535     break;
536   case MVT::i16:
537     Opc = Mips::SH;
538     break;
539   case MVT::i32:
540     Opc = Mips::SW;
541     break;
542   case MVT::f32:
543     if (UnsupportedFPMode)
544       return false;
545     Opc = Mips::SWC1;
546     break;
547   case MVT::f64:
548     if (UnsupportedFPMode)
549       return false;
550     Opc = Mips::SDC1;
551     break;
552   default:
553     return false;
554   }
555   emitInstStore(Opc, SrcReg, Addr.getReg(), Addr.getOffset());
556   return true;
557 }
558
559 bool MipsFastISel::selectLoad(const Instruction *I) {
560   // Atomic loads need special handling.
561   if (cast<LoadInst>(I)->isAtomic())
562     return false;
563
564   // Verify we have a legal type before going any further.
565   MVT VT;
566   if (!isLoadTypeLegal(I->getType(), VT))
567     return false;
568
569   // See if we can handle this address.
570   Address Addr;
571   if (!computeAddress(I->getOperand(0), Addr))
572     return false;
573
574   unsigned ResultReg;
575   if (!emitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
576     return false;
577   updateValueMap(I, ResultReg);
578   return true;
579 }
580
581 bool MipsFastISel::selectStore(const Instruction *I) {
582   Value *Op0 = I->getOperand(0);
583   unsigned SrcReg = 0;
584
585   // Atomic stores need special handling.
586   if (cast<StoreInst>(I)->isAtomic())
587     return false;
588
589   // Verify we have a legal type before going any further.
590   MVT VT;
591   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
592     return false;
593
594   // Get the value to be stored into a register.
595   SrcReg = getRegForValue(Op0);
596   if (SrcReg == 0)
597     return false;
598
599   // See if we can handle this address.
600   Address Addr;
601   if (!computeAddress(I->getOperand(1), Addr))
602     return false;
603
604   if (!emitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
605     return false;
606   return true;
607 }
608
609 //
610 // This can cause a redundant sltiu to be generated.
611 // FIXME: try and eliminate this in a future patch.
612 //
613 bool MipsFastISel::selectBranch(const Instruction *I) {
614   const BranchInst *BI = cast<BranchInst>(I);
615   MachineBasicBlock *BrBB = FuncInfo.MBB;
616   //
617   // TBB is the basic block for the case where the comparison is true.
618   // FBB is the basic block for the case where the comparison is false.
619   // if (cond) goto TBB
620   // goto FBB
621   // TBB:
622   //
623   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
624   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
625   BI->getCondition();
626   // For now, just try the simplest case where it's fed by a compare.
627   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
628     unsigned CondReg = createResultReg(&Mips::GPR32RegClass);
629     if (!emitCmp(CondReg, CI))
630       return false;
631     BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(Mips::BGTZ))
632         .addReg(CondReg)
633         .addMBB(TBB);
634     fastEmitBranch(FBB, DbgLoc);
635     FuncInfo.MBB->addSuccessor(TBB);
636     return true;
637   }
638   return false;
639 }
640
641 bool MipsFastISel::selectCmp(const Instruction *I) {
642   const CmpInst *CI = cast<CmpInst>(I);
643   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
644   if (!emitCmp(ResultReg, CI))
645     return false;
646   updateValueMap(I, ResultReg);
647   return true;
648 }
649
650 // Attempt to fast-select a floating-point extend instruction.
651 bool MipsFastISel::selectFPExt(const Instruction *I) {
652   if (UnsupportedFPMode)
653     return false;
654   Value *Src = I->getOperand(0);
655   EVT SrcVT = TLI.getValueType(Src->getType(), true);
656   EVT DestVT = TLI.getValueType(I->getType(), true);
657
658   if (SrcVT != MVT::f32 || DestVT != MVT::f64)
659     return false;
660
661   unsigned SrcReg =
662       getRegForValue(Src); // his must be a 32 bit floating point register class
663                            // maybe we should handle this differently
664   if (!SrcReg)
665     return false;
666
667   unsigned DestReg = createResultReg(&Mips::AFGR64RegClass);
668   emitInst(Mips::CVT_D32_S, DestReg).addReg(SrcReg);
669   updateValueMap(I, DestReg);
670   return true;
671 }
672
673 // Attempt to fast-select a floating-point truncate instruction.
674 bool MipsFastISel::selectFPTrunc(const Instruction *I) {
675   if (UnsupportedFPMode)
676     return false;
677   Value *Src = I->getOperand(0);
678   EVT SrcVT = TLI.getValueType(Src->getType(), true);
679   EVT DestVT = TLI.getValueType(I->getType(), true);
680
681   if (SrcVT != MVT::f64 || DestVT != MVT::f32)
682     return false;
683
684   unsigned SrcReg = getRegForValue(Src);
685   if (!SrcReg)
686     return false;
687
688   unsigned DestReg = createResultReg(&Mips::FGR32RegClass);
689   if (!DestReg)
690     return false;
691
692   emitInst(Mips::CVT_S_D32, DestReg).addReg(SrcReg);
693   updateValueMap(I, DestReg);
694   return true;
695 }
696
697 // Attempt to fast-select a floating-point-to-integer conversion.
698 bool MipsFastISel::selectFPToInt(const Instruction *I, bool IsSigned) {
699   if (UnsupportedFPMode)
700     return false;
701   MVT DstVT, SrcVT;
702   if (!IsSigned)
703     return false; // We don't handle this case yet. There is no native
704                   // instruction for this but it can be synthesized.
705   Type *DstTy = I->getType();
706   if (!isTypeLegal(DstTy, DstVT))
707     return false;
708
709   if (DstVT != MVT::i32)
710     return false;
711
712   Value *Src = I->getOperand(0);
713   Type *SrcTy = Src->getType();
714   if (!isTypeLegal(SrcTy, SrcVT))
715     return false;
716
717   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
718     return false;
719
720   unsigned SrcReg = getRegForValue(Src);
721   if (SrcReg == 0)
722     return false;
723
724   // Determine the opcode for the conversion, which takes place
725   // entirely within FPRs.
726   unsigned DestReg = createResultReg(&Mips::GPR32RegClass);
727   unsigned TempReg = createResultReg(&Mips::FGR32RegClass);
728   unsigned Opc;
729
730   if (SrcVT == MVT::f32)
731     Opc = Mips::TRUNC_W_S;
732   else
733     Opc = Mips::TRUNC_W_D32;
734
735   // Generate the convert.
736   emitInst(Opc, TempReg).addReg(SrcReg);
737
738   emitInst(Mips::MFC1, DestReg).addReg(TempReg);
739
740   updateValueMap(I, DestReg);
741   return true;
742 }
743 //
744 bool MipsFastISel::processCallArgs(CallLoweringInfo &CLI,
745                                    SmallVectorImpl<MVT> &OutVTs,
746                                    unsigned &NumBytes) {
747   CallingConv::ID CC = CLI.CallConv;
748   SmallVector<CCValAssign, 16> ArgLocs;
749   CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
750   CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
751   // Get a count of how many bytes are to be pushed on the stack.
752   NumBytes = CCInfo.getNextStackOffset();
753   // This is the minimum argument area used for A0-A3.
754   if (NumBytes < 16)
755     NumBytes = 16;
756
757   emitInst(Mips::ADJCALLSTACKDOWN).addImm(16);
758   // Process the args.
759   MVT firstMVT;
760   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
761     CCValAssign &VA = ArgLocs[i];
762     const Value *ArgVal = CLI.OutVals[VA.getValNo()];
763     MVT ArgVT = OutVTs[VA.getValNo()];
764
765     if (i == 0) {
766       firstMVT = ArgVT;
767       if (ArgVT == MVT::f32) {
768         VA.convertToReg(Mips::F12);
769       } else if (ArgVT == MVT::f64) {
770         VA.convertToReg(Mips::D6);
771       }
772     } else if (i == 1) {
773       if ((firstMVT == MVT::f32) || (firstMVT == MVT::f64)) {
774         if (ArgVT == MVT::f32) {
775           VA.convertToReg(Mips::F14);
776         } else if (ArgVT == MVT::f64) {
777           VA.convertToReg(Mips::D7);
778         }
779       }
780     }
781     if (((ArgVT == MVT::i32) || (ArgVT == MVT::f32)) && VA.isMemLoc()) {
782       switch (VA.getLocMemOffset()) {
783       case 0:
784         VA.convertToReg(Mips::A0);
785         break;
786       case 4:
787         VA.convertToReg(Mips::A1);
788         break;
789       case 8:
790         VA.convertToReg(Mips::A2);
791         break;
792       case 12:
793         VA.convertToReg(Mips::A3);
794         break;
795       default:
796         break;
797       }
798     }
799     unsigned ArgReg = getRegForValue(ArgVal);
800     if (!ArgReg)
801       return false;
802
803     // Handle arg promotion: SExt, ZExt, AExt.
804     switch (VA.getLocInfo()) {
805     case CCValAssign::Full:
806       break;
807     case CCValAssign::AExt:
808     case CCValAssign::SExt: {
809       MVT DestVT = VA.getLocVT();
810       MVT SrcVT = ArgVT;
811       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
812       if (!ArgReg)
813         return false;
814       break;
815     }
816     case CCValAssign::ZExt: {
817       MVT DestVT = VA.getLocVT();
818       MVT SrcVT = ArgVT;
819       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
820       if (!ArgReg)
821         return false;
822       break;
823     }
824     default:
825       llvm_unreachable("Unknown arg promotion!");
826     }
827
828     // Now copy/store arg to correct locations.
829     if (VA.isRegLoc() && !VA.needsCustom()) {
830       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
831               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
832       CLI.OutRegs.push_back(VA.getLocReg());
833     } else if (VA.needsCustom()) {
834       llvm_unreachable("Mips does not use custom args.");
835       return false;
836     } else {
837       //
838       // FIXME: This path will currently return false. It was copied
839       // from the AArch64 port and should be essentially fine for Mips too.
840       // The work to finish up this path will be done in a follow-on patch.
841       //
842       assert(VA.isMemLoc() && "Assuming store on stack.");
843       // Don't emit stores for undef values.
844       if (isa<UndefValue>(ArgVal))
845         continue;
846
847       // Need to store on the stack.
848       // FIXME: This alignment is incorrect but this path is disabled
849       // for now (will return false). We need to determine the right alignment
850       // based on the normal alignment for the underlying machine type.
851       //
852       unsigned ArgSize = RoundUpToAlignment(ArgVT.getSizeInBits(), 4);
853
854       unsigned BEAlign = 0;
855       if (ArgSize < 8 && !Subtarget->isLittle())
856         BEAlign = 8 - ArgSize;
857
858       Address Addr;
859       Addr.setKind(Address::RegBase);
860       Addr.setReg(Mips::SP);
861       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
862
863       unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
864       MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
865           MachinePointerInfo::getStack(Addr.getOffset()),
866           MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
867       (void)(MMO);
868       // if (!emitStore(ArgVT, ArgReg, Addr, MMO))
869       return false; // can't store on the stack yet.
870     }
871   }
872
873   return true;
874 }
875
876 bool MipsFastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
877                               unsigned NumBytes) {
878   CallingConv::ID CC = CLI.CallConv;
879   emitInst(Mips::ADJCALLSTACKUP).addImm(16);
880   if (RetVT != MVT::isVoid) {
881     SmallVector<CCValAssign, 16> RVLocs;
882     CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
883     CCInfo.AnalyzeCallResult(RetVT, RetCC_Mips);
884
885     // Only handle a single return value.
886     if (RVLocs.size() != 1)
887       return false;
888     // Copy all of the result registers out of their specified physreg.
889     MVT CopyVT = RVLocs[0].getValVT();
890     // Special handling for extended integers.
891     if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
892       CopyVT = MVT::i32;
893
894     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
895     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
896             TII.get(TargetOpcode::COPY),
897             ResultReg).addReg(RVLocs[0].getLocReg());
898     CLI.InRegs.push_back(RVLocs[0].getLocReg());
899
900     CLI.ResultReg = ResultReg;
901     CLI.NumResultRegs = 1;
902   }
903   return true;
904 }
905
906 bool MipsFastISel::fastLowerCall(CallLoweringInfo &CLI) {
907   CallingConv::ID CC = CLI.CallConv;
908   bool IsTailCall = CLI.IsTailCall;
909   bool IsVarArg = CLI.IsVarArg;
910   const Value *Callee = CLI.Callee;
911   // const char *SymName = CLI.SymName;
912
913   // Allow SelectionDAG isel to handle tail calls.
914   if (IsTailCall)
915     return false;
916
917   // Let SDISel handle vararg functions.
918   if (IsVarArg)
919     return false;
920
921   // FIXME: Only handle *simple* calls for now.
922   MVT RetVT;
923   if (CLI.RetTy->isVoidTy())
924     RetVT = MVT::isVoid;
925   else if (!isTypeLegal(CLI.RetTy, RetVT))
926     return false;
927
928   for (auto Flag : CLI.OutFlags)
929     if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
930       return false;
931
932   // Set up the argument vectors.
933   SmallVector<MVT, 16> OutVTs;
934   OutVTs.reserve(CLI.OutVals.size());
935
936   for (auto *Val : CLI.OutVals) {
937     MVT VT;
938     if (!isTypeLegal(Val->getType(), VT) &&
939         !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
940       return false;
941
942     // We don't handle vector parameters yet.
943     if (VT.isVector() || VT.getSizeInBits() > 64)
944       return false;
945
946     OutVTs.push_back(VT);
947   }
948
949   Address Addr;
950   if (!computeCallAddress(Callee, Addr))
951     return false;
952
953   // Handle the arguments now that we've gotten them.
954   unsigned NumBytes;
955   if (!processCallArgs(CLI, OutVTs, NumBytes))
956     return false;
957
958   // Issue the call.
959   unsigned DestAddress = materializeGV(Addr.getGlobalValue(), MVT::i32);
960   emitInst(TargetOpcode::COPY, Mips::T9).addReg(DestAddress);
961   MachineInstrBuilder MIB =
962       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Mips::JALR),
963               Mips::RA).addReg(Mips::T9);
964
965   // Add implicit physical register uses to the call.
966   for (auto Reg : CLI.OutRegs)
967     MIB.addReg(Reg, RegState::Implicit);
968
969   // Add a register mask with the call-preserved registers.
970   // Proper defs for return values will be added by setPhysRegsDeadExcept().
971   MIB.addRegMask(TRI.getCallPreservedMask(CC));
972
973   CLI.Call = MIB;
974
975   // Add implicit physical register uses to the call.
976   for (auto Reg : CLI.OutRegs)
977     MIB.addReg(Reg, RegState::Implicit);
978
979   // Add a register mask with the call-preserved registers.  Proper
980   // defs for return values will be added by setPhysRegsDeadExcept().
981   MIB.addRegMask(TRI.getCallPreservedMask(CC));
982
983   CLI.Call = MIB;
984   // Finish off the call including any return values.
985   return finishCall(CLI, RetVT, NumBytes);
986 }
987
988 bool MipsFastISel::selectRet(const Instruction *I) {
989   const ReturnInst *Ret = cast<ReturnInst>(I);
990
991   if (!FuncInfo.CanLowerReturn)
992     return false;
993   if (Ret->getNumOperands() > 0) {
994     return false;
995   }
996   emitInst(Mips::RetRA);
997   return true;
998 }
999
1000 bool MipsFastISel::selectTrunc(const Instruction *I) {
1001   // The high bits for a type smaller than the register size are assumed to be
1002   // undefined.
1003   Value *Op = I->getOperand(0);
1004
1005   EVT SrcVT, DestVT;
1006   SrcVT = TLI.getValueType(Op->getType(), true);
1007   DestVT = TLI.getValueType(I->getType(), true);
1008
1009   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1010     return false;
1011   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1012     return false;
1013
1014   unsigned SrcReg = getRegForValue(Op);
1015   if (!SrcReg)
1016     return false;
1017
1018   // Because the high bits are undefined, a truncate doesn't generate
1019   // any code.
1020   updateValueMap(I, SrcReg);
1021   return true;
1022 }
1023 bool MipsFastISel::selectIntExt(const Instruction *I) {
1024   Type *DestTy = I->getType();
1025   Value *Src = I->getOperand(0);
1026   Type *SrcTy = Src->getType();
1027
1028   bool isZExt = isa<ZExtInst>(I);
1029   unsigned SrcReg = getRegForValue(Src);
1030   if (!SrcReg)
1031     return false;
1032
1033   EVT SrcEVT, DestEVT;
1034   SrcEVT = TLI.getValueType(SrcTy, true);
1035   DestEVT = TLI.getValueType(DestTy, true);
1036   if (!SrcEVT.isSimple())
1037     return false;
1038   if (!DestEVT.isSimple())
1039     return false;
1040
1041   MVT SrcVT = SrcEVT.getSimpleVT();
1042   MVT DestVT = DestEVT.getSimpleVT();
1043   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
1044
1045   if (!emitIntExt(SrcVT, SrcReg, DestVT, ResultReg, isZExt))
1046     return false;
1047   updateValueMap(I, ResultReg);
1048   return true;
1049 }
1050 bool MipsFastISel::emitIntSExt32r1(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1051                                    unsigned DestReg) {
1052   unsigned ShiftAmt;
1053   switch (SrcVT.SimpleTy) {
1054   default:
1055     return false;
1056   case MVT::i8:
1057     ShiftAmt = 24;
1058     break;
1059   case MVT::i16:
1060     ShiftAmt = 16;
1061     break;
1062   }
1063   unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
1064   emitInst(Mips::SLL, TempReg).addReg(SrcReg).addImm(ShiftAmt);
1065   emitInst(Mips::SRA, DestReg).addReg(TempReg).addImm(ShiftAmt);
1066   return true;
1067 }
1068
1069 bool MipsFastISel::emitIntSExt32r2(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1070                                    unsigned DestReg) {
1071   switch (SrcVT.SimpleTy) {
1072   default:
1073     return false;
1074   case MVT::i8:
1075     emitInst(Mips::SEB, DestReg).addReg(SrcReg);
1076     break;
1077   case MVT::i16:
1078     emitInst(Mips::SEH, DestReg).addReg(SrcReg);
1079     break;
1080   }
1081   return true;
1082 }
1083
1084 bool MipsFastISel::emitIntSExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1085                                unsigned DestReg) {
1086   if ((DestVT != MVT::i32) && (DestVT != MVT::i16))
1087     return false;
1088   if (Subtarget->hasMips32r2())
1089     return emitIntSExt32r2(SrcVT, SrcReg, DestVT, DestReg);
1090   return emitIntSExt32r1(SrcVT, SrcReg, DestVT, DestReg);
1091 }
1092
1093 bool MipsFastISel::emitIntZExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1094                                unsigned DestReg) {
1095   switch (SrcVT.SimpleTy) {
1096   default:
1097     return false;
1098   case MVT::i1:
1099     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(1);
1100     break;
1101   case MVT::i8:
1102     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(0xff);
1103     break;
1104   case MVT::i16:
1105     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(0xffff);
1106     break;
1107   }
1108   return true;
1109 }
1110
1111 bool MipsFastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1112                               unsigned DestReg, bool IsZExt) {
1113   if (IsZExt)
1114     return emitIntZExt(SrcVT, SrcReg, DestVT, DestReg);
1115   return emitIntSExt(SrcVT, SrcReg, DestVT, DestReg);
1116 }
1117
1118 unsigned MipsFastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1119                                   bool isZExt) {
1120   unsigned DestReg = createResultReg(&Mips::GPR32RegClass);
1121   return emitIntExt(SrcVT, SrcReg, DestVT, DestReg, isZExt);
1122 }
1123
1124 bool MipsFastISel::fastSelectInstruction(const Instruction *I) {
1125   if (!TargetSupported)
1126     return false;
1127   switch (I->getOpcode()) {
1128   default:
1129     break;
1130   case Instruction::Load:
1131     return selectLoad(I);
1132   case Instruction::Store:
1133     return selectStore(I);
1134   case Instruction::Br:
1135     return selectBranch(I);
1136   case Instruction::Ret:
1137     return selectRet(I);
1138   case Instruction::Trunc:
1139     return selectTrunc(I);
1140   case Instruction::ZExt:
1141   case Instruction::SExt:
1142     return selectIntExt(I);
1143   case Instruction::FPTrunc:
1144     return selectFPTrunc(I);
1145   case Instruction::FPExt:
1146     return selectFPExt(I);
1147   case Instruction::FPToSI:
1148     return selectFPToInt(I, /*isSigned*/ true);
1149   case Instruction::FPToUI:
1150     return selectFPToInt(I, /*isSigned*/ false);
1151   case Instruction::ICmp:
1152   case Instruction::FCmp:
1153     return selectCmp(I);
1154   }
1155   return false;
1156 }
1157
1158 unsigned MipsFastISel::getRegEnsuringSimpleIntegerWidening(const Value *V,
1159                                                            bool IsUnsigned) {
1160   unsigned VReg = getRegForValue(V);
1161   if (VReg == 0)
1162     return 0;
1163   MVT VMVT = TLI.getValueType(V->getType(), true).getSimpleVT();
1164   if ((VMVT == MVT::i8) || (VMVT == MVT::i16)) {
1165     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
1166     if (!emitIntExt(VMVT, VReg, MVT::i32, TempReg, IsUnsigned))
1167       return 0;
1168     VReg = TempReg;
1169   }
1170   return VReg;
1171 }
1172
1173 namespace llvm {
1174 FastISel *Mips::createFastISel(FunctionLoweringInfo &funcInfo,
1175                                const TargetLibraryInfo *libInfo) {
1176   return new MipsFastISel(funcInfo, libInfo);
1177 }
1178 }