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