Mips fast-isel - handle functions which return i8 or i6 .
[oota-llvm.git] / lib / Target / Mips / MipsFastISel.cpp
1 //===-- MipsastISel.cpp - Mips FastISel implementation
2 //---------------------===//
3
4 #include "MipsCCState.h"
5 #include "MipsInstrInfo.h"
6 #include "MipsISelLowering.h"
7 #include "MipsMachineFunction.h"
8 #include "MipsRegisterInfo.h"
9 #include "MipsSubtarget.h"
10 #include "MipsTargetMachine.h"
11 #include "llvm/Analysis/TargetLibraryInfo.h"
12 #include "llvm/CodeGen/FastISel.h"
13 #include "llvm/CodeGen/FunctionLoweringInfo.h"
14 #include "llvm/CodeGen/MachineInstrBuilder.h"
15 #include "llvm/CodeGen/MachineRegisterInfo.h"
16 #include "llvm/IR/GlobalAlias.h"
17 #include "llvm/IR/GlobalVariable.h"
18 #include "llvm/Target/TargetInstrInfo.h"
19
20 using namespace llvm;
21
22 namespace {
23
24 class MipsFastISel final : public FastISel {
25
26   // All possible address modes.
27   class Address {
28   public:
29     typedef enum { RegBase, FrameIndexBase } BaseKind;
30
31   private:
32     BaseKind Kind;
33     union {
34       unsigned Reg;
35       int FI;
36     } Base;
37
38     int64_t Offset;
39
40     const GlobalValue *GV;
41
42   public:
43     // Innocuous defaults for our address.
44     Address() : Kind(RegBase), Offset(0), GV(0) { Base.Reg = 0; }
45     void setKind(BaseKind K) { Kind = K; }
46     BaseKind getKind() const { return Kind; }
47     bool isRegBase() const { return Kind == RegBase; }
48     bool isFIBase() const { return Kind == FrameIndexBase; }
49     void setReg(unsigned Reg) {
50       assert(isRegBase() && "Invalid base register access!");
51       Base.Reg = Reg;
52     }
53     unsigned getReg() const {
54       assert(isRegBase() && "Invalid base register access!");
55       return Base.Reg;
56     }
57     void setFI(unsigned FI) {
58       assert(isFIBase() && "Invalid base frame index access!");
59       Base.FI = FI;
60     }
61     unsigned getFI() const {
62       assert(isFIBase() && "Invalid base frame index access!");
63       return Base.FI;
64     }
65
66     void setOffset(int64_t Offset_) { Offset = Offset_; }
67     int64_t getOffset() const { return Offset; }
68     void setGlobalValue(const GlobalValue *G) { GV = G; }
69     const GlobalValue *getGlobalValue() { return GV; }
70   };
71
72   /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
73   /// make the right decision when generating code for different targets.
74   const TargetMachine &TM;
75   const MipsSubtarget *Subtarget;
76   const TargetInstrInfo &TII;
77   const TargetLowering &TLI;
78   MipsFunctionInfo *MFI;
79
80   // Convenience variables to avoid some queries.
81   LLVMContext *Context;
82
83   bool fastLowerCall(CallLoweringInfo &CLI) override;
84
85   bool TargetSupported;
86   bool UnsupportedFPMode; // To allow fast-isel to proceed and just not handle
87   // floating point but not reject doing fast-isel in other
88   // situations
89
90 private:
91   // Selection routines.
92   bool selectLogicalOp(const Instruction *I);
93   bool selectLoad(const Instruction *I);
94   bool selectStore(const Instruction *I);
95   bool selectBranch(const Instruction *I);
96   bool selectCmp(const Instruction *I);
97   bool selectFPExt(const Instruction *I);
98   bool selectFPTrunc(const Instruction *I);
99   bool selectFPToInt(const Instruction *I, bool IsSigned);
100   bool selectRet(const Instruction *I);
101   bool selectTrunc(const Instruction *I);
102   bool selectIntExt(const Instruction *I);
103   bool selectShift(const Instruction *I);
104
105   // Utility helper routines.
106   bool isTypeLegal(Type *Ty, MVT &VT);
107   bool isTypeSupported(Type *Ty, MVT &VT);
108   bool isLoadTypeLegal(Type *Ty, MVT &VT);
109   bool computeAddress(const Value *Obj, Address &Addr);
110   bool computeCallAddress(const Value *V, Address &Addr);
111   void simplifyAddress(Address &Addr);
112
113   // Emit helper routines.
114   bool emitCmp(unsigned DestReg, const CmpInst *CI);
115   bool emitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
116                 unsigned Alignment = 0);
117   bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
118                  MachineMemOperand *MMO = nullptr);
119   bool emitStore(MVT VT, unsigned SrcReg, Address &Addr,
120                  unsigned Alignment = 0);
121   unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
122   bool emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg,
123
124                   bool IsZExt);
125   bool emitIntZExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg);
126
127   bool emitIntSExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, unsigned DestReg);
128   bool emitIntSExt32r1(MVT SrcVT, unsigned SrcReg, MVT DestVT,
129                        unsigned DestReg);
130   bool emitIntSExt32r2(MVT SrcVT, unsigned SrcReg, MVT DestVT,
131                        unsigned DestReg);
132
133   unsigned getRegEnsuringSimpleIntegerWidening(const Value *, bool IsUnsigned);
134
135   unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
136                          const Value *RHS);
137
138   unsigned materializeFP(const ConstantFP *CFP, MVT VT);
139   unsigned materializeGV(const GlobalValue *GV, MVT VT);
140   unsigned materializeInt(const Constant *C, MVT VT);
141   unsigned materialize32BitInt(int64_t Imm, const TargetRegisterClass *RC);
142
143   MachineInstrBuilder emitInst(unsigned Opc) {
144     return BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
145   }
146   MachineInstrBuilder emitInst(unsigned Opc, unsigned DstReg) {
147     return BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
148                    DstReg);
149   }
150   MachineInstrBuilder emitInstStore(unsigned Opc, unsigned SrcReg,
151                                     unsigned MemReg, int64_t MemOffset) {
152     return emitInst(Opc).addReg(SrcReg).addReg(MemReg).addImm(MemOffset);
153   }
154   MachineInstrBuilder emitInstLoad(unsigned Opc, unsigned DstReg,
155                                    unsigned MemReg, int64_t MemOffset) {
156     return emitInst(Opc, DstReg).addReg(MemReg).addImm(MemOffset);
157   }
158   // for some reason, this default is not generated by tablegen
159   // so we explicitly generate it here.
160   //
161   unsigned fastEmitInst_riir(uint64_t inst, const TargetRegisterClass *RC,
162                              unsigned Op0, bool Op0IsKill, uint64_t imm1,
163                              uint64_t imm2, unsigned Op3, bool Op3IsKill) {
164     return 0;
165   }
166
167   // Call handling routines.
168 private:
169   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
170   bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
171                        unsigned &NumBytes);
172   bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
173
174 public:
175   // Backend specific FastISel code.
176   explicit MipsFastISel(FunctionLoweringInfo &funcInfo,
177                         const TargetLibraryInfo *libInfo)
178       : FastISel(funcInfo, libInfo), TM(funcInfo.MF->getTarget()),
179         Subtarget(&funcInfo.MF->getSubtarget<MipsSubtarget>()),
180         TII(*Subtarget->getInstrInfo()), TLI(*Subtarget->getTargetLowering()) {
181     MFI = funcInfo.MF->getInfo<MipsFunctionInfo>();
182     Context = &funcInfo.Fn->getContext();
183     TargetSupported =
184         ((TM.getRelocationModel() == Reloc::PIC_) &&
185          ((Subtarget->hasMips32r2() || Subtarget->hasMips32()) &&
186           (static_cast<const MipsTargetMachine &>(TM).getABI().IsO32())));
187     UnsupportedFPMode = Subtarget->isFP64bit();
188   }
189
190   unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
191   unsigned fastMaterializeConstant(const Constant *C) override;
192   bool fastSelectInstruction(const Instruction *I) override;
193
194 #include "MipsGenFastISel.inc"
195 };
196 } // end anonymous namespace.
197
198 static bool CC_Mips(unsigned ValNo, MVT ValVT, MVT LocVT,
199                     CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
200                     CCState &State) LLVM_ATTRIBUTE_UNUSED;
201
202 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, MVT LocVT,
203                             CCValAssign::LocInfo LocInfo,
204                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
205   llvm_unreachable("should not be called");
206 }
207
208 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, MVT LocVT,
209                             CCValAssign::LocInfo LocInfo,
210                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
211   llvm_unreachable("should not be called");
212 }
213
214 #include "MipsGenCallingConv.inc"
215
216 CCAssignFn *MipsFastISel::CCAssignFnForCall(CallingConv::ID CC) const {
217   return CC_MipsO32;
218 }
219
220 unsigned MipsFastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
221                                      const Value *LHS, const Value *RHS) {
222   // Canonicalize immediates to the RHS first.
223   if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
224     std::swap(LHS, RHS);
225
226   unsigned Opc;
227   if (ISDOpc == ISD::AND) {
228     Opc = Mips::AND;
229   } else if (ISDOpc == ISD::OR) {
230     Opc = Mips::OR;
231   } else if (ISDOpc == ISD::XOR) {
232     Opc = Mips::XOR;
233   } else
234     llvm_unreachable("unexpected opcode");
235
236   unsigned LHSReg = getRegForValue(LHS);
237   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
238   if (!ResultReg)
239     return 0;
240
241   unsigned RHSReg;
242   if (!LHSReg)
243     return 0;
244
245   if (const auto *C = dyn_cast<ConstantInt>(RHS))
246     RHSReg = materializeInt(C, MVT::i32);
247   else
248     RHSReg = getRegForValue(RHS);
249
250   if (!RHSReg)
251     return 0;
252
253   emitInst(Opc, ResultReg).addReg(LHSReg).addReg(RHSReg);
254   return ResultReg;
255 }
256
257 unsigned MipsFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
258   assert(TLI.getValueType(AI->getType(), true) == MVT::i32 &&
259          "Alloca should always return a pointer.");
260
261   DenseMap<const AllocaInst *, int>::iterator SI =
262       FuncInfo.StaticAllocaMap.find(AI);
263
264   if (SI != FuncInfo.StaticAllocaMap.end()) {
265     unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
266     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Mips::LEA_ADDiu),
267             ResultReg)
268         .addFrameIndex(SI->second)
269         .addImm(0);
270     return ResultReg;
271   }
272
273   return 0;
274 }
275
276 unsigned MipsFastISel::materializeInt(const Constant *C, MVT VT) {
277   if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
278     return 0;
279   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
280   const ConstantInt *CI = cast<ConstantInt>(C);
281   int64_t Imm;
282   if ((VT != MVT::i1) && CI->isNegative())
283     Imm = CI->getSExtValue();
284   else
285     Imm = CI->getZExtValue();
286   return materialize32BitInt(Imm, RC);
287 }
288
289 unsigned MipsFastISel::materialize32BitInt(int64_t Imm,
290                                            const TargetRegisterClass *RC) {
291   unsigned ResultReg = createResultReg(RC);
292
293   if (isInt<16>(Imm)) {
294     unsigned Opc = Mips::ADDiu;
295     emitInst(Opc, ResultReg).addReg(Mips::ZERO).addImm(Imm);
296     return ResultReg;
297   } else if (isUInt<16>(Imm)) {
298     emitInst(Mips::ORi, ResultReg).addReg(Mips::ZERO).addImm(Imm);
299     return ResultReg;
300   }
301   unsigned Lo = Imm & 0xFFFF;
302   unsigned Hi = (Imm >> 16) & 0xFFFF;
303   if (Lo) {
304     // Both Lo and Hi have nonzero bits.
305     unsigned TmpReg = createResultReg(RC);
306     emitInst(Mips::LUi, TmpReg).addImm(Hi);
307     emitInst(Mips::ORi, ResultReg).addReg(TmpReg).addImm(Lo);
308   } else {
309     emitInst(Mips::LUi, ResultReg).addImm(Hi);
310   }
311   return ResultReg;
312 }
313
314 unsigned MipsFastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
315   if (UnsupportedFPMode)
316     return 0;
317   int64_t Imm = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
318   if (VT == MVT::f32) {
319     const TargetRegisterClass *RC = &Mips::FGR32RegClass;
320     unsigned DestReg = createResultReg(RC);
321     unsigned TempReg = materialize32BitInt(Imm, &Mips::GPR32RegClass);
322     emitInst(Mips::MTC1, DestReg).addReg(TempReg);
323     return DestReg;
324   } else if (VT == MVT::f64) {
325     const TargetRegisterClass *RC = &Mips::AFGR64RegClass;
326     unsigned DestReg = createResultReg(RC);
327     unsigned TempReg1 = materialize32BitInt(Imm >> 32, &Mips::GPR32RegClass);
328     unsigned TempReg2 =
329         materialize32BitInt(Imm & 0xFFFFFFFF, &Mips::GPR32RegClass);
330     emitInst(Mips::BuildPairF64, DestReg).addReg(TempReg2).addReg(TempReg1);
331     return DestReg;
332   }
333   return 0;
334 }
335
336 unsigned MipsFastISel::materializeGV(const GlobalValue *GV, MVT VT) {
337   // For now 32-bit only.
338   if (VT != MVT::i32)
339     return 0;
340   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
341   unsigned DestReg = createResultReg(RC);
342   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
343   bool IsThreadLocal = GVar && GVar->isThreadLocal();
344   // TLS not supported at this time.
345   if (IsThreadLocal)
346     return 0;
347   emitInst(Mips::LW, DestReg)
348       .addReg(MFI->getGlobalBaseReg())
349       .addGlobalAddress(GV, 0, MipsII::MO_GOT);
350   if ((GV->hasInternalLinkage() ||
351        (GV->hasLocalLinkage() && !isa<Function>(GV)))) {
352     unsigned TempReg = createResultReg(RC);
353     emitInst(Mips::ADDiu, TempReg)
354         .addReg(DestReg)
355         .addGlobalAddress(GV, 0, MipsII::MO_ABS_LO);
356     DestReg = TempReg;
357   }
358   return DestReg;
359 }
360
361 // Materialize a constant into a register, and return the register
362 // number (or zero if we failed to handle it).
363 unsigned MipsFastISel::fastMaterializeConstant(const Constant *C) {
364   EVT CEVT = TLI.getValueType(C->getType(), true);
365
366   // Only handle simple types.
367   if (!CEVT.isSimple())
368     return 0;
369   MVT VT = CEVT.getSimpleVT();
370
371   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
372     return (UnsupportedFPMode) ? 0 : materializeFP(CFP, VT);
373   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
374     return materializeGV(GV, VT);
375   else if (isa<ConstantInt>(C))
376     return materializeInt(C, VT);
377
378   return 0;
379 }
380
381 bool MipsFastISel::computeAddress(const Value *Obj, Address &Addr) {
382
383   const User *U = nullptr;
384   unsigned Opcode = Instruction::UserOp1;
385   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
386     // Don't walk into other basic blocks unless the object is an alloca from
387     // another block, otherwise it may not have a virtual register assigned.
388     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
389         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
390       Opcode = I->getOpcode();
391       U = I;
392     }
393   } else if (isa<ConstantExpr>(Obj))
394     return false;
395   switch (Opcode) {
396   default:
397     break;
398   case Instruction::BitCast: {
399     // Look through bitcasts.
400     return computeAddress(U->getOperand(0), Addr);
401   }
402   case Instruction::GetElementPtr: {
403     Address SavedAddr = Addr;
404     uint64_t TmpOffset = Addr.getOffset();
405     // Iterate through the GEP folding the constants into offsets where
406     // we can.
407     gep_type_iterator GTI = gep_type_begin(U);
408     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
409          ++i, ++GTI) {
410       const Value *Op = *i;
411       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
412         const StructLayout *SL = DL.getStructLayout(STy);
413         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
414         TmpOffset += SL->getElementOffset(Idx);
415       } else {
416         uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
417         for (;;) {
418           if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
419             // Constant-offset addressing.
420             TmpOffset += CI->getSExtValue() * S;
421             break;
422           }
423           if (canFoldAddIntoGEP(U, Op)) {
424             // A compatible add with a constant operand. Fold the constant.
425             ConstantInt *CI =
426                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
427             TmpOffset += CI->getSExtValue() * S;
428             // Iterate on the other operand.
429             Op = cast<AddOperator>(Op)->getOperand(0);
430             continue;
431           }
432           // Unsupported
433           goto unsupported_gep;
434         }
435       }
436     }
437     // Try to grab the base operand now.
438     Addr.setOffset(TmpOffset);
439     if (computeAddress(U->getOperand(0), Addr))
440       return true;
441     // We failed, restore everything and try the other options.
442     Addr = SavedAddr;
443   unsupported_gep:
444     break;
445   }
446   case Instruction::Alloca: {
447     const AllocaInst *AI = cast<AllocaInst>(Obj);
448     DenseMap<const AllocaInst *, int>::iterator SI =
449         FuncInfo.StaticAllocaMap.find(AI);
450     if (SI != FuncInfo.StaticAllocaMap.end()) {
451       Addr.setKind(Address::FrameIndexBase);
452       Addr.setFI(SI->second);
453       return true;
454     }
455     break;
456   }
457   }
458   Addr.setReg(getRegForValue(Obj));
459   return Addr.getReg() != 0;
460 }
461
462 bool MipsFastISel::computeCallAddress(const Value *V, Address &Addr) {
463   const GlobalValue *GV = dyn_cast<GlobalValue>(V);
464   if (GV && isa<Function>(GV) && cast<Function>(GV)->isIntrinsic())
465     return false;
466   if (!GV)
467     return false;
468   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
469     Addr.setGlobalValue(GV);
470     return true;
471   }
472   return false;
473 }
474
475 bool MipsFastISel::isTypeLegal(Type *Ty, MVT &VT) {
476   EVT evt = TLI.getValueType(Ty, true);
477   // Only handle simple types.
478   if (evt == MVT::Other || !evt.isSimple())
479     return false;
480   VT = evt.getSimpleVT();
481
482   // Handle all legal types, i.e. a register that will directly hold this
483   // value.
484   return TLI.isTypeLegal(VT);
485 }
486
487 bool MipsFastISel::isTypeSupported(Type *Ty, MVT &VT) {
488   if (Ty->isVectorTy())
489     return false;
490
491   if (isTypeLegal(Ty, VT))
492     return true;
493
494   // If this is a type than can be sign or zero-extended to a basic operation
495   // go ahead and accept it now.
496   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
497     return true;
498
499   return false;
500 }
501
502 bool MipsFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
503   if (isTypeLegal(Ty, VT))
504     return true;
505   // We will extend this in a later patch:
506   //   If this is a type than can be sign or zero-extended to a basic operation
507   //   go ahead and accept it now.
508   if (VT == MVT::i8 || VT == MVT::i16)
509     return true;
510   return false;
511 }
512 // Because of how EmitCmp is called with fast-isel, you can
513 // end up with redundant "andi" instructions after the sequences emitted below.
514 // We should try and solve this issue in the future.
515 //
516 bool MipsFastISel::emitCmp(unsigned ResultReg, const CmpInst *CI) {
517   const Value *Left = CI->getOperand(0), *Right = CI->getOperand(1);
518   bool IsUnsigned = CI->isUnsigned();
519   unsigned LeftReg = getRegEnsuringSimpleIntegerWidening(Left, IsUnsigned);
520   if (LeftReg == 0)
521     return false;
522   unsigned RightReg = getRegEnsuringSimpleIntegerWidening(Right, IsUnsigned);
523   if (RightReg == 0)
524     return false;
525   CmpInst::Predicate P = CI->getPredicate();
526
527   switch (P) {
528   default:
529     return false;
530   case CmpInst::ICMP_EQ: {
531     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
532     emitInst(Mips::XOR, TempReg).addReg(LeftReg).addReg(RightReg);
533     emitInst(Mips::SLTiu, ResultReg).addReg(TempReg).addImm(1);
534     break;
535   }
536   case CmpInst::ICMP_NE: {
537     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
538     emitInst(Mips::XOR, TempReg).addReg(LeftReg).addReg(RightReg);
539     emitInst(Mips::SLTu, ResultReg).addReg(Mips::ZERO).addReg(TempReg);
540     break;
541   }
542   case CmpInst::ICMP_UGT: {
543     emitInst(Mips::SLTu, ResultReg).addReg(RightReg).addReg(LeftReg);
544     break;
545   }
546   case CmpInst::ICMP_ULT: {
547     emitInst(Mips::SLTu, ResultReg).addReg(LeftReg).addReg(RightReg);
548     break;
549   }
550   case CmpInst::ICMP_UGE: {
551     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
552     emitInst(Mips::SLTu, TempReg).addReg(LeftReg).addReg(RightReg);
553     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
554     break;
555   }
556   case CmpInst::ICMP_ULE: {
557     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
558     emitInst(Mips::SLTu, TempReg).addReg(RightReg).addReg(LeftReg);
559     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
560     break;
561   }
562   case CmpInst::ICMP_SGT: {
563     emitInst(Mips::SLT, ResultReg).addReg(RightReg).addReg(LeftReg);
564     break;
565   }
566   case CmpInst::ICMP_SLT: {
567     emitInst(Mips::SLT, ResultReg).addReg(LeftReg).addReg(RightReg);
568     break;
569   }
570   case CmpInst::ICMP_SGE: {
571     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
572     emitInst(Mips::SLT, TempReg).addReg(LeftReg).addReg(RightReg);
573     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
574     break;
575   }
576   case CmpInst::ICMP_SLE: {
577     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
578     emitInst(Mips::SLT, TempReg).addReg(RightReg).addReg(LeftReg);
579     emitInst(Mips::XORi, ResultReg).addReg(TempReg).addImm(1);
580     break;
581   }
582   case CmpInst::FCMP_OEQ:
583   case CmpInst::FCMP_UNE:
584   case CmpInst::FCMP_OLT:
585   case CmpInst::FCMP_OLE:
586   case CmpInst::FCMP_OGT:
587   case CmpInst::FCMP_OGE: {
588     if (UnsupportedFPMode)
589       return false;
590     bool IsFloat = Left->getType()->isFloatTy();
591     bool IsDouble = Left->getType()->isDoubleTy();
592     if (!IsFloat && !IsDouble)
593       return false;
594     unsigned Opc, CondMovOpc;
595     switch (P) {
596     case CmpInst::FCMP_OEQ:
597       Opc = IsFloat ? Mips::C_EQ_S : Mips::C_EQ_D32;
598       CondMovOpc = Mips::MOVT_I;
599       break;
600     case CmpInst::FCMP_UNE:
601       Opc = IsFloat ? Mips::C_EQ_S : Mips::C_EQ_D32;
602       CondMovOpc = Mips::MOVF_I;
603       break;
604     case CmpInst::FCMP_OLT:
605       Opc = IsFloat ? Mips::C_OLT_S : Mips::C_OLT_D32;
606       CondMovOpc = Mips::MOVT_I;
607       break;
608     case CmpInst::FCMP_OLE:
609       Opc = IsFloat ? Mips::C_OLE_S : Mips::C_OLE_D32;
610       CondMovOpc = Mips::MOVT_I;
611       break;
612     case CmpInst::FCMP_OGT:
613       Opc = IsFloat ? Mips::C_ULE_S : Mips::C_ULE_D32;
614       CondMovOpc = Mips::MOVF_I;
615       break;
616     case CmpInst::FCMP_OGE:
617       Opc = IsFloat ? Mips::C_ULT_S : Mips::C_ULT_D32;
618       CondMovOpc = Mips::MOVF_I;
619       break;
620     default:
621       llvm_unreachable("Only switching of a subset of CCs.");
622     }
623     unsigned RegWithZero = createResultReg(&Mips::GPR32RegClass);
624     unsigned RegWithOne = createResultReg(&Mips::GPR32RegClass);
625     emitInst(Mips::ADDiu, RegWithZero).addReg(Mips::ZERO).addImm(0);
626     emitInst(Mips::ADDiu, RegWithOne).addReg(Mips::ZERO).addImm(1);
627     emitInst(Opc).addReg(LeftReg).addReg(RightReg).addReg(
628         Mips::FCC0, RegState::ImplicitDefine);
629     MachineInstrBuilder MI = emitInst(CondMovOpc, ResultReg)
630                                  .addReg(RegWithOne)
631                                  .addReg(Mips::FCC0)
632                                  .addReg(RegWithZero, RegState::Implicit);
633     MI->tieOperands(0, 3);
634     break;
635   }
636   }
637   return true;
638 }
639 bool MipsFastISel::emitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
640                             unsigned Alignment) {
641   //
642   // more cases will be handled here in following patches.
643   //
644   unsigned Opc;
645   switch (VT.SimpleTy) {
646   case MVT::i32: {
647     ResultReg = createResultReg(&Mips::GPR32RegClass);
648     Opc = Mips::LW;
649     break;
650   }
651   case MVT::i16: {
652     ResultReg = createResultReg(&Mips::GPR32RegClass);
653     Opc = Mips::LHu;
654     break;
655   }
656   case MVT::i8: {
657     ResultReg = createResultReg(&Mips::GPR32RegClass);
658     Opc = Mips::LBu;
659     break;
660   }
661   case MVT::f32: {
662     if (UnsupportedFPMode)
663       return false;
664     ResultReg = createResultReg(&Mips::FGR32RegClass);
665     Opc = Mips::LWC1;
666     break;
667   }
668   case MVT::f64: {
669     if (UnsupportedFPMode)
670       return false;
671     ResultReg = createResultReg(&Mips::AFGR64RegClass);
672     Opc = Mips::LDC1;
673     break;
674   }
675   default:
676     return false;
677   }
678   if (Addr.isRegBase()) {
679     simplifyAddress(Addr);
680     emitInstLoad(Opc, ResultReg, Addr.getReg(), Addr.getOffset());
681     return true;
682   }
683   if (Addr.isFIBase()) {
684     unsigned FI = Addr.getFI();
685     unsigned Align = 4;
686     unsigned Offset = Addr.getOffset();
687     MachineFrameInfo &MFI = *MF->getFrameInfo();
688     MachineMemOperand *MMO = MF->getMachineMemOperand(
689         MachinePointerInfo::getFixedStack(FI), MachineMemOperand::MOLoad,
690         MFI.getObjectSize(FI), Align);
691     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
692         .addFrameIndex(FI)
693         .addImm(Offset)
694         .addMemOperand(MMO);
695     return true;
696   }
697   return false;
698 }
699
700 bool MipsFastISel::emitStore(MVT VT, unsigned SrcReg, Address &Addr,
701                              unsigned Alignment) {
702   //
703   // more cases will be handled here in following patches.
704   //
705   unsigned Opc;
706   switch (VT.SimpleTy) {
707   case MVT::i8:
708     Opc = Mips::SB;
709     break;
710   case MVT::i16:
711     Opc = Mips::SH;
712     break;
713   case MVT::i32:
714     Opc = Mips::SW;
715     break;
716   case MVT::f32:
717     if (UnsupportedFPMode)
718       return false;
719     Opc = Mips::SWC1;
720     break;
721   case MVT::f64:
722     if (UnsupportedFPMode)
723       return false;
724     Opc = Mips::SDC1;
725     break;
726   default:
727     return false;
728   }
729   if (Addr.isRegBase()) {
730     simplifyAddress(Addr);
731     emitInstStore(Opc, SrcReg, Addr.getReg(), Addr.getOffset());
732     return true;
733   }
734   if (Addr.isFIBase()) {
735     unsigned FI = Addr.getFI();
736     unsigned Align = 4;
737     unsigned Offset = Addr.getOffset();
738     MachineFrameInfo &MFI = *MF->getFrameInfo();
739     MachineMemOperand *MMO = MF->getMachineMemOperand(
740         MachinePointerInfo::getFixedStack(FI), MachineMemOperand::MOLoad,
741         MFI.getObjectSize(FI), Align);
742     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
743         .addReg(SrcReg)
744         .addFrameIndex(FI)
745         .addImm(Offset)
746         .addMemOperand(MMO);
747     return true;
748   }
749   return false;
750 }
751
752 bool MipsFastISel::selectLogicalOp(const Instruction *I) {
753   MVT VT;
754   if (!isTypeSupported(I->getType(), VT))
755     return false;
756
757   unsigned ResultReg;
758   switch (I->getOpcode()) {
759   default:
760     llvm_unreachable("Unexpected instruction.");
761   case Instruction::And:
762     ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
763     break;
764   case Instruction::Or:
765     ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
766     break;
767   case Instruction::Xor:
768     ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
769     break;
770   }
771
772   if (!ResultReg)
773     return false;
774
775   updateValueMap(I, ResultReg);
776   return true;
777 }
778
779 bool MipsFastISel::selectLoad(const Instruction *I) {
780   // Atomic loads need special handling.
781   if (cast<LoadInst>(I)->isAtomic())
782     return false;
783
784   // Verify we have a legal type before going any further.
785   MVT VT;
786   if (!isLoadTypeLegal(I->getType(), VT))
787     return false;
788
789   // See if we can handle this address.
790   Address Addr;
791   if (!computeAddress(I->getOperand(0), Addr))
792     return false;
793
794   unsigned ResultReg;
795   if (!emitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
796     return false;
797   updateValueMap(I, ResultReg);
798   return true;
799 }
800
801 bool MipsFastISel::selectStore(const Instruction *I) {
802   Value *Op0 = I->getOperand(0);
803   unsigned SrcReg = 0;
804
805   // Atomic stores need special handling.
806   if (cast<StoreInst>(I)->isAtomic())
807     return false;
808
809   // Verify we have a legal type before going any further.
810   MVT VT;
811   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
812     return false;
813
814   // Get the value to be stored into a register.
815   SrcReg = getRegForValue(Op0);
816   if (SrcReg == 0)
817     return false;
818
819   // See if we can handle this address.
820   Address Addr;
821   if (!computeAddress(I->getOperand(1), Addr))
822     return false;
823
824   if (!emitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
825     return false;
826   return true;
827 }
828
829 //
830 // This can cause a redundant sltiu to be generated.
831 // FIXME: try and eliminate this in a future patch.
832 //
833 bool MipsFastISel::selectBranch(const Instruction *I) {
834   const BranchInst *BI = cast<BranchInst>(I);
835   MachineBasicBlock *BrBB = FuncInfo.MBB;
836   //
837   // TBB is the basic block for the case where the comparison is true.
838   // FBB is the basic block for the case where the comparison is false.
839   // if (cond) goto TBB
840   // goto FBB
841   // TBB:
842   //
843   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
844   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
845   BI->getCondition();
846   // For now, just try the simplest case where it's fed by a compare.
847   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
848     unsigned CondReg = createResultReg(&Mips::GPR32RegClass);
849     if (!emitCmp(CondReg, CI))
850       return false;
851     BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(Mips::BGTZ))
852         .addReg(CondReg)
853         .addMBB(TBB);
854     fastEmitBranch(FBB, DbgLoc);
855     FuncInfo.MBB->addSuccessor(TBB);
856     return true;
857   }
858   return false;
859 }
860
861 bool MipsFastISel::selectCmp(const Instruction *I) {
862   const CmpInst *CI = cast<CmpInst>(I);
863   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
864   if (!emitCmp(ResultReg, CI))
865     return false;
866   updateValueMap(I, ResultReg);
867   return true;
868 }
869
870 // Attempt to fast-select a floating-point extend instruction.
871 bool MipsFastISel::selectFPExt(const Instruction *I) {
872   if (UnsupportedFPMode)
873     return false;
874   Value *Src = I->getOperand(0);
875   EVT SrcVT = TLI.getValueType(Src->getType(), true);
876   EVT DestVT = TLI.getValueType(I->getType(), true);
877
878   if (SrcVT != MVT::f32 || DestVT != MVT::f64)
879     return false;
880
881   unsigned SrcReg =
882       getRegForValue(Src); // his must be a 32 bit floating point register class
883                            // maybe we should handle this differently
884   if (!SrcReg)
885     return false;
886
887   unsigned DestReg = createResultReg(&Mips::AFGR64RegClass);
888   emitInst(Mips::CVT_D32_S, DestReg).addReg(SrcReg);
889   updateValueMap(I, DestReg);
890   return true;
891 }
892
893 // Attempt to fast-select a floating-point truncate instruction.
894 bool MipsFastISel::selectFPTrunc(const Instruction *I) {
895   if (UnsupportedFPMode)
896     return false;
897   Value *Src = I->getOperand(0);
898   EVT SrcVT = TLI.getValueType(Src->getType(), true);
899   EVT DestVT = TLI.getValueType(I->getType(), true);
900
901   if (SrcVT != MVT::f64 || DestVT != MVT::f32)
902     return false;
903
904   unsigned SrcReg = getRegForValue(Src);
905   if (!SrcReg)
906     return false;
907
908   unsigned DestReg = createResultReg(&Mips::FGR32RegClass);
909   if (!DestReg)
910     return false;
911
912   emitInst(Mips::CVT_S_D32, DestReg).addReg(SrcReg);
913   updateValueMap(I, DestReg);
914   return true;
915 }
916
917 // Attempt to fast-select a floating-point-to-integer conversion.
918 bool MipsFastISel::selectFPToInt(const Instruction *I, bool IsSigned) {
919   if (UnsupportedFPMode)
920     return false;
921   MVT DstVT, SrcVT;
922   if (!IsSigned)
923     return false; // We don't handle this case yet. There is no native
924                   // instruction for this but it can be synthesized.
925   Type *DstTy = I->getType();
926   if (!isTypeLegal(DstTy, DstVT))
927     return false;
928
929   if (DstVT != MVT::i32)
930     return false;
931
932   Value *Src = I->getOperand(0);
933   Type *SrcTy = Src->getType();
934   if (!isTypeLegal(SrcTy, SrcVT))
935     return false;
936
937   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
938     return false;
939
940   unsigned SrcReg = getRegForValue(Src);
941   if (SrcReg == 0)
942     return false;
943
944   // Determine the opcode for the conversion, which takes place
945   // entirely within FPRs.
946   unsigned DestReg = createResultReg(&Mips::GPR32RegClass);
947   unsigned TempReg = createResultReg(&Mips::FGR32RegClass);
948   unsigned Opc;
949
950   if (SrcVT == MVT::f32)
951     Opc = Mips::TRUNC_W_S;
952   else
953     Opc = Mips::TRUNC_W_D32;
954
955   // Generate the convert.
956   emitInst(Opc, TempReg).addReg(SrcReg);
957
958   emitInst(Mips::MFC1, DestReg).addReg(TempReg);
959
960   updateValueMap(I, DestReg);
961   return true;
962 }
963 //
964 bool MipsFastISel::processCallArgs(CallLoweringInfo &CLI,
965                                    SmallVectorImpl<MVT> &OutVTs,
966                                    unsigned &NumBytes) {
967   CallingConv::ID CC = CLI.CallConv;
968   SmallVector<CCValAssign, 16> ArgLocs;
969   CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
970   CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
971   // Get a count of how many bytes are to be pushed on the stack.
972   NumBytes = CCInfo.getNextStackOffset();
973   // This is the minimum argument area used for A0-A3.
974   if (NumBytes < 16)
975     NumBytes = 16;
976
977   emitInst(Mips::ADJCALLSTACKDOWN).addImm(16);
978   // Process the args.
979   MVT firstMVT;
980   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
981     CCValAssign &VA = ArgLocs[i];
982     const Value *ArgVal = CLI.OutVals[VA.getValNo()];
983     MVT ArgVT = OutVTs[VA.getValNo()];
984
985     if (i == 0) {
986       firstMVT = ArgVT;
987       if (ArgVT == MVT::f32) {
988         VA.convertToReg(Mips::F12);
989       } else if (ArgVT == MVT::f64) {
990         VA.convertToReg(Mips::D6);
991       }
992     } else if (i == 1) {
993       if ((firstMVT == MVT::f32) || (firstMVT == MVT::f64)) {
994         if (ArgVT == MVT::f32) {
995           VA.convertToReg(Mips::F14);
996         } else if (ArgVT == MVT::f64) {
997           VA.convertToReg(Mips::D7);
998         }
999       }
1000     }
1001     if (((ArgVT == MVT::i32) || (ArgVT == MVT::f32)) && VA.isMemLoc()) {
1002       switch (VA.getLocMemOffset()) {
1003       case 0:
1004         VA.convertToReg(Mips::A0);
1005         break;
1006       case 4:
1007         VA.convertToReg(Mips::A1);
1008         break;
1009       case 8:
1010         VA.convertToReg(Mips::A2);
1011         break;
1012       case 12:
1013         VA.convertToReg(Mips::A3);
1014         break;
1015       default:
1016         break;
1017       }
1018     }
1019     unsigned ArgReg = getRegForValue(ArgVal);
1020     if (!ArgReg)
1021       return false;
1022
1023     // Handle arg promotion: SExt, ZExt, AExt.
1024     switch (VA.getLocInfo()) {
1025     case CCValAssign::Full:
1026       break;
1027     case CCValAssign::AExt:
1028     case CCValAssign::SExt: {
1029       MVT DestVT = VA.getLocVT();
1030       MVT SrcVT = ArgVT;
1031       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
1032       if (!ArgReg)
1033         return false;
1034       break;
1035     }
1036     case CCValAssign::ZExt: {
1037       MVT DestVT = VA.getLocVT();
1038       MVT SrcVT = ArgVT;
1039       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
1040       if (!ArgReg)
1041         return false;
1042       break;
1043     }
1044     default:
1045       llvm_unreachable("Unknown arg promotion!");
1046     }
1047
1048     // Now copy/store arg to correct locations.
1049     if (VA.isRegLoc() && !VA.needsCustom()) {
1050       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1051               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
1052       CLI.OutRegs.push_back(VA.getLocReg());
1053     } else if (VA.needsCustom()) {
1054       llvm_unreachable("Mips does not use custom args.");
1055       return false;
1056     } else {
1057       //
1058       // FIXME: This path will currently return false. It was copied
1059       // from the AArch64 port and should be essentially fine for Mips too.
1060       // The work to finish up this path will be done in a follow-on patch.
1061       //
1062       assert(VA.isMemLoc() && "Assuming store on stack.");
1063       // Don't emit stores for undef values.
1064       if (isa<UndefValue>(ArgVal))
1065         continue;
1066
1067       // Need to store on the stack.
1068       // FIXME: This alignment is incorrect but this path is disabled
1069       // for now (will return false). We need to determine the right alignment
1070       // based on the normal alignment for the underlying machine type.
1071       //
1072       unsigned ArgSize = RoundUpToAlignment(ArgVT.getSizeInBits(), 4);
1073
1074       unsigned BEAlign = 0;
1075       if (ArgSize < 8 && !Subtarget->isLittle())
1076         BEAlign = 8 - ArgSize;
1077
1078       Address Addr;
1079       Addr.setKind(Address::RegBase);
1080       Addr.setReg(Mips::SP);
1081       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1082
1083       unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
1084       MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
1085           MachinePointerInfo::getStack(Addr.getOffset()),
1086           MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
1087       (void)(MMO);
1088       // if (!emitStore(ArgVT, ArgReg, Addr, MMO))
1089       return false; // can't store on the stack yet.
1090     }
1091   }
1092
1093   return true;
1094 }
1095
1096 bool MipsFastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
1097                               unsigned NumBytes) {
1098   CallingConv::ID CC = CLI.CallConv;
1099   emitInst(Mips::ADJCALLSTACKUP).addImm(16);
1100   if (RetVT != MVT::isVoid) {
1101     SmallVector<CCValAssign, 16> RVLocs;
1102     CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
1103     CCInfo.AnalyzeCallResult(RetVT, RetCC_Mips);
1104
1105     // Only handle a single return value.
1106     if (RVLocs.size() != 1)
1107       return false;
1108     // Copy all of the result registers out of their specified physreg.
1109     MVT CopyVT = RVLocs[0].getValVT();
1110     // Special handling for extended integers.
1111     if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
1112       CopyVT = MVT::i32;
1113
1114     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1115     if (!ResultReg)
1116       return false;
1117     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1118             TII.get(TargetOpcode::COPY),
1119             ResultReg).addReg(RVLocs[0].getLocReg());
1120     CLI.InRegs.push_back(RVLocs[0].getLocReg());
1121
1122     CLI.ResultReg = ResultReg;
1123     CLI.NumResultRegs = 1;
1124   }
1125   return true;
1126 }
1127
1128 bool MipsFastISel::fastLowerCall(CallLoweringInfo &CLI) {
1129   CallingConv::ID CC = CLI.CallConv;
1130   bool IsTailCall = CLI.IsTailCall;
1131   bool IsVarArg = CLI.IsVarArg;
1132   const Value *Callee = CLI.Callee;
1133   // const char *SymName = CLI.SymName;
1134
1135   // Allow SelectionDAG isel to handle tail calls.
1136   if (IsTailCall)
1137     return false;
1138
1139   // Let SDISel handle vararg functions.
1140   if (IsVarArg)
1141     return false;
1142
1143   // FIXME: Only handle *simple* calls for now.
1144   MVT RetVT;
1145   if (CLI.RetTy->isVoidTy())
1146     RetVT = MVT::isVoid;
1147   else if (!isTypeSupported(CLI.RetTy, RetVT))
1148     return false;
1149
1150   for (auto Flag : CLI.OutFlags)
1151     if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
1152       return false;
1153
1154   // Set up the argument vectors.
1155   SmallVector<MVT, 16> OutVTs;
1156   OutVTs.reserve(CLI.OutVals.size());
1157
1158   for (auto *Val : CLI.OutVals) {
1159     MVT VT;
1160     if (!isTypeLegal(Val->getType(), VT) &&
1161         !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
1162       return false;
1163
1164     // We don't handle vector parameters yet.
1165     if (VT.isVector() || VT.getSizeInBits() > 64)
1166       return false;
1167
1168     OutVTs.push_back(VT);
1169   }
1170
1171   Address Addr;
1172   if (!computeCallAddress(Callee, Addr))
1173     return false;
1174
1175   // Handle the arguments now that we've gotten them.
1176   unsigned NumBytes;
1177   if (!processCallArgs(CLI, OutVTs, NumBytes))
1178     return false;
1179
1180   // Issue the call.
1181   unsigned DestAddress = materializeGV(Addr.getGlobalValue(), MVT::i32);
1182   emitInst(TargetOpcode::COPY, Mips::T9).addReg(DestAddress);
1183   MachineInstrBuilder MIB =
1184       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Mips::JALR),
1185               Mips::RA).addReg(Mips::T9);
1186
1187   // Add implicit physical register uses to the call.
1188   for (auto Reg : CLI.OutRegs)
1189     MIB.addReg(Reg, RegState::Implicit);
1190
1191   // Add a register mask with the call-preserved registers.
1192   // Proper defs for return values will be added by setPhysRegsDeadExcept().
1193   MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
1194
1195   CLI.Call = MIB;
1196
1197   // Finish off the call including any return values.
1198   return finishCall(CLI, RetVT, NumBytes);
1199 }
1200
1201 bool MipsFastISel::selectRet(const Instruction *I) {
1202   const Function &F = *I->getParent()->getParent();
1203   const ReturnInst *Ret = cast<ReturnInst>(I);
1204
1205   if (!FuncInfo.CanLowerReturn)
1206     return false;
1207
1208   // Build a list of return value registers.
1209   SmallVector<unsigned, 4> RetRegs;
1210
1211   if (Ret->getNumOperands() > 0) {
1212     CallingConv::ID CC = F.getCallingConv();
1213     SmallVector<ISD::OutputArg, 4> Outs;
1214     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1215     // Analyze operands of the call, assigning locations to each operand.
1216     SmallVector<CCValAssign, 16> ValLocs;
1217     MipsCCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs,
1218                        I->getContext());
1219     CCAssignFn *RetCC = RetCC_Mips;
1220     CCInfo.AnalyzeReturn(Outs, RetCC);
1221
1222     // Only handle a single return value for now.
1223     if (ValLocs.size() != 1)
1224       return false;
1225
1226     CCValAssign &VA = ValLocs[0];
1227     const Value *RV = Ret->getOperand(0);
1228
1229     // Don't bother handling odd stuff for now.
1230     if ((VA.getLocInfo() != CCValAssign::Full) &&
1231         (VA.getLocInfo() != CCValAssign::BCvt))
1232       return false;
1233
1234     // Only handle register returns for now.
1235     if (!VA.isRegLoc())
1236       return false;
1237
1238     unsigned Reg = getRegForValue(RV);
1239     if (Reg == 0)
1240       return false;
1241
1242     unsigned SrcReg = Reg + VA.getValNo();
1243     unsigned DestReg = VA.getLocReg();
1244     // Avoid a cross-class copy. This is very unlikely.
1245     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
1246       return false;
1247
1248     EVT RVEVT = TLI.getValueType(RV->getType());
1249     if (!RVEVT.isSimple())
1250       return false;
1251
1252     if (RVEVT.isVector())
1253       return false;
1254
1255     MVT RVVT = RVEVT.getSimpleVT();
1256     if (RVVT == MVT::f128)
1257       return false;
1258
1259     MVT DestVT = VA.getValVT();
1260     // Special handling for extended integers.
1261     if (RVVT != DestVT) {
1262       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
1263         return false;
1264
1265       if (Outs[0].Flags.isZExt() || Outs[0].Flags.isSExt()) {
1266         bool IsZExt = Outs[0].Flags.isZExt();
1267         SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
1268         if (SrcReg == 0)
1269           return false;
1270       }
1271     }
1272
1273     // Make the copy.
1274     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1275             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
1276
1277     // Add register to return instruction.
1278     RetRegs.push_back(VA.getLocReg());
1279   }
1280   MachineInstrBuilder MIB = emitInst(Mips::RetRA);
1281   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1282     MIB.addReg(RetRegs[i], RegState::Implicit);
1283   return true;
1284 }
1285
1286 bool MipsFastISel::selectTrunc(const Instruction *I) {
1287   // The high bits for a type smaller than the register size are assumed to be
1288   // undefined.
1289   Value *Op = I->getOperand(0);
1290
1291   EVT SrcVT, DestVT;
1292   SrcVT = TLI.getValueType(Op->getType(), true);
1293   DestVT = TLI.getValueType(I->getType(), true);
1294
1295   if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1296     return false;
1297   if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1298     return false;
1299
1300   unsigned SrcReg = getRegForValue(Op);
1301   if (!SrcReg)
1302     return false;
1303
1304   // Because the high bits are undefined, a truncate doesn't generate
1305   // any code.
1306   updateValueMap(I, SrcReg);
1307   return true;
1308 }
1309 bool MipsFastISel::selectIntExt(const Instruction *I) {
1310   Type *DestTy = I->getType();
1311   Value *Src = I->getOperand(0);
1312   Type *SrcTy = Src->getType();
1313
1314   bool isZExt = isa<ZExtInst>(I);
1315   unsigned SrcReg = getRegForValue(Src);
1316   if (!SrcReg)
1317     return false;
1318
1319   EVT SrcEVT, DestEVT;
1320   SrcEVT = TLI.getValueType(SrcTy, true);
1321   DestEVT = TLI.getValueType(DestTy, true);
1322   if (!SrcEVT.isSimple())
1323     return false;
1324   if (!DestEVT.isSimple())
1325     return false;
1326
1327   MVT SrcVT = SrcEVT.getSimpleVT();
1328   MVT DestVT = DestEVT.getSimpleVT();
1329   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
1330
1331   if (!emitIntExt(SrcVT, SrcReg, DestVT, ResultReg, isZExt))
1332     return false;
1333   updateValueMap(I, ResultReg);
1334   return true;
1335 }
1336 bool MipsFastISel::emitIntSExt32r1(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1337                                    unsigned DestReg) {
1338   unsigned ShiftAmt;
1339   switch (SrcVT.SimpleTy) {
1340   default:
1341     return false;
1342   case MVT::i8:
1343     ShiftAmt = 24;
1344     break;
1345   case MVT::i16:
1346     ShiftAmt = 16;
1347     break;
1348   }
1349   unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
1350   emitInst(Mips::SLL, TempReg).addReg(SrcReg).addImm(ShiftAmt);
1351   emitInst(Mips::SRA, DestReg).addReg(TempReg).addImm(ShiftAmt);
1352   return true;
1353 }
1354
1355 bool MipsFastISel::emitIntSExt32r2(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1356                                    unsigned DestReg) {
1357   switch (SrcVT.SimpleTy) {
1358   default:
1359     return false;
1360   case MVT::i8:
1361     emitInst(Mips::SEB, DestReg).addReg(SrcReg);
1362     break;
1363   case MVT::i16:
1364     emitInst(Mips::SEH, DestReg).addReg(SrcReg);
1365     break;
1366   }
1367   return true;
1368 }
1369
1370 bool MipsFastISel::emitIntSExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1371                                unsigned DestReg) {
1372   if ((DestVT != MVT::i32) && (DestVT != MVT::i16))
1373     return false;
1374   if (Subtarget->hasMips32r2())
1375     return emitIntSExt32r2(SrcVT, SrcReg, DestVT, DestReg);
1376   return emitIntSExt32r1(SrcVT, SrcReg, DestVT, DestReg);
1377 }
1378
1379 bool MipsFastISel::emitIntZExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1380                                unsigned DestReg) {
1381   switch (SrcVT.SimpleTy) {
1382   default:
1383     return false;
1384   case MVT::i1:
1385     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(1);
1386     break;
1387   case MVT::i8:
1388     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(0xff);
1389     break;
1390   case MVT::i16:
1391     emitInst(Mips::ANDi, DestReg).addReg(SrcReg).addImm(0xffff);
1392     break;
1393   }
1394   return true;
1395 }
1396
1397 bool MipsFastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1398                               unsigned DestReg, bool IsZExt) {
1399   // FastISel does not have plumbing to deal with extensions where the SrcVT or
1400   // DestVT are odd things, so test to make sure that they are both types we can
1401   // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
1402   // bail out to SelectionDAG.
1403   if (((DestVT != MVT::i8) && (DestVT != MVT::i16) && (DestVT != MVT::i32)) ||
1404       ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) && (SrcVT != MVT::i16)))
1405     return false;
1406   if (IsZExt)
1407     return emitIntZExt(SrcVT, SrcReg, DestVT, DestReg);
1408   return emitIntSExt(SrcVT, SrcReg, DestVT, DestReg);
1409 }
1410
1411 unsigned MipsFastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1412                                   bool isZExt) {
1413   unsigned DestReg = createResultReg(&Mips::GPR32RegClass);
1414   bool Success = emitIntExt(SrcVT, SrcReg, DestVT, DestReg, isZExt);
1415   return Success ? DestReg : 0;
1416 }
1417
1418 bool MipsFastISel::selectShift(const Instruction *I) {
1419   MVT RetVT;
1420
1421   if (!isTypeSupported(I->getType(), RetVT))
1422     return false;
1423
1424   unsigned ResultReg = createResultReg(&Mips::GPR32RegClass);
1425   if (!ResultReg)
1426     return false;
1427
1428   unsigned Opcode = I->getOpcode();
1429   const Value *Op0 = I->getOperand(0);
1430   unsigned Op0Reg = getRegForValue(Op0);
1431   if (!Op0Reg)
1432     return false;
1433
1434   // If AShr or LShr, then we need to make sure the operand0 is sign extended.
1435   if (Opcode == Instruction::AShr || Opcode == Instruction::LShr) {
1436     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
1437     if (!TempReg)
1438       return false;
1439
1440     MVT Op0MVT = TLI.getValueType(Op0->getType(), true).getSimpleVT();
1441     bool IsZExt = Opcode == Instruction::LShr;
1442     if (!emitIntExt(Op0MVT, Op0Reg, MVT::i32, TempReg, IsZExt))
1443       return false;
1444
1445     Op0Reg = TempReg;
1446   }
1447
1448   if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
1449     uint64_t ShiftVal = C->getZExtValue();
1450
1451     switch (Opcode) {
1452     default:
1453       llvm_unreachable("Unexpected instruction.");
1454     case Instruction::Shl:
1455       Opcode = Mips::SLL;
1456       break;
1457     case Instruction::AShr:
1458       Opcode = Mips::SRA;
1459       break;
1460     case Instruction::LShr:
1461       Opcode = Mips::SRL;
1462       break;
1463     }
1464
1465     emitInst(Opcode, ResultReg).addReg(Op0Reg).addImm(ShiftVal);
1466     updateValueMap(I, ResultReg);
1467     return true;
1468   }
1469
1470   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1471   if (!Op1Reg)
1472     return false;
1473
1474   switch (Opcode) {
1475   default:
1476     llvm_unreachable("Unexpected instruction.");
1477   case Instruction::Shl:
1478     Opcode = Mips::SLLV;
1479     break;
1480   case Instruction::AShr:
1481     Opcode = Mips::SRAV;
1482     break;
1483   case Instruction::LShr:
1484     Opcode = Mips::SRLV;
1485     break;
1486   }
1487
1488   emitInst(Opcode, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1489   updateValueMap(I, ResultReg);
1490   return true;
1491 }
1492
1493 bool MipsFastISel::fastSelectInstruction(const Instruction *I) {
1494   if (!TargetSupported)
1495     return false;
1496   switch (I->getOpcode()) {
1497   default:
1498     break;
1499   case Instruction::Load:
1500     return selectLoad(I);
1501   case Instruction::Store:
1502     return selectStore(I);
1503   case Instruction::Shl:
1504   case Instruction::LShr:
1505   case Instruction::AShr:
1506     return selectShift(I);
1507   case Instruction::And:
1508   case Instruction::Or:
1509   case Instruction::Xor:
1510     return selectLogicalOp(I);
1511   case Instruction::Br:
1512     return selectBranch(I);
1513   case Instruction::Ret:
1514     return selectRet(I);
1515   case Instruction::Trunc:
1516     return selectTrunc(I);
1517   case Instruction::ZExt:
1518   case Instruction::SExt:
1519     return selectIntExt(I);
1520   case Instruction::FPTrunc:
1521     return selectFPTrunc(I);
1522   case Instruction::FPExt:
1523     return selectFPExt(I);
1524   case Instruction::FPToSI:
1525     return selectFPToInt(I, /*isSigned*/ true);
1526   case Instruction::FPToUI:
1527     return selectFPToInt(I, /*isSigned*/ false);
1528   case Instruction::ICmp:
1529   case Instruction::FCmp:
1530     return selectCmp(I);
1531   }
1532   return false;
1533 }
1534
1535 unsigned MipsFastISel::getRegEnsuringSimpleIntegerWidening(const Value *V,
1536                                                            bool IsUnsigned) {
1537   unsigned VReg = getRegForValue(V);
1538   if (VReg == 0)
1539     return 0;
1540   MVT VMVT = TLI.getValueType(V->getType(), true).getSimpleVT();
1541   if ((VMVT == MVT::i8) || (VMVT == MVT::i16)) {
1542     unsigned TempReg = createResultReg(&Mips::GPR32RegClass);
1543     if (!emitIntExt(VMVT, VReg, MVT::i32, TempReg, IsUnsigned))
1544       return 0;
1545     VReg = TempReg;
1546   }
1547   return VReg;
1548 }
1549
1550 void MipsFastISel::simplifyAddress(Address &Addr) {
1551   if (!isInt<16>(Addr.getOffset())) {
1552     unsigned TempReg =
1553         materialize32BitInt(Addr.getOffset(), &Mips::GPR32RegClass);
1554     unsigned DestReg = createResultReg(&Mips::GPR32RegClass);
1555     emitInst(Mips::ADDu, DestReg).addReg(TempReg).addReg(Addr.getReg());
1556     Addr.setReg(DestReg);
1557     Addr.setOffset(0);
1558   }
1559 }
1560
1561 namespace llvm {
1562 FastISel *Mips::createFastISel(FunctionLoweringInfo &funcInfo,
1563                                const TargetLibraryInfo *libInfo) {
1564   return new MipsFastISel(funcInfo, libInfo);
1565 }
1566 }