734f0363df731540d263000642f6b55b4ad13895
[oota-llvm.git] / lib / Target / Hexagon / HexagonISelLowering.cpp
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
40 using namespace llvm;
41
42 #define DEBUG_TYPE "hexagon-lowering"
43
44 static cl::opt<bool>
45 EmitJumpTables("hexagon-emit-jump-tables", cl::init(true), cl::Hidden,
46                cl::desc("Control jump table emission on Hexagon target"));
47
48 namespace {
49 class HexagonCCState : public CCState {
50   int NumNamedVarArgParams;
51
52 public:
53   HexagonCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
54                  SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
55                  int NumNamedVarArgParams)
56       : CCState(CC, isVarArg, MF, locs, C),
57         NumNamedVarArgParams(NumNamedVarArgParams) {}
58
59   int getNumNamedVarArgParams() const { return NumNamedVarArgParams; }
60 };
61 }
62
63 // Implement calling convention for Hexagon.
64 static bool
65 CC_Hexagon(unsigned ValNo, MVT ValVT,
66            MVT LocVT, CCValAssign::LocInfo LocInfo,
67            ISD::ArgFlagsTy ArgFlags, CCState &State);
68
69 static bool
70 CC_Hexagon32(unsigned ValNo, MVT ValVT,
71              MVT LocVT, CCValAssign::LocInfo LocInfo,
72              ISD::ArgFlagsTy ArgFlags, CCState &State);
73
74 static bool
75 CC_Hexagon64(unsigned ValNo, MVT ValVT,
76              MVT LocVT, CCValAssign::LocInfo LocInfo,
77              ISD::ArgFlagsTy ArgFlags, CCState &State);
78
79 static bool
80 RetCC_Hexagon(unsigned ValNo, MVT ValVT,
81               MVT LocVT, CCValAssign::LocInfo LocInfo,
82               ISD::ArgFlagsTy ArgFlags, CCState &State);
83
84 static bool
85 RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
86                 MVT LocVT, CCValAssign::LocInfo LocInfo,
87                 ISD::ArgFlagsTy ArgFlags, CCState &State);
88
89 static bool
90 RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
91                 MVT LocVT, CCValAssign::LocInfo LocInfo,
92                 ISD::ArgFlagsTy ArgFlags, CCState &State);
93
94 static bool
95 CC_Hexagon_VarArg (unsigned ValNo, MVT ValVT,
96             MVT LocVT, CCValAssign::LocInfo LocInfo,
97             ISD::ArgFlagsTy ArgFlags, CCState &State) {
98   HexagonCCState &HState = static_cast<HexagonCCState &>(State);
99
100   // NumNamedVarArgParams can not be zero for a VarArg function.
101   assert((HState.getNumNamedVarArgParams() > 0) &&
102          "NumNamedVarArgParams is not bigger than zero.");
103
104   if ((int)ValNo < HState.getNumNamedVarArgParams()) {
105     // Deal with named arguments.
106     return CC_Hexagon(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
107   }
108
109   // Deal with un-named arguments.
110   unsigned ofst;
111   if (ArgFlags.isByVal()) {
112     // If pass-by-value, the size allocated on stack is decided
113     // by ArgFlags.getByValSize(), not by the size of LocVT.
114     assert ((ArgFlags.getByValSize() > 8) &&
115             "ByValSize must be bigger than 8 bytes");
116     ofst = State.AllocateStack(ArgFlags.getByValSize(), 4);
117     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
118     return false;
119   }
120   if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
121     LocVT = MVT::i32;
122     ValVT = MVT::i32;
123     if (ArgFlags.isSExt())
124       LocInfo = CCValAssign::SExt;
125     else if (ArgFlags.isZExt())
126       LocInfo = CCValAssign::ZExt;
127     else
128       LocInfo = CCValAssign::AExt;
129   }
130   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
131     ofst = State.AllocateStack(4, 4);
132     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
133     return false;
134   }
135   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
136     ofst = State.AllocateStack(8, 8);
137     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
138     return false;
139   }
140   llvm_unreachable(nullptr);
141 }
142
143
144 static bool
145 CC_Hexagon (unsigned ValNo, MVT ValVT,
146             MVT LocVT, CCValAssign::LocInfo LocInfo,
147             ISD::ArgFlagsTy ArgFlags, CCState &State) {
148
149   if (ArgFlags.isByVal()) {
150     // Passed on stack.
151     assert ((ArgFlags.getByValSize() > 8) &&
152             "ByValSize must be bigger than 8 bytes");
153     unsigned Offset = State.AllocateStack(ArgFlags.getByValSize(), 4);
154     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
155     return false;
156   }
157
158   if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
159     LocVT = MVT::i32;
160     ValVT = MVT::i32;
161     if (ArgFlags.isSExt())
162       LocInfo = CCValAssign::SExt;
163     else if (ArgFlags.isZExt())
164       LocInfo = CCValAssign::ZExt;
165     else
166       LocInfo = CCValAssign::AExt;
167   } else if (LocVT == MVT::v4i8 || LocVT == MVT::v2i16) {
168     LocVT = MVT::i32;
169     LocInfo = CCValAssign::BCvt;
170   } else if (LocVT == MVT::v8i8 || LocVT == MVT::v4i16 || LocVT == MVT::v2i32) {
171     LocVT = MVT::i64;
172     LocInfo = CCValAssign::BCvt;
173   }
174
175   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
176     if (!CC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
177       return false;
178   }
179
180   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
181     if (!CC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
182       return false;
183   }
184
185   return true;  // CC didn't match.
186 }
187
188
189 static bool CC_Hexagon32(unsigned ValNo, MVT ValVT,
190                          MVT LocVT, CCValAssign::LocInfo LocInfo,
191                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
192
193   static const MCPhysReg RegList[] = {
194     Hexagon::R0, Hexagon::R1, Hexagon::R2, Hexagon::R3, Hexagon::R4,
195     Hexagon::R5
196   };
197   if (unsigned Reg = State.AllocateReg(RegList)) {
198     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
199     return false;
200   }
201
202   unsigned Offset = State.AllocateStack(4, 4);
203   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
204   return false;
205 }
206
207 static bool CC_Hexagon64(unsigned ValNo, MVT ValVT,
208                          MVT LocVT, CCValAssign::LocInfo LocInfo,
209                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
210
211   if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
212     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
213     return false;
214   }
215
216   static const MCPhysReg RegList1[] = {
217     Hexagon::D1, Hexagon::D2
218   };
219   static const MCPhysReg RegList2[] = {
220     Hexagon::R1, Hexagon::R3
221   };
222   if (unsigned Reg = State.AllocateReg(RegList1, RegList2)) {
223     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
224     return false;
225   }
226
227   unsigned Offset = State.AllocateStack(8, 8, Hexagon::D2);
228   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
229   return false;
230 }
231
232 static bool RetCC_Hexagon(unsigned ValNo, MVT ValVT,
233                           MVT LocVT, CCValAssign::LocInfo LocInfo,
234                           ISD::ArgFlagsTy ArgFlags, CCState &State) {
235
236
237   if (LocVT == MVT::i1 ||
238       LocVT == MVT::i8 ||
239       LocVT == MVT::i16) {
240     LocVT = MVT::i32;
241     ValVT = MVT::i32;
242     if (ArgFlags.isSExt())
243       LocInfo = CCValAssign::SExt;
244     else if (ArgFlags.isZExt())
245       LocInfo = CCValAssign::ZExt;
246     else
247       LocInfo = CCValAssign::AExt;
248   } else if (LocVT == MVT::v4i8 || LocVT == MVT::v2i16) {
249     LocVT = MVT::i32;
250     LocInfo = CCValAssign::BCvt;
251   } else if (LocVT == MVT::v8i8 || LocVT == MVT::v4i16 || LocVT == MVT::v2i32) {
252     LocVT = MVT::i64;
253     LocInfo = CCValAssign::BCvt;
254   }
255
256   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
257     if (!RetCC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
258     return false;
259   }
260
261   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
262     if (!RetCC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
263     return false;
264   }
265
266   return true;  // CC didn't match.
267 }
268
269 static bool RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
270                             MVT LocVT, CCValAssign::LocInfo LocInfo,
271                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
272
273   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
274     if (unsigned Reg = State.AllocateReg(Hexagon::R0)) {
275       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
276       return false;
277     }
278   }
279
280   unsigned Offset = State.AllocateStack(4, 4);
281   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
282   return false;
283 }
284
285 static bool RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
286                             MVT LocVT, CCValAssign::LocInfo LocInfo,
287                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
288   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
289     if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
290       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
291       return false;
292     }
293   }
294
295   unsigned Offset = State.AllocateStack(8, 8);
296   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
297   return false;
298 }
299
300 SDValue
301 HexagonTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG)
302 const {
303   return SDValue();
304 }
305
306 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
307 /// by "Src" to address "Dst" of size "Size".  Alignment information is
308 /// specified by the specific parameter attribute. The copy will be passed as
309 /// a byval function parameter.  Sometimes what we are copying is the end of a
310 /// larger object, the part that does not fit in registers.
311 static SDValue
312 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
313                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
314                           SDLoc dl) {
315
316   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
317   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
318                        /*isVolatile=*/false, /*AlwaysInline=*/false,
319                        /*isTailCall=*/false,
320                        MachinePointerInfo(), MachinePointerInfo());
321 }
322
323
324 // LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
325 // passed by value, the function prototype is modified to return void and
326 // the value is stored in memory pointed by a pointer passed by caller.
327 SDValue
328 HexagonTargetLowering::LowerReturn(SDValue Chain,
329                                    CallingConv::ID CallConv, bool isVarArg,
330                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
331                                    const SmallVectorImpl<SDValue> &OutVals,
332                                    SDLoc dl, SelectionDAG &DAG) const {
333
334   // CCValAssign - represent the assignment of the return value to locations.
335   SmallVector<CCValAssign, 16> RVLocs;
336
337   // CCState - Info about the registers and stack slot.
338   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
339                  *DAG.getContext());
340
341   // Analyze return values of ISD::RET
342   CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
343
344   SDValue Flag;
345   SmallVector<SDValue, 4> RetOps(1, Chain);
346
347   // Copy the result values into the output registers.
348   for (unsigned i = 0; i != RVLocs.size(); ++i) {
349     CCValAssign &VA = RVLocs[i];
350
351     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
352
353     // Guarantee that all emitted copies are stuck together with flags.
354     Flag = Chain.getValue(1);
355     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
356   }
357
358   RetOps[0] = Chain;  // Update chain.
359
360   // Add the flag if we have it.
361   if (Flag.getNode())
362     RetOps.push_back(Flag);
363
364   return DAG.getNode(HexagonISD::RET_FLAG, dl, MVT::Other, RetOps);
365 }
366
367
368
369
370 /// LowerCallResult - Lower the result values of an ISD::CALL into the
371 /// appropriate copies out of appropriate physical registers.  This assumes that
372 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
373 /// being lowered. Returns a SDNode with the same number of values as the
374 /// ISD::CALL.
375 SDValue
376 HexagonTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
377                                        CallingConv::ID CallConv, bool isVarArg,
378                                        const
379                                        SmallVectorImpl<ISD::InputArg> &Ins,
380                                        SDLoc dl, SelectionDAG &DAG,
381                                        SmallVectorImpl<SDValue> &InVals,
382                                        const SmallVectorImpl<SDValue> &OutVals,
383                                        SDValue Callee) const {
384
385   // Assign locations to each value returned by this call.
386   SmallVector<CCValAssign, 16> RVLocs;
387
388   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
389                  *DAG.getContext());
390
391   CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
392
393   // Copy all of the result registers out of their specified physreg.
394   for (unsigned i = 0; i != RVLocs.size(); ++i) {
395     Chain = DAG.getCopyFromReg(Chain, dl,
396                                RVLocs[i].getLocReg(),
397                                RVLocs[i].getValVT(), InFlag).getValue(1);
398     InFlag = Chain.getValue(2);
399     InVals.push_back(Chain.getValue(0));
400   }
401
402   return Chain;
403 }
404
405 /// LowerCall - Functions arguments are copied from virtual regs to
406 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
407 SDValue
408 HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
409                                  SmallVectorImpl<SDValue> &InVals) const {
410   SelectionDAG &DAG                     = CLI.DAG;
411   SDLoc &dl                             = CLI.DL;
412   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
413   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
414   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
415   SDValue Chain                         = CLI.Chain;
416   SDValue Callee                        = CLI.Callee;
417   bool &isTailCall                      = CLI.IsTailCall;
418   CallingConv::ID CallConv              = CLI.CallConv;
419   bool isVarArg                         = CLI.IsVarArg;
420   bool doesNotReturn                    = CLI.DoesNotReturn;
421
422   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
423   MachineFunction &MF = DAG.getMachineFunction();
424
425   // Check for varargs.
426   int NumNamedVarArgParams = -1;
427   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee))
428   {
429     const Function* CalleeFn = nullptr;
430     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, MVT::i32);
431     if ((CalleeFn = dyn_cast<Function>(GA->getGlobal())))
432     {
433       // If a function has zero args and is a vararg function, that's
434       // disallowed so it must be an undeclared function.  Do not assume
435       // varargs if the callee is undefined.
436       if (CalleeFn->isVarArg() &&
437           CalleeFn->getFunctionType()->getNumParams() != 0) {
438         NumNamedVarArgParams = CalleeFn->getFunctionType()->getNumParams();
439       }
440     }
441   }
442
443   // Analyze operands of the call, assigning locations to each operand.
444   SmallVector<CCValAssign, 16> ArgLocs;
445   HexagonCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
446                         *DAG.getContext(), NumNamedVarArgParams);
447
448   if (isVarArg)
449     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_VarArg);
450   else
451     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
452
453   if (DAG.getTarget().Options.DisableTailCalls)
454     isTailCall = false;
455
456   if (isTailCall) {
457     bool StructAttrFlag = MF.getFunction()->hasStructRetAttr();
458     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
459                                                    isVarArg, IsStructRet,
460                                                    StructAttrFlag,
461                                                    Outs, OutVals, Ins, DAG);
462     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
463       CCValAssign &VA = ArgLocs[i];
464       if (VA.isMemLoc()) {
465         isTailCall = false;
466         break;
467       }
468     }
469     DEBUG(dbgs() << (isTailCall ? "Eligible for Tail Call\n"
470                                 : "Argument must be passed on stack. "
471                                   "Not eligible for Tail Call\n"));
472   }
473   // Get a count of how many bytes are to be pushed on the stack.
474   unsigned NumBytes = CCInfo.getNextStackOffset();
475   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
476   SmallVector<SDValue, 8> MemOpChains;
477
478   auto &HRI =
479       static_cast<const HexagonRegisterInfo&>(*Subtarget->getRegisterInfo());
480   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, HRI.getStackRegister(),
481                                         getPointerTy());
482
483   // Walk the register/memloc assignments, inserting copies/loads.
484   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
485     CCValAssign &VA = ArgLocs[i];
486     SDValue Arg = OutVals[i];
487     ISD::ArgFlagsTy Flags = Outs[i].Flags;
488
489     // Promote the value if needed.
490     switch (VA.getLocInfo()) {
491       default:
492         // Loc info must be one of Full, SExt, ZExt, or AExt.
493         llvm_unreachable("Unknown loc info!");
494       case CCValAssign::BCvt:
495       case CCValAssign::Full:
496         break;
497       case CCValAssign::SExt:
498         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
499         break;
500       case CCValAssign::ZExt:
501         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
502         break;
503       case CCValAssign::AExt:
504         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
505         break;
506     }
507
508     if (VA.isMemLoc()) {
509       unsigned LocMemOffset = VA.getLocMemOffset();
510       SDValue MemAddr = DAG.getConstant(LocMemOffset, StackPtr.getValueType());
511       MemAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, MemAddr);
512       if (Flags.isByVal()) {
513         // The argument is a struct passed by value. According to LLVM, "Arg"
514         // is is pointer.
515         MemOpChains.push_back(CreateCopyOfByValArgument(Arg, MemAddr, Chain,
516                                                         Flags, DAG, dl));
517       } else {
518         MachinePointerInfo LocPI = MachinePointerInfo::getStack(LocMemOffset);
519         SDValue S = DAG.getStore(Chain, dl, Arg, MemAddr, LocPI, false,
520                                  false, 0);
521         MemOpChains.push_back(S);
522       }
523       continue;
524     }
525
526     // Arguments that can be passed on register must be kept at RegsToPass
527     // vector.
528     if (VA.isRegLoc())
529       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
530   }
531
532   // Transform all store nodes into one single node because all store
533   // nodes are independent of each other.
534   if (!MemOpChains.empty())
535     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
536
537   if (!isTailCall) {
538     SDValue C = DAG.getConstant(NumBytes, getPointerTy(), true);
539     Chain = DAG.getCALLSEQ_START(Chain, C, dl);
540   }
541
542   // Build a sequence of copy-to-reg nodes chained together with token
543   // chain and flag operands which copy the outgoing args into registers.
544   // The InFlag in necessary since all emitted instructions must be
545   // stuck together.
546   SDValue InFlag;
547   if (!isTailCall) {
548     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
549       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
550                                RegsToPass[i].second, InFlag);
551       InFlag = Chain.getValue(1);
552     }
553   } else {
554     // For tail calls lower the arguments to the 'real' stack slot.
555     //
556     // Force all the incoming stack arguments to be loaded from the stack
557     // before any new outgoing arguments are stored to the stack, because the
558     // outgoing stack slots may alias the incoming argument stack slots, and
559     // the alias isn't otherwise explicit. This is slightly more conservative
560     // than necessary, because it means that each store effectively depends
561     // on every argument instead of just those arguments it would clobber.
562     //
563     // Do not flag preceding copytoreg stuff together with the following stuff.
564     InFlag = SDValue();
565     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
566       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
567                                RegsToPass[i].second, InFlag);
568       InFlag = Chain.getValue(1);
569     }
570     InFlag = SDValue();
571   }
572
573   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
574   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
575   // node so that legalize doesn't hack it.
576   if (flag_aligned_memcpy) {
577     const char *MemcpyName =
578       "__hexagon_memcpy_likely_aligned_min32bytes_mult8bytes";
579     Callee = DAG.getTargetExternalSymbol(MemcpyName, getPointerTy());
580     flag_aligned_memcpy = false;
581   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
582     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy());
583   } else if (ExternalSymbolSDNode *S =
584              dyn_cast<ExternalSymbolSDNode>(Callee)) {
585     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
586   }
587
588   // Returns a chain & a flag for retval copy to use.
589   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
590   SmallVector<SDValue, 8> Ops;
591   Ops.push_back(Chain);
592   Ops.push_back(Callee);
593
594   // Add argument registers to the end of the list so that they are
595   // known live into the call.
596   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
597     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
598                                   RegsToPass[i].second.getValueType()));
599   }
600
601   if (InFlag.getNode())
602     Ops.push_back(InFlag);
603
604   if (isTailCall)
605     return DAG.getNode(HexagonISD::TC_RETURN, dl, NodeTys, Ops);
606
607   int OpCode = doesNotReturn ? HexagonISD::CALLv3nr : HexagonISD::CALLv3;
608   Chain = DAG.getNode(OpCode, dl, NodeTys, Ops);
609   InFlag = Chain.getValue(1);
610
611   // Create the CALLSEQ_END node.
612   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
613                              DAG.getIntPtrConstant(0, true), InFlag, dl);
614   InFlag = Chain.getValue(1);
615
616   // Handle result values, copying them out of physregs into vregs that we
617   // return.
618   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
619                          InVals, OutVals, Callee);
620 }
621
622 static bool getIndexedAddressParts(SDNode *Ptr, EVT VT,
623                                    bool isSEXTLoad, SDValue &Base,
624                                    SDValue &Offset, bool &isInc,
625                                    SelectionDAG &DAG) {
626   if (Ptr->getOpcode() != ISD::ADD)
627     return false;
628
629   if (VT == MVT::i64 || VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
630     isInc = (Ptr->getOpcode() == ISD::ADD);
631     Base = Ptr->getOperand(0);
632     Offset = Ptr->getOperand(1);
633     // Ensure that Offset is a constant.
634     return (isa<ConstantSDNode>(Offset));
635   }
636
637   return false;
638 }
639
640 // TODO: Put this function along with the other isS* functions in
641 // HexagonISelDAGToDAG.cpp into a common file. Or better still, use the
642 // functions defined in HexagonOperands.td.
643 static bool Is_PostInc_S4_Offset(SDNode * S, int ShiftAmount) {
644   ConstantSDNode *N = cast<ConstantSDNode>(S);
645
646   // immS4 predicate - True if the immediate fits in a 4-bit sign extended.
647   // field.
648   int64_t v = (int64_t)N->getSExtValue();
649   int64_t m = 0;
650   if (ShiftAmount > 0) {
651     m = v % ShiftAmount;
652     v = v >> ShiftAmount;
653   }
654   return (v <= 7) && (v >= -8) && (m == 0);
655 }
656
657 /// getPostIndexedAddressParts - returns true by value, base pointer and
658 /// offset pointer and addressing mode by reference if this node can be
659 /// combined with a load / store to form a post-indexed load / store.
660 bool HexagonTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
661                                                        SDValue &Base,
662                                                        SDValue &Offset,
663                                                        ISD::MemIndexedMode &AM,
664                                                        SelectionDAG &DAG) const
665 {
666   EVT VT;
667   SDValue Ptr;
668   bool isSEXTLoad = false;
669
670   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
671     VT  = LD->getMemoryVT();
672     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
673   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
674     VT  = ST->getMemoryVT();
675     if (ST->getValue().getValueType() == MVT::i64 && ST->isTruncatingStore()) {
676       return false;
677     }
678   } else {
679     return false;
680   }
681
682   bool isInc = false;
683   bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
684                                         isInc, DAG);
685   // ShiftAmount = number of left-shifted bits in the Hexagon instruction.
686   int ShiftAmount = VT.getSizeInBits() / 16;
687   if (isLegal && Is_PostInc_S4_Offset(Offset.getNode(), ShiftAmount)) {
688     AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
689     return true;
690   }
691
692   return false;
693 }
694
695 SDValue HexagonTargetLowering::LowerINLINEASM(SDValue Op,
696                                               SelectionDAG &DAG) const {
697   SDNode *Node = Op.getNode();
698   MachineFunction &MF = DAG.getMachineFunction();
699   auto &FuncInfo = *MF.getInfo<HexagonMachineFunctionInfo>();
700   switch (Node->getOpcode()) {
701     case ISD::INLINEASM: {
702       unsigned NumOps = Node->getNumOperands();
703       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
704         --NumOps;  // Ignore the flag operand.
705
706       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
707         if (FuncInfo.hasClobberLR())
708           break;
709         unsigned Flags =
710           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
711         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
712         ++i;  // Skip the ID value.
713
714         switch (InlineAsm::getKind(Flags)) {
715         default: llvm_unreachable("Bad flags!");
716           case InlineAsm::Kind_RegDef:
717           case InlineAsm::Kind_RegUse:
718           case InlineAsm::Kind_Imm:
719           case InlineAsm::Kind_Clobber:
720           case InlineAsm::Kind_Mem: {
721             for (; NumVals; --NumVals, ++i) {}
722             break;
723           }
724           case InlineAsm::Kind_RegDefEarlyClobber: {
725             for (; NumVals; --NumVals, ++i) {
726               unsigned Reg =
727                 cast<RegisterSDNode>(Node->getOperand(i))->getReg();
728
729               // Check it to be lr
730               const HexagonRegisterInfo *QRI = Subtarget->getRegisterInfo();
731               if (Reg == QRI->getRARegister()) {
732                 FuncInfo.setHasClobberLR(true);
733                 break;
734               }
735             }
736             break;
737           }
738         }
739       }
740     }
741   } // Node->getOpcode
742   return Op;
743 }
744
745
746 //
747 // Taken from the XCore backend.
748 //
749 SDValue HexagonTargetLowering::
750 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
751 {
752   SDValue Chain = Op.getOperand(0);
753   SDValue Table = Op.getOperand(1);
754   SDValue Index = Op.getOperand(2);
755   SDLoc dl(Op);
756   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
757   unsigned JTI = JT->getIndex();
758   MachineFunction &MF = DAG.getMachineFunction();
759   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
760   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
761
762   // Mark all jump table targets as address taken.
763   const std::vector<MachineJumpTableEntry> &JTE = MJTI->getJumpTables();
764   const std::vector<MachineBasicBlock*> &JTBBs = JTE[JTI].MBBs;
765   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
766     MachineBasicBlock *MBB = JTBBs[i];
767     MBB->setHasAddressTaken();
768     // This line is needed to set the hasAddressTaken flag on the BasicBlock
769     // object.
770     BlockAddress::get(const_cast<BasicBlock *>(MBB->getBasicBlock()));
771   }
772
773   SDValue JumpTableBase = DAG.getNode(HexagonISD::JT, dl,
774                                       getPointerTy(), TargetJT);
775   SDValue ShiftIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
776                                    DAG.getConstant(2, MVT::i32));
777   SDValue JTAddress = DAG.getNode(ISD::ADD, dl, MVT::i32, JumpTableBase,
778                                   ShiftIndex);
779   SDValue LoadTarget = DAG.getLoad(MVT::i32, dl, Chain, JTAddress,
780                                    MachinePointerInfo(), false, false, false,
781                                    0);
782   return DAG.getNode(HexagonISD::BR_JT, dl, MVT::Other, Chain, LoadTarget);
783 }
784
785
786 SDValue
787 HexagonTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
788                                                SelectionDAG &DAG) const {
789   SDValue Chain = Op.getOperand(0);
790   SDValue Size = Op.getOperand(1);
791   SDValue Align = Op.getOperand(2);
792   SDLoc dl(Op);
793
794   ConstantSDNode *AlignConst = dyn_cast<ConstantSDNode>(Align);
795   assert(AlignConst && "Non-constant Align in LowerDYNAMIC_STACKALLOC");
796
797   unsigned A = AlignConst->getSExtValue();
798   auto &HST = static_cast<const HexagonSubtarget&>(DAG.getSubtarget());
799   auto &HFI = *HST.getFrameLowering();
800   // "Zero" means natural stack alignment.
801   if (A == 0)
802     A = HFI.getStackAlignment();
803
804   DEBUG({
805     dbgs () << LLVM_FUNCTION_NAME << " Align: " << A << " Size: ";
806     Size.getNode()->dump(&DAG);
807     dbgs() << "\n";
808   });
809
810   SDValue AC = DAG.getConstant(A, MVT::i32);
811   SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
812   return DAG.getNode(HexagonISD::ALLOCA, dl, VTs, Chain, Size, AC);
813 }
814
815 SDValue
816 HexagonTargetLowering::LowerFormalArguments(SDValue Chain,
817                                             CallingConv::ID CallConv,
818                                             bool isVarArg,
819                                             const
820                                             SmallVectorImpl<ISD::InputArg> &Ins,
821                                             SDLoc dl, SelectionDAG &DAG,
822                                             SmallVectorImpl<SDValue> &InVals)
823 const {
824
825   MachineFunction &MF = DAG.getMachineFunction();
826   MachineFrameInfo *MFI = MF.getFrameInfo();
827   MachineRegisterInfo &RegInfo = MF.getRegInfo();
828   auto &FuncInfo = *MF.getInfo<HexagonMachineFunctionInfo>();
829
830   // Assign locations to all of the incoming arguments.
831   SmallVector<CCValAssign, 16> ArgLocs;
832   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
833                  *DAG.getContext());
834
835   CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
836
837   // For LLVM, in the case when returning a struct by value (>8byte),
838   // the first argument is a pointer that points to the location on caller's
839   // stack where the return value will be stored. For Hexagon, the location on
840   // caller's stack is passed only when the struct size is smaller than (and
841   // equal to) 8 bytes. If not, no address will be passed into callee and
842   // callee return the result direclty through R0/R1.
843
844   SmallVector<SDValue, 4> MemOps;
845
846   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
847     CCValAssign &VA = ArgLocs[i];
848     ISD::ArgFlagsTy Flags = Ins[i].Flags;
849     unsigned ObjSize;
850     unsigned StackLocation;
851     int FI;
852
853     if (   (VA.isRegLoc() && !Flags.isByVal())
854         || (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() > 8)) {
855       // Arguments passed in registers
856       // 1. int, long long, ptr args that get allocated in register.
857       // 2. Large struct that gets an register to put its address in.
858       EVT RegVT = VA.getLocVT();
859       if (RegVT == MVT::i8 || RegVT == MVT::i16 ||
860           RegVT == MVT::i32 || RegVT == MVT::f32) {
861         unsigned VReg =
862           RegInfo.createVirtualRegister(&Hexagon::IntRegsRegClass);
863         RegInfo.addLiveIn(VA.getLocReg(), VReg);
864         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
865       } else if (RegVT == MVT::i64 || RegVT == MVT::f64) {
866         unsigned VReg =
867           RegInfo.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
868         RegInfo.addLiveIn(VA.getLocReg(), VReg);
869         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
870       } else {
871         assert (0);
872       }
873     } else if (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() <= 8) {
874       assert (0 && "ByValSize must be bigger than 8 bytes");
875     } else {
876       // Sanity check.
877       assert(VA.isMemLoc());
878
879       if (Flags.isByVal()) {
880         // If it's a byval parameter, then we need to compute the
881         // "real" size, not the size of the pointer.
882         ObjSize = Flags.getByValSize();
883       } else {
884         ObjSize = VA.getLocVT().getStoreSizeInBits() >> 3;
885       }
886
887       StackLocation = HEXAGON_LRFP_SIZE + VA.getLocMemOffset();
888       // Create the frame index object for this incoming parameter...
889       FI = MFI->CreateFixedObject(ObjSize, StackLocation, true);
890
891       // Create the SelectionDAG nodes cordl, responding to a load
892       // from this parameter.
893       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
894
895       if (Flags.isByVal()) {
896         // If it's a pass-by-value aggregate, then do not dereference the stack
897         // location. Instead, we should generate a reference to the stack
898         // location.
899         InVals.push_back(FIN);
900       } else {
901         InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
902                                      MachinePointerInfo(), false, false,
903                                      false, 0));
904       }
905     }
906   }
907
908   if (!MemOps.empty())
909     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
910
911   if (isVarArg) {
912     // This will point to the next argument passed via stack.
913     int FrameIndex = MFI->CreateFixedObject(Hexagon_PointerSize,
914                                             HEXAGON_LRFP_SIZE +
915                                             CCInfo.getNextStackOffset(),
916                                             true);
917     FuncInfo.setVarArgsFrameIndex(FrameIndex);
918   }
919
920   return Chain;
921 }
922
923 SDValue
924 HexagonTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
925   // VASTART stores the address of the VarArgsFrameIndex slot into the
926   // memory location argument.
927   MachineFunction &MF = DAG.getMachineFunction();
928   HexagonMachineFunctionInfo *QFI = MF.getInfo<HexagonMachineFunctionInfo>();
929   SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
930   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
931   return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr,
932                       Op.getOperand(1), MachinePointerInfo(SV), false,
933                       false, 0);
934 }
935
936 // Creates a SPLAT instruction for a constant value VAL.
937 static SDValue createSplat(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue Val) {
938   if (VT.getSimpleVT() == MVT::v4i8)
939     return DAG.getNode(HexagonISD::VSPLATB, dl, VT, Val);
940
941   if (VT.getSimpleVT() == MVT::v4i16)
942     return DAG.getNode(HexagonISD::VSPLATH, dl, VT, Val);
943
944   return SDValue();
945 }
946
947 static bool isSExtFree(SDValue N) {
948   // A sign-extend of a truncate of a sign-extend is free.
949   if (N.getOpcode() == ISD::TRUNCATE &&
950       N.getOperand(0).getOpcode() == ISD::AssertSext)
951     return true;
952   // We have sign-extended loads.
953   if (N.getOpcode() == ISD::LOAD)
954     return true;
955   return false;
956 }
957
958 SDValue HexagonTargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
959   SDLoc dl(Op);
960   SDValue InpVal = Op.getOperand(0);
961   if (isa<ConstantSDNode>(InpVal)) {
962     uint64_t V = cast<ConstantSDNode>(InpVal)->getZExtValue();
963     return DAG.getTargetConstant(countPopulation(V), MVT::i64);
964   }
965   SDValue PopOut = DAG.getNode(HexagonISD::POPCOUNT, dl, MVT::i32, InpVal);
966   return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, PopOut);
967 }
968
969 SDValue HexagonTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
970   SDLoc dl(Op);
971
972   SDValue LHS = Op.getOperand(0);
973   SDValue RHS = Op.getOperand(1);
974   SDValue Cmp = Op.getOperand(2);
975   ISD::CondCode CC = cast<CondCodeSDNode>(Cmp)->get();
976
977   EVT VT = Op.getValueType();
978   EVT LHSVT = LHS.getValueType();
979   EVT RHSVT = RHS.getValueType();
980
981   if (LHSVT == MVT::v2i16) {
982     assert(ISD::isSignedIntSetCC(CC) || ISD::isUnsignedIntSetCC(CC));
983     unsigned ExtOpc = ISD::isSignedIntSetCC(CC) ? ISD::SIGN_EXTEND
984                                                 : ISD::ZERO_EXTEND;
985     SDValue LX = DAG.getNode(ExtOpc, dl, MVT::v2i32, LHS);
986     SDValue RX = DAG.getNode(ExtOpc, dl, MVT::v2i32, RHS);
987     SDValue SC = DAG.getNode(ISD::SETCC, dl, MVT::v2i1, LX, RX, Cmp);
988     return SC;
989   }
990
991   // Treat all other vector types as legal.
992   if (VT.isVector())
993     return Op;
994
995   // Equals and not equals should use sign-extend, not zero-extend, since
996   // we can represent small negative values in the compare instructions.
997   // The LLVM default is to use zero-extend arbitrarily in these cases.
998   if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
999       (RHSVT == MVT::i8 || RHSVT == MVT::i16) &&
1000       (LHSVT == MVT::i8 || LHSVT == MVT::i16)) {
1001     ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS);
1002     if (C && C->getAPIntValue().isNegative()) {
1003       LHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, LHS);
1004       RHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, RHS);
1005       return DAG.getNode(ISD::SETCC, dl, Op.getValueType(),
1006                          LHS, RHS, Op.getOperand(2));
1007     }
1008     if (isSExtFree(LHS) || isSExtFree(RHS)) {
1009       LHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, LHS);
1010       RHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, RHS);
1011       return DAG.getNode(ISD::SETCC, dl, Op.getValueType(),
1012                          LHS, RHS, Op.getOperand(2));
1013     }
1014   }
1015   return SDValue();
1016 }
1017
1018 SDValue HexagonTargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG)
1019       const {
1020   SDValue PredOp = Op.getOperand(0);
1021   SDValue Op1 = Op.getOperand(1), Op2 = Op.getOperand(2);
1022   EVT OpVT = Op1.getValueType();
1023   SDLoc DL(Op);
1024
1025   if (OpVT == MVT::v2i16) {
1026     SDValue X1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i32, Op1);
1027     SDValue X2 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i32, Op2);
1028     SDValue SL = DAG.getNode(ISD::VSELECT, DL, MVT::v2i32, PredOp, X1, X2);
1029     SDValue TR = DAG.getNode(ISD::TRUNCATE, DL, MVT::v2i16, SL);
1030     return TR;
1031   }
1032
1033   return SDValue();
1034 }
1035
1036 // Handle only specific vector loads.
1037 SDValue HexagonTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1038   EVT VT = Op.getValueType();
1039   SDLoc DL(Op);
1040   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
1041   SDValue Chain = LoadNode->getChain();
1042   SDValue Ptr = Op.getOperand(1);
1043   SDValue LoweredLoad;
1044   SDValue Result;
1045   SDValue Base = LoadNode->getBasePtr();
1046   ISD::LoadExtType Ext = LoadNode->getExtensionType();
1047   unsigned Alignment = LoadNode->getAlignment();
1048   SDValue LoadChain;
1049
1050   if(Ext == ISD::NON_EXTLOAD)
1051     Ext = ISD::ZEXTLOAD;
1052
1053   if (VT == MVT::v4i16) {
1054     if (Alignment == 2) {
1055       SDValue Loads[4];
1056       // Base load.
1057       Loads[0] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Base,
1058                                 LoadNode->getPointerInfo(), MVT::i16,
1059                                 LoadNode->isVolatile(),
1060                                 LoadNode->isNonTemporal(),
1061                                 LoadNode->isInvariant(),
1062                                 Alignment);
1063       // Base+2 load.
1064       SDValue Increment = DAG.getConstant(2, MVT::i32);
1065       Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
1066       Loads[1] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
1067                                 LoadNode->getPointerInfo(), MVT::i16,
1068                                 LoadNode->isVolatile(),
1069                                 LoadNode->isNonTemporal(),
1070                                 LoadNode->isInvariant(),
1071                                 Alignment);
1072       // SHL 16, then OR base and base+2.
1073       SDValue ShiftAmount = DAG.getConstant(16, MVT::i32);
1074       SDValue Tmp1 = DAG.getNode(ISD::SHL, DL, MVT::i32, Loads[1], ShiftAmount);
1075       SDValue Tmp2 = DAG.getNode(ISD::OR, DL, MVT::i32, Tmp1, Loads[0]);
1076       // Base + 4.
1077       Increment = DAG.getConstant(4, MVT::i32);
1078       Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
1079       Loads[2] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
1080                                 LoadNode->getPointerInfo(), MVT::i16,
1081                                 LoadNode->isVolatile(),
1082                                 LoadNode->isNonTemporal(),
1083                                 LoadNode->isInvariant(),
1084                                 Alignment);
1085       // Base + 6.
1086       Increment = DAG.getConstant(6, MVT::i32);
1087       Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
1088       Loads[3] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
1089                                 LoadNode->getPointerInfo(), MVT::i16,
1090                                 LoadNode->isVolatile(),
1091                                 LoadNode->isNonTemporal(),
1092                                 LoadNode->isInvariant(),
1093                                 Alignment);
1094       // SHL 16, then OR base+4 and base+6.
1095       Tmp1 = DAG.getNode(ISD::SHL, DL, MVT::i32, Loads[3], ShiftAmount);
1096       SDValue Tmp4 = DAG.getNode(ISD::OR, DL, MVT::i32, Tmp1, Loads[2]);
1097       // Combine to i64. This could be optimised out later if we can
1098       // affect reg allocation of this code.
1099       Result = DAG.getNode(HexagonISD::COMBINE, DL, MVT::i64, Tmp4, Tmp2);
1100       LoadChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1101                               Loads[0].getValue(1), Loads[1].getValue(1),
1102                               Loads[2].getValue(1), Loads[3].getValue(1));
1103     } else {
1104       // Perform default type expansion.
1105       Result = DAG.getLoad(MVT::i64, DL, Chain, Ptr, LoadNode->getPointerInfo(),
1106                            LoadNode->isVolatile(), LoadNode->isNonTemporal(),
1107                           LoadNode->isInvariant(), LoadNode->getAlignment());
1108       LoadChain = Result.getValue(1);
1109     }
1110   } else
1111     llvm_unreachable("Custom lowering unsupported load");
1112
1113   Result = DAG.getNode(ISD::BITCAST, DL, VT, Result);
1114   // Since we pretend to lower a load, we need the original chain
1115   // info attached to the result.
1116   SDValue Ops[] = { Result, LoadChain };
1117
1118   return DAG.getMergeValues(Ops, DL);
1119 }
1120
1121
1122 SDValue
1123 HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
1124   EVT ValTy = Op.getValueType();
1125   SDLoc dl(Op);
1126   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1127   SDValue Res;
1128   if (CP->isMachineConstantPoolEntry())
1129     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), ValTy,
1130                                     CP->getAlignment());
1131   else
1132     Res = DAG.getTargetConstantPool(CP->getConstVal(), ValTy,
1133                                     CP->getAlignment());
1134   return DAG.getNode(HexagonISD::CONST32, dl, ValTy, Res);
1135 }
1136
1137 SDValue
1138 HexagonTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
1139   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
1140   MachineFunction &MF = DAG.getMachineFunction();
1141   MachineFrameInfo *MFI = MF.getFrameInfo();
1142   MFI->setReturnAddressIsTaken(true);
1143
1144   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1145     return SDValue();
1146
1147   EVT VT = Op.getValueType();
1148   SDLoc dl(Op);
1149   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1150   if (Depth) {
1151     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1152     SDValue Offset = DAG.getConstant(4, MVT::i32);
1153     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
1154                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
1155                        MachinePointerInfo(), false, false, false, 0);
1156   }
1157
1158   // Return LR, which contains the return address. Mark it an implicit live-in.
1159   unsigned Reg = MF.addLiveIn(TRI->getRARegister(), getRegClassFor(MVT::i32));
1160   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
1161 }
1162
1163 SDValue
1164 HexagonTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1165   const HexagonRegisterInfo *TRI = Subtarget->getRegisterInfo();
1166   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1167   MFI->setFrameAddressIsTaken(true);
1168
1169   EVT VT = Op.getValueType();
1170   SDLoc dl(Op);
1171   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1172   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1173                                          TRI->getFrameRegister(), VT);
1174   while (Depth--)
1175     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1176                             MachinePointerInfo(),
1177                             false, false, false, 0);
1178   return FrameAddr;
1179 }
1180
1181 SDValue HexagonTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1182                                                  SelectionDAG& DAG) const {
1183   SDLoc dl(Op);
1184   return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
1185 }
1186
1187
1188 SDValue HexagonTargetLowering::LowerGLOBALADDRESS(SDValue Op,
1189                                                   SelectionDAG &DAG) const {
1190   SDValue Result;
1191   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1192   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
1193   SDLoc dl(Op);
1194   Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
1195
1196   const HexagonTargetObjectFile *TLOF =
1197       static_cast<const HexagonTargetObjectFile *>(
1198           getTargetMachine().getObjFileLowering());
1199   if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine())) {
1200     return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), Result);
1201   }
1202
1203   return DAG.getNode(HexagonISD::CONST32, dl, getPointerTy(), Result);
1204 }
1205
1206 // Specifies that for loads and stores VT can be promoted to PromotedLdStVT.
1207 void HexagonTargetLowering::promoteLdStType(EVT VT, EVT PromotedLdStVT) {
1208   if (VT != PromotedLdStVT) {
1209     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
1210     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(),
1211                       PromotedLdStVT.getSimpleVT());
1212
1213     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
1214     AddPromotedToType(ISD::STORE, VT.getSimpleVT(),
1215                       PromotedLdStVT.getSimpleVT());
1216   }
1217 }
1218
1219 SDValue
1220 HexagonTargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1221   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1222   SDValue BA_SD =  DAG.getTargetBlockAddress(BA, MVT::i32);
1223   SDLoc dl(Op);
1224   return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), BA_SD);
1225 }
1226
1227 //===----------------------------------------------------------------------===//
1228 // TargetLowering Implementation
1229 //===----------------------------------------------------------------------===//
1230
1231 HexagonTargetLowering::HexagonTargetLowering(const TargetMachine &TM,
1232                                              const HexagonSubtarget &STI)
1233     : TargetLowering(TM), Subtarget(&STI) {
1234
1235   // Set up the register classes.
1236   addRegisterClass(MVT::v2i1, &Hexagon::PredRegsRegClass);  // bbbbaaaa
1237   addRegisterClass(MVT::v4i1, &Hexagon::PredRegsRegClass);  // ddccbbaa
1238   addRegisterClass(MVT::v8i1, &Hexagon::PredRegsRegClass);  // hgfedcba
1239   addRegisterClass(MVT::i32, &Hexagon::IntRegsRegClass);
1240   addRegisterClass(MVT::v4i8, &Hexagon::IntRegsRegClass);
1241   addRegisterClass(MVT::v2i16, &Hexagon::IntRegsRegClass);
1242   promoteLdStType(MVT::v4i8, MVT::i32);
1243   promoteLdStType(MVT::v2i16, MVT::i32);
1244
1245   if (Subtarget->hasV5TOps()) {
1246     addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
1247     addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
1248   }
1249
1250   addRegisterClass(MVT::i64, &Hexagon::DoubleRegsRegClass);
1251   addRegisterClass(MVT::v8i8, &Hexagon::DoubleRegsRegClass);
1252   addRegisterClass(MVT::v4i16, &Hexagon::DoubleRegsRegClass);
1253   addRegisterClass(MVT::v2i32, &Hexagon::DoubleRegsRegClass);
1254   promoteLdStType(MVT::v8i8, MVT::i64);
1255
1256   // Custom lower v4i16 load only. Let v4i16 store to be
1257   // promoted for now.
1258   setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
1259   AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::i64);
1260   setOperationAction(ISD::STORE, MVT::v4i16, Promote);
1261   AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::i64);
1262   promoteLdStType(MVT::v2i32, MVT::i64);
1263
1264   for (unsigned i = (unsigned) MVT::FIRST_VECTOR_VALUETYPE;
1265        i <= (unsigned) MVT::LAST_VECTOR_VALUETYPE; ++i) {
1266     MVT::SimpleValueType VT = (MVT::SimpleValueType) i;
1267
1268     // Hexagon does not have support for the following operations,
1269     // so they need to be expanded.
1270     setOperationAction(ISD::SELECT, VT, Expand);
1271     setOperationAction(ISD::SDIV, VT, Expand);
1272     setOperationAction(ISD::SREM, VT, Expand);
1273     setOperationAction(ISD::UDIV, VT, Expand);
1274     setOperationAction(ISD::UREM, VT, Expand);
1275     setOperationAction(ISD::ROTL, VT, Expand);
1276     setOperationAction(ISD::ROTR, VT, Expand);
1277     setOperationAction(ISD::FDIV, VT, Expand);
1278     setOperationAction(ISD::FNEG, VT, Expand);
1279     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1280     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1281     setOperationAction(ISD::UDIVREM, VT, Expand);
1282     setOperationAction(ISD::SDIVREM, VT, Expand);
1283     setOperationAction(ISD::FPOW, VT, Expand);
1284     setOperationAction(ISD::CTPOP, VT, Expand);
1285     setOperationAction(ISD::CTLZ, VT, Expand);
1286     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
1287     setOperationAction(ISD::CTTZ, VT, Expand);
1288     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
1289
1290     // Expand all any extend loads.
1291     for (unsigned j = (unsigned) MVT::FIRST_VECTOR_VALUETYPE;
1292                   j <= (unsigned) MVT::LAST_VECTOR_VALUETYPE; ++j)
1293       setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType) j, VT, Expand);
1294
1295     // Expand all trunc stores.
1296     for (unsigned TargetVT = (unsigned) MVT::FIRST_VECTOR_VALUETYPE;
1297          TargetVT <= (unsigned) MVT::LAST_VECTOR_VALUETYPE; ++TargetVT)
1298       setTruncStoreAction(VT, (MVT::SimpleValueType) TargetVT, Expand);
1299
1300     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
1301     setOperationAction(ISD::ConstantPool, VT, Expand);
1302     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
1303     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
1304     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
1305     setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
1306     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Expand);
1307     setOperationAction(ISD::INSERT_SUBVECTOR, VT, Expand);
1308     setOperationAction(ISD::CONCAT_VECTORS, VT, Expand);
1309     setOperationAction(ISD::SRA, VT, Custom);
1310     setOperationAction(ISD::SHL, VT, Custom);
1311     setOperationAction(ISD::SRL, VT, Custom);
1312
1313     if (!isTypeLegal(VT))
1314       continue;
1315
1316     setOperationAction(ISD::ADD, VT, Legal);
1317     setOperationAction(ISD::SUB, VT, Legal);
1318     setOperationAction(ISD::MUL, VT, Legal);
1319
1320     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1321     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1322     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1323     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1324     setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1325     setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1326   }
1327
1328   setOperationAction(ISD::SETCC, MVT::v2i16, Custom);
1329   setOperationAction(ISD::VSELECT, MVT::v2i16, Custom);
1330   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
1331   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
1332
1333   setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1334
1335   addRegisterClass(MVT::i1, &Hexagon::PredRegsRegClass);
1336
1337   computeRegisterProperties(Subtarget->getRegisterInfo());
1338
1339   // Align loop entry
1340   setPrefLoopAlignment(4);
1341
1342   // Limits for inline expansion of memcpy/memmove
1343   MaxStoresPerMemcpy = 6;
1344   MaxStoresPerMemmove = 6;
1345
1346   //
1347   // Library calls for unsupported operations
1348   //
1349
1350   setLibcallName(RTLIB::SINTTOFP_I128_F64, "__hexagon_floattidf");
1351   setLibcallName(RTLIB::SINTTOFP_I128_F32, "__hexagon_floattisf");
1352
1353   setLibcallName(RTLIB::FPTOUINT_F32_I128, "__hexagon_fixunssfti");
1354   setLibcallName(RTLIB::FPTOUINT_F64_I128, "__hexagon_fixunsdfti");
1355
1356   setLibcallName(RTLIB::FPTOSINT_F32_I128, "__hexagon_fixsfti");
1357   setLibcallName(RTLIB::FPTOSINT_F64_I128, "__hexagon_fixdfti");
1358
1359   setLibcallName(RTLIB::SDIV_I32, "__hexagon_divsi3");
1360   setOperationAction(ISD::SDIV, MVT::i32, Expand);
1361   setLibcallName(RTLIB::SREM_I32, "__hexagon_umodsi3");
1362   setOperationAction(ISD::SREM, MVT::i32, Expand);
1363
1364   setLibcallName(RTLIB::SDIV_I64, "__hexagon_divdi3");
1365   setOperationAction(ISD::SDIV, MVT::i64, Expand);
1366   setLibcallName(RTLIB::SREM_I64, "__hexagon_moddi3");
1367   setOperationAction(ISD::SREM, MVT::i64, Expand);
1368
1369   setLibcallName(RTLIB::UDIV_I32, "__hexagon_udivsi3");
1370   setOperationAction(ISD::UDIV, MVT::i32, Expand);
1371
1372   setLibcallName(RTLIB::UDIV_I64, "__hexagon_udivdi3");
1373   setOperationAction(ISD::UDIV, MVT::i64, Expand);
1374
1375   setLibcallName(RTLIB::UREM_I32, "__hexagon_umodsi3");
1376   setOperationAction(ISD::UREM, MVT::i32, Expand);
1377
1378   setLibcallName(RTLIB::UREM_I64, "__hexagon_umoddi3");
1379   setOperationAction(ISD::UREM, MVT::i64, Expand);
1380
1381   setLibcallName(RTLIB::DIV_F32, "__hexagon_divsf3");
1382   setOperationAction(ISD::FDIV, MVT::f32, Expand);
1383
1384   setLibcallName(RTLIB::DIV_F64, "__hexagon_divdf3");
1385   setOperationAction(ISD::FDIV, MVT::f64, Expand);
1386
1387   setLibcallName(RTLIB::ADD_F64, "__hexagon_adddf3");
1388   setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
1389   setLibcallName(RTLIB::MUL_F64, "__hexagon_muldf3");
1390
1391   setOperationAction(ISD::FSQRT, MVT::f32, Expand);
1392   setOperationAction(ISD::FSQRT, MVT::f64, Expand);
1393   setOperationAction(ISD::FSIN, MVT::f32, Expand);
1394   setOperationAction(ISD::FSIN, MVT::f64, Expand);
1395
1396   if (Subtarget->hasV5TOps()) {
1397     // Hexagon V5 Support.
1398     setOperationAction(ISD::FADD, MVT::f32, Legal);
1399     setOperationAction(ISD::FADD, MVT::f64, Expand);
1400     setOperationAction(ISD::FSUB, MVT::f32, Legal);
1401     setOperationAction(ISD::FSUB, MVT::f64, Expand);
1402     setOperationAction(ISD::FMUL, MVT::f64, Expand);
1403     setOperationAction(ISD::FP_EXTEND, MVT::f32, Legal);
1404     setCondCodeAction(ISD::SETOEQ, MVT::f32, Legal);
1405     setCondCodeAction(ISD::SETOEQ, MVT::f64, Legal);
1406     setCondCodeAction(ISD::SETUEQ, MVT::f32, Legal);
1407     setCondCodeAction(ISD::SETUEQ, MVT::f64, Legal);
1408
1409     setCondCodeAction(ISD::SETOGE, MVT::f32, Legal);
1410     setCondCodeAction(ISD::SETOGE, MVT::f64, Legal);
1411     setCondCodeAction(ISD::SETUGE, MVT::f32, Legal);
1412     setCondCodeAction(ISD::SETUGE, MVT::f64, Legal);
1413
1414     setCondCodeAction(ISD::SETOGT, MVT::f32, Legal);
1415     setCondCodeAction(ISD::SETOGT, MVT::f64, Legal);
1416     setCondCodeAction(ISD::SETUGT, MVT::f32, Legal);
1417     setCondCodeAction(ISD::SETUGT, MVT::f64, Legal);
1418
1419     setCondCodeAction(ISD::SETOLE, MVT::f32, Legal);
1420     setCondCodeAction(ISD::SETOLE, MVT::f64, Legal);
1421     setCondCodeAction(ISD::SETOLT, MVT::f32, Legal);
1422     setCondCodeAction(ISD::SETOLT, MVT::f64, Legal);
1423
1424     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
1425     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
1426
1427     setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
1428     setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
1429     setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
1430     setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
1431
1432     setOperationAction(ISD::FP_TO_UINT, MVT::i8, Promote);
1433     setOperationAction(ISD::FP_TO_SINT, MVT::i8, Promote);
1434     setOperationAction(ISD::UINT_TO_FP, MVT::i8, Promote);
1435     setOperationAction(ISD::SINT_TO_FP, MVT::i8, Promote);
1436
1437     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
1438     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
1439     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
1440     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
1441
1442     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1443     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1444     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1445     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1446
1447     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1448     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1449     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1450     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1451
1452     setOperationAction(ISD::FABS, MVT::f32, Legal);
1453     setOperationAction(ISD::FABS, MVT::f64, Expand);
1454
1455     setOperationAction(ISD::FNEG, MVT::f32, Legal);
1456     setOperationAction(ISD::FNEG, MVT::f64, Expand);
1457   } else {
1458
1459     // Expand fp<->uint.
1460     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Expand);
1461     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
1462
1463     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
1464     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
1465
1466     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__hexagon_floatdisf");
1467     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__hexagon_floatundisf");
1468
1469     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__hexagon_floatunsisf");
1470     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__hexagon_floatsisf");
1471
1472     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__hexagon_floatdidf");
1473     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__hexagon_floatundidf");
1474
1475     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__hexagon_floatunsidf");
1476     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__hexagon_floatsidf");
1477
1478     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__hexagon_fixunssfsi");
1479     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__hexagon_fixunssfdi");
1480
1481     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__hexagon_fixdfdi");
1482     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__hexagon_fixsfdi");
1483
1484     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__hexagon_fixunsdfsi");
1485     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__hexagon_fixunsdfdi");
1486
1487
1488     setLibcallName(RTLIB::ADD_F32, "__hexagon_addsf3");
1489     setOperationAction(ISD::FADD, MVT::f32, Expand);
1490     setOperationAction(ISD::FADD, MVT::f64, Expand);
1491
1492     setLibcallName(RTLIB::SUB_F32, "__hexagon_subsf3");
1493     setOperationAction(ISD::FSUB, MVT::f32, Expand);
1494     setOperationAction(ISD::FSUB, MVT::f64, Expand);
1495
1496     setLibcallName(RTLIB::FPEXT_F32_F64, "__hexagon_extendsfdf2");
1497     setOperationAction(ISD::FP_EXTEND, MVT::f32, Expand);
1498
1499     setLibcallName(RTLIB::OEQ_F32, "__hexagon_eqsf2");
1500     setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
1501
1502     setLibcallName(RTLIB::OEQ_F64, "__hexagon_eqdf2");
1503     setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
1504
1505     setLibcallName(RTLIB::OGE_F32, "__hexagon_gesf2");
1506     setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
1507
1508     setLibcallName(RTLIB::OGE_F64, "__hexagon_gedf2");
1509     setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
1510
1511     setLibcallName(RTLIB::OGT_F32, "__hexagon_gtsf2");
1512     setCondCodeAction(ISD::SETOGT, MVT::f32, Expand);
1513
1514     setLibcallName(RTLIB::OGT_F64, "__hexagon_gtdf2");
1515     setCondCodeAction(ISD::SETOGT, MVT::f64, Expand);
1516
1517     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__hexagon_fixdfsi");
1518     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Expand);
1519
1520     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__hexagon_fixsfsi");
1521     setOperationAction(ISD::FP_TO_SINT, MVT::f32, Expand);
1522
1523     setLibcallName(RTLIB::OLE_F64, "__hexagon_ledf2");
1524     setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
1525
1526     setLibcallName(RTLIB::OLE_F32, "__hexagon_lesf2");
1527     setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
1528
1529     setLibcallName(RTLIB::OLT_F64, "__hexagon_ltdf2");
1530     setCondCodeAction(ISD::SETOLT, MVT::f64, Expand);
1531
1532     setLibcallName(RTLIB::OLT_F32, "__hexagon_ltsf2");
1533     setCondCodeAction(ISD::SETOLT, MVT::f32, Expand);
1534
1535     setOperationAction(ISD::FMUL, MVT::f64, Expand);
1536
1537     setLibcallName(RTLIB::MUL_F32, "__hexagon_mulsf3");
1538     setOperationAction(ISD::MUL, MVT::f32, Expand);
1539
1540     setLibcallName(RTLIB::UNE_F64, "__hexagon_nedf2");
1541     setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
1542
1543     setLibcallName(RTLIB::UNE_F32, "__hexagon_nesf2");
1544
1545     setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
1546     setOperationAction(ISD::SUB, MVT::f64, Expand);
1547
1548     setLibcallName(RTLIB::SUB_F32, "__hexagon_subsf3");
1549     setOperationAction(ISD::SUB, MVT::f32, Expand);
1550
1551     setLibcallName(RTLIB::FPROUND_F64_F32, "__hexagon_truncdfsf2");
1552     setOperationAction(ISD::FP_ROUND, MVT::f64, Expand);
1553
1554     setLibcallName(RTLIB::UO_F64, "__hexagon_unorddf2");
1555     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
1556
1557     setLibcallName(RTLIB::O_F64, "__hexagon_unorddf2");
1558     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
1559
1560     setLibcallName(RTLIB::O_F32, "__hexagon_unordsf2");
1561     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
1562
1563     setLibcallName(RTLIB::UO_F32, "__hexagon_unordsf2");
1564     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
1565
1566     setOperationAction(ISD::FABS, MVT::f32, Expand);
1567     setOperationAction(ISD::FABS, MVT::f64, Expand);
1568     setOperationAction(ISD::FNEG, MVT::f32, Expand);
1569     setOperationAction(ISD::FNEG, MVT::f64, Expand);
1570   }
1571
1572   setLibcallName(RTLIB::SREM_I32, "__hexagon_modsi3");
1573   setOperationAction(ISD::SREM, MVT::i32, Expand);
1574
1575   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
1576   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
1577   setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1578   setIndexedLoadAction(ISD::POST_INC, MVT::i64, Legal);
1579
1580   setIndexedStoreAction(ISD::POST_INC, MVT::i8, Legal);
1581   setIndexedStoreAction(ISD::POST_INC, MVT::i16, Legal);
1582   setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1583   setIndexedStoreAction(ISD::POST_INC, MVT::i64, Legal);
1584
1585   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
1586
1587   // Turn FP extload into load/fextend.
1588   for (MVT VT : MVT::fp_valuetypes())
1589     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1590
1591   // No extending loads from i32.
1592   for (MVT VT : MVT::integer_valuetypes()) {
1593     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
1594     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
1595     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
1596   }
1597
1598   // Turn FP truncstore into trunc + store.
1599   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1600
1601   // Custom legalize GlobalAddress nodes into CONST32.
1602   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1603   setOperationAction(ISD::GlobalAddress, MVT::i8, Custom);
1604   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1605   // Truncate action?
1606   setOperationAction(ISD::TRUNCATE, MVT::i64, Expand);
1607
1608   // Hexagon doesn't have sext_inreg, replace them with shl/sra.
1609   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1610
1611   // Hexagon has no REM or DIVREM operations.
1612   setOperationAction(ISD::UREM, MVT::i32, Expand);
1613   setOperationAction(ISD::SREM, MVT::i32, Expand);
1614   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1615   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1616   setOperationAction(ISD::SREM, MVT::i64, Expand);
1617   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
1618   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
1619
1620   setOperationAction(ISD::BSWAP, MVT::i64, Expand);
1621
1622   // Lower SELECT_CC to SETCC and SELECT.
1623   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1624   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
1625   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
1626
1627   if (Subtarget->hasV5TOps()) {
1628
1629     // We need to make the operation type of SELECT node to be Custom,
1630     // such that we don't go into the infinite loop of
1631     // select ->  setcc -> select_cc -> select loop.
1632     setOperationAction(ISD::SELECT, MVT::f32, Custom);
1633     setOperationAction(ISD::SELECT, MVT::f64, Custom);
1634
1635     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
1636     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
1637
1638   } else {
1639
1640     // Hexagon has no select or setcc: expand to SELECT_CC.
1641     setOperationAction(ISD::SELECT, MVT::f32, Expand);
1642     setOperationAction(ISD::SELECT, MVT::f64, Expand);
1643   }
1644
1645   // Hexagon needs to optimize cases with negative constants.
1646   setOperationAction(ISD::SETCC, MVT::i16, Custom);
1647   setOperationAction(ISD::SETCC, MVT::i8, Custom);
1648
1649   if (EmitJumpTables) {
1650     setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1651   } else {
1652     setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1653   }
1654   // Increase jump tables cutover to 5, was 4.
1655   setMinimumJumpTableEntries(5);
1656
1657   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
1658   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
1659   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1660   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
1661   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
1662
1663   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1664
1665   setOperationAction(ISD::FSIN, MVT::f64, Expand);
1666   setOperationAction(ISD::FCOS, MVT::f64, Expand);
1667   setOperationAction(ISD::FREM, MVT::f64, Expand);
1668   setOperationAction(ISD::FSIN, MVT::f32, Expand);
1669   setOperationAction(ISD::FCOS, MVT::f32, Expand);
1670   setOperationAction(ISD::FREM, MVT::f32, Expand);
1671   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1672   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1673
1674   // In V4, we have double word add/sub with carry. The problem with
1675   // modelling this instruction is that it produces 2 results - Rdd and Px.
1676   // To model update of Px, we will have to use Defs[p0..p3] which will
1677   // cause any predicate live range to spill. So, we pretend we dont't
1678   // have these instructions.
1679   setOperationAction(ISD::ADDE, MVT::i8, Expand);
1680   setOperationAction(ISD::ADDE, MVT::i16, Expand);
1681   setOperationAction(ISD::ADDE, MVT::i32, Expand);
1682   setOperationAction(ISD::ADDE, MVT::i64, Expand);
1683   setOperationAction(ISD::SUBE, MVT::i8, Expand);
1684   setOperationAction(ISD::SUBE, MVT::i16, Expand);
1685   setOperationAction(ISD::SUBE, MVT::i32, Expand);
1686   setOperationAction(ISD::SUBE, MVT::i64, Expand);
1687   setOperationAction(ISD::ADDC, MVT::i8, Expand);
1688   setOperationAction(ISD::ADDC, MVT::i16, Expand);
1689   setOperationAction(ISD::ADDC, MVT::i32, Expand);
1690   setOperationAction(ISD::ADDC, MVT::i64, Expand);
1691   setOperationAction(ISD::SUBC, MVT::i8, Expand);
1692   setOperationAction(ISD::SUBC, MVT::i16, Expand);
1693   setOperationAction(ISD::SUBC, MVT::i32, Expand);
1694   setOperationAction(ISD::SUBC, MVT::i64, Expand);
1695
1696   // Only add and sub that detect overflow are the saturating ones.
1697   for (MVT VT : MVT::integer_valuetypes()) {
1698     setOperationAction(ISD::UADDO, VT, Expand);
1699     setOperationAction(ISD::SADDO, VT, Expand);
1700     setOperationAction(ISD::USUBO, VT, Expand);
1701     setOperationAction(ISD::SSUBO, VT, Expand);
1702   }
1703
1704   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1705   setOperationAction(ISD::CTPOP, MVT::i64, Expand);
1706   setOperationAction(ISD::CTTZ, MVT::i32, Expand);
1707   setOperationAction(ISD::CTTZ, MVT::i64, Expand);
1708   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1709   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
1710   setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1711   setOperationAction(ISD::CTLZ, MVT::i64, Expand);
1712   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1713   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
1714
1715   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1716   setOperationAction(ISD::ROTR, MVT::i32, Expand);
1717   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1718   setOperationAction(ISD::ROTL, MVT::i64, Expand);
1719   setOperationAction(ISD::ROTR, MVT::i64, Expand);
1720   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
1721   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
1722   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
1723   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
1724
1725   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1726   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1727   setOperationAction(ISD::FPOW, MVT::f64, Expand);
1728   setOperationAction(ISD::FPOW, MVT::f32, Expand);
1729
1730   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1731   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1732   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1733
1734   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1735   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1736
1737   setOperationAction(ISD::MULHS, MVT::i64, Expand);
1738   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
1739   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
1740
1741   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
1742
1743   setExceptionPointerRegister(Hexagon::R0);
1744   setExceptionSelectorRegister(Hexagon::R1);
1745
1746   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1747   setOperationAction(ISD::VASTART, MVT::Other, Custom);
1748
1749   // Use the default implementation.
1750   setOperationAction(ISD::VAARG, MVT::Other, Expand);
1751   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1752   setOperationAction(ISD::VAEND, MVT::Other, Expand);
1753   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1754   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1755
1756   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1757   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
1758
1759   setMinFunctionAlignment(2);
1760
1761   // Needed for DYNAMIC_STACKALLOC expansion.
1762   const HexagonRegisterInfo *QRI = Subtarget->getRegisterInfo();
1763   setStackPointerRegisterToSaveRestore(QRI->getStackRegister());
1764   setSchedulingPreference(Sched::VLIW);
1765 }
1766
1767 const char*
1768 HexagonTargetLowering::getTargetNodeName(unsigned Opcode) const {
1769   switch (Opcode) {
1770   default: return nullptr;
1771   case HexagonISD::CONST32:     return "HexagonISD::CONST32";
1772   case HexagonISD::CONST32_GP: return "HexagonISD::CONST32_GP";
1773   case HexagonISD::CONST32_Int_Real: return "HexagonISD::CONST32_Int_Real";
1774   case HexagonISD::ALLOCA:      return "HexagonISD::ALLOCA";
1775   case HexagonISD::CMPICC:      return "HexagonISD::CMPICC";
1776   case HexagonISD::CMPFCC:      return "HexagonISD::CMPFCC";
1777   case HexagonISD::BRICC:       return "HexagonISD::BRICC";
1778   case HexagonISD::BRFCC:       return "HexagonISD::BRFCC";
1779   case HexagonISD::SELECT_ICC:  return "HexagonISD::SELECT_ICC";
1780   case HexagonISD::SELECT_FCC:  return "HexagonISD::SELECT_FCC";
1781   case HexagonISD::Hi:          return "HexagonISD::Hi";
1782   case HexagonISD::Lo:          return "HexagonISD::Lo";
1783   case HexagonISD::JT: return "HexagonISD::JT";
1784   case HexagonISD::CP: return "HexagonISD::CP";
1785   case HexagonISD::POPCOUNT: return "HexagonISD::POPCOUNT";
1786   case HexagonISD::COMBINE: return "HexagonISD::COMBINE";
1787   case HexagonISD::PACKHL: return "HexagonISD::PACKHL";
1788   case HexagonISD::VSPLATB: return "HexagonISD::VSPLTB";
1789   case HexagonISD::VSPLATH: return "HexagonISD::VSPLATH";
1790   case HexagonISD::SHUFFEB: return "HexagonISD::SHUFFEB";
1791   case HexagonISD::SHUFFEH: return "HexagonISD::SHUFFEH";
1792   case HexagonISD::SHUFFOB: return "HexagonISD::SHUFFOB";
1793   case HexagonISD::SHUFFOH: return "HexagonISD::SHUFFOH";
1794   case HexagonISD::VSXTBH: return "HexagonISD::VSXTBH";
1795   case HexagonISD::VSXTBW: return "HexagonISD::VSXTBW";
1796   case HexagonISD::VSRAW: return "HexagonISD::VSRAW";
1797   case HexagonISD::VSRAH: return "HexagonISD::VSRAH";
1798   case HexagonISD::VSRLW: return "HexagonISD::VSRLW";
1799   case HexagonISD::VSRLH: return "HexagonISD::VSRLH";
1800   case HexagonISD::VSHLW: return "HexagonISD::VSHLW";
1801   case HexagonISD::VSHLH: return "HexagonISD::VSHLH";
1802   case HexagonISD::VCMPBEQ: return "HexagonISD::VCMPBEQ";
1803   case HexagonISD::VCMPBGT: return "HexagonISD::VCMPBGT";
1804   case HexagonISD::VCMPBGTU: return "HexagonISD::VCMPBGTU";
1805   case HexagonISD::VCMPHEQ: return "HexagonISD::VCMPHEQ";
1806   case HexagonISD::VCMPHGT: return "HexagonISD::VCMPHGT";
1807   case HexagonISD::VCMPHGTU: return "HexagonISD::VCMPHGTU";
1808   case HexagonISD::VCMPWEQ: return "HexagonISD::VCMPWEQ";
1809   case HexagonISD::VCMPWGT: return "HexagonISD::VCMPWGT";
1810   case HexagonISD::VCMPWGTU: return "HexagonISD::VCMPWGTU";
1811   case HexagonISD::INSERT_ri: return "HexagonISD::INSERT_ri";
1812   case HexagonISD::INSERT_rd: return "HexagonISD::INSERT_rd";
1813   case HexagonISD::INSERT_riv: return "HexagonISD::INSERT_riv";
1814   case HexagonISD::INSERT_rdv: return "HexagonISD::INSERT_rdv";
1815   case HexagonISD::EXTRACTU_ri: return "HexagonISD::EXTRACTU_ri";
1816   case HexagonISD::EXTRACTU_rd: return "HexagonISD::EXTRACTU_rd";
1817   case HexagonISD::EXTRACTU_riv: return "HexagonISD::EXTRACTU_riv";
1818   case HexagonISD::EXTRACTU_rdv: return "HexagonISD::EXTRACTU_rdv";
1819   case HexagonISD::FTOI:        return "HexagonISD::FTOI";
1820   case HexagonISD::ITOF:        return "HexagonISD::ITOF";
1821   case HexagonISD::CALLv3:      return "HexagonISD::CALLv3";
1822   case HexagonISD::CALLv3nr:    return "HexagonISD::CALLv3nr";
1823   case HexagonISD::CALLR:       return "HexagonISD::CALLR";
1824   case HexagonISD::RET_FLAG:    return "HexagonISD::RET_FLAG";
1825   case HexagonISD::BR_JT:       return "HexagonISD::BR_JT";
1826   case HexagonISD::TC_RETURN:   return "HexagonISD::TC_RETURN";
1827   case HexagonISD::EH_RETURN: return "HexagonISD::EH_RETURN";
1828   }
1829 }
1830
1831 bool
1832 HexagonTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
1833   EVT MTy1 = EVT::getEVT(Ty1);
1834   EVT MTy2 = EVT::getEVT(Ty2);
1835   if (!MTy1.isSimple() || !MTy2.isSimple()) {
1836     return false;
1837   }
1838   return ((MTy1.getSimpleVT() == MVT::i64) && (MTy2.getSimpleVT() == MVT::i32));
1839 }
1840
1841 bool HexagonTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1842   if (!VT1.isSimple() || !VT2.isSimple()) {
1843     return false;
1844   }
1845   return ((VT1.getSimpleVT() == MVT::i64) && (VT2.getSimpleVT() == MVT::i32));
1846 }
1847
1848 // shouldExpandBuildVectorWithShuffles
1849 // Should we expand the build vector with shuffles?
1850 bool
1851 HexagonTargetLowering::shouldExpandBuildVectorWithShuffles(EVT VT,
1852                                   unsigned DefinedValues) const {
1853
1854   // Hexagon vector shuffle operates on element sizes of bytes or halfwords
1855   EVT EltVT = VT.getVectorElementType();
1856   int EltBits = EltVT.getSizeInBits();
1857   if ((EltBits != 8) && (EltBits != 16))
1858     return false;
1859
1860   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
1861 }
1862
1863 // LowerVECTOR_SHUFFLE - Lower a vector shuffle (V1, V2, V3).  V1 and
1864 // V2 are the two vectors to select data from, V3 is the permutation.
1865 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
1866   const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
1867   SDValue V1 = Op.getOperand(0);
1868   SDValue V2 = Op.getOperand(1);
1869   SDLoc dl(Op);
1870   EVT VT = Op.getValueType();
1871
1872   if (V2.getOpcode() == ISD::UNDEF)
1873     V2 = V1;
1874
1875   if (SVN->isSplat()) {
1876     int Lane = SVN->getSplatIndex();
1877     if (Lane == -1) Lane = 0;
1878
1879     // Test if V1 is a SCALAR_TO_VECTOR.
1880     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
1881       return createSplat(DAG, dl, VT, V1.getOperand(0));
1882
1883     // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
1884     // (and probably will turn into a SCALAR_TO_VECTOR once legalization
1885     // reaches it).
1886     if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
1887         !isa<ConstantSDNode>(V1.getOperand(0))) {
1888       bool IsScalarToVector = true;
1889       for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
1890         if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
1891           IsScalarToVector = false;
1892           break;
1893         }
1894       if (IsScalarToVector)
1895         return createSplat(DAG, dl, VT, V1.getOperand(0));
1896     }
1897     return createSplat(DAG, dl, VT, DAG.getConstant(Lane, MVT::i32));
1898   }
1899
1900   // FIXME: We need to support more general vector shuffles.  See
1901   // below the comment from the ARM backend that deals in the general
1902   // case with the vector shuffles.  For now, let expand handle these.
1903   return SDValue();
1904
1905   // If the shuffle is not directly supported and it has 4 elements, use
1906   // the PerfectShuffle-generated table to synthesize it from other shuffles.
1907 }
1908
1909 // If BUILD_VECTOR has same base element repeated several times,
1910 // report true.
1911 static bool isCommonSplatElement(BuildVectorSDNode *BVN) {
1912   unsigned NElts = BVN->getNumOperands();
1913   SDValue V0 = BVN->getOperand(0);
1914
1915   for (unsigned i = 1, e = NElts; i != e; ++i) {
1916     if (BVN->getOperand(i) != V0)
1917       return false;
1918   }
1919   return true;
1920 }
1921
1922 // LowerVECTOR_SHIFT - Lower a vector shift. Try to convert
1923 // <VT> = SHL/SRA/SRL <VT> by <VT> to Hexagon specific
1924 // <VT> = SHL/SRA/SRL <VT> by <IT/i32>.
1925 static SDValue LowerVECTOR_SHIFT(SDValue Op, SelectionDAG &DAG) {
1926   BuildVectorSDNode *BVN = 0;
1927   SDValue V1 = Op.getOperand(0);
1928   SDValue V2 = Op.getOperand(1);
1929   SDValue V3;
1930   SDLoc dl(Op);
1931   EVT VT = Op.getValueType();
1932
1933   if ((BVN = dyn_cast<BuildVectorSDNode>(V1.getNode())) &&
1934       isCommonSplatElement(BVN))
1935     V3 = V2;
1936   else if ((BVN = dyn_cast<BuildVectorSDNode>(V2.getNode())) &&
1937            isCommonSplatElement(BVN))
1938     V3 = V1;
1939   else
1940     return SDValue();
1941
1942   SDValue CommonSplat = BVN->getOperand(0);
1943   SDValue Result;
1944
1945   if (VT.getSimpleVT() == MVT::v4i16) {
1946     switch (Op.getOpcode()) {
1947     case ISD::SRA:
1948       Result = DAG.getNode(HexagonISD::VSRAH, dl, VT, V3, CommonSplat);
1949       break;
1950     case ISD::SHL:
1951       Result = DAG.getNode(HexagonISD::VSHLH, dl, VT, V3, CommonSplat);
1952       break;
1953     case ISD::SRL:
1954       Result = DAG.getNode(HexagonISD::VSRLH, dl, VT, V3, CommonSplat);
1955       break;
1956     default:
1957       return SDValue();
1958     }
1959   } else if (VT.getSimpleVT() == MVT::v2i32) {
1960     switch (Op.getOpcode()) {
1961     case ISD::SRA:
1962       Result = DAG.getNode(HexagonISD::VSRAW, dl, VT, V3, CommonSplat);
1963       break;
1964     case ISD::SHL:
1965       Result = DAG.getNode(HexagonISD::VSHLW, dl, VT, V3, CommonSplat);
1966       break;
1967     case ISD::SRL:
1968       Result = DAG.getNode(HexagonISD::VSRLW, dl, VT, V3, CommonSplat);
1969       break;
1970     default:
1971       return SDValue();
1972     }
1973   } else {
1974     return SDValue();
1975   }
1976
1977   return DAG.getNode(ISD::BITCAST, dl, VT, Result);
1978 }
1979
1980 SDValue
1981 HexagonTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
1982   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
1983   SDLoc dl(Op);
1984   EVT VT = Op.getValueType();
1985
1986   unsigned Size = VT.getSizeInBits();
1987
1988   // A vector larger than 64 bits cannot be represented in Hexagon.
1989   // Expand will split the vector.
1990   if (Size > 64)
1991     return SDValue();
1992
1993   APInt APSplatBits, APSplatUndef;
1994   unsigned SplatBitSize;
1995   bool HasAnyUndefs;
1996   unsigned NElts = BVN->getNumOperands();
1997
1998   // Try to generate a SPLAT instruction.
1999   if ((VT.getSimpleVT() == MVT::v4i8 || VT.getSimpleVT() == MVT::v4i16) &&
2000       (BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
2001                             HasAnyUndefs, 0, true) && SplatBitSize <= 16)) {
2002     unsigned SplatBits = APSplatBits.getZExtValue();
2003     int32_t SextVal = ((int32_t) (SplatBits << (32 - SplatBitSize)) >>
2004                        (32 - SplatBitSize));
2005     return createSplat(DAG, dl, VT, DAG.getConstant(SextVal, MVT::i32));
2006   }
2007
2008   // Try to generate COMBINE to build v2i32 vectors.
2009   if (VT.getSimpleVT() == MVT::v2i32) {
2010     SDValue V0 = BVN->getOperand(0);
2011     SDValue V1 = BVN->getOperand(1);
2012
2013     if (V0.getOpcode() == ISD::UNDEF)
2014       V0 = DAG.getConstant(0, MVT::i32);
2015     if (V1.getOpcode() == ISD::UNDEF)
2016       V1 = DAG.getConstant(0, MVT::i32);
2017
2018     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(V0);
2019     ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(V1);
2020     // If the element isn't a constant, it is in a register:
2021     // generate a COMBINE Register Register instruction.
2022     if (!C0 || !C1)
2023       return DAG.getNode(HexagonISD::COMBINE, dl, VT, V1, V0);
2024
2025     // If one of the operands is an 8 bit integer constant, generate
2026     // a COMBINE Immediate Immediate instruction.
2027     if (isInt<8>(C0->getSExtValue()) ||
2028         isInt<8>(C1->getSExtValue()))
2029       return DAG.getNode(HexagonISD::COMBINE, dl, VT, V1, V0);
2030   }
2031
2032   // Try to generate a S2_packhl to build v2i16 vectors.
2033   if (VT.getSimpleVT() == MVT::v2i16) {
2034     for (unsigned i = 0, e = NElts; i != e; ++i) {
2035       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
2036         continue;
2037       ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(BVN->getOperand(i));
2038       // If the element isn't a constant, it is in a register:
2039       // generate a S2_packhl instruction.
2040       if (!Cst) {
2041         SDValue pack = DAG.getNode(HexagonISD::PACKHL, dl, MVT::v4i16,
2042                                    BVN->getOperand(1), BVN->getOperand(0));
2043
2044         return DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl, MVT::v2i16,
2045                                           pack);
2046       }
2047     }
2048   }
2049
2050   // In the general case, generate a CONST32 or a CONST64 for constant vectors,
2051   // and insert_vector_elt for all the other cases.
2052   uint64_t Res = 0;
2053   unsigned EltSize = Size / NElts;
2054   SDValue ConstVal;
2055   uint64_t Mask = ~uint64_t(0ULL) >> (64 - EltSize);
2056   bool HasNonConstantElements = false;
2057
2058   for (unsigned i = 0, e = NElts; i != e; ++i) {
2059     // LLVM's BUILD_VECTOR operands are in Little Endian mode, whereas Hexagon's
2060     // combine, const64, etc. are Big Endian.
2061     unsigned OpIdx = NElts - i - 1;
2062     SDValue Operand = BVN->getOperand(OpIdx);
2063     if (Operand.getOpcode() == ISD::UNDEF)
2064       continue;
2065
2066     int64_t Val = 0;
2067     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Operand))
2068       Val = Cst->getSExtValue();
2069     else
2070       HasNonConstantElements = true;
2071
2072     Val &= Mask;
2073     Res = (Res << EltSize) | Val;
2074   }
2075
2076   if (Size == 64)
2077     ConstVal = DAG.getConstant(Res, MVT::i64);
2078   else
2079     ConstVal = DAG.getConstant(Res, MVT::i32);
2080
2081   // When there are non constant operands, add them with INSERT_VECTOR_ELT to
2082   // ConstVal, the constant part of the vector.
2083   if (HasNonConstantElements) {
2084     EVT EltVT = VT.getVectorElementType();
2085     SDValue Width = DAG.getConstant(EltVT.getSizeInBits(), MVT::i64);
2086     SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
2087                                   DAG.getConstant(32, MVT::i64));
2088
2089     for (unsigned i = 0, e = NElts; i != e; ++i) {
2090       // LLVM's BUILD_VECTOR operands are in Little Endian mode, whereas Hexagon
2091       // is Big Endian.
2092       unsigned OpIdx = NElts - i - 1;
2093       SDValue Operand = BVN->getOperand(OpIdx);
2094       if (isa<ConstantSDNode>(Operand))
2095         // This operand is already in ConstVal.
2096         continue;
2097
2098       if (VT.getSizeInBits() == 64 &&
2099           Operand.getValueType().getSizeInBits() == 32) {
2100         SDValue C = DAG.getConstant(0, MVT::i32);
2101         Operand = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, Operand);
2102       }
2103
2104       SDValue Idx = DAG.getConstant(OpIdx, MVT::i64);
2105       SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i64, Idx, Width);
2106       SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
2107       const SDValue Ops[] = {ConstVal, Operand, Combined};
2108
2109       if (VT.getSizeInBits() == 32)
2110         ConstVal = DAG.getNode(HexagonISD::INSERT_riv, dl, MVT::i32, Ops);
2111       else
2112         ConstVal = DAG.getNode(HexagonISD::INSERT_rdv, dl, MVT::i64, Ops);
2113     }
2114   }
2115
2116   return DAG.getNode(ISD::BITCAST, dl, VT, ConstVal);
2117 }
2118
2119 SDValue
2120 HexagonTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
2121                                            SelectionDAG &DAG) const {
2122   SDLoc dl(Op);
2123   EVT VT = Op.getValueType();
2124   unsigned NElts = Op.getNumOperands();
2125   SDValue Vec = Op.getOperand(0);
2126   EVT VecVT = Vec.getValueType();
2127   SDValue Width = DAG.getConstant(VecVT.getSizeInBits(), MVT::i64);
2128   SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
2129                                 DAG.getConstant(32, MVT::i64));
2130   SDValue ConstVal = DAG.getConstant(0, MVT::i64);
2131
2132   ConstantSDNode *W = dyn_cast<ConstantSDNode>(Width);
2133   ConstantSDNode *S = dyn_cast<ConstantSDNode>(Shifted);
2134
2135   if ((VecVT.getSimpleVT() == MVT::v2i16) && (NElts == 2) && W && S) {
2136     if ((W->getZExtValue() == 32) && ((S->getZExtValue() >> 32) == 32)) {
2137       // We are trying to concat two v2i16 to a single v4i16.
2138       SDValue Vec0 = Op.getOperand(1);
2139       SDValue Combined  = DAG.getNode(HexagonISD::COMBINE, dl, VT, Vec0, Vec);
2140       return DAG.getNode(ISD::BITCAST, dl, VT, Combined);
2141     }
2142   }
2143
2144   if ((VecVT.getSimpleVT() == MVT::v4i8) && (NElts == 2) && W && S) {
2145     if ((W->getZExtValue() == 32) && ((S->getZExtValue() >> 32) == 32)) {
2146       // We are trying to concat two v4i8 to a single v8i8.
2147       SDValue Vec0 = Op.getOperand(1);
2148       SDValue Combined  = DAG.getNode(HexagonISD::COMBINE, dl, VT, Vec0, Vec);
2149       return DAG.getNode(ISD::BITCAST, dl, VT, Combined);
2150     }
2151   }
2152
2153   for (unsigned i = 0, e = NElts; i != e; ++i) {
2154     unsigned OpIdx = NElts - i - 1;
2155     SDValue Operand = Op.getOperand(OpIdx);
2156
2157     if (VT.getSizeInBits() == 64 &&
2158         Operand.getValueType().getSizeInBits() == 32) {
2159       SDValue C = DAG.getConstant(0, MVT::i32);
2160       Operand = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, Operand);
2161     }
2162
2163     SDValue Idx = DAG.getConstant(OpIdx, MVT::i64);
2164     SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i64, Idx, Width);
2165     SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
2166     const SDValue Ops[] = {ConstVal, Operand, Combined};
2167
2168     if (VT.getSizeInBits() == 32)
2169       ConstVal = DAG.getNode(HexagonISD::INSERT_riv, dl, MVT::i32, Ops);
2170     else
2171       ConstVal = DAG.getNode(HexagonISD::INSERT_rdv, dl, MVT::i64, Ops);
2172   }
2173
2174   return DAG.getNode(ISD::BITCAST, dl, VT, ConstVal);
2175 }
2176
2177 SDValue
2178 HexagonTargetLowering::LowerEXTRACT_VECTOR(SDValue Op,
2179                                            SelectionDAG &DAG) const {
2180   EVT VT = Op.getValueType();
2181   int VTN = VT.isVector() ? VT.getVectorNumElements() : 1;
2182   SDLoc dl(Op);
2183   SDValue Idx = Op.getOperand(1);
2184   SDValue Vec = Op.getOperand(0);
2185   EVT VecVT = Vec.getValueType();
2186   EVT EltVT = VecVT.getVectorElementType();
2187   int EltSize = EltVT.getSizeInBits();
2188   SDValue Width = DAG.getConstant(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT ?
2189                                   EltSize : VTN * EltSize, MVT::i64);
2190
2191   // Constant element number.
2192   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Idx)) {
2193     SDValue Offset = DAG.getConstant(C->getZExtValue() * EltSize, MVT::i32);
2194     const SDValue Ops[] = {Vec, Width, Offset};
2195
2196     ConstantSDNode *W = dyn_cast<ConstantSDNode>(Width);
2197     assert(W && "Non constant width in LowerEXTRACT_VECTOR");
2198
2199     SDValue N;
2200     // For certain extracts, it is a simple _hi/_lo subreg.
2201     if (VecVT.getSimpleVT() == MVT::v2i32) {
2202       // v2i32 -> i32 vselect.
2203       if (C->getZExtValue() == 0)
2204         N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl,
2205                                        MVT::i32, Vec);
2206       else if (C->getZExtValue() == 1)
2207         N = DAG.getTargetExtractSubreg(Hexagon::subreg_hireg, dl,
2208                                        MVT::i32, Vec);
2209       else
2210         llvm_unreachable("Bad offset");
2211     } else if ((VecVT.getSimpleVT() == MVT::v4i16) &&
2212                (W->getZExtValue() == 32)) {
2213       // v4i16 -> v2i16/i32 vselect.
2214       if (C->getZExtValue() == 0)
2215         N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl,
2216                                        MVT::i32, Vec);
2217       else if (C->getZExtValue() == 2)
2218         N = DAG.getTargetExtractSubreg(Hexagon::subreg_hireg, dl,
2219                                        MVT::i32, Vec);
2220       else
2221         llvm_unreachable("Bad offset");
2222     }  else if ((VecVT.getSimpleVT() == MVT::v8i8) &&
2223                (W->getZExtValue() == 32)) {
2224       // v8i8 -> v4i8/i32 vselect.
2225       if (C->getZExtValue() == 0)
2226         N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl,
2227                                        MVT::i32, Vec);
2228       else if (C->getZExtValue() == 4)
2229         N = DAG.getTargetExtractSubreg(Hexagon::subreg_hireg, dl,
2230                                        MVT::i32, Vec);
2231       else
2232         llvm_unreachable("Bad offset");
2233     } else if (VecVT.getSizeInBits() == 32) {
2234         N = DAG.getNode(HexagonISD::EXTRACTU_ri, dl, MVT::i32, Ops);
2235     } else {
2236       N = DAG.getNode(HexagonISD::EXTRACTU_rd, dl, MVT::i64, Ops);
2237       if (VT.getSizeInBits() == 32)
2238         N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl, MVT::i32, N);
2239     }
2240
2241     return DAG.getNode(ISD::BITCAST, dl, VT, N);
2242   }
2243
2244   // Variable element number.
2245   SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i32, Idx,
2246                                DAG.getConstant(EltSize, MVT::i32));
2247   SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
2248                                 DAG.getConstant(32, MVT::i64));
2249   SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
2250
2251   const SDValue Ops[] = {Vec, Combined};
2252
2253   SDValue N;
2254   if (VecVT.getSizeInBits() == 32) {
2255     N = DAG.getNode(HexagonISD::EXTRACTU_riv, dl, MVT::i32, Ops);
2256   } else {
2257     N = DAG.getNode(HexagonISD::EXTRACTU_rdv, dl, MVT::i64, Ops);
2258     if (VT.getSizeInBits() == 32)
2259       N = DAG.getTargetExtractSubreg(Hexagon::subreg_loreg, dl, MVT::i32, N);
2260   }
2261   return DAG.getNode(ISD::BITCAST, dl, VT, N);
2262 }
2263
2264 SDValue
2265 HexagonTargetLowering::LowerINSERT_VECTOR(SDValue Op,
2266                                           SelectionDAG &DAG) const {
2267   EVT VT = Op.getValueType();
2268   int VTN = VT.isVector() ? VT.getVectorNumElements() : 1;
2269   SDLoc dl(Op);
2270   SDValue Vec = Op.getOperand(0);
2271   SDValue Val = Op.getOperand(1);
2272   SDValue Idx = Op.getOperand(2);
2273   EVT VecVT = Vec.getValueType();
2274   EVT EltVT = VecVT.getVectorElementType();
2275   int EltSize = EltVT.getSizeInBits();
2276   SDValue Width = DAG.getConstant(Op.getOpcode() == ISD::INSERT_VECTOR_ELT ?
2277                                   EltSize : VTN * EltSize, MVT::i64);
2278
2279   if (ConstantSDNode *C = cast<ConstantSDNode>(Idx)) {
2280     SDValue Offset = DAG.getConstant(C->getSExtValue() * EltSize, MVT::i32);
2281     const SDValue Ops[] = {Vec, Val, Width, Offset};
2282
2283     SDValue N;
2284     if (VT.getSizeInBits() == 32)
2285       N = DAG.getNode(HexagonISD::INSERT_ri, dl, MVT::i32, Ops);
2286     else
2287       N = DAG.getNode(HexagonISD::INSERT_rd, dl, MVT::i64, Ops);
2288
2289     return DAG.getNode(ISD::BITCAST, dl, VT, N);
2290   }
2291
2292   // Variable element number.
2293   SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i32, Idx,
2294                                DAG.getConstant(EltSize, MVT::i32));
2295   SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
2296                                 DAG.getConstant(32, MVT::i64));
2297   SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
2298
2299   if (VT.getSizeInBits() == 64 &&
2300       Val.getValueType().getSizeInBits() == 32) {
2301     SDValue C = DAG.getConstant(0, MVT::i32);
2302     Val = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, Val);
2303   }
2304
2305   const SDValue Ops[] = {Vec, Val, Combined};
2306
2307   SDValue N;
2308   if (VT.getSizeInBits() == 32)
2309     N = DAG.getNode(HexagonISD::INSERT_riv, dl, MVT::i32, Ops);
2310   else
2311     N = DAG.getNode(HexagonISD::INSERT_rdv, dl, MVT::i64, Ops);
2312
2313   return DAG.getNode(ISD::BITCAST, dl, VT, N);
2314 }
2315
2316 bool
2317 HexagonTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
2318   // Assuming the caller does not have either a signext or zeroext modifier, and
2319   // only one value is accepted, any reasonable truncation is allowed.
2320   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
2321     return false;
2322
2323   // FIXME: in principle up to 64-bit could be made safe, but it would be very
2324   // fragile at the moment: any support for multiple value returns would be
2325   // liable to disallow tail calls involving i64 -> iN truncation in many cases.
2326   return Ty1->getPrimitiveSizeInBits() <= 32;
2327 }
2328
2329 SDValue
2330 HexagonTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
2331   SDValue Chain     = Op.getOperand(0);
2332   SDValue Offset    = Op.getOperand(1);
2333   SDValue Handler   = Op.getOperand(2);
2334   SDLoc dl(Op);
2335
2336   // Mark function as containing a call to EH_RETURN.
2337   HexagonMachineFunctionInfo *FuncInfo =
2338     DAG.getMachineFunction().getInfo<HexagonMachineFunctionInfo>();
2339   FuncInfo->setHasEHReturn();
2340
2341   unsigned OffsetReg = Hexagon::R28;
2342
2343   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(),
2344                                   DAG.getRegister(Hexagon::R30, getPointerTy()),
2345                                   DAG.getIntPtrConstant(4));
2346   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
2347                        false, false, 0);
2348   Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
2349
2350   // Not needed we already use it as explict input to EH_RETURN.
2351   // MF.getRegInfo().addLiveOut(OffsetReg);
2352
2353   return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
2354 }
2355
2356 SDValue
2357 HexagonTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2358   switch (Op.getOpcode()) {
2359     default: llvm_unreachable("Should not custom lower this!");
2360     case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
2361     case ISD::INSERT_SUBVECTOR:   return LowerINSERT_VECTOR(Op, DAG);
2362     case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR(Op, DAG);
2363     case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_VECTOR(Op, DAG);
2364     case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR(Op, DAG);
2365     case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
2366     case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
2367     case ISD::SRA:
2368     case ISD::SHL:
2369     case ISD::SRL:
2370       return LowerVECTOR_SHIFT(Op, DAG);
2371     case ISD::ConstantPool:
2372       return LowerConstantPool(Op, DAG);
2373     case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
2374       // Frame & Return address.  Currently unimplemented.
2375     case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
2376     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
2377     case ISD::GlobalTLSAddress:
2378                           llvm_unreachable("TLS not implemented for Hexagon.");
2379     case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
2380     case ISD::GlobalAddress:      return LowerGLOBALADDRESS(Op, DAG);
2381     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
2382     case ISD::VASTART:            return LowerVASTART(Op, DAG);
2383     case ISD::BR_JT:              return LowerBR_JT(Op, DAG);
2384     // Custom lower some vector loads.
2385     case ISD::LOAD:               return LowerLOAD(Op, DAG);
2386
2387     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
2388     case ISD::SELECT:             return Op;
2389     case ISD::SETCC:              return LowerSETCC(Op, DAG);
2390     case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
2391     case ISD::CTPOP:              return LowerCTPOP(Op, DAG);
2392     case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2393     case ISD::INLINEASM:          return LowerINLINEASM(Op, DAG);
2394
2395   }
2396 }
2397
2398 MachineBasicBlock *
2399 HexagonTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2400                                                    MachineBasicBlock *BB)
2401       const {
2402   switch (MI->getOpcode()) {
2403     case Hexagon::ALLOCA: {
2404       MachineFunction *MF = BB->getParent();
2405       auto *FuncInfo = MF->getInfo<HexagonMachineFunctionInfo>();
2406       FuncInfo->addAllocaAdjustInst(MI);
2407       return BB;
2408     }
2409     default: llvm_unreachable("Unexpected instr type to insert");
2410   } // switch
2411 }
2412
2413 //===----------------------------------------------------------------------===//
2414 // Inline Assembly Support
2415 //===----------------------------------------------------------------------===//
2416
2417 std::pair<unsigned, const TargetRegisterClass *>
2418 HexagonTargetLowering::getRegForInlineAsmConstraint(
2419     const TargetRegisterInfo *TRI, const std::string &Constraint,
2420     MVT VT) const {
2421   if (Constraint.size() == 1) {
2422     switch (Constraint[0]) {
2423     case 'r':   // R0-R31
2424        switch (VT.SimpleTy) {
2425        default:
2426          llvm_unreachable("getRegForInlineAsmConstraint Unhandled data type");
2427        case MVT::i32:
2428        case MVT::i16:
2429        case MVT::i8:
2430        case MVT::f32:
2431          return std::make_pair(0U, &Hexagon::IntRegsRegClass);
2432        case MVT::i64:
2433        case MVT::f64:
2434          return std::make_pair(0U, &Hexagon::DoubleRegsRegClass);
2435       }
2436     default:
2437       llvm_unreachable("Unknown asm register class");
2438     }
2439   }
2440
2441   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2442 }
2443
2444 /// isFPImmLegal - Returns true if the target can instruction select the
2445 /// specified FP immediate natively. If false, the legalizer will
2446 /// materialize the FP immediate as a load from a constant pool.
2447 bool HexagonTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2448   return Subtarget->hasV5TOps();
2449 }
2450
2451 /// isLegalAddressingMode - Return true if the addressing mode represented by
2452 /// AM is legal for this target, for a load/store of the specified type.
2453 bool HexagonTargetLowering::isLegalAddressingMode(const AddrMode &AM,
2454                                                   Type *Ty) const {
2455   // Allows a signed-extended 11-bit immediate field.
2456   if (AM.BaseOffs <= -(1LL << 13) || AM.BaseOffs >= (1LL << 13)-1) {
2457     return false;
2458   }
2459
2460   // No global is ever allowed as a base.
2461   if (AM.BaseGV) {
2462     return false;
2463   }
2464
2465   int Scale = AM.Scale;
2466   if (Scale < 0) Scale = -Scale;
2467   switch (Scale) {
2468   case 0:  // No scale reg, "r+i", "r", or just "i".
2469     break;
2470   default: // No scaled addressing mode.
2471     return false;
2472   }
2473   return true;
2474 }
2475
2476 /// isLegalICmpImmediate - Return true if the specified immediate is legal
2477 /// icmp immediate, that is the target has icmp instructions which can compare
2478 /// a register against the immediate without having to materialize the
2479 /// immediate into a register.
2480 bool HexagonTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
2481   return Imm >= -512 && Imm <= 511;
2482 }
2483
2484 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2485 /// for tail call optimization. Targets which want to do tail call
2486 /// optimization should implement this function.
2487 bool HexagonTargetLowering::IsEligibleForTailCallOptimization(
2488                                  SDValue Callee,
2489                                  CallingConv::ID CalleeCC,
2490                                  bool isVarArg,
2491                                  bool isCalleeStructRet,
2492                                  bool isCallerStructRet,
2493                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
2494                                  const SmallVectorImpl<SDValue> &OutVals,
2495                                  const SmallVectorImpl<ISD::InputArg> &Ins,
2496                                  SelectionDAG& DAG) const {
2497   const Function *CallerF = DAG.getMachineFunction().getFunction();
2498   CallingConv::ID CallerCC = CallerF->getCallingConv();
2499   bool CCMatch = CallerCC == CalleeCC;
2500
2501   // ***************************************************************************
2502   //  Look for obvious safe cases to perform tail call optimization that do not
2503   //  require ABI changes.
2504   // ***************************************************************************
2505
2506   // If this is a tail call via a function pointer, then don't do it!
2507   if (!(dyn_cast<GlobalAddressSDNode>(Callee))
2508       && !(dyn_cast<ExternalSymbolSDNode>(Callee))) {
2509     return false;
2510   }
2511
2512   // Do not optimize if the calling conventions do not match.
2513   if (!CCMatch)
2514     return false;
2515
2516   // Do not tail call optimize vararg calls.
2517   if (isVarArg)
2518     return false;
2519
2520   // Also avoid tail call optimization if either caller or callee uses struct
2521   // return semantics.
2522   if (isCalleeStructRet || isCallerStructRet)
2523     return false;
2524
2525   // In addition to the cases above, we also disable Tail Call Optimization if
2526   // the calling convention code that at least one outgoing argument needs to
2527   // go on the stack. We cannot check that here because at this point that
2528   // information is not available.
2529   return true;
2530 }
2531
2532 // Return true when the given node fits in a positive half word.
2533 bool llvm::isPositiveHalfWord(SDNode *N) {
2534   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
2535   if (CN && CN->getSExtValue() > 0 && isInt<16>(CN->getSExtValue()))
2536     return true;
2537
2538   switch (N->getOpcode()) {
2539   default:
2540     return false;
2541   case ISD::SIGN_EXTEND_INREG:
2542     return true;
2543   }
2544 }