1//===-- Mips16ISelLowering.h - Mips16 DAG Lowering Interface ----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Subclass of MipsTargetLowering specialized for mips16.
11//
12//===----------------------------------------------------------------------===//
13#include "Mips16ISelLowering.h"
14#include "MCTargetDesc/MipsBaseInfo.h"
15#include "MipsRegisterInfo.h"
16#include "MipsTargetMachine.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/Support/CommandLine.h"
20#include "llvm/Target/TargetInstrInfo.h"
21#include <string>
22
23using namespace llvm;
24
25#define DEBUG_TYPE "mips-lower"
26
27static cl::opt<bool> DontExpandCondPseudos16(
28  "mips16-dont-expand-cond-pseudo",
29  cl::init(false),
30  cl::desc("Dont expand conditional move related "
31           "pseudos for Mips 16"),
32  cl::Hidden);
33
34namespace {
35struct Mips16Libcall {
36  RTLIB::Libcall Libcall;
37  const char *Name;
38
39  bool operator<(const Mips16Libcall &RHS) const {
40    return std::strcmp(Name, RHS.Name) < 0;
41  }
42};
43
44struct Mips16IntrinsicHelperType{
45  const char* Name;
46  const char* Helper;
47
48  bool operator<(const Mips16IntrinsicHelperType &RHS) const {
49    return std::strcmp(Name, RHS.Name) < 0;
50  }
51  bool operator==(const Mips16IntrinsicHelperType &RHS) const {
52    return std::strcmp(Name, RHS.Name) == 0;
53  }
54};
55}
56
57// Libcalls for which no helper is generated. Sorted by name for binary search.
58static const Mips16Libcall HardFloatLibCalls[] = {
59  { RTLIB::ADD_F64, "__mips16_adddf3" },
60  { RTLIB::ADD_F32, "__mips16_addsf3" },
61  { RTLIB::DIV_F64, "__mips16_divdf3" },
62  { RTLIB::DIV_F32, "__mips16_divsf3" },
63  { RTLIB::OEQ_F64, "__mips16_eqdf2" },
64  { RTLIB::OEQ_F32, "__mips16_eqsf2" },
65  { RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2" },
66  { RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi" },
67  { RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi" },
68  { RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf" },
69  { RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf" },
70  { RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf" },
71  { RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf" },
72  { RTLIB::OGE_F64, "__mips16_gedf2" },
73  { RTLIB::OGE_F32, "__mips16_gesf2" },
74  { RTLIB::OGT_F64, "__mips16_gtdf2" },
75  { RTLIB::OGT_F32, "__mips16_gtsf2" },
76  { RTLIB::OLE_F64, "__mips16_ledf2" },
77  { RTLIB::OLE_F32, "__mips16_lesf2" },
78  { RTLIB::OLT_F64, "__mips16_ltdf2" },
79  { RTLIB::OLT_F32, "__mips16_ltsf2" },
80  { RTLIB::MUL_F64, "__mips16_muldf3" },
81  { RTLIB::MUL_F32, "__mips16_mulsf3" },
82  { RTLIB::UNE_F64, "__mips16_nedf2" },
83  { RTLIB::UNE_F32, "__mips16_nesf2" },
84  { RTLIB::UNKNOWN_LIBCALL, "__mips16_ret_dc" }, // No associated libcall.
85  { RTLIB::UNKNOWN_LIBCALL, "__mips16_ret_df" }, // No associated libcall.
86  { RTLIB::UNKNOWN_LIBCALL, "__mips16_ret_sc" }, // No associated libcall.
87  { RTLIB::UNKNOWN_LIBCALL, "__mips16_ret_sf" }, // No associated libcall.
88  { RTLIB::SUB_F64, "__mips16_subdf3" },
89  { RTLIB::SUB_F32, "__mips16_subsf3" },
90  { RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2" },
91  { RTLIB::UO_F64, "__mips16_unorddf2" },
92  { RTLIB::UO_F32, "__mips16_unordsf2" }
93};
94
95static const Mips16IntrinsicHelperType Mips16IntrinsicHelper[] = {
96  {"__fixunsdfsi", "__mips16_call_stub_2" },
97  {"ceil",  "__mips16_call_stub_df_2"},
98  {"ceilf", "__mips16_call_stub_sf_1"},
99  {"copysign",  "__mips16_call_stub_df_10"},
100  {"copysignf", "__mips16_call_stub_sf_5"},
101  {"cos",  "__mips16_call_stub_df_2"},
102  {"cosf", "__mips16_call_stub_sf_1"},
103  {"exp2",  "__mips16_call_stub_df_2"},
104  {"exp2f", "__mips16_call_stub_sf_1"},
105  {"floor",  "__mips16_call_stub_df_2"},
106  {"floorf", "__mips16_call_stub_sf_1"},
107  {"log2",  "__mips16_call_stub_df_2"},
108  {"log2f", "__mips16_call_stub_sf_1"},
109  {"nearbyint",  "__mips16_call_stub_df_2"},
110  {"nearbyintf", "__mips16_call_stub_sf_1"},
111  {"rint",  "__mips16_call_stub_df_2"},
112  {"rintf", "__mips16_call_stub_sf_1"},
113  {"sin",  "__mips16_call_stub_df_2"},
114  {"sinf", "__mips16_call_stub_sf_1"},
115  {"sqrt",  "__mips16_call_stub_df_2"},
116  {"sqrtf", "__mips16_call_stub_sf_1"},
117  {"trunc",  "__mips16_call_stub_df_2"},
118  {"truncf", "__mips16_call_stub_sf_1"},
119};
120
121Mips16TargetLowering::Mips16TargetLowering(MipsTargetMachine &TM)
122  : MipsTargetLowering(TM) {
123
124  // Set up the register classes
125  addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
126
127  if (Subtarget->inMips16HardFloat())
128    setMips16HardFloatLibCalls();
129
130  setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Expand);
131  setOperationAction(ISD::ATOMIC_CMP_SWAP,    MVT::i32,   Expand);
132  setOperationAction(ISD::ATOMIC_SWAP,        MVT::i32,   Expand);
133  setOperationAction(ISD::ATOMIC_LOAD_ADD,    MVT::i32,   Expand);
134  setOperationAction(ISD::ATOMIC_LOAD_SUB,    MVT::i32,   Expand);
135  setOperationAction(ISD::ATOMIC_LOAD_AND,    MVT::i32,   Expand);
136  setOperationAction(ISD::ATOMIC_LOAD_OR,     MVT::i32,   Expand);
137  setOperationAction(ISD::ATOMIC_LOAD_XOR,    MVT::i32,   Expand);
138  setOperationAction(ISD::ATOMIC_LOAD_NAND,   MVT::i32,   Expand);
139  setOperationAction(ISD::ATOMIC_LOAD_MIN,    MVT::i32,   Expand);
140  setOperationAction(ISD::ATOMIC_LOAD_MAX,    MVT::i32,   Expand);
141  setOperationAction(ISD::ATOMIC_LOAD_UMIN,   MVT::i32,   Expand);
142  setOperationAction(ISD::ATOMIC_LOAD_UMAX,   MVT::i32,   Expand);
143
144  setOperationAction(ISD::ROTR, MVT::i32,  Expand);
145  setOperationAction(ISD::ROTR, MVT::i64,  Expand);
146  setOperationAction(ISD::BSWAP, MVT::i32, Expand);
147  setOperationAction(ISD::BSWAP, MVT::i64, Expand);
148
149  computeRegisterProperties();
150}
151
152const MipsTargetLowering *
153llvm::createMips16TargetLowering(MipsTargetMachine &TM) {
154  return new Mips16TargetLowering(TM);
155}
156
157bool
158Mips16TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
159                                                    unsigned,
160                                                    bool *Fast) const {
161  return false;
162}
163
164MachineBasicBlock *
165Mips16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
166                                                  MachineBasicBlock *BB) const {
167  switch (MI->getOpcode()) {
168  default:
169    return MipsTargetLowering::EmitInstrWithCustomInserter(MI, BB);
170  case Mips::SelBeqZ:
171    return emitSel16(Mips::BeqzRxImm16, MI, BB);
172  case Mips::SelBneZ:
173    return emitSel16(Mips::BnezRxImm16, MI, BB);
174  case Mips::SelTBteqZCmpi:
175    return emitSeliT16(Mips::Bteqz16, Mips::CmpiRxImmX16, MI, BB);
176  case Mips::SelTBteqZSlti:
177    return emitSeliT16(Mips::Bteqz16, Mips::SltiRxImmX16, MI, BB);
178  case Mips::SelTBteqZSltiu:
179    return emitSeliT16(Mips::Bteqz16, Mips::SltiuRxImmX16, MI, BB);
180  case Mips::SelTBtneZCmpi:
181    return emitSeliT16(Mips::Btnez16, Mips::CmpiRxImmX16, MI, BB);
182  case Mips::SelTBtneZSlti:
183    return emitSeliT16(Mips::Btnez16, Mips::SltiRxImmX16, MI, BB);
184  case Mips::SelTBtneZSltiu:
185    return emitSeliT16(Mips::Btnez16, Mips::SltiuRxImmX16, MI, BB);
186  case Mips::SelTBteqZCmp:
187    return emitSelT16(Mips::Bteqz16, Mips::CmpRxRy16, MI, BB);
188  case Mips::SelTBteqZSlt:
189    return emitSelT16(Mips::Bteqz16, Mips::SltRxRy16, MI, BB);
190  case Mips::SelTBteqZSltu:
191    return emitSelT16(Mips::Bteqz16, Mips::SltuRxRy16, MI, BB);
192  case Mips::SelTBtneZCmp:
193    return emitSelT16(Mips::Btnez16, Mips::CmpRxRy16, MI, BB);
194  case Mips::SelTBtneZSlt:
195    return emitSelT16(Mips::Btnez16, Mips::SltRxRy16, MI, BB);
196  case Mips::SelTBtneZSltu:
197    return emitSelT16(Mips::Btnez16, Mips::SltuRxRy16, MI, BB);
198  case Mips::BteqzT8CmpX16:
199    return emitFEXT_T8I816_ins(Mips::Bteqz16, Mips::CmpRxRy16, MI, BB);
200  case Mips::BteqzT8SltX16:
201    return emitFEXT_T8I816_ins(Mips::Bteqz16, Mips::SltRxRy16, MI, BB);
202  case Mips::BteqzT8SltuX16:
203    // TBD: figure out a way to get this or remove the instruction
204    // altogether.
205    return emitFEXT_T8I816_ins(Mips::Bteqz16, Mips::SltuRxRy16, MI, BB);
206  case Mips::BtnezT8CmpX16:
207    return emitFEXT_T8I816_ins(Mips::Btnez16, Mips::CmpRxRy16, MI, BB);
208  case Mips::BtnezT8SltX16:
209    return emitFEXT_T8I816_ins(Mips::Btnez16, Mips::SltRxRy16, MI, BB);
210  case Mips::BtnezT8SltuX16:
211    // TBD: figure out a way to get this or remove the instruction
212    // altogether.
213    return emitFEXT_T8I816_ins(Mips::Btnez16, Mips::SltuRxRy16, MI, BB);
214  case Mips::BteqzT8CmpiX16: return emitFEXT_T8I8I16_ins(
215    Mips::Bteqz16, Mips::CmpiRxImm16, Mips::CmpiRxImmX16, false, MI, BB);
216  case Mips::BteqzT8SltiX16: return emitFEXT_T8I8I16_ins(
217    Mips::Bteqz16, Mips::SltiRxImm16, Mips::SltiRxImmX16, true, MI, BB);
218  case Mips::BteqzT8SltiuX16: return emitFEXT_T8I8I16_ins(
219    Mips::Bteqz16, Mips::SltiuRxImm16, Mips::SltiuRxImmX16, false, MI, BB);
220  case Mips::BtnezT8CmpiX16: return emitFEXT_T8I8I16_ins(
221    Mips::Btnez16, Mips::CmpiRxImm16, Mips::CmpiRxImmX16, false, MI, BB);
222  case Mips::BtnezT8SltiX16: return emitFEXT_T8I8I16_ins(
223    Mips::Btnez16, Mips::SltiRxImm16, Mips::SltiRxImmX16, true, MI, BB);
224  case Mips::BtnezT8SltiuX16: return emitFEXT_T8I8I16_ins(
225    Mips::Btnez16, Mips::SltiuRxImm16, Mips::SltiuRxImmX16, false, MI, BB);
226    break;
227  case Mips::SltCCRxRy16:
228    return emitFEXT_CCRX16_ins(Mips::SltRxRy16, MI, BB);
229    break;
230  case Mips::SltiCCRxImmX16:
231    return emitFEXT_CCRXI16_ins
232      (Mips::SltiRxImm16, Mips::SltiRxImmX16, MI, BB);
233  case Mips::SltiuCCRxImmX16:
234    return emitFEXT_CCRXI16_ins
235      (Mips::SltiuRxImm16, Mips::SltiuRxImmX16, MI, BB);
236  case Mips::SltuCCRxRy16:
237    return emitFEXT_CCRX16_ins
238      (Mips::SltuRxRy16, MI, BB);
239  }
240}
241
242bool Mips16TargetLowering::
243isEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
244                                  unsigned NextStackOffset,
245                                  const MipsFunctionInfo& FI) const {
246  // No tail call optimization for mips16.
247  return false;
248}
249
250void Mips16TargetLowering::setMips16HardFloatLibCalls() {
251  for (unsigned I = 0; I != array_lengthof(HardFloatLibCalls); ++I) {
252    assert((I == 0 || HardFloatLibCalls[I - 1] < HardFloatLibCalls[I]) &&
253           "Array not sorted!");
254    if (HardFloatLibCalls[I].Libcall != RTLIB::UNKNOWN_LIBCALL)
255      setLibcallName(HardFloatLibCalls[I].Libcall, HardFloatLibCalls[I].Name);
256  }
257
258  setLibcallName(RTLIB::O_F64, "__mips16_unorddf2");
259  setLibcallName(RTLIB::O_F32, "__mips16_unordsf2");
260}
261
262//
263// The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
264// cleaner way to do all of this but it will have to wait until the traditional
265// gcc mechanism is completed.
266//
267// For Pic, in order for Mips16 code to call Mips32 code which according the abi
268// have either arguments or returned values placed in floating point registers,
269// we use a set of helper functions. (This includes functions which return type
270//  complex which on Mips are returned in a pair of floating point registers).
271//
272// This is an encoding that we inherited from gcc.
273// In Mips traditional O32, N32 ABI, floating point numbers are passed in
274// floating point argument registers 1,2 only when the first and optionally
275// the second arguments are float (sf) or double (df).
276// For Mips16 we are only concerned with the situations where floating point
277// arguments are being passed in floating point registers by the ABI, because
278// Mips16 mode code cannot execute floating point instructions to load those
279// values and hence helper functions are needed.
280// The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
281// the helper function suffixs for these are:
282//                        0,  1,    5,        9,         2,   6,        10
283// this suffix can then be calculated as follows:
284// for a given argument Arg:
285//     Arg1x, Arg2x = 1 :  Arg is sf
286//                    2 :  Arg is df
287//                    0:   Arg is neither sf or df
288// So this stub is the string for number Arg1x + Arg2x*4.
289// However not all numbers between 0 and 10 are possible, we check anyway and
290// assert if the impossible exists.
291//
292
293unsigned int Mips16TargetLowering::getMips16HelperFunctionStubNumber
294  (ArgListTy &Args) const {
295  unsigned int resultNum = 0;
296  if (Args.size() >= 1) {
297    Type *t = Args[0].Ty;
298    if (t->isFloatTy()) {
299      resultNum = 1;
300    }
301    else if (t->isDoubleTy()) {
302      resultNum = 2;
303    }
304  }
305  if (resultNum) {
306    if (Args.size() >=2) {
307      Type *t = Args[1].Ty;
308      if (t->isFloatTy()) {
309        resultNum += 4;
310      }
311      else if (t->isDoubleTy()) {
312        resultNum += 8;
313      }
314    }
315  }
316  return resultNum;
317}
318
319//
320// prefixs are attached to stub numbers depending on the return type .
321// return type: float  sf_
322//              double df_
323//              single complex sc_
324//              double complext dc_
325//              others  NO PREFIX
326//
327//
328// The full name of a helper function is__mips16_call_stub +
329//    return type dependent prefix + stub number
330//
331//
332// This is something that probably should be in a different source file and
333// perhaps done differently but my main purpose is to not waste runtime
334// on something that we can enumerate in the source. Another possibility is
335// to have a python script to generate these mapping tables. This will do
336// for now. There are a whole series of helper function mapping arrays, one
337// for each return type class as outlined above. There there are 11 possible
338//  entries. Ones with 0 are ones which should never be selected
339//
340// All the arrays are similar except for ones which return neither
341// sf, df, sc, dc, in which only care about ones which have sf or df as a
342// first parameter.
343//
344#define P_ "__mips16_call_stub_"
345#define MAX_STUB_NUMBER 10
346#define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
347#define T P "0" , T1
348#define P P_
349static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
350  {nullptr, T1 };
351#undef P
352#define P P_ "sf_"
353static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
354  { T };
355#undef P
356#define P P_ "df_"
357static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
358  { T };
359#undef P
360#define P P_ "sc_"
361static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
362  { T };
363#undef P
364#define P P_ "dc_"
365static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
366  { T };
367#undef P
368#undef P_
369
370
371const char* Mips16TargetLowering::
372  getMips16HelperFunction
373    (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
374  const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
375#ifndef NDEBUG
376  const unsigned int maxStubNum = 10;
377  assert(stubNum <= maxStubNum);
378  const bool validStubNum[maxStubNum+1] =
379    {true, true, true, false, false, true, true, false, false, true, true};
380  assert(validStubNum[stubNum]);
381#endif
382  const char *result;
383  if (RetTy->isFloatTy()) {
384    result = sfMips16Helper[stubNum];
385  }
386  else if (RetTy ->isDoubleTy()) {
387    result = dfMips16Helper[stubNum];
388  }
389  else if (RetTy->isStructTy()) {
390    // check if it's complex
391    if (RetTy->getNumContainedTypes() == 2) {
392      if ((RetTy->getContainedType(0)->isFloatTy()) &&
393          (RetTy->getContainedType(1)->isFloatTy())) {
394        result = scMips16Helper[stubNum];
395      }
396      else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
397               (RetTy->getContainedType(1)->isDoubleTy())) {
398        result = dcMips16Helper[stubNum];
399      }
400      else {
401        llvm_unreachable("Uncovered condition");
402      }
403    }
404    else {
405      llvm_unreachable("Uncovered condition");
406    }
407  }
408  else {
409    if (stubNum == 0) {
410      needHelper = false;
411      return "";
412    }
413    result = vMips16Helper[stubNum];
414  }
415  needHelper = true;
416  return result;
417}
418
419void Mips16TargetLowering::
420getOpndList(SmallVectorImpl<SDValue> &Ops,
421            std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
422            bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
423            CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
424  SelectionDAG &DAG = CLI.DAG;
425  MachineFunction &MF = DAG.getMachineFunction();
426  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
427  const char* Mips16HelperFunction = nullptr;
428  bool NeedMips16Helper = false;
429
430  if (Subtarget->inMips16HardFloat()) {
431    //
432    // currently we don't have symbols tagged with the mips16 or mips32
433    // qualifier so we will assume that we don't know what kind it is.
434    // and generate the helper
435    //
436    bool LookupHelper = true;
437    if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(CLI.Callee)) {
438      Mips16Libcall Find = { RTLIB::UNKNOWN_LIBCALL, S->getSymbol() };
439
440      if (std::binary_search(std::begin(HardFloatLibCalls),
441                             std::end(HardFloatLibCalls), Find))
442        LookupHelper = false;
443      else {
444        const char *Symbol = S->getSymbol();
445        Mips16IntrinsicHelperType IntrinsicFind = { Symbol, "" };
446        const Mips16HardFloatInfo::FuncSignature *Signature =
447            Mips16HardFloatInfo::findFuncSignature(Symbol);
448        if (!IsPICCall && (Signature && (FuncInfo->StubsNeeded.find(Symbol) ==
449                                         FuncInfo->StubsNeeded.end()))) {
450          FuncInfo->StubsNeeded[Symbol] = Signature;
451          //
452          // S2 is normally saved if the stub is for a function which
453          // returns a float or double value and is not otherwise. This is
454          // because more work is required after the function the stub
455          // is calling completes, and so the stub cannot directly return
456          // and the stub has no stack space to store the return address so
457          // S2 is used for that purpose.
458          // In order to take advantage of not saving S2, we need to also
459          // optimize the call in the stub and this requires some further
460          // functionality in MipsAsmPrinter which we don't have yet.
461          // So for now we always save S2. The optimization will be done
462          // in a follow-on patch.
463          //
464          if (1 || (Signature->RetSig != Mips16HardFloatInfo::NoFPRet))
465            FuncInfo->setSaveS2();
466        }
467        // one more look at list of intrinsics
468        const Mips16IntrinsicHelperType *Helper =
469            std::lower_bound(std::begin(Mips16IntrinsicHelper),
470                             std::end(Mips16IntrinsicHelper), IntrinsicFind);
471        if (Helper != std::end(Mips16IntrinsicHelper) &&
472            *Helper == IntrinsicFind) {
473          Mips16HelperFunction = Helper->Helper;
474          NeedMips16Helper = true;
475          LookupHelper = false;
476        }
477
478      }
479    } else if (GlobalAddressSDNode *G =
480                   dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
481      Mips16Libcall Find = { RTLIB::UNKNOWN_LIBCALL,
482                             G->getGlobal()->getName().data() };
483
484      if (std::binary_search(std::begin(HardFloatLibCalls),
485                             std::end(HardFloatLibCalls), Find))
486        LookupHelper = false;
487    }
488    if (LookupHelper)
489      Mips16HelperFunction =
490        getMips16HelperFunction(CLI.RetTy, CLI.getArgs(), NeedMips16Helper);
491  }
492
493  SDValue JumpTarget = Callee;
494
495  // T9 should contain the address of the callee function if
496  // -reloction-model=pic or it is an indirect call.
497  if (IsPICCall || !GlobalOrExternal) {
498    unsigned V0Reg = Mips::V0;
499    if (NeedMips16Helper) {
500      RegsToPass.push_front(std::make_pair(V0Reg, Callee));
501      JumpTarget = DAG.getExternalSymbol(Mips16HelperFunction, getPointerTy());
502      ExternalSymbolSDNode *S = cast<ExternalSymbolSDNode>(JumpTarget);
503      JumpTarget = getAddrGlobal(S, JumpTarget.getValueType(), DAG,
504                                 MipsII::MO_GOT, Chain,
505                                 FuncInfo->callPtrInfo(S->getSymbol()));
506    } else
507      RegsToPass.push_front(std::make_pair((unsigned)Mips::T9, Callee));
508  }
509
510  Ops.push_back(JumpTarget);
511
512  MipsTargetLowering::getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal,
513                                  InternalLinkage, CLI, Callee, Chain);
514}
515
516MachineBasicBlock *Mips16TargetLowering::
517emitSel16(unsigned Opc, MachineInstr *MI, MachineBasicBlock *BB) const {
518  if (DontExpandCondPseudos16)
519    return BB;
520  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
521  DebugLoc DL = MI->getDebugLoc();
522  // To "insert" a SELECT_CC instruction, we actually have to insert the
523  // diamond control-flow pattern.  The incoming instruction knows the
524  // destination vreg to set, the condition code register to branch on, the
525  // true/false values to select between, and a branch opcode to use.
526  const BasicBlock *LLVM_BB = BB->getBasicBlock();
527  MachineFunction::iterator It = BB;
528  ++It;
529
530  //  thisMBB:
531  //  ...
532  //   TrueVal = ...
533  //   setcc r1, r2, r3
534  //   bNE   r1, r0, copy1MBB
535  //   fallthrough --> copy0MBB
536  MachineBasicBlock *thisMBB  = BB;
537  MachineFunction *F = BB->getParent();
538  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
539  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
540  F->insert(It, copy0MBB);
541  F->insert(It, sinkMBB);
542
543  // Transfer the remainder of BB and its successor edges to sinkMBB.
544  sinkMBB->splice(sinkMBB->begin(), BB,
545                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
546  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
547
548  // Next, add the true and fallthrough blocks as its successors.
549  BB->addSuccessor(copy0MBB);
550  BB->addSuccessor(sinkMBB);
551
552  BuildMI(BB, DL, TII->get(Opc)).addReg(MI->getOperand(3).getReg())
553    .addMBB(sinkMBB);
554
555  //  copy0MBB:
556  //   %FalseValue = ...
557  //   # fallthrough to sinkMBB
558  BB = copy0MBB;
559
560  // Update machine-CFG edges
561  BB->addSuccessor(sinkMBB);
562
563  //  sinkMBB:
564  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
565  //  ...
566  BB = sinkMBB;
567
568  BuildMI(*BB, BB->begin(), DL,
569          TII->get(Mips::PHI), MI->getOperand(0).getReg())
570    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
571    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
572
573  MI->eraseFromParent();   // The pseudo instruction is gone now.
574  return BB;
575}
576
577MachineBasicBlock *Mips16TargetLowering::emitSelT16
578  (unsigned Opc1, unsigned Opc2,
579   MachineInstr *MI, MachineBasicBlock *BB) const {
580  if (DontExpandCondPseudos16)
581    return BB;
582  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
583  DebugLoc DL = MI->getDebugLoc();
584  // To "insert" a SELECT_CC instruction, we actually have to insert the
585  // diamond control-flow pattern.  The incoming instruction knows the
586  // destination vreg to set, the condition code register to branch on, the
587  // true/false values to select between, and a branch opcode to use.
588  const BasicBlock *LLVM_BB = BB->getBasicBlock();
589  MachineFunction::iterator It = BB;
590  ++It;
591
592  //  thisMBB:
593  //  ...
594  //   TrueVal = ...
595  //   setcc r1, r2, r3
596  //   bNE   r1, r0, copy1MBB
597  //   fallthrough --> copy0MBB
598  MachineBasicBlock *thisMBB  = BB;
599  MachineFunction *F = BB->getParent();
600  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
601  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
602  F->insert(It, copy0MBB);
603  F->insert(It, sinkMBB);
604
605  // Transfer the remainder of BB and its successor edges to sinkMBB.
606  sinkMBB->splice(sinkMBB->begin(), BB,
607                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
608  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
609
610  // Next, add the true and fallthrough blocks as its successors.
611  BB->addSuccessor(copy0MBB);
612  BB->addSuccessor(sinkMBB);
613
614  BuildMI(BB, DL, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
615    .addReg(MI->getOperand(4).getReg());
616  BuildMI(BB, DL, TII->get(Opc1)).addMBB(sinkMBB);
617
618  //  copy0MBB:
619  //   %FalseValue = ...
620  //   # fallthrough to sinkMBB
621  BB = copy0MBB;
622
623  // Update machine-CFG edges
624  BB->addSuccessor(sinkMBB);
625
626  //  sinkMBB:
627  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
628  //  ...
629  BB = sinkMBB;
630
631  BuildMI(*BB, BB->begin(), DL,
632          TII->get(Mips::PHI), MI->getOperand(0).getReg())
633    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
634    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
635
636  MI->eraseFromParent();   // The pseudo instruction is gone now.
637  return BB;
638
639}
640
641MachineBasicBlock *Mips16TargetLowering::emitSeliT16
642  (unsigned Opc1, unsigned Opc2,
643   MachineInstr *MI, MachineBasicBlock *BB) const {
644  if (DontExpandCondPseudos16)
645    return BB;
646  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
647  DebugLoc DL = MI->getDebugLoc();
648  // To "insert" a SELECT_CC instruction, we actually have to insert the
649  // diamond control-flow pattern.  The incoming instruction knows the
650  // destination vreg to set, the condition code register to branch on, the
651  // true/false values to select between, and a branch opcode to use.
652  const BasicBlock *LLVM_BB = BB->getBasicBlock();
653  MachineFunction::iterator It = BB;
654  ++It;
655
656  //  thisMBB:
657  //  ...
658  //   TrueVal = ...
659  //   setcc r1, r2, r3
660  //   bNE   r1, r0, copy1MBB
661  //   fallthrough --> copy0MBB
662  MachineBasicBlock *thisMBB  = BB;
663  MachineFunction *F = BB->getParent();
664  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
665  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
666  F->insert(It, copy0MBB);
667  F->insert(It, sinkMBB);
668
669  // Transfer the remainder of BB and its successor edges to sinkMBB.
670  sinkMBB->splice(sinkMBB->begin(), BB,
671                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
672  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
673
674  // Next, add the true and fallthrough blocks as its successors.
675  BB->addSuccessor(copy0MBB);
676  BB->addSuccessor(sinkMBB);
677
678  BuildMI(BB, DL, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
679    .addImm(MI->getOperand(4).getImm());
680  BuildMI(BB, DL, TII->get(Opc1)).addMBB(sinkMBB);
681
682  //  copy0MBB:
683  //   %FalseValue = ...
684  //   # fallthrough to sinkMBB
685  BB = copy0MBB;
686
687  // Update machine-CFG edges
688  BB->addSuccessor(sinkMBB);
689
690  //  sinkMBB:
691  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
692  //  ...
693  BB = sinkMBB;
694
695  BuildMI(*BB, BB->begin(), DL,
696          TII->get(Mips::PHI), MI->getOperand(0).getReg())
697    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
698    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
699
700  MI->eraseFromParent();   // The pseudo instruction is gone now.
701  return BB;
702
703}
704
705MachineBasicBlock
706  *Mips16TargetLowering::emitFEXT_T8I816_ins(unsigned BtOpc, unsigned CmpOpc,
707                                             MachineInstr *MI,
708                                             MachineBasicBlock *BB) const {
709  if (DontExpandCondPseudos16)
710    return BB;
711  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
712  unsigned regX = MI->getOperand(0).getReg();
713  unsigned regY = MI->getOperand(1).getReg();
714  MachineBasicBlock *target = MI->getOperand(2).getMBB();
715  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(CmpOpc)).addReg(regX)
716    .addReg(regY);
717  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(BtOpc)).addMBB(target);
718  MI->eraseFromParent();   // The pseudo instruction is gone now.
719  return BB;
720}
721
722MachineBasicBlock *Mips16TargetLowering::emitFEXT_T8I8I16_ins(
723  unsigned BtOpc, unsigned CmpiOpc, unsigned CmpiXOpc, bool ImmSigned,
724  MachineInstr *MI,  MachineBasicBlock *BB) const {
725  if (DontExpandCondPseudos16)
726    return BB;
727  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
728  unsigned regX = MI->getOperand(0).getReg();
729  int64_t imm = MI->getOperand(1).getImm();
730  MachineBasicBlock *target = MI->getOperand(2).getMBB();
731  unsigned CmpOpc;
732  if (isUInt<8>(imm))
733    CmpOpc = CmpiOpc;
734  else if ((!ImmSigned && isUInt<16>(imm)) ||
735           (ImmSigned && isInt<16>(imm)))
736    CmpOpc = CmpiXOpc;
737  else
738    llvm_unreachable("immediate field not usable");
739  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(CmpOpc)).addReg(regX)
740    .addImm(imm);
741  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(BtOpc)).addMBB(target);
742  MI->eraseFromParent();   // The pseudo instruction is gone now.
743  return BB;
744}
745
746static unsigned Mips16WhichOp8uOr16simm
747  (unsigned shortOp, unsigned longOp, int64_t Imm) {
748  if (isUInt<8>(Imm))
749    return shortOp;
750  else if (isInt<16>(Imm))
751    return longOp;
752  else
753    llvm_unreachable("immediate field not usable");
754}
755
756MachineBasicBlock *Mips16TargetLowering::emitFEXT_CCRX16_ins(
757  unsigned SltOpc,
758  MachineInstr *MI,  MachineBasicBlock *BB) const {
759  if (DontExpandCondPseudos16)
760    return BB;
761  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
762  unsigned CC = MI->getOperand(0).getReg();
763  unsigned regX = MI->getOperand(1).getReg();
764  unsigned regY = MI->getOperand(2).getReg();
765  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(SltOpc)).addReg(regX).addReg(
766      regY);
767  BuildMI(*BB, MI, MI->getDebugLoc(),
768          TII->get(Mips::MoveR3216), CC).addReg(Mips::T8);
769  MI->eraseFromParent();   // The pseudo instruction is gone now.
770  return BB;
771}
772
773MachineBasicBlock *Mips16TargetLowering::emitFEXT_CCRXI16_ins(
774  unsigned SltiOpc, unsigned SltiXOpc,
775  MachineInstr *MI,  MachineBasicBlock *BB )const {
776  if (DontExpandCondPseudos16)
777    return BB;
778  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
779  unsigned CC = MI->getOperand(0).getReg();
780  unsigned regX = MI->getOperand(1).getReg();
781  int64_t Imm = MI->getOperand(2).getImm();
782  unsigned SltOpc = Mips16WhichOp8uOr16simm(SltiOpc, SltiXOpc, Imm);
783  BuildMI(*BB, MI, MI->getDebugLoc(),
784          TII->get(SltOpc)).addReg(regX).addImm(Imm);
785  BuildMI(*BB, MI, MI->getDebugLoc(),
786          TII->get(Mips::MoveR3216), CC).addReg(Mips::T8);
787  MI->eraseFromParent();   // The pseudo instruction is gone now.
788  return BB;
789
790}
791