HexagonISelLowering.cpp revision 3450f800aa65c91f0496816ba6061a422a74c1fe
1//===-- HexagonISelLowering.cpp - Hexagon DAG Lowering Implementation -----===//
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// This file implements the interfaces that Hexagon uses to lower LLVM code
11// into a selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "HexagonISelLowering.h"
16#include "HexagonMachineFunctionInfo.h"
17#include "HexagonSubtarget.h"
18#include "HexagonTargetMachine.h"
19#include "HexagonTargetObjectFile.h"
20#include "llvm/CodeGen/CallingConvLower.h"
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/SelectionDAGISel.h"
27#include "llvm/CodeGen/ValueTypes.h"
28#include "llvm/IR/CallingConv.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalAlias.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/InlineAsm.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39
40using namespace llvm;
41
42const unsigned Hexagon_MAX_RET_SIZE = 64;
43
44static cl::opt<bool>
45EmitJumpTables("hexagon-emit-jump-tables", cl::init(true), cl::Hidden,
46               cl::desc("Control jump table emission on Hexagon target"));
47
48int NumNamedVarArgParams = -1;
49
50// Implement calling convention for Hexagon.
51static bool
52CC_Hexagon(unsigned ValNo, MVT ValVT,
53           MVT LocVT, CCValAssign::LocInfo LocInfo,
54           ISD::ArgFlagsTy ArgFlags, CCState &State);
55
56static bool
57CC_Hexagon32(unsigned ValNo, MVT ValVT,
58             MVT LocVT, CCValAssign::LocInfo LocInfo,
59             ISD::ArgFlagsTy ArgFlags, CCState &State);
60
61static bool
62CC_Hexagon64(unsigned ValNo, MVT ValVT,
63             MVT LocVT, CCValAssign::LocInfo LocInfo,
64             ISD::ArgFlagsTy ArgFlags, CCState &State);
65
66static bool
67RetCC_Hexagon(unsigned ValNo, MVT ValVT,
68              MVT LocVT, CCValAssign::LocInfo LocInfo,
69              ISD::ArgFlagsTy ArgFlags, CCState &State);
70
71static bool
72RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
73                MVT LocVT, CCValAssign::LocInfo LocInfo,
74                ISD::ArgFlagsTy ArgFlags, CCState &State);
75
76static bool
77RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
78                MVT LocVT, CCValAssign::LocInfo LocInfo,
79                ISD::ArgFlagsTy ArgFlags, CCState &State);
80
81static bool
82CC_Hexagon_VarArg (unsigned ValNo, MVT ValVT,
83            MVT LocVT, CCValAssign::LocInfo LocInfo,
84            ISD::ArgFlagsTy ArgFlags, CCState &State) {
85
86  // NumNamedVarArgParams can not be zero for a VarArg function.
87  assert ( (NumNamedVarArgParams > 0) &&
88           "NumNamedVarArgParams is not bigger than zero.");
89
90  if ( (int)ValNo < NumNamedVarArgParams ) {
91    // Deal with named arguments.
92    return CC_Hexagon(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
93  }
94
95  // Deal with un-named arguments.
96  unsigned ofst;
97  if (ArgFlags.isByVal()) {
98    // If pass-by-value, the size allocated on stack is decided
99    // by ArgFlags.getByValSize(), not by the size of LocVT.
100    assert ((ArgFlags.getByValSize() > 8) &&
101            "ByValSize must be bigger than 8 bytes");
102    ofst = State.AllocateStack(ArgFlags.getByValSize(), 4);
103    State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
104    return false;
105  }
106  if (LocVT == MVT::i32 || LocVT == MVT::f32) {
107    ofst = State.AllocateStack(4, 4);
108    State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
109    return false;
110  }
111  if (LocVT == MVT::i64 || LocVT == MVT::f64) {
112    ofst = State.AllocateStack(8, 8);
113    State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
114    return false;
115  }
116  llvm_unreachable(0);
117}
118
119
120static bool
121CC_Hexagon (unsigned ValNo, MVT ValVT,
122            MVT LocVT, CCValAssign::LocInfo LocInfo,
123            ISD::ArgFlagsTy ArgFlags, CCState &State) {
124
125  if (ArgFlags.isByVal()) {
126    // Passed on stack.
127    assert ((ArgFlags.getByValSize() > 8) &&
128            "ByValSize must be bigger than 8 bytes");
129    unsigned Offset = State.AllocateStack(ArgFlags.getByValSize(), 4);
130    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
131    return false;
132  }
133
134  if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
135    LocVT = MVT::i32;
136    ValVT = MVT::i32;
137    if (ArgFlags.isSExt())
138      LocInfo = CCValAssign::SExt;
139    else if (ArgFlags.isZExt())
140      LocInfo = CCValAssign::ZExt;
141    else
142      LocInfo = CCValAssign::AExt;
143  }
144
145  if (LocVT == MVT::i32 || LocVT == MVT::f32) {
146    if (!CC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
147      return false;
148  }
149
150  if (LocVT == MVT::i64 || LocVT == MVT::f64) {
151    if (!CC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
152      return false;
153  }
154
155  return true;  // CC didn't match.
156}
157
158
159static bool CC_Hexagon32(unsigned ValNo, MVT ValVT,
160                         MVT LocVT, CCValAssign::LocInfo LocInfo,
161                         ISD::ArgFlagsTy ArgFlags, CCState &State) {
162
163  static const uint16_t RegList[] = {
164    Hexagon::R0, Hexagon::R1, Hexagon::R2, Hexagon::R3, Hexagon::R4,
165    Hexagon::R5
166  };
167  if (unsigned Reg = State.AllocateReg(RegList, 6)) {
168    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
169    return false;
170  }
171
172  unsigned Offset = State.AllocateStack(4, 4);
173  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
174  return false;
175}
176
177static bool CC_Hexagon64(unsigned ValNo, MVT ValVT,
178                         MVT LocVT, CCValAssign::LocInfo LocInfo,
179                         ISD::ArgFlagsTy ArgFlags, CCState &State) {
180
181  if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
182    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
183    return false;
184  }
185
186  static const uint16_t RegList1[] = {
187    Hexagon::D1, Hexagon::D2
188  };
189  static const uint16_t RegList2[] = {
190    Hexagon::R1, Hexagon::R3
191  };
192  if (unsigned Reg = State.AllocateReg(RegList1, RegList2, 2)) {
193    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
194    return false;
195  }
196
197  unsigned Offset = State.AllocateStack(8, 8, Hexagon::D2);
198  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
199  return false;
200}
201
202static bool RetCC_Hexagon(unsigned ValNo, MVT ValVT,
203                          MVT LocVT, CCValAssign::LocInfo LocInfo,
204                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
205
206
207  if (LocVT == MVT::i1 ||
208      LocVT == MVT::i8 ||
209      LocVT == MVT::i16) {
210    LocVT = MVT::i32;
211    ValVT = MVT::i32;
212    if (ArgFlags.isSExt())
213      LocInfo = CCValAssign::SExt;
214    else if (ArgFlags.isZExt())
215      LocInfo = CCValAssign::ZExt;
216    else
217      LocInfo = CCValAssign::AExt;
218  }
219
220  if (LocVT == MVT::i32 || LocVT == MVT::f32) {
221    if (!RetCC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
222    return false;
223  }
224
225  if (LocVT == MVT::i64 || LocVT == MVT::f64) {
226    if (!RetCC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
227    return false;
228  }
229
230  return true;  // CC didn't match.
231}
232
233static bool RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
234                            MVT LocVT, CCValAssign::LocInfo LocInfo,
235                            ISD::ArgFlagsTy ArgFlags, CCState &State) {
236
237  if (LocVT == MVT::i32 || LocVT == MVT::f32) {
238    if (unsigned Reg = State.AllocateReg(Hexagon::R0)) {
239      State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
240      return false;
241    }
242  }
243
244  unsigned Offset = State.AllocateStack(4, 4);
245  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
246  return false;
247}
248
249static bool RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
250                            MVT LocVT, CCValAssign::LocInfo LocInfo,
251                            ISD::ArgFlagsTy ArgFlags, CCState &State) {
252  if (LocVT == MVT::i64 || LocVT == MVT::f64) {
253    if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
254      State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
255      return false;
256    }
257  }
258
259  unsigned Offset = State.AllocateStack(8, 8);
260  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
261  return false;
262}
263
264SDValue
265HexagonTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG)
266const {
267  return SDValue();
268}
269
270/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
271/// by "Src" to address "Dst" of size "Size".  Alignment information is
272/// specified by the specific parameter attribute. The copy will be passed as
273/// a byval function parameter.  Sometimes what we are copying is the end of a
274/// larger object, the part that does not fit in registers.
275static SDValue
276CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
277                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
278                          DebugLoc dl) {
279
280  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
281  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
282                       /*isVolatile=*/false, /*AlwaysInline=*/false,
283                       MachinePointerInfo(), MachinePointerInfo());
284}
285
286
287// LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
288// passed by value, the function prototype is modified to return void and
289// the value is stored in memory pointed by a pointer passed by caller.
290SDValue
291HexagonTargetLowering::LowerReturn(SDValue Chain,
292                                   CallingConv::ID CallConv, bool isVarArg,
293                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
294                                   const SmallVectorImpl<SDValue> &OutVals,
295                                   DebugLoc dl, SelectionDAG &DAG) const {
296
297  // CCValAssign - represent the assignment of the return value to locations.
298  SmallVector<CCValAssign, 16> RVLocs;
299
300  // CCState - Info about the registers and stack slot.
301  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
302                 getTargetMachine(), RVLocs, *DAG.getContext());
303
304  // Analyze return values of ISD::RET
305  CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
306
307  SDValue Flag;
308  SmallVector<SDValue, 4> RetOps(1, Chain);
309
310  // Copy the result values into the output registers.
311  for (unsigned i = 0; i != RVLocs.size(); ++i) {
312    CCValAssign &VA = RVLocs[i];
313
314    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
315
316    // Guarantee that all emitted copies are stuck together with flags.
317    Flag = Chain.getValue(1);
318    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
319  }
320
321  RetOps[0] = Chain;  // Update chain.
322
323  // Add the flag if we have it.
324  if (Flag.getNode())
325    RetOps.push_back(Flag);
326
327  return DAG.getNode(HexagonISD::RET_FLAG, dl, MVT::Other,
328                     &RetOps[0], RetOps.size());
329}
330
331
332
333
334/// LowerCallResult - Lower the result values of an ISD::CALL into the
335/// appropriate copies out of appropriate physical registers.  This assumes that
336/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
337/// being lowered. Returns a SDNode with the same number of values as the
338/// ISD::CALL.
339SDValue
340HexagonTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
341                                       CallingConv::ID CallConv, bool isVarArg,
342                                       const
343                                       SmallVectorImpl<ISD::InputArg> &Ins,
344                                       DebugLoc dl, SelectionDAG &DAG,
345                                       SmallVectorImpl<SDValue> &InVals,
346                                       const SmallVectorImpl<SDValue> &OutVals,
347                                       SDValue Callee) const {
348
349  // Assign locations to each value returned by this call.
350  SmallVector<CCValAssign, 16> RVLocs;
351
352  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
353                 getTargetMachine(), RVLocs, *DAG.getContext());
354
355  CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
356
357  // Copy all of the result registers out of their specified physreg.
358  for (unsigned i = 0; i != RVLocs.size(); ++i) {
359    Chain = DAG.getCopyFromReg(Chain, dl,
360                               RVLocs[i].getLocReg(),
361                               RVLocs[i].getValVT(), InFlag).getValue(1);
362    InFlag = Chain.getValue(2);
363    InVals.push_back(Chain.getValue(0));
364  }
365
366  return Chain;
367}
368
369/// LowerCall - Functions arguments are copied from virtual regs to
370/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
371SDValue
372HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
373                                 SmallVectorImpl<SDValue> &InVals) const {
374  SelectionDAG &DAG                     = CLI.DAG;
375  DebugLoc &dl                          = CLI.DL;
376  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
377  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
378  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
379  SDValue Chain                         = CLI.Chain;
380  SDValue Callee                        = CLI.Callee;
381  bool &isTailCall                      = CLI.IsTailCall;
382  CallingConv::ID CallConv              = CLI.CallConv;
383  bool isVarArg                         = CLI.IsVarArg;
384
385  bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
386
387  // Analyze operands of the call, assigning locations to each operand.
388  SmallVector<CCValAssign, 16> ArgLocs;
389  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
390                 getTargetMachine(), ArgLocs, *DAG.getContext());
391
392  // Check for varargs.
393  NumNamedVarArgParams = -1;
394  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee))
395  {
396    const Function* CalleeFn = NULL;
397    Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, MVT::i32);
398    if ((CalleeFn = dyn_cast<Function>(GA->getGlobal())))
399    {
400      // If a function has zero args and is a vararg function, that's
401      // disallowed so it must be an undeclared function.  Do not assume
402      // varargs if the callee is undefined.
403      if (CalleeFn->isVarArg() &&
404          CalleeFn->getFunctionType()->getNumParams() != 0) {
405        NumNamedVarArgParams = CalleeFn->getFunctionType()->getNumParams();
406      }
407    }
408  }
409
410  if (NumNamedVarArgParams > 0)
411    CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_VarArg);
412  else
413    CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
414
415
416  if(isTailCall) {
417    bool StructAttrFlag =
418      DAG.getMachineFunction().getFunction()->hasStructRetAttr();
419    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
420                                                   isVarArg, IsStructRet,
421                                                   StructAttrFlag,
422                                                   Outs, OutVals, Ins, DAG);
423    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i){
424      CCValAssign &VA = ArgLocs[i];
425      if (VA.isMemLoc()) {
426        isTailCall = false;
427        break;
428      }
429    }
430    if (isTailCall) {
431      DEBUG(dbgs () << "Eligible for Tail Call\n");
432    } else {
433      DEBUG(dbgs () <<
434            "Argument must be passed on stack. Not eligible for Tail Call\n");
435    }
436  }
437  // Get a count of how many bytes are to be pushed on the stack.
438  unsigned NumBytes = CCInfo.getNextStackOffset();
439  SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
440  SmallVector<SDValue, 8> MemOpChains;
441
442  SDValue StackPtr =
443    DAG.getCopyFromReg(Chain, dl, TM.getRegisterInfo()->getStackRegister(),
444                       getPointerTy());
445
446  // Walk the register/memloc assignments, inserting copies/loads.
447  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
448    CCValAssign &VA = ArgLocs[i];
449    SDValue Arg = OutVals[i];
450    ISD::ArgFlagsTy Flags = Outs[i].Flags;
451
452    // Promote the value if needed.
453    switch (VA.getLocInfo()) {
454      default:
455        // Loc info must be one of Full, SExt, ZExt, or AExt.
456        llvm_unreachable("Unknown loc info!");
457      case CCValAssign::Full:
458        break;
459      case CCValAssign::SExt:
460        Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
461        break;
462      case CCValAssign::ZExt:
463        Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
464        break;
465      case CCValAssign::AExt:
466        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
467        break;
468    }
469
470    if (VA.isMemLoc()) {
471      unsigned LocMemOffset = VA.getLocMemOffset();
472      SDValue PtrOff = DAG.getConstant(LocMemOffset, StackPtr.getValueType());
473      PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
474
475      if (Flags.isByVal()) {
476        // The argument is a struct passed by value. According to LLVM, "Arg"
477        // is is pointer.
478        MemOpChains.push_back(CreateCopyOfByValArgument(Arg, PtrOff, Chain,
479                                                        Flags, DAG, dl));
480      } else {
481        // The argument is not passed by value. "Arg" is a buildin type. It is
482        // not a pointer.
483        MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
484                                           MachinePointerInfo(),false, false,
485                                           0));
486      }
487      continue;
488    }
489
490    // Arguments that can be passed on register must be kept at RegsToPass
491    // vector.
492    if (VA.isRegLoc()) {
493      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
494    }
495  }
496
497  // Transform all store nodes into one single node because all store
498  // nodes are independent of each other.
499  if (!MemOpChains.empty()) {
500    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOpChains[0],
501                        MemOpChains.size());
502  }
503
504  if (!isTailCall)
505    Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes,
506                                                        getPointerTy(), true));
507
508  // Build a sequence of copy-to-reg nodes chained together with token
509  // chain and flag operands which copy the outgoing args into registers.
510  // The InFlag in necessary since all emitted instructions must be
511  // stuck together.
512  SDValue InFlag;
513  if (!isTailCall) {
514    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
515      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
516                               RegsToPass[i].second, InFlag);
517      InFlag = Chain.getValue(1);
518    }
519  }
520
521  // For tail calls lower the arguments to the 'real' stack slot.
522  if (isTailCall) {
523    // Force all the incoming stack arguments to be loaded from the stack
524    // before any new outgoing arguments are stored to the stack, because the
525    // outgoing stack slots may alias the incoming argument stack slots, and
526    // the alias isn't otherwise explicit. This is slightly more conservative
527    // than necessary, because it means that each store effectively depends
528    // on every argument instead of just those arguments it would clobber.
529    //
530    // Do not flag preceding copytoreg stuff together with the following stuff.
531    InFlag = SDValue();
532    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
533      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
534                               RegsToPass[i].second, InFlag);
535      InFlag = Chain.getValue(1);
536    }
537    InFlag =SDValue();
538  }
539
540  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
541  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
542  // node so that legalize doesn't hack it.
543  if (flag_aligned_memcpy) {
544    const char *MemcpyName =
545      "__hexagon_memcpy_likely_aligned_min32bytes_mult8bytes";
546    Callee =
547      DAG.getTargetExternalSymbol(MemcpyName, getPointerTy());
548    flag_aligned_memcpy = false;
549  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
550    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy());
551  } else if (ExternalSymbolSDNode *S =
552             dyn_cast<ExternalSymbolSDNode>(Callee)) {
553    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
554  }
555
556  // Returns a chain & a flag for retval copy to use.
557  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
558  SmallVector<SDValue, 8> Ops;
559  Ops.push_back(Chain);
560  Ops.push_back(Callee);
561
562  // Add argument registers to the end of the list so that they are
563  // known live into the call.
564  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
565    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
566                                  RegsToPass[i].second.getValueType()));
567  }
568
569  if (InFlag.getNode()) {
570    Ops.push_back(InFlag);
571  }
572
573  if (isTailCall)
574    return DAG.getNode(HexagonISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
575
576  Chain = DAG.getNode(HexagonISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
577  InFlag = Chain.getValue(1);
578
579  // Create the CALLSEQ_END node.
580  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
581                             DAG.getIntPtrConstant(0, true), InFlag);
582  InFlag = Chain.getValue(1);
583
584  // Handle result values, copying them out of physregs into vregs that we
585  // return.
586  return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
587                         InVals, OutVals, Callee);
588}
589
590static bool getIndexedAddressParts(SDNode *Ptr, EVT VT,
591                                   bool isSEXTLoad, SDValue &Base,
592                                   SDValue &Offset, bool &isInc,
593                                   SelectionDAG &DAG) {
594  if (Ptr->getOpcode() != ISD::ADD)
595  return false;
596
597  if (VT == MVT::i64 || VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
598    isInc = (Ptr->getOpcode() == ISD::ADD);
599    Base = Ptr->getOperand(0);
600    Offset = Ptr->getOperand(1);
601    // Ensure that Offset is a constant.
602    return (isa<ConstantSDNode>(Offset));
603  }
604
605  return false;
606}
607
608// TODO: Put this function along with the other isS* functions in
609// HexagonISelDAGToDAG.cpp into a common file. Or better still, use the
610// functions defined in HexagonOperands.td.
611static bool Is_PostInc_S4_Offset(SDNode * S, int ShiftAmount) {
612  ConstantSDNode *N = cast<ConstantSDNode>(S);
613
614  // immS4 predicate - True if the immediate fits in a 4-bit sign extended.
615  // field.
616  int64_t v = (int64_t)N->getSExtValue();
617  int64_t m = 0;
618  if (ShiftAmount > 0) {
619    m = v % ShiftAmount;
620    v = v >> ShiftAmount;
621  }
622  return (v <= 7) && (v >= -8) && (m == 0);
623}
624
625/// getPostIndexedAddressParts - returns true by value, base pointer and
626/// offset pointer and addressing mode by reference if this node can be
627/// combined with a load / store to form a post-indexed load / store.
628bool HexagonTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
629                                                       SDValue &Base,
630                                                       SDValue &Offset,
631                                                       ISD::MemIndexedMode &AM,
632                                                       SelectionDAG &DAG) const
633{
634  EVT VT;
635  SDValue Ptr;
636  bool isSEXTLoad = false;
637
638  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
639    VT  = LD->getMemoryVT();
640    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
641  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
642    VT  = ST->getMemoryVT();
643    if (ST->getValue().getValueType() == MVT::i64 && ST->isTruncatingStore()) {
644      return false;
645    }
646  } else {
647    return false;
648  }
649
650  bool isInc = false;
651  bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
652                                        isInc, DAG);
653  // ShiftAmount = number of left-shifted bits in the Hexagon instruction.
654  int ShiftAmount = VT.getSizeInBits() / 16;
655  if (isLegal && Is_PostInc_S4_Offset(Offset.getNode(), ShiftAmount)) {
656    AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
657    return true;
658  }
659
660  return false;
661}
662
663SDValue HexagonTargetLowering::LowerINLINEASM(SDValue Op,
664                                              SelectionDAG &DAG) const {
665  SDNode *Node = Op.getNode();
666  MachineFunction &MF = DAG.getMachineFunction();
667  HexagonMachineFunctionInfo *FuncInfo =
668    MF.getInfo<HexagonMachineFunctionInfo>();
669  switch (Node->getOpcode()) {
670    case ISD::INLINEASM: {
671      unsigned NumOps = Node->getNumOperands();
672      if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
673        --NumOps;  // Ignore the flag operand.
674
675      for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
676        if (FuncInfo->hasClobberLR())
677          break;
678        unsigned Flags =
679          cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
680        unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
681        ++i;  // Skip the ID value.
682
683        switch (InlineAsm::getKind(Flags)) {
684        default: llvm_unreachable("Bad flags!");
685          case InlineAsm::Kind_RegDef:
686          case InlineAsm::Kind_RegUse:
687          case InlineAsm::Kind_Imm:
688          case InlineAsm::Kind_Clobber:
689          case InlineAsm::Kind_Mem: {
690            for (; NumVals; --NumVals, ++i) {}
691            break;
692          }
693          case InlineAsm::Kind_RegDefEarlyClobber: {
694            for (; NumVals; --NumVals, ++i) {
695              unsigned Reg =
696                cast<RegisterSDNode>(Node->getOperand(i))->getReg();
697
698              // Check it to be lr
699              if (Reg == TM.getRegisterInfo()->getRARegister()) {
700                FuncInfo->setHasClobberLR(true);
701                break;
702              }
703            }
704            break;
705          }
706        }
707      }
708    }
709  } // Node->getOpcode
710  return Op;
711}
712
713
714//
715// Taken from the XCore backend.
716//
717SDValue HexagonTargetLowering::
718LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
719{
720  SDValue Chain = Op.getOperand(0);
721  SDValue Table = Op.getOperand(1);
722  SDValue Index = Op.getOperand(2);
723  DebugLoc dl = Op.getDebugLoc();
724  JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
725  unsigned JTI = JT->getIndex();
726  MachineFunction &MF = DAG.getMachineFunction();
727  const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
728  SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
729
730  // Mark all jump table targets as address taken.
731  const std::vector<MachineJumpTableEntry> &JTE = MJTI->getJumpTables();
732  const std::vector<MachineBasicBlock*> &JTBBs = JTE[JTI].MBBs;
733  for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
734    MachineBasicBlock *MBB = JTBBs[i];
735    MBB->setHasAddressTaken();
736    // This line is needed to set the hasAddressTaken flag on the BasicBlock
737    // object.
738    BlockAddress::get(const_cast<BasicBlock *>(MBB->getBasicBlock()));
739  }
740
741  SDValue JumpTableBase = DAG.getNode(HexagonISD::WrapperJT, dl,
742                                      getPointerTy(), TargetJT);
743  SDValue ShiftIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
744                                   DAG.getConstant(2, MVT::i32));
745  SDValue JTAddress = DAG.getNode(ISD::ADD, dl, MVT::i32, JumpTableBase,
746                                  ShiftIndex);
747  SDValue LoadTarget = DAG.getLoad(MVT::i32, dl, Chain, JTAddress,
748                                   MachinePointerInfo(), false, false, false,
749                                   0);
750  return DAG.getNode(HexagonISD::BR_JT, dl, MVT::Other, Chain, LoadTarget);
751}
752
753
754SDValue
755HexagonTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
756                                               SelectionDAG &DAG) const {
757  SDValue Chain = Op.getOperand(0);
758  SDValue Size = Op.getOperand(1);
759  DebugLoc dl = Op.getDebugLoc();
760
761  unsigned SPReg = getStackPointerRegisterToSaveRestore();
762
763  // Get a reference to the stack pointer.
764  SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
765
766  // Subtract the dynamic size from the actual stack size to
767  // obtain the new stack size.
768  SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
769
770  //
771  // For Hexagon, the outgoing memory arguments area should be on top of the
772  // alloca area on the stack i.e., the outgoing memory arguments should be
773  // at a lower address than the alloca area. Move the alloca area down the
774  // stack by adding back the space reserved for outgoing arguments to SP
775  // here.
776  //
777  // We do not know what the size of the outgoing args is at this point.
778  // So, we add a pseudo instruction ADJDYNALLOC that will adjust the
779  // stack pointer. We patch this instruction with the correct, known
780  // offset in emitPrologue().
781  //
782  // Use a placeholder immediate (zero) for now. This will be patched up
783  // by emitPrologue().
784  SDValue ArgAdjust = DAG.getNode(HexagonISD::ADJDYNALLOC, dl,
785                                  MVT::i32,
786                                  Sub,
787                                  DAG.getConstant(0, MVT::i32));
788
789  // The Sub result contains the new stack start address, so it
790  // must be placed in the stack pointer register.
791  SDValue CopyChain = DAG.getCopyToReg(Chain, dl,
792                                       TM.getRegisterInfo()->getStackRegister(),
793                                       Sub);
794
795  SDValue Ops[2] = { ArgAdjust, CopyChain };
796  return DAG.getMergeValues(Ops, 2, dl);
797}
798
799SDValue
800HexagonTargetLowering::LowerFormalArguments(SDValue Chain,
801                                            CallingConv::ID CallConv,
802                                            bool isVarArg,
803                                            const
804                                            SmallVectorImpl<ISD::InputArg> &Ins,
805                                            DebugLoc dl, SelectionDAG &DAG,
806                                            SmallVectorImpl<SDValue> &InVals)
807const {
808
809  MachineFunction &MF = DAG.getMachineFunction();
810  MachineFrameInfo *MFI = MF.getFrameInfo();
811  MachineRegisterInfo &RegInfo = MF.getRegInfo();
812  HexagonMachineFunctionInfo *FuncInfo =
813    MF.getInfo<HexagonMachineFunctionInfo>();
814
815
816  // Assign locations to all of the incoming arguments.
817  SmallVector<CCValAssign, 16> ArgLocs;
818  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
819                 getTargetMachine(), ArgLocs, *DAG.getContext());
820
821  CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
822
823  // For LLVM, in the case when returning a struct by value (>8byte),
824  // the first argument is a pointer that points to the location on caller's
825  // stack where the return value will be stored. For Hexagon, the location on
826  // caller's stack is passed only when the struct size is smaller than (and
827  // equal to) 8 bytes. If not, no address will be passed into callee and
828  // callee return the result direclty through R0/R1.
829
830  SmallVector<SDValue, 4> MemOps;
831
832  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
833    CCValAssign &VA = ArgLocs[i];
834    ISD::ArgFlagsTy Flags = Ins[i].Flags;
835    unsigned ObjSize;
836    unsigned StackLocation;
837    int FI;
838
839    if (   (VA.isRegLoc() && !Flags.isByVal())
840        || (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() > 8)) {
841      // Arguments passed in registers
842      // 1. int, long long, ptr args that get allocated in register.
843      // 2. Large struct that gets an register to put its address in.
844      EVT RegVT = VA.getLocVT();
845      if (RegVT == MVT::i8 || RegVT == MVT::i16 ||
846          RegVT == MVT::i32 || RegVT == MVT::f32) {
847        unsigned VReg =
848          RegInfo.createVirtualRegister(&Hexagon::IntRegsRegClass);
849        RegInfo.addLiveIn(VA.getLocReg(), VReg);
850        InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
851      } else if (RegVT == MVT::i64) {
852        unsigned VReg =
853          RegInfo.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
854        RegInfo.addLiveIn(VA.getLocReg(), VReg);
855        InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
856      } else {
857        assert (0);
858      }
859    } else if (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() <= 8) {
860      assert (0 && "ByValSize must be bigger than 8 bytes");
861    } else {
862      // Sanity check.
863      assert(VA.isMemLoc());
864
865      if (Flags.isByVal()) {
866        // If it's a byval parameter, then we need to compute the
867        // "real" size, not the size of the pointer.
868        ObjSize = Flags.getByValSize();
869      } else {
870        ObjSize = VA.getLocVT().getStoreSizeInBits() >> 3;
871      }
872
873      StackLocation = HEXAGON_LRFP_SIZE + VA.getLocMemOffset();
874      // Create the frame index object for this incoming parameter...
875      FI = MFI->CreateFixedObject(ObjSize, StackLocation, true);
876
877      // Create the SelectionDAG nodes cordl, responding to a load
878      // from this parameter.
879      SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
880
881      if (Flags.isByVal()) {
882        // If it's a pass-by-value aggregate, then do not dereference the stack
883        // location. Instead, we should generate a reference to the stack
884        // location.
885        InVals.push_back(FIN);
886      } else {
887        InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
888                                     MachinePointerInfo(), false, false,
889                                     false, 0));
890      }
891    }
892  }
893
894  if (!MemOps.empty())
895    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOps[0],
896                        MemOps.size());
897
898  if (isVarArg) {
899    // This will point to the next argument passed via stack.
900    int FrameIndex = MFI->CreateFixedObject(Hexagon_PointerSize,
901                                            HEXAGON_LRFP_SIZE +
902                                            CCInfo.getNextStackOffset(),
903                                            true);
904    FuncInfo->setVarArgsFrameIndex(FrameIndex);
905  }
906
907  return Chain;
908}
909
910SDValue
911HexagonTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
912  // VASTART stores the address of the VarArgsFrameIndex slot into the
913  // memory location argument.
914  MachineFunction &MF = DAG.getMachineFunction();
915  HexagonMachineFunctionInfo *QFI = MF.getInfo<HexagonMachineFunctionInfo>();
916  SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
917  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
918  return DAG.getStore(Op.getOperand(0), Op.getDebugLoc(), Addr,
919                      Op.getOperand(1), MachinePointerInfo(SV), false,
920                      false, 0);
921}
922
923SDValue
924HexagonTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
925  SDValue LHS = Op.getOperand(0);
926  SDValue RHS = Op.getOperand(1);
927  SDValue CC = Op.getOperand(4);
928  SDValue TrueVal = Op.getOperand(2);
929  SDValue FalseVal = Op.getOperand(3);
930  DebugLoc dl = Op.getDebugLoc();
931  SDNode* OpNode = Op.getNode();
932  EVT SVT = OpNode->getValueType(0);
933
934  SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i1, LHS, RHS, CC);
935  return DAG.getNode(ISD::SELECT, dl, SVT, Cond, TrueVal, FalseVal);
936}
937
938SDValue
939HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
940  EVT ValTy = Op.getValueType();
941
942  DebugLoc dl = Op.getDebugLoc();
943  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
944  SDValue Res;
945  if (CP->isMachineConstantPoolEntry())
946    Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), ValTy,
947                                    CP->getAlignment());
948  else
949    Res = DAG.getTargetConstantPool(CP->getConstVal(), ValTy,
950                                    CP->getAlignment());
951  return DAG.getNode(HexagonISD::CONST32, dl, ValTy, Res);
952}
953
954SDValue
955HexagonTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
956  const TargetRegisterInfo *TRI = TM.getRegisterInfo();
957  MachineFunction &MF = DAG.getMachineFunction();
958  MachineFrameInfo *MFI = MF.getFrameInfo();
959  MFI->setReturnAddressIsTaken(true);
960
961  EVT VT = Op.getValueType();
962  DebugLoc dl = Op.getDebugLoc();
963  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
964  if (Depth) {
965    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
966    SDValue Offset = DAG.getConstant(4, MVT::i32);
967    return DAG.getLoad(VT, dl, DAG.getEntryNode(),
968                       DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
969                       MachinePointerInfo(), false, false, false, 0);
970  }
971
972  // Return LR, which contains the return address. Mark it an implicit live-in.
973  unsigned Reg = MF.addLiveIn(TRI->getRARegister(), getRegClassFor(MVT::i32));
974  return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
975}
976
977SDValue
978HexagonTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
979  const HexagonRegisterInfo  *TRI = TM.getRegisterInfo();
980  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
981  MFI->setFrameAddressIsTaken(true);
982
983  EVT VT = Op.getValueType();
984  DebugLoc dl = Op.getDebugLoc();
985  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
986  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
987                                         TRI->getFrameRegister(), VT);
988  while (Depth--)
989    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
990                            MachinePointerInfo(),
991                            false, false, false, 0);
992  return FrameAddr;
993}
994
995
996SDValue HexagonTargetLowering::LowerMEMBARRIER(SDValue Op,
997                                               SelectionDAG& DAG) const {
998  DebugLoc dl = Op.getDebugLoc();
999  return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other,  Op.getOperand(0));
1000}
1001
1002
1003SDValue HexagonTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1004                                                 SelectionDAG& DAG) const {
1005  DebugLoc dl = Op.getDebugLoc();
1006  return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
1007}
1008
1009
1010SDValue HexagonTargetLowering::LowerGLOBALADDRESS(SDValue Op,
1011                                                  SelectionDAG &DAG) const {
1012  SDValue Result;
1013  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1014  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
1015  DebugLoc dl = Op.getDebugLoc();
1016  Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
1017
1018  const HexagonTargetObjectFile &TLOF =
1019      static_cast<const HexagonTargetObjectFile &>(getObjFileLowering());
1020  if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1021    return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), Result);
1022  }
1023
1024  return DAG.getNode(HexagonISD::CONST32, dl, getPointerTy(), Result);
1025}
1026
1027//===----------------------------------------------------------------------===//
1028// TargetLowering Implementation
1029//===----------------------------------------------------------------------===//
1030
1031HexagonTargetLowering::HexagonTargetLowering(HexagonTargetMachine
1032                                             &targetmachine)
1033  : TargetLowering(targetmachine, new HexagonTargetObjectFile()),
1034    TM(targetmachine) {
1035
1036    const HexagonRegisterInfo* QRI = TM.getRegisterInfo();
1037
1038    // Set up the register classes.
1039    addRegisterClass(MVT::i32, &Hexagon::IntRegsRegClass);
1040    addRegisterClass(MVT::i64, &Hexagon::DoubleRegsRegClass);
1041
1042    if (QRI->Subtarget.hasV5TOps()) {
1043      addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
1044      addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
1045    }
1046
1047    addRegisterClass(MVT::i1, &Hexagon::PredRegsRegClass);
1048
1049    computeRegisterProperties();
1050
1051    // Align loop entry
1052    setPrefLoopAlignment(4);
1053
1054    // Limits for inline expansion of memcpy/memmove
1055    MaxStoresPerMemcpy = 6;
1056    MaxStoresPerMemmove = 6;
1057
1058    //
1059    // Library calls for unsupported operations
1060    //
1061
1062    setLibcallName(RTLIB::SINTTOFP_I128_F64, "__hexagon_floattidf");
1063    setLibcallName(RTLIB::SINTTOFP_I128_F32, "__hexagon_floattisf");
1064
1065    setLibcallName(RTLIB::FPTOUINT_F32_I128, "__hexagon_fixunssfti");
1066    setLibcallName(RTLIB::FPTOUINT_F64_I128, "__hexagon_fixunsdfti");
1067
1068    setLibcallName(RTLIB::FPTOSINT_F32_I128, "__hexagon_fixsfti");
1069    setLibcallName(RTLIB::FPTOSINT_F64_I128, "__hexagon_fixdfti");
1070
1071    setLibcallName(RTLIB::SDIV_I32, "__hexagon_divsi3");
1072    setOperationAction(ISD::SDIV,  MVT::i32, Expand);
1073    setLibcallName(RTLIB::SREM_I32, "__hexagon_umodsi3");
1074    setOperationAction(ISD::SREM,  MVT::i32, Expand);
1075
1076    setLibcallName(RTLIB::SDIV_I64, "__hexagon_divdi3");
1077    setOperationAction(ISD::SDIV,  MVT::i64, Expand);
1078    setLibcallName(RTLIB::SREM_I64, "__hexagon_moddi3");
1079    setOperationAction(ISD::SREM,  MVT::i64, Expand);
1080
1081    setLibcallName(RTLIB::UDIV_I32, "__hexagon_udivsi3");
1082    setOperationAction(ISD::UDIV,  MVT::i32, Expand);
1083
1084    setLibcallName(RTLIB::UDIV_I64, "__hexagon_udivdi3");
1085    setOperationAction(ISD::UDIV,  MVT::i64, Expand);
1086
1087    setLibcallName(RTLIB::UREM_I32, "__hexagon_umodsi3");
1088    setOperationAction(ISD::UREM,  MVT::i32, Expand);
1089
1090    setLibcallName(RTLIB::UREM_I64, "__hexagon_umoddi3");
1091    setOperationAction(ISD::UREM,  MVT::i64, Expand);
1092
1093    setLibcallName(RTLIB::DIV_F32, "__hexagon_divsf3");
1094    setOperationAction(ISD::FDIV,  MVT::f32, Expand);
1095
1096    setLibcallName(RTLIB::DIV_F64, "__hexagon_divdf3");
1097    setOperationAction(ISD::FDIV,  MVT::f64, Expand);
1098
1099    setOperationAction(ISD::FSQRT,  MVT::f32, Expand);
1100    setOperationAction(ISD::FSQRT,  MVT::f64, Expand);
1101    setOperationAction(ISD::FSIN,  MVT::f32, Expand);
1102    setOperationAction(ISD::FSIN,  MVT::f64, Expand);
1103
1104    if (QRI->Subtarget.hasV5TOps()) {
1105      // Hexagon V5 Support.
1106      setOperationAction(ISD::FADD,       MVT::f32, Legal);
1107      setOperationAction(ISD::FADD,       MVT::f64, Legal);
1108      setOperationAction(ISD::FP_EXTEND,  MVT::f32, Legal);
1109      setCondCodeAction(ISD::SETOEQ,      MVT::f32, Legal);
1110      setCondCodeAction(ISD::SETOEQ,      MVT::f64, Legal);
1111      setCondCodeAction(ISD::SETUEQ,      MVT::f32, Legal);
1112      setCondCodeAction(ISD::SETUEQ,      MVT::f64, Legal);
1113
1114      setCondCodeAction(ISD::SETOGE,      MVT::f32, Legal);
1115      setCondCodeAction(ISD::SETOGE,      MVT::f64, Legal);
1116      setCondCodeAction(ISD::SETUGE,      MVT::f32, Legal);
1117      setCondCodeAction(ISD::SETUGE,      MVT::f64, Legal);
1118
1119      setCondCodeAction(ISD::SETOGT,      MVT::f32, Legal);
1120      setCondCodeAction(ISD::SETOGT,      MVT::f64, Legal);
1121      setCondCodeAction(ISD::SETUGT,      MVT::f32, Legal);
1122      setCondCodeAction(ISD::SETUGT,      MVT::f64, Legal);
1123
1124      setCondCodeAction(ISD::SETOLE,      MVT::f32, Legal);
1125      setCondCodeAction(ISD::SETOLE,      MVT::f64, Legal);
1126      setCondCodeAction(ISD::SETOLT,      MVT::f32, Legal);
1127      setCondCodeAction(ISD::SETOLT,      MVT::f64, Legal);
1128
1129      setOperationAction(ISD::ConstantFP,  MVT::f32, Legal);
1130      setOperationAction(ISD::ConstantFP,  MVT::f64, Legal);
1131
1132      setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
1133      setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
1134      setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
1135      setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
1136
1137      setOperationAction(ISD::FP_TO_UINT, MVT::i8, Promote);
1138      setOperationAction(ISD::FP_TO_SINT, MVT::i8, Promote);
1139      setOperationAction(ISD::UINT_TO_FP, MVT::i8, Promote);
1140      setOperationAction(ISD::SINT_TO_FP, MVT::i8, Promote);
1141
1142      setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
1143      setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
1144      setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
1145      setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
1146
1147      setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1148      setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1149      setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1150      setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1151
1152      setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1153      setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1154      setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1155      setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1156
1157      setOperationAction(ISD::FABS,  MVT::f32, Legal);
1158      setOperationAction(ISD::FABS,  MVT::f64, Expand);
1159
1160      setOperationAction(ISD::FNEG,  MVT::f32, Legal);
1161      setOperationAction(ISD::FNEG,  MVT::f64, Expand);
1162    } else {
1163
1164      // Expand fp<->uint.
1165      setOperationAction(ISD::FP_TO_SINT,  MVT::i32, Expand);
1166      setOperationAction(ISD::FP_TO_UINT,  MVT::i32, Expand);
1167
1168      setOperationAction(ISD::SINT_TO_FP,  MVT::i32, Expand);
1169      setOperationAction(ISD::UINT_TO_FP,  MVT::i32, Expand);
1170
1171      setLibcallName(RTLIB::SINTTOFP_I64_F32, "__hexagon_floatdisf");
1172      setLibcallName(RTLIB::UINTTOFP_I64_F32, "__hexagon_floatundisf");
1173
1174      setLibcallName(RTLIB::UINTTOFP_I32_F32, "__hexagon_floatunsisf");
1175      setLibcallName(RTLIB::SINTTOFP_I32_F32, "__hexagon_floatsisf");
1176
1177      setLibcallName(RTLIB::SINTTOFP_I64_F64, "__hexagon_floatdidf");
1178      setLibcallName(RTLIB::UINTTOFP_I64_F64, "__hexagon_floatundidf");
1179
1180      setLibcallName(RTLIB::UINTTOFP_I32_F64, "__hexagon_floatunsidf");
1181      setLibcallName(RTLIB::SINTTOFP_I32_F64, "__hexagon_floatsidf");
1182
1183      setLibcallName(RTLIB::FPTOUINT_F32_I32, "__hexagon_fixunssfsi");
1184      setLibcallName(RTLIB::FPTOUINT_F32_I64, "__hexagon_fixunssfdi");
1185
1186      setLibcallName(RTLIB::FPTOSINT_F64_I64, "__hexagon_fixdfdi");
1187      setLibcallName(RTLIB::FPTOSINT_F32_I64, "__hexagon_fixsfdi");
1188
1189      setLibcallName(RTLIB::FPTOUINT_F64_I32, "__hexagon_fixunsdfsi");
1190      setLibcallName(RTLIB::FPTOUINT_F64_I64, "__hexagon_fixunsdfdi");
1191
1192      setLibcallName(RTLIB::ADD_F64, "__hexagon_adddf3");
1193      setOperationAction(ISD::FADD,  MVT::f64, Expand);
1194
1195      setLibcallName(RTLIB::ADD_F32, "__hexagon_addsf3");
1196      setOperationAction(ISD::FADD,  MVT::f32, Expand);
1197
1198      setLibcallName(RTLIB::FPEXT_F32_F64, "__hexagon_extendsfdf2");
1199      setOperationAction(ISD::FP_EXTEND,  MVT::f32, Expand);
1200
1201      setLibcallName(RTLIB::OEQ_F32, "__hexagon_eqsf2");
1202      setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
1203
1204      setLibcallName(RTLIB::OEQ_F64, "__hexagon_eqdf2");
1205      setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
1206
1207      setLibcallName(RTLIB::OGE_F32, "__hexagon_gesf2");
1208      setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
1209
1210      setLibcallName(RTLIB::OGE_F64, "__hexagon_gedf2");
1211      setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
1212
1213      setLibcallName(RTLIB::OGT_F32, "__hexagon_gtsf2");
1214      setCondCodeAction(ISD::SETOGT, MVT::f32, Expand);
1215
1216      setLibcallName(RTLIB::OGT_F64, "__hexagon_gtdf2");
1217      setCondCodeAction(ISD::SETOGT, MVT::f64, Expand);
1218
1219      setLibcallName(RTLIB::FPTOSINT_F64_I32, "__hexagon_fixdfsi");
1220      setOperationAction(ISD::FP_TO_SINT, MVT::f64, Expand);
1221
1222      setLibcallName(RTLIB::FPTOSINT_F32_I32, "__hexagon_fixsfsi");
1223      setOperationAction(ISD::FP_TO_SINT, MVT::f32, Expand);
1224
1225      setLibcallName(RTLIB::OLE_F64, "__hexagon_ledf2");
1226      setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
1227
1228      setLibcallName(RTLIB::OLE_F32, "__hexagon_lesf2");
1229      setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
1230
1231      setLibcallName(RTLIB::OLT_F64, "__hexagon_ltdf2");
1232      setCondCodeAction(ISD::SETOLT, MVT::f64, Expand);
1233
1234      setLibcallName(RTLIB::OLT_F32, "__hexagon_ltsf2");
1235      setCondCodeAction(ISD::SETOLT, MVT::f32, Expand);
1236
1237      setLibcallName(RTLIB::MUL_F64, "__hexagon_muldf3");
1238      setOperationAction(ISD::FMUL, MVT::f64, Expand);
1239
1240      setLibcallName(RTLIB::MUL_F32, "__hexagon_mulsf3");
1241      setOperationAction(ISD::MUL, MVT::f32, Expand);
1242
1243      setLibcallName(RTLIB::UNE_F64, "__hexagon_nedf2");
1244      setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
1245
1246      setLibcallName(RTLIB::UNE_F32, "__hexagon_nesf2");
1247
1248      setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
1249      setOperationAction(ISD::SUB, MVT::f64, Expand);
1250
1251      setLibcallName(RTLIB::SUB_F32, "__hexagon_subsf3");
1252      setOperationAction(ISD::SUB, MVT::f32, Expand);
1253
1254      setLibcallName(RTLIB::FPROUND_F64_F32, "__hexagon_truncdfsf2");
1255      setOperationAction(ISD::FP_ROUND, MVT::f64, Expand);
1256
1257      setLibcallName(RTLIB::UO_F64, "__hexagon_unorddf2");
1258      setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
1259
1260      setLibcallName(RTLIB::O_F64, "__hexagon_unorddf2");
1261      setCondCodeAction(ISD::SETO, MVT::f64, Expand);
1262
1263      setLibcallName(RTLIB::O_F32, "__hexagon_unordsf2");
1264      setCondCodeAction(ISD::SETO, MVT::f32, Expand);
1265
1266      setLibcallName(RTLIB::UO_F32, "__hexagon_unordsf2");
1267      setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
1268
1269      setOperationAction(ISD::FABS,  MVT::f32, Expand);
1270      setOperationAction(ISD::FABS,  MVT::f64, Expand);
1271      setOperationAction(ISD::FNEG,  MVT::f32, Expand);
1272      setOperationAction(ISD::FNEG,  MVT::f64, Expand);
1273    }
1274
1275    setLibcallName(RTLIB::SREM_I32, "__hexagon_modsi3");
1276    setOperationAction(ISD::SREM, MVT::i32, Expand);
1277
1278    setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
1279    setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
1280    setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1281    setIndexedLoadAction(ISD::POST_INC, MVT::i64, Legal);
1282
1283    setIndexedStoreAction(ISD::POST_INC, MVT::i8, Legal);
1284    setIndexedStoreAction(ISD::POST_INC, MVT::i16, Legal);
1285    setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1286    setIndexedStoreAction(ISD::POST_INC, MVT::i64, Legal);
1287
1288    setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
1289
1290    // Turn FP extload into load/fextend.
1291    setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
1292    // Hexagon has a i1 sign extending load.
1293    setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
1294    // Turn FP truncstore into trunc + store.
1295    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1296
1297    // Custom legalize GlobalAddress nodes into CONST32.
1298    setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1299    setOperationAction(ISD::GlobalAddress, MVT::i8, Custom);
1300    // Truncate action?
1301    setOperationAction(ISD::TRUNCATE, MVT::i64, Expand);
1302
1303    // Hexagon doesn't have sext_inreg, replace them with shl/sra.
1304    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
1305
1306    // Hexagon has no REM or DIVREM operations.
1307    setOperationAction(ISD::UREM, MVT::i32, Expand);
1308    setOperationAction(ISD::SREM, MVT::i32, Expand);
1309    setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1310    setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1311    setOperationAction(ISD::SREM, MVT::i64, Expand);
1312    setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
1313    setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
1314
1315    setOperationAction(ISD::BSWAP, MVT::i64, Expand);
1316
1317    // Lower SELECT_CC to SETCC and SELECT.
1318    setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
1319    setOperationAction(ISD::SELECT_CC, MVT::i64,   Custom);
1320
1321    if (QRI->Subtarget.hasV5TOps()) {
1322
1323      // We need to make the operation type of SELECT node to be Custom,
1324      // such that we don't go into the infinite loop of
1325      // select ->  setcc -> select_cc -> select loop.
1326      setOperationAction(ISD::SELECT, MVT::f32, Custom);
1327      setOperationAction(ISD::SELECT, MVT::f64, Custom);
1328
1329      setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
1330      setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
1331      setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
1332
1333    } else {
1334
1335      // Hexagon has no select or setcc: expand to SELECT_CC.
1336      setOperationAction(ISD::SELECT, MVT::f32, Expand);
1337      setOperationAction(ISD::SELECT, MVT::f64, Expand);
1338
1339      // This is a workaround documented in DAGCombiner.cpp:2892 We don't
1340      // support SELECT_CC on every type.
1341      setOperationAction(ISD::SELECT_CC, MVT::Other,   Expand);
1342
1343    }
1344
1345    setOperationAction(ISD::BR_CC, MVT::Other, Expand);
1346    setOperationAction(ISD::BRIND, MVT::Other, Expand);
1347    if (EmitJumpTables) {
1348      setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1349    } else {
1350      setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1351    }
1352    // Increase jump tables cutover to 5, was 4.
1353    setMinimumJumpTableEntries(5);
1354
1355    setOperationAction(ISD::BR_CC, MVT::i32, Expand);
1356
1357    setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
1358    setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1359
1360    setOperationAction(ISD::FSIN , MVT::f64, Expand);
1361    setOperationAction(ISD::FCOS , MVT::f64, Expand);
1362    setOperationAction(ISD::FREM , MVT::f64, Expand);
1363    setOperationAction(ISD::FSIN , MVT::f32, Expand);
1364    setOperationAction(ISD::FCOS , MVT::f32, Expand);
1365    setOperationAction(ISD::FREM , MVT::f32, Expand);
1366    setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1367    setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1368    setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1369    setOperationAction(ISD::CTTZ , MVT::i32, Expand);
1370    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1371    setOperationAction(ISD::CTLZ , MVT::i32, Expand);
1372    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1373    setOperationAction(ISD::ROTL , MVT::i32, Expand);
1374    setOperationAction(ISD::ROTR , MVT::i32, Expand);
1375    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1376    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1377    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1378    setOperationAction(ISD::FPOW , MVT::f64, Expand);
1379    setOperationAction(ISD::FPOW , MVT::f32, Expand);
1380
1381    setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1382    setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1383    setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1384
1385    setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1386    setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1387
1388    setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
1389    setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
1390
1391    setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
1392    setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
1393    setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
1394    setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
1395
1396    setOperationAction(ISD::EH_RETURN,     MVT::Other, Expand);
1397
1398    if (TM.getSubtargetImpl()->isSubtargetV2()) {
1399      setExceptionPointerRegister(Hexagon::R20);
1400      setExceptionSelectorRegister(Hexagon::R21);
1401    } else {
1402      setExceptionPointerRegister(Hexagon::R0);
1403      setExceptionSelectorRegister(Hexagon::R1);
1404    }
1405
1406    // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1407    setOperationAction(ISD::VASTART           , MVT::Other, Custom);
1408
1409    // Use the default implementation.
1410    setOperationAction(ISD::VAARG             , MVT::Other, Expand);
1411    setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
1412    setOperationAction(ISD::VAEND             , MVT::Other, Expand);
1413    setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
1414    setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
1415
1416
1417    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
1418    setOperationAction(ISD::INLINEASM         , MVT::Other, Custom);
1419
1420    setMinFunctionAlignment(2);
1421
1422    // Needed for DYNAMIC_STACKALLOC expansion.
1423    unsigned StackRegister = TM.getRegisterInfo()->getStackRegister();
1424    setStackPointerRegisterToSaveRestore(StackRegister);
1425    setSchedulingPreference(Sched::VLIW);
1426}
1427
1428
1429const char*
1430HexagonTargetLowering::getTargetNodeName(unsigned Opcode) const {
1431  switch (Opcode) {
1432    default: return 0;
1433    case HexagonISD::CONST32:     return "HexagonISD::CONST32";
1434    case HexagonISD::ADJDYNALLOC: return "HexagonISD::ADJDYNALLOC";
1435    case HexagonISD::CMPICC:      return "HexagonISD::CMPICC";
1436    case HexagonISD::CMPFCC:      return "HexagonISD::CMPFCC";
1437    case HexagonISD::BRICC:       return "HexagonISD::BRICC";
1438    case HexagonISD::BRFCC:       return "HexagonISD::BRFCC";
1439    case HexagonISD::SELECT_ICC:  return "HexagonISD::SELECT_ICC";
1440    case HexagonISD::SELECT_FCC:  return "HexagonISD::SELECT_FCC";
1441    case HexagonISD::Hi:          return "HexagonISD::Hi";
1442    case HexagonISD::Lo:          return "HexagonISD::Lo";
1443    case HexagonISD::FTOI:        return "HexagonISD::FTOI";
1444    case HexagonISD::ITOF:        return "HexagonISD::ITOF";
1445    case HexagonISD::CALL:        return "HexagonISD::CALL";
1446    case HexagonISD::RET_FLAG:    return "HexagonISD::RET_FLAG";
1447    case HexagonISD::BR_JT:       return "HexagonISD::BR_JT";
1448    case HexagonISD::TC_RETURN:   return "HexagonISD::TC_RETURN";
1449  }
1450}
1451
1452bool
1453HexagonTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
1454  EVT MTy1 = EVT::getEVT(Ty1);
1455  EVT MTy2 = EVT::getEVT(Ty2);
1456  if (!MTy1.isSimple() || !MTy2.isSimple()) {
1457    return false;
1458  }
1459  return ((MTy1.getSimpleVT() == MVT::i64) && (MTy2.getSimpleVT() == MVT::i32));
1460}
1461
1462bool HexagonTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1463  if (!VT1.isSimple() || !VT2.isSimple()) {
1464    return false;
1465  }
1466  return ((VT1.getSimpleVT() == MVT::i64) && (VT2.getSimpleVT() == MVT::i32));
1467}
1468
1469SDValue
1470HexagonTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1471  switch (Op.getOpcode()) {
1472    default: llvm_unreachable("Should not custom lower this!");
1473    case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1474      // Frame & Return address.  Currently unimplemented.
1475    case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1476    case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1477    case ISD::GlobalTLSAddress:
1478                          llvm_unreachable("TLS not implemented for Hexagon.");
1479    case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, DAG);
1480    case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
1481    case ISD::GlobalAddress:      return LowerGLOBALADDRESS(Op, DAG);
1482    case ISD::VASTART:            return LowerVASTART(Op, DAG);
1483    case ISD::BR_JT:              return LowerBR_JT(Op, DAG);
1484
1485    case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1486    case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1487    case ISD::SELECT:             return Op;
1488    case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1489    case ISD::INLINEASM:          return LowerINLINEASM(Op, DAG);
1490
1491  }
1492}
1493
1494
1495
1496//===----------------------------------------------------------------------===//
1497//                           Hexagon Scheduler Hooks
1498//===----------------------------------------------------------------------===//
1499MachineBasicBlock *
1500HexagonTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1501                                                   MachineBasicBlock *BB)
1502const {
1503  switch (MI->getOpcode()) {
1504    case Hexagon::ADJDYNALLOC: {
1505      MachineFunction *MF = BB->getParent();
1506      HexagonMachineFunctionInfo *FuncInfo =
1507        MF->getInfo<HexagonMachineFunctionInfo>();
1508      FuncInfo->addAllocaAdjustInst(MI);
1509      return BB;
1510    }
1511    default: llvm_unreachable("Unexpected instr type to insert");
1512  } // switch
1513}
1514
1515//===----------------------------------------------------------------------===//
1516// Inline Assembly Support
1517//===----------------------------------------------------------------------===//
1518
1519std::pair<unsigned, const TargetRegisterClass*>
1520HexagonTargetLowering::getRegForInlineAsmConstraint(const
1521                                                    std::string &Constraint,
1522                                                    EVT VT) const {
1523  if (Constraint.size() == 1) {
1524    switch (Constraint[0]) {
1525    case 'r':   // R0-R31
1526       switch (VT.getSimpleVT().SimpleTy) {
1527       default:
1528         llvm_unreachable("getRegForInlineAsmConstraint Unhandled data type");
1529       case MVT::i32:
1530       case MVT::i16:
1531       case MVT::i8:
1532       case MVT::f32:
1533         return std::make_pair(0U, &Hexagon::IntRegsRegClass);
1534       case MVT::i64:
1535       case MVT::f64:
1536         return std::make_pair(0U, &Hexagon::DoubleRegsRegClass);
1537      }
1538    default:
1539      llvm_unreachable("Unknown asm register class");
1540    }
1541  }
1542
1543  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1544}
1545
1546/// isFPImmLegal - Returns true if the target can instruction select the
1547/// specified FP immediate natively. If false, the legalizer will
1548/// materialize the FP immediate as a load from a constant pool.
1549bool HexagonTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1550  const HexagonRegisterInfo* QRI = TM.getRegisterInfo();
1551  return QRI->Subtarget.hasV5TOps();
1552}
1553
1554/// isLegalAddressingMode - Return true if the addressing mode represented by
1555/// AM is legal for this target, for a load/store of the specified type.
1556bool HexagonTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1557                                                  Type *Ty) const {
1558  // Allows a signed-extended 11-bit immediate field.
1559  if (AM.BaseOffs <= -(1LL << 13) || AM.BaseOffs >= (1LL << 13)-1) {
1560    return false;
1561  }
1562
1563  // No global is ever allowed as a base.
1564  if (AM.BaseGV) {
1565    return false;
1566  }
1567
1568  int Scale = AM.Scale;
1569  if (Scale < 0) Scale = -Scale;
1570  switch (Scale) {
1571  case 0:  // No scale reg, "r+i", "r", or just "i".
1572    break;
1573  default: // No scaled addressing mode.
1574    return false;
1575  }
1576  return true;
1577}
1578
1579/// isLegalICmpImmediate - Return true if the specified immediate is legal
1580/// icmp immediate, that is the target has icmp instructions which can compare
1581/// a register against the immediate without having to materialize the
1582/// immediate into a register.
1583bool HexagonTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1584  return Imm >= -512 && Imm <= 511;
1585}
1586
1587/// IsEligibleForTailCallOptimization - Check whether the call is eligible
1588/// for tail call optimization. Targets which want to do tail call
1589/// optimization should implement this function.
1590bool HexagonTargetLowering::IsEligibleForTailCallOptimization(
1591                                 SDValue Callee,
1592                                 CallingConv::ID CalleeCC,
1593                                 bool isVarArg,
1594                                 bool isCalleeStructRet,
1595                                 bool isCallerStructRet,
1596                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
1597                                 const SmallVectorImpl<SDValue> &OutVals,
1598                                 const SmallVectorImpl<ISD::InputArg> &Ins,
1599                                 SelectionDAG& DAG) const {
1600  const Function *CallerF = DAG.getMachineFunction().getFunction();
1601  CallingConv::ID CallerCC = CallerF->getCallingConv();
1602  bool CCMatch = CallerCC == CalleeCC;
1603
1604  // ***************************************************************************
1605  //  Look for obvious safe cases to perform tail call optimization that do not
1606  //  require ABI changes.
1607  // ***************************************************************************
1608
1609  // If this is a tail call via a function pointer, then don't do it!
1610  if (!(dyn_cast<GlobalAddressSDNode>(Callee))
1611      && !(dyn_cast<ExternalSymbolSDNode>(Callee))) {
1612    return false;
1613  }
1614
1615  // Do not optimize if the calling conventions do not match.
1616  if (!CCMatch)
1617    return false;
1618
1619  // Do not tail call optimize vararg calls.
1620  if (isVarArg)
1621    return false;
1622
1623  // Also avoid tail call optimization if either caller or callee uses struct
1624  // return semantics.
1625  if (isCalleeStructRet || isCallerStructRet)
1626    return false;
1627
1628  // In addition to the cases above, we also disable Tail Call Optimization if
1629  // the calling convention code that at least one outgoing argument needs to
1630  // go on the stack. We cannot check that here because at this point that
1631  // information is not available.
1632  return true;
1633}
1634