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