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