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 "Hexagon.h"
17 #include "HexagonMachineFunctionInfo.h"
18 #include "HexagonRegisterInfo.h"
19 #include "HexagonSubtarget.h"
20 #include "HexagonTargetMachine.h"
21 #include "HexagonTargetObjectFile.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RuntimeLibcalls.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/TargetCallingConv.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/IR/BasicBlock.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/Value.h"
48 #include "llvm/MC/MCRegisterInfo.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CodeGen.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetMachine.h"
57 #include <algorithm>
58 #include <cassert>
59 #include <cstddef>
60 #include <cstdint>
61 #include <limits>
62 #include <utility>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "hexagon-lowering"
67 
68 static cl::opt<bool> EmitJumpTables("hexagon-emit-jump-tables",
69   cl::init(true), cl::Hidden,
70   cl::desc("Control jump table emission on Hexagon target"));
71 
72 static cl::opt<bool> EnableHexSDNodeSched("enable-hexagon-sdnode-sched",
73   cl::Hidden, cl::ZeroOrMore, cl::init(false),
74   cl::desc("Enable Hexagon SDNode scheduling"));
75 
76 static cl::opt<bool> EnableFastMath("ffast-math",
77   cl::Hidden, cl::ZeroOrMore, cl::init(false),
78   cl::desc("Enable Fast Math processing"));
79 
80 static cl::opt<int> MinimumJumpTables("minimum-jump-tables",
81   cl::Hidden, cl::ZeroOrMore, cl::init(5),
82   cl::desc("Set minimum jump tables"));
83 
84 static cl::opt<int> MaxStoresPerMemcpyCL("max-store-memcpy",
85   cl::Hidden, cl::ZeroOrMore, cl::init(6),
86   cl::desc("Max #stores to inline memcpy"));
87 
88 static cl::opt<int> MaxStoresPerMemcpyOptSizeCL("max-store-memcpy-Os",
89   cl::Hidden, cl::ZeroOrMore, cl::init(4),
90   cl::desc("Max #stores to inline memcpy"));
91 
92 static cl::opt<int> MaxStoresPerMemmoveCL("max-store-memmove",
93   cl::Hidden, cl::ZeroOrMore, cl::init(6),
94   cl::desc("Max #stores to inline memmove"));
95 
96 static cl::opt<int> MaxStoresPerMemmoveOptSizeCL("max-store-memmove-Os",
97   cl::Hidden, cl::ZeroOrMore, cl::init(4),
98   cl::desc("Max #stores to inline memmove"));
99 
100 static cl::opt<int> MaxStoresPerMemsetCL("max-store-memset",
101   cl::Hidden, cl::ZeroOrMore, cl::init(8),
102   cl::desc("Max #stores to inline memset"));
103 
104 static cl::opt<int> MaxStoresPerMemsetOptSizeCL("max-store-memset-Os",
105   cl::Hidden, cl::ZeroOrMore, cl::init(4),
106   cl::desc("Max #stores to inline memset"));
107 
108 static cl::opt<bool> AlignLoads("hexagon-align-loads",
109   cl::Hidden, cl::init(false),
110   cl::desc("Rewrite unaligned loads as a pair of aligned loads"));
111 
112 
113 namespace {
114 
115   class HexagonCCState : public CCState {
116     unsigned NumNamedVarArgParams = 0;
117 
118   public:
119     HexagonCCState(CallingConv::ID CC, bool IsVarArg, MachineFunction &MF,
120                    SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
121                    unsigned NumNamedArgs)
122         : CCState(CC, IsVarArg, MF, locs, C),
123           NumNamedVarArgParams(NumNamedArgs) {}
124     unsigned getNumNamedVarArgParams() const { return NumNamedVarArgParams; }
125   };
126 
127 } // end anonymous namespace
128 
129 
130 // Implement calling convention for Hexagon.
131 
132 static bool CC_SkipOdd(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
133                        CCValAssign::LocInfo &LocInfo,
134                        ISD::ArgFlagsTy &ArgFlags, CCState &State) {
135   static const MCPhysReg ArgRegs[] = {
136     Hexagon::R0, Hexagon::R1, Hexagon::R2,
137     Hexagon::R3, Hexagon::R4, Hexagon::R5
138   };
139   const unsigned NumArgRegs = array_lengthof(ArgRegs);
140   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
141 
142   // RegNum is an index into ArgRegs: skip a register if RegNum is odd.
143   if (RegNum != NumArgRegs && RegNum % 2 == 1)
144     State.AllocateReg(ArgRegs[RegNum]);
145 
146   // Always return false here, as this function only makes sure that the first
147   // unallocated register has an even register number and does not actually
148   // allocate a register for the current argument.
149   return false;
150 }
151 
152 #include "HexagonGenCallingConv.inc"
153 
154 
155 SDValue
156 HexagonTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG)
157       const {
158   return SDValue();
159 }
160 
161 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
162 /// by "Src" to address "Dst" of size "Size".  Alignment information is
163 /// specified by the specific parameter attribute. The copy will be passed as
164 /// a byval function parameter.  Sometimes what we are copying is the end of a
165 /// larger object, the part that does not fit in registers.
166 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
167                                          SDValue Chain, ISD::ArgFlagsTy Flags,
168                                          SelectionDAG &DAG, const SDLoc &dl) {
169   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
170   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
171                        /*isVolatile=*/false, /*AlwaysInline=*/false,
172                        /*isTailCall=*/false,
173                        MachinePointerInfo(), MachinePointerInfo());
174 }
175 
176 bool
177 HexagonTargetLowering::CanLowerReturn(
178     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
179     const SmallVectorImpl<ISD::OutputArg> &Outs,
180     LLVMContext &Context) const {
181   SmallVector<CCValAssign, 16> RVLocs;
182   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
183 
184   if (MF.getSubtarget<HexagonSubtarget>().useHVXOps())
185     return CCInfo.CheckReturn(Outs, RetCC_Hexagon_HVX);
186   return CCInfo.CheckReturn(Outs, RetCC_Hexagon);
187 }
188 
189 // LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
190 // passed by value, the function prototype is modified to return void and
191 // the value is stored in memory pointed by a pointer passed by caller.
192 SDValue
193 HexagonTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
194                                    bool IsVarArg,
195                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
196                                    const SmallVectorImpl<SDValue> &OutVals,
197                                    const SDLoc &dl, SelectionDAG &DAG) const {
198   // CCValAssign - represent the assignment of the return value to locations.
199   SmallVector<CCValAssign, 16> RVLocs;
200 
201   // CCState - Info about the registers and stack slot.
202   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
203                  *DAG.getContext());
204 
205   // Analyze return values of ISD::RET
206   if (Subtarget.useHVXOps())
207     CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon_HVX);
208   else
209     CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
210 
211   SDValue Flag;
212   SmallVector<SDValue, 4> RetOps(1, Chain);
213 
214   // Copy the result values into the output registers.
215   for (unsigned i = 0; i != RVLocs.size(); ++i) {
216     CCValAssign &VA = RVLocs[i];
217 
218     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
219 
220     // Guarantee that all emitted copies are stuck together with flags.
221     Flag = Chain.getValue(1);
222     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
223   }
224 
225   RetOps[0] = Chain;  // Update chain.
226 
227   // Add the flag if we have it.
228   if (Flag.getNode())
229     RetOps.push_back(Flag);
230 
231   return DAG.getNode(HexagonISD::RET_FLAG, dl, MVT::Other, RetOps);
232 }
233 
234 bool HexagonTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
235   // If either no tail call or told not to tail call at all, don't.
236   auto Attr =
237       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
238   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
239     return false;
240 
241   return true;
242 }
243 
244 unsigned  HexagonTargetLowering::getRegisterByName(const char* RegName, EVT VT,
245                                               SelectionDAG &DAG) const {
246   // Just support r19, the linux kernel uses it.
247   unsigned Reg = StringSwitch<unsigned>(RegName)
248                      .Case("r19", Hexagon::R19)
249                      .Default(0);
250   if (Reg)
251     return Reg;
252 
253   report_fatal_error("Invalid register name global variable");
254 }
255 
256 /// LowerCallResult - Lower the result values of an ISD::CALL into the
257 /// appropriate copies out of appropriate physical registers.  This assumes that
258 /// Chain/Glue are the input chain/glue to use, and that TheCall is the call
259 /// being lowered. Returns a SDNode with the same number of values as the
260 /// ISD::CALL.
261 SDValue HexagonTargetLowering::LowerCallResult(
262     SDValue Chain, SDValue Glue, CallingConv::ID CallConv, bool IsVarArg,
263     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
264     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
265     const SmallVectorImpl<SDValue> &OutVals, SDValue Callee) const {
266   // Assign locations to each value returned by this call.
267   SmallVector<CCValAssign, 16> RVLocs;
268 
269   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
270                  *DAG.getContext());
271 
272   if (Subtarget.useHVXOps())
273     CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon_HVX);
274   else
275     CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
276 
277   // Copy all of the result registers out of their specified physreg.
278   for (unsigned i = 0; i != RVLocs.size(); ++i) {
279     SDValue RetVal;
280     if (RVLocs[i].getValVT() == MVT::i1) {
281       // Return values of type MVT::i1 require special handling. The reason
282       // is that MVT::i1 is associated with the PredRegs register class, but
283       // values of that type are still returned in R0. Generate an explicit
284       // copy into a predicate register from R0, and treat the value of the
285       // predicate register as the call result.
286       auto &MRI = DAG.getMachineFunction().getRegInfo();
287       SDValue FR0 = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
288                                        MVT::i32, Glue);
289       // FR0 = (Value, Chain, Glue)
290       unsigned PredR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
291       SDValue TPR = DAG.getCopyToReg(FR0.getValue(1), dl, PredR,
292                                      FR0.getValue(0), FR0.getValue(2));
293       // TPR = (Chain, Glue)
294       // Don't glue this CopyFromReg, because it copies from a virtual
295       // register. If it is glued to the call, InstrEmitter will add it
296       // as an implicit def to the call (EmitMachineNode).
297       RetVal = DAG.getCopyFromReg(TPR.getValue(0), dl, PredR, MVT::i1);
298       Glue = TPR.getValue(1);
299       Chain = TPR.getValue(0);
300     } else {
301       RetVal = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
302                                   RVLocs[i].getValVT(), Glue);
303       Glue = RetVal.getValue(2);
304       Chain = RetVal.getValue(1);
305     }
306     InVals.push_back(RetVal.getValue(0));
307   }
308 
309   return Chain;
310 }
311 
312 /// LowerCall - Functions arguments are copied from virtual regs to
313 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
314 SDValue
315 HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
316                                  SmallVectorImpl<SDValue> &InVals) const {
317   SelectionDAG &DAG                     = CLI.DAG;
318   SDLoc &dl                             = CLI.DL;
319   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
320   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
321   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
322   SDValue Chain                         = CLI.Chain;
323   SDValue Callee                        = CLI.Callee;
324   CallingConv::ID CallConv              = CLI.CallConv;
325   bool IsVarArg                         = CLI.IsVarArg;
326   bool DoesNotReturn                    = CLI.DoesNotReturn;
327 
328   bool IsStructRet    = Outs.empty() ? false : Outs[0].Flags.isSRet();
329   MachineFunction &MF = DAG.getMachineFunction();
330   MachineFrameInfo &MFI = MF.getFrameInfo();
331   auto PtrVT = getPointerTy(MF.getDataLayout());
332 
333   unsigned NumParams = CLI.CS.getInstruction()
334                         ? CLI.CS.getFunctionType()->getNumParams()
335                         : 0;
336   if (GlobalAddressSDNode *GAN = dyn_cast<GlobalAddressSDNode>(Callee))
337     Callee = DAG.getTargetGlobalAddress(GAN->getGlobal(), dl, MVT::i32);
338 
339   // Analyze operands of the call, assigning locations to each operand.
340   SmallVector<CCValAssign, 16> ArgLocs;
341   HexagonCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext(),
342                         NumParams);
343 
344   if (Subtarget.useHVXOps())
345     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_HVX);
346   else
347     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
348 
349   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
350   if (Attr.getValueAsString() == "true")
351     CLI.IsTailCall = false;
352 
353   if (CLI.IsTailCall) {
354     bool StructAttrFlag = MF.getFunction().hasStructRetAttr();
355     CLI.IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
356                         IsVarArg, IsStructRet, StructAttrFlag, Outs,
357                         OutVals, Ins, DAG);
358     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
359       CCValAssign &VA = ArgLocs[i];
360       if (VA.isMemLoc()) {
361         CLI.IsTailCall = false;
362         break;
363       }
364     }
365     LLVM_DEBUG(dbgs() << (CLI.IsTailCall ? "Eligible for Tail Call\n"
366                                          : "Argument must be passed on stack. "
367                                            "Not eligible for Tail Call\n"));
368   }
369   // Get a count of how many bytes are to be pushed on the stack.
370   unsigned NumBytes = CCInfo.getNextStackOffset();
371   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
372   SmallVector<SDValue, 8> MemOpChains;
373 
374   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
375   SDValue StackPtr =
376       DAG.getCopyFromReg(Chain, dl, HRI.getStackRegister(), PtrVT);
377 
378   bool NeedsArgAlign = false;
379   unsigned LargestAlignSeen = 0;
380   // Walk the register/memloc assignments, inserting copies/loads.
381   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
382     CCValAssign &VA = ArgLocs[i];
383     SDValue Arg = OutVals[i];
384     ISD::ArgFlagsTy Flags = Outs[i].Flags;
385     // Record if we need > 8 byte alignment on an argument.
386     bool ArgAlign = Subtarget.isHVXVectorType(VA.getValVT());
387     NeedsArgAlign |= ArgAlign;
388 
389     // Promote the value if needed.
390     switch (VA.getLocInfo()) {
391       default:
392         // Loc info must be one of Full, BCvt, SExt, ZExt, or AExt.
393         llvm_unreachable("Unknown loc info!");
394       case CCValAssign::Full:
395         break;
396       case CCValAssign::BCvt:
397         Arg = DAG.getBitcast(VA.getLocVT(), Arg);
398         break;
399       case CCValAssign::SExt:
400         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
401         break;
402       case CCValAssign::ZExt:
403         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
404         break;
405       case CCValAssign::AExt:
406         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
407         break;
408     }
409 
410     if (VA.isMemLoc()) {
411       unsigned LocMemOffset = VA.getLocMemOffset();
412       SDValue MemAddr = DAG.getConstant(LocMemOffset, dl,
413                                         StackPtr.getValueType());
414       MemAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, MemAddr);
415       if (ArgAlign)
416         LargestAlignSeen = std::max(LargestAlignSeen,
417                                     VA.getLocVT().getStoreSizeInBits() >> 3);
418       if (Flags.isByVal()) {
419         // The argument is a struct passed by value. According to LLVM, "Arg"
420         // is a pointer.
421         MemOpChains.push_back(CreateCopyOfByValArgument(Arg, MemAddr, Chain,
422                                                         Flags, DAG, dl));
423       } else {
424         MachinePointerInfo LocPI = MachinePointerInfo::getStack(
425             DAG.getMachineFunction(), LocMemOffset);
426         SDValue S = DAG.getStore(Chain, dl, Arg, MemAddr, LocPI);
427         MemOpChains.push_back(S);
428       }
429       continue;
430     }
431 
432     // Arguments that can be passed on register must be kept at RegsToPass
433     // vector.
434     if (VA.isRegLoc())
435       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
436   }
437 
438   if (NeedsArgAlign && Subtarget.hasV60Ops()) {
439     LLVM_DEBUG(dbgs() << "Function needs byte stack align due to call args\n");
440     unsigned VecAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
441     LargestAlignSeen = std::max(LargestAlignSeen, VecAlign);
442     MFI.ensureMaxAlignment(LargestAlignSeen);
443   }
444   // Transform all store nodes into one single node because all store
445   // nodes are independent of each other.
446   if (!MemOpChains.empty())
447     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
448 
449   SDValue Glue;
450   if (!CLI.IsTailCall) {
451     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
452     Glue = Chain.getValue(1);
453   }
454 
455   // Build a sequence of copy-to-reg nodes chained together with token
456   // chain and flag operands which copy the outgoing args into registers.
457   // The Glue is necessary since all emitted instructions must be
458   // stuck together.
459   if (!CLI.IsTailCall) {
460     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
461       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
462                                RegsToPass[i].second, Glue);
463       Glue = Chain.getValue(1);
464     }
465   } else {
466     // For tail calls lower the arguments to the 'real' stack slot.
467     //
468     // Force all the incoming stack arguments to be loaded from the stack
469     // before any new outgoing arguments are stored to the stack, because the
470     // outgoing stack slots may alias the incoming argument stack slots, and
471     // the alias isn't otherwise explicit. This is slightly more conservative
472     // than necessary, because it means that each store effectively depends
473     // on every argument instead of just those arguments it would clobber.
474     //
475     // Do not flag preceding copytoreg stuff together with the following stuff.
476     Glue = SDValue();
477     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
478       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
479                                RegsToPass[i].second, Glue);
480       Glue = Chain.getValue(1);
481     }
482     Glue = SDValue();
483   }
484 
485   bool LongCalls = MF.getSubtarget<HexagonSubtarget>().useLongCalls();
486   unsigned Flags = LongCalls ? HexagonII::HMOTF_ConstExtended : 0;
487 
488   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
489   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
490   // node so that legalize doesn't hack it.
491   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
492     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, PtrVT, 0, Flags);
493   } else if (ExternalSymbolSDNode *S =
494              dyn_cast<ExternalSymbolSDNode>(Callee)) {
495     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, Flags);
496   }
497 
498   // Returns a chain & a flag for retval copy to use.
499   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
500   SmallVector<SDValue, 8> Ops;
501   Ops.push_back(Chain);
502   Ops.push_back(Callee);
503 
504   // Add argument registers to the end of the list so that they are
505   // known live into the call.
506   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
507     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
508                                   RegsToPass[i].second.getValueType()));
509   }
510 
511   const uint32_t *Mask = HRI.getCallPreservedMask(MF, CallConv);
512   assert(Mask && "Missing call preserved mask for calling convention");
513   Ops.push_back(DAG.getRegisterMask(Mask));
514 
515   if (Glue.getNode())
516     Ops.push_back(Glue);
517 
518   if (CLI.IsTailCall) {
519     MFI.setHasTailCall();
520     return DAG.getNode(HexagonISD::TC_RETURN, dl, NodeTys, Ops);
521   }
522 
523   // Set this here because we need to know this for "hasFP" in frame lowering.
524   // The target-independent code calls getFrameRegister before setting it, and
525   // getFrameRegister uses hasFP to determine whether the function has FP.
526   MFI.setHasCalls(true);
527 
528   unsigned OpCode = DoesNotReturn ? HexagonISD::CALLnr : HexagonISD::CALL;
529   Chain = DAG.getNode(OpCode, dl, NodeTys, Ops);
530   Glue = Chain.getValue(1);
531 
532   // Create the CALLSEQ_END node.
533   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
534                              DAG.getIntPtrConstant(0, dl, true), Glue, dl);
535   Glue = Chain.getValue(1);
536 
537   // Handle result values, copying them out of physregs into vregs that we
538   // return.
539   return LowerCallResult(Chain, Glue, CallConv, IsVarArg, Ins, dl, DAG,
540                          InVals, OutVals, Callee);
541 }
542 
543 /// Returns true by value, base pointer and offset pointer and addressing
544 /// mode by reference if this node can be combined with a load / store to
545 /// form a post-indexed load / store.
546 bool HexagonTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
547       SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM,
548       SelectionDAG &DAG) const {
549   LSBaseSDNode *LSN = dyn_cast<LSBaseSDNode>(N);
550   if (!LSN)
551     return false;
552   EVT VT = LSN->getMemoryVT();
553   if (!VT.isSimple())
554     return false;
555   bool IsLegalType = VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 ||
556                      VT == MVT::i64 || VT == MVT::f32 || VT == MVT::f64 ||
557                      VT == MVT::v2i16 || VT == MVT::v2i32 || VT == MVT::v4i8 ||
558                      VT == MVT::v4i16 || VT == MVT::v8i8 ||
559                      Subtarget.isHVXVectorType(VT.getSimpleVT());
560   if (!IsLegalType)
561     return false;
562 
563   if (Op->getOpcode() != ISD::ADD)
564     return false;
565   Base = Op->getOperand(0);
566   Offset = Op->getOperand(1);
567   if (!isa<ConstantSDNode>(Offset.getNode()))
568     return false;
569   AM = ISD::POST_INC;
570 
571   int32_t V = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
572   return Subtarget.getInstrInfo()->isValidAutoIncImm(VT, V);
573 }
574 
575 SDValue
576 HexagonTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
577   MachineFunction &MF = DAG.getMachineFunction();
578   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
579   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
580   unsigned LR = HRI.getRARegister();
581 
582   if (Op.getOpcode() != ISD::INLINEASM || HMFI.hasClobberLR())
583     return Op;
584 
585   unsigned NumOps = Op.getNumOperands();
586   if (Op.getOperand(NumOps-1).getValueType() == MVT::Glue)
587     --NumOps;  // Ignore the flag operand.
588 
589   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
590     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
591     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
592     ++i;  // Skip the ID value.
593 
594     switch (InlineAsm::getKind(Flags)) {
595       default:
596         llvm_unreachable("Bad flags!");
597       case InlineAsm::Kind_RegUse:
598       case InlineAsm::Kind_Imm:
599       case InlineAsm::Kind_Mem:
600         i += NumVals;
601         break;
602       case InlineAsm::Kind_Clobber:
603       case InlineAsm::Kind_RegDef:
604       case InlineAsm::Kind_RegDefEarlyClobber: {
605         for (; NumVals; --NumVals, ++i) {
606           unsigned Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
607           if (Reg != LR)
608             continue;
609           HMFI.setHasClobberLR(true);
610           return Op;
611         }
612         break;
613       }
614     }
615   }
616 
617   return Op;
618 }
619 
620 // Need to transform ISD::PREFETCH into something that doesn't inherit
621 // all of the properties of ISD::PREFETCH, specifically SDNPMayLoad and
622 // SDNPMayStore.
623 SDValue HexagonTargetLowering::LowerPREFETCH(SDValue Op,
624                                              SelectionDAG &DAG) const {
625   SDValue Chain = Op.getOperand(0);
626   SDValue Addr = Op.getOperand(1);
627   // Lower it to DCFETCH($reg, #0).  A "pat" will try to merge the offset in,
628   // if the "reg" is fed by an "add".
629   SDLoc DL(Op);
630   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
631   return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
632 }
633 
634 // Custom-handle ISD::READCYCLECOUNTER because the target-independent SDNode
635 // is marked as having side-effects, while the register read on Hexagon does
636 // not have any. TableGen refuses to accept the direct pattern from that node
637 // to the A4_tfrcpp.
638 SDValue HexagonTargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
639                                                      SelectionDAG &DAG) const {
640   SDValue Chain = Op.getOperand(0);
641   SDLoc dl(Op);
642   SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
643   return DAG.getNode(HexagonISD::READCYCLE, dl, VTs, Chain);
644 }
645 
646 SDValue HexagonTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
647       SelectionDAG &DAG) const {
648   SDValue Chain = Op.getOperand(0);
649   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
650   // Lower the hexagon_prefetch builtin to DCFETCH, as above.
651   if (IntNo == Intrinsic::hexagon_prefetch) {
652     SDValue Addr = Op.getOperand(2);
653     SDLoc DL(Op);
654     SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
655     return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
656   }
657   return SDValue();
658 }
659 
660 SDValue
661 HexagonTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
662                                                SelectionDAG &DAG) const {
663   SDValue Chain = Op.getOperand(0);
664   SDValue Size = Op.getOperand(1);
665   SDValue Align = Op.getOperand(2);
666   SDLoc dl(Op);
667 
668   ConstantSDNode *AlignConst = dyn_cast<ConstantSDNode>(Align);
669   assert(AlignConst && "Non-constant Align in LowerDYNAMIC_STACKALLOC");
670 
671   unsigned A = AlignConst->getSExtValue();
672   auto &HFI = *Subtarget.getFrameLowering();
673   // "Zero" means natural stack alignment.
674   if (A == 0)
675     A = HFI.getStackAlignment();
676 
677   LLVM_DEBUG({
678     dbgs () << __func__ << " Align: " << A << " Size: ";
679     Size.getNode()->dump(&DAG);
680     dbgs() << "\n";
681   });
682 
683   SDValue AC = DAG.getConstant(A, dl, MVT::i32);
684   SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
685   SDValue AA = DAG.getNode(HexagonISD::ALLOCA, dl, VTs, Chain, Size, AC);
686 
687   DAG.ReplaceAllUsesOfValueWith(Op, AA);
688   return AA;
689 }
690 
691 SDValue HexagonTargetLowering::LowerFormalArguments(
692     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
693     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
694     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
695   MachineFunction &MF = DAG.getMachineFunction();
696   MachineFrameInfo &MFI = MF.getFrameInfo();
697   MachineRegisterInfo &MRI = MF.getRegInfo();
698 
699   // Assign locations to all of the incoming arguments.
700   SmallVector<CCValAssign, 16> ArgLocs;
701   HexagonCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext(),
702                         MF.getFunction().getFunctionType()->getNumParams());
703 
704   if (Subtarget.useHVXOps())
705     CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon_HVX);
706   else
707     CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
708 
709   // For LLVM, in the case when returning a struct by value (>8byte),
710   // the first argument is a pointer that points to the location on caller's
711   // stack where the return value will be stored. For Hexagon, the location on
712   // caller's stack is passed only when the struct size is smaller than (and
713   // equal to) 8 bytes. If not, no address will be passed into callee and
714   // callee return the result direclty through R0/R1.
715 
716   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
717 
718   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
719     CCValAssign &VA = ArgLocs[i];
720     ISD::ArgFlagsTy Flags = Ins[i].Flags;
721     bool ByVal = Flags.isByVal();
722 
723     // Arguments passed in registers:
724     // 1. 32- and 64-bit values and HVX vectors are passed directly,
725     // 2. Large structs are passed via an address, and the address is
726     //    passed in a register.
727     if (VA.isRegLoc() && ByVal && Flags.getByValSize() <= 8)
728       llvm_unreachable("ByValSize must be bigger than 8 bytes");
729 
730     bool InReg = VA.isRegLoc() &&
731                  (!ByVal || (ByVal && Flags.getByValSize() > 8));
732 
733     if (InReg) {
734       MVT RegVT = VA.getLocVT();
735       if (VA.getLocInfo() == CCValAssign::BCvt)
736         RegVT = VA.getValVT();
737 
738       const TargetRegisterClass *RC = getRegClassFor(RegVT);
739       unsigned VReg = MRI.createVirtualRegister(RC);
740       SDValue Copy = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
741 
742       // Treat values of type MVT::i1 specially: they are passed in
743       // registers of type i32, but they need to remain as values of
744       // type i1 for consistency of the argument lowering.
745       if (VA.getValVT() == MVT::i1) {
746         assert(RegVT.getSizeInBits() <= 32);
747         SDValue T = DAG.getNode(ISD::AND, dl, RegVT,
748                                 Copy, DAG.getConstant(1, dl, RegVT));
749         Copy = DAG.getSetCC(dl, MVT::i1, T, DAG.getConstant(0, dl, RegVT),
750                             ISD::SETNE);
751       } else {
752 #ifndef NDEBUG
753         unsigned RegSize = RegVT.getSizeInBits();
754         assert(RegSize == 32 || RegSize == 64 ||
755                Subtarget.isHVXVectorType(RegVT));
756 #endif
757       }
758       InVals.push_back(Copy);
759       MRI.addLiveIn(VA.getLocReg(), VReg);
760     } else {
761       assert(VA.isMemLoc() && "Argument should be passed in memory");
762 
763       // If it's a byval parameter, then we need to compute the
764       // "real" size, not the size of the pointer.
765       unsigned ObjSize = Flags.isByVal()
766                             ? Flags.getByValSize()
767                             : VA.getLocVT().getStoreSizeInBits() / 8;
768 
769       // Create the frame index object for this incoming parameter.
770       int Offset = HEXAGON_LRFP_SIZE + VA.getLocMemOffset();
771       int FI = MFI.CreateFixedObject(ObjSize, Offset, true);
772       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
773 
774       if (Flags.isByVal()) {
775         // If it's a pass-by-value aggregate, then do not dereference the stack
776         // location. Instead, we should generate a reference to the stack
777         // location.
778         InVals.push_back(FIN);
779       } else {
780         SDValue L = DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
781                                 MachinePointerInfo::getFixedStack(MF, FI, 0));
782         InVals.push_back(L);
783       }
784     }
785   }
786 
787 
788   if (IsVarArg) {
789     // This will point to the next argument passed via stack.
790     int Offset = HEXAGON_LRFP_SIZE + CCInfo.getNextStackOffset();
791     int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
792     HMFI.setVarArgsFrameIndex(FI);
793   }
794 
795   return Chain;
796 }
797 
798 SDValue
799 HexagonTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
800   // VASTART stores the address of the VarArgsFrameIndex slot into the
801   // memory location argument.
802   MachineFunction &MF = DAG.getMachineFunction();
803   HexagonMachineFunctionInfo *QFI = MF.getInfo<HexagonMachineFunctionInfo>();
804   SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
805   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
806   return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr, Op.getOperand(1),
807                       MachinePointerInfo(SV));
808 }
809 
810 SDValue HexagonTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
811   const SDLoc &dl(Op);
812   SDValue LHS = Op.getOperand(0);
813   SDValue RHS = Op.getOperand(1);
814   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
815   MVT ResTy = ty(Op);
816   MVT OpTy = ty(LHS);
817 
818   if (OpTy == MVT::v2i16 || OpTy == MVT::v4i8) {
819     MVT ElemTy = OpTy.getVectorElementType();
820     assert(ElemTy.isScalarInteger());
821     MVT WideTy = MVT::getVectorVT(MVT::getIntegerVT(2*ElemTy.getSizeInBits()),
822                                   OpTy.getVectorNumElements());
823     return DAG.getSetCC(dl, ResTy,
824                         DAG.getSExtOrTrunc(LHS, SDLoc(LHS), WideTy),
825                         DAG.getSExtOrTrunc(RHS, SDLoc(RHS), WideTy), CC);
826   }
827 
828   // Treat all other vector types as legal.
829   if (ResTy.isVector())
830     return Op;
831 
832   // Comparisons of short integers should use sign-extend, not zero-extend,
833   // since we can represent small negative values in the compare instructions.
834   // The LLVM default is to use zero-extend arbitrarily in these cases.
835   auto isSExtFree = [this](SDValue N) {
836     switch (N.getOpcode()) {
837       case ISD::TRUNCATE: {
838         // A sign-extend of a truncate of a sign-extend is free.
839         SDValue Op = N.getOperand(0);
840         if (Op.getOpcode() != ISD::AssertSext)
841           return false;
842         EVT OrigTy = cast<VTSDNode>(Op.getOperand(1))->getVT();
843         unsigned ThisBW = ty(N).getSizeInBits();
844         unsigned OrigBW = OrigTy.getSizeInBits();
845         // The type that was sign-extended to get the AssertSext must be
846         // narrower than the type of N (so that N has still the same value
847         // as the original).
848         return ThisBW >= OrigBW;
849       }
850       case ISD::LOAD:
851         // We have sign-extended loads.
852         return true;
853     }
854     return false;
855   };
856 
857   if (OpTy == MVT::i8 || OpTy == MVT::i16) {
858     ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS);
859     bool IsNegative = C && C->getAPIntValue().isNegative();
860     if (IsNegative || isSExtFree(LHS) || isSExtFree(RHS))
861       return DAG.getSetCC(dl, ResTy,
862                           DAG.getSExtOrTrunc(LHS, SDLoc(LHS), MVT::i32),
863                           DAG.getSExtOrTrunc(RHS, SDLoc(RHS), MVT::i32), CC);
864   }
865 
866   return SDValue();
867 }
868 
869 SDValue
870 HexagonTargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
871   SDValue PredOp = Op.getOperand(0);
872   SDValue Op1 = Op.getOperand(1), Op2 = Op.getOperand(2);
873   EVT OpVT = Op1.getValueType();
874   SDLoc DL(Op);
875 
876   if (OpVT == MVT::v2i16) {
877     SDValue X1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i32, Op1);
878     SDValue X2 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i32, Op2);
879     SDValue SL = DAG.getNode(ISD::VSELECT, DL, MVT::v2i32, PredOp, X1, X2);
880     SDValue TR = DAG.getNode(ISD::TRUNCATE, DL, MVT::v2i16, SL);
881     return TR;
882   }
883 
884   return SDValue();
885 }
886 
887 static Constant *convert_i1_to_i8(const Constant *ConstVal) {
888   SmallVector<Constant *, 128> NewConst;
889   const ConstantVector *CV = dyn_cast<ConstantVector>(ConstVal);
890   if (!CV)
891     return nullptr;
892 
893   LLVMContext &Ctx = ConstVal->getContext();
894   IRBuilder<> IRB(Ctx);
895   unsigned NumVectorElements = CV->getNumOperands();
896   assert(isPowerOf2_32(NumVectorElements) &&
897          "conversion only supported for pow2 VectorSize!");
898 
899   for (unsigned i = 0; i < NumVectorElements / 8; ++i) {
900     uint8_t x = 0;
901     for (unsigned j = 0; j < 8; ++j) {
902       uint8_t y = CV->getOperand(i * 8 + j)->getUniqueInteger().getZExtValue();
903       x |= y << (7 - j);
904     }
905     assert((x == 0 || x == 255) && "Either all 0's or all 1's expected!");
906     NewConst.push_back(IRB.getInt8(x));
907   }
908   return ConstantVector::get(NewConst);
909 }
910 
911 SDValue
912 HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
913   EVT ValTy = Op.getValueType();
914   ConstantPoolSDNode *CPN = cast<ConstantPoolSDNode>(Op);
915   Constant *CVal = nullptr;
916   bool isVTi1Type = false;
917   if (const Constant *ConstVal = dyn_cast<Constant>(CPN->getConstVal())) {
918     Type *CValTy = ConstVal->getType();
919     if (CValTy->isVectorTy() &&
920         CValTy->getVectorElementType()->isIntegerTy(1)) {
921       CVal = convert_i1_to_i8(ConstVal);
922       isVTi1Type = (CVal != nullptr);
923     }
924   }
925   unsigned Align = CPN->getAlignment();
926   bool IsPositionIndependent = isPositionIndependent();
927   unsigned char TF = IsPositionIndependent ? HexagonII::MO_PCREL : 0;
928 
929   unsigned Offset = 0;
930   SDValue T;
931   if (CPN->isMachineConstantPoolEntry())
932     T = DAG.getTargetConstantPool(CPN->getMachineCPVal(), ValTy, Align, Offset,
933                                   TF);
934   else if (isVTi1Type)
935     T = DAG.getTargetConstantPool(CVal, ValTy, Align, Offset, TF);
936   else
937     T = DAG.getTargetConstantPool(CPN->getConstVal(), ValTy, Align, Offset, TF);
938 
939   assert(cast<ConstantPoolSDNode>(T)->getTargetFlags() == TF &&
940          "Inconsistent target flag encountered");
941 
942   if (IsPositionIndependent)
943     return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), ValTy, T);
944   return DAG.getNode(HexagonISD::CP, SDLoc(Op), ValTy, T);
945 }
946 
947 SDValue
948 HexagonTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
949   EVT VT = Op.getValueType();
950   int Idx = cast<JumpTableSDNode>(Op)->getIndex();
951   if (isPositionIndependent()) {
952     SDValue T = DAG.getTargetJumpTable(Idx, VT, HexagonII::MO_PCREL);
953     return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), VT, T);
954   }
955 
956   SDValue T = DAG.getTargetJumpTable(Idx, VT);
957   return DAG.getNode(HexagonISD::JT, SDLoc(Op), VT, T);
958 }
959 
960 SDValue
961 HexagonTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
962   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
963   MachineFunction &MF = DAG.getMachineFunction();
964   MachineFrameInfo &MFI = MF.getFrameInfo();
965   MFI.setReturnAddressIsTaken(true);
966 
967   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
968     return SDValue();
969 
970   EVT VT = Op.getValueType();
971   SDLoc dl(Op);
972   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
973   if (Depth) {
974     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
975     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
976     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
977                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
978                        MachinePointerInfo());
979   }
980 
981   // Return LR, which contains the return address. Mark it an implicit live-in.
982   unsigned Reg = MF.addLiveIn(HRI.getRARegister(), getRegClassFor(MVT::i32));
983   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
984 }
985 
986 SDValue
987 HexagonTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
988   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
989   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
990   MFI.setFrameAddressIsTaken(true);
991 
992   EVT VT = Op.getValueType();
993   SDLoc dl(Op);
994   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
995   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
996                                          HRI.getFrameRegister(), VT);
997   while (Depth--)
998     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
999                             MachinePointerInfo());
1000   return FrameAddr;
1001 }
1002 
1003 SDValue
1004 HexagonTargetLowering::LowerATOMIC_FENCE(SDValue Op, SelectionDAG& DAG) const {
1005   SDLoc dl(Op);
1006   return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
1007 }
1008 
1009 SDValue
1010 HexagonTargetLowering::LowerGLOBALADDRESS(SDValue Op, SelectionDAG &DAG) const {
1011   SDLoc dl(Op);
1012   auto *GAN = cast<GlobalAddressSDNode>(Op);
1013   auto PtrVT = getPointerTy(DAG.getDataLayout());
1014   auto *GV = GAN->getGlobal();
1015   int64_t Offset = GAN->getOffset();
1016 
1017   auto &HLOF = *HTM.getObjFileLowering();
1018   Reloc::Model RM = HTM.getRelocationModel();
1019 
1020   if (RM == Reloc::Static) {
1021     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
1022     const GlobalObject *GO = GV->getBaseObject();
1023     if (GO && Subtarget.useSmallData() && HLOF.isGlobalInSmallSection(GO, HTM))
1024       return DAG.getNode(HexagonISD::CONST32_GP, dl, PtrVT, GA);
1025     return DAG.getNode(HexagonISD::CONST32, dl, PtrVT, GA);
1026   }
1027 
1028   bool UsePCRel = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
1029   if (UsePCRel) {
1030     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset,
1031                                             HexagonII::MO_PCREL);
1032     return DAG.getNode(HexagonISD::AT_PCREL, dl, PtrVT, GA);
1033   }
1034 
1035   // Use GOT index.
1036   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1037   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, HexagonII::MO_GOT);
1038   SDValue Off = DAG.getConstant(Offset, dl, MVT::i32);
1039   return DAG.getNode(HexagonISD::AT_GOT, dl, PtrVT, GOT, GA, Off);
1040 }
1041 
1042 // Specifies that for loads and stores VT can be promoted to PromotedLdStVT.
1043 SDValue
1044 HexagonTargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1045   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1046   SDLoc dl(Op);
1047   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1048 
1049   Reloc::Model RM = HTM.getRelocationModel();
1050   if (RM == Reloc::Static) {
1051     SDValue A = DAG.getTargetBlockAddress(BA, PtrVT);
1052     return DAG.getNode(HexagonISD::CONST32_GP, dl, PtrVT, A);
1053   }
1054 
1055   SDValue A = DAG.getTargetBlockAddress(BA, PtrVT, 0, HexagonII::MO_PCREL);
1056   return DAG.getNode(HexagonISD::AT_PCREL, dl, PtrVT, A);
1057 }
1058 
1059 SDValue
1060 HexagonTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op, SelectionDAG &DAG)
1061       const {
1062   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1063   SDValue GOTSym = DAG.getTargetExternalSymbol(HEXAGON_GOT_SYM_NAME, PtrVT,
1064                                                HexagonII::MO_PCREL);
1065   return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), PtrVT, GOTSym);
1066 }
1067 
1068 SDValue
1069 HexagonTargetLowering::GetDynamicTLSAddr(SelectionDAG &DAG, SDValue Chain,
1070       GlobalAddressSDNode *GA, SDValue Glue, EVT PtrVT, unsigned ReturnReg,
1071       unsigned char OperandFlags) const {
1072   MachineFunction &MF = DAG.getMachineFunction();
1073   MachineFrameInfo &MFI = MF.getFrameInfo();
1074   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1075   SDLoc dl(GA);
1076   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
1077                                            GA->getValueType(0),
1078                                            GA->getOffset(),
1079                                            OperandFlags);
1080   // Create Operands for the call.The Operands should have the following:
1081   // 1. Chain SDValue
1082   // 2. Callee which in this case is the Global address value.
1083   // 3. Registers live into the call.In this case its R0, as we
1084   //    have just one argument to be passed.
1085   // 4. Glue.
1086   // Note: The order is important.
1087 
1088   const auto &HRI = *Subtarget.getRegisterInfo();
1089   const uint32_t *Mask = HRI.getCallPreservedMask(MF, CallingConv::C);
1090   assert(Mask && "Missing call preserved mask for calling convention");
1091   SDValue Ops[] = { Chain, TGA, DAG.getRegister(Hexagon::R0, PtrVT),
1092                     DAG.getRegisterMask(Mask), Glue };
1093   Chain = DAG.getNode(HexagonISD::CALL, dl, NodeTys, Ops);
1094 
1095   // Inform MFI that function has calls.
1096   MFI.setAdjustsStack(true);
1097 
1098   Glue = Chain.getValue(1);
1099   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
1100 }
1101 
1102 //
1103 // Lower using the intial executable model for TLS addresses
1104 //
1105 SDValue
1106 HexagonTargetLowering::LowerToTLSInitialExecModel(GlobalAddressSDNode *GA,
1107       SelectionDAG &DAG) const {
1108   SDLoc dl(GA);
1109   int64_t Offset = GA->getOffset();
1110   auto PtrVT = getPointerTy(DAG.getDataLayout());
1111 
1112   // Get the thread pointer.
1113   SDValue TP = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Hexagon::UGP, PtrVT);
1114 
1115   bool IsPositionIndependent = isPositionIndependent();
1116   unsigned char TF =
1117       IsPositionIndependent ? HexagonII::MO_IEGOT : HexagonII::MO_IE;
1118 
1119   // First generate the TLS symbol address
1120   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT,
1121                                            Offset, TF);
1122 
1123   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1124 
1125   if (IsPositionIndependent) {
1126     // Generate the GOT pointer in case of position independent code
1127     SDValue GOT = LowerGLOBAL_OFFSET_TABLE(Sym, DAG);
1128 
1129     // Add the TLS Symbol address to GOT pointer.This gives
1130     // GOT relative relocation for the symbol.
1131     Sym = DAG.getNode(ISD::ADD, dl, PtrVT, GOT, Sym);
1132   }
1133 
1134   // Load the offset value for TLS symbol.This offset is relative to
1135   // thread pointer.
1136   SDValue LoadOffset =
1137       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Sym, MachinePointerInfo());
1138 
1139   // Address of the thread local variable is the add of thread
1140   // pointer and the offset of the variable.
1141   return DAG.getNode(ISD::ADD, dl, PtrVT, TP, LoadOffset);
1142 }
1143 
1144 //
1145 // Lower using the local executable model for TLS addresses
1146 //
1147 SDValue
1148 HexagonTargetLowering::LowerToTLSLocalExecModel(GlobalAddressSDNode *GA,
1149       SelectionDAG &DAG) const {
1150   SDLoc dl(GA);
1151   int64_t Offset = GA->getOffset();
1152   auto PtrVT = getPointerTy(DAG.getDataLayout());
1153 
1154   // Get the thread pointer.
1155   SDValue TP = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Hexagon::UGP, PtrVT);
1156   // Generate the TLS symbol address
1157   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT, Offset,
1158                                            HexagonII::MO_TPREL);
1159   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1160 
1161   // Address of the thread local variable is the add of thread
1162   // pointer and the offset of the variable.
1163   return DAG.getNode(ISD::ADD, dl, PtrVT, TP, Sym);
1164 }
1165 
1166 //
1167 // Lower using the general dynamic model for TLS addresses
1168 //
1169 SDValue
1170 HexagonTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1171       SelectionDAG &DAG) const {
1172   SDLoc dl(GA);
1173   int64_t Offset = GA->getOffset();
1174   auto PtrVT = getPointerTy(DAG.getDataLayout());
1175 
1176   // First generate the TLS symbol address
1177   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT, Offset,
1178                                            HexagonII::MO_GDGOT);
1179 
1180   // Then, generate the GOT pointer
1181   SDValue GOT = LowerGLOBAL_OFFSET_TABLE(TGA, DAG);
1182 
1183   // Add the TLS symbol and the GOT pointer
1184   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1185   SDValue Chain = DAG.getNode(ISD::ADD, dl, PtrVT, GOT, Sym);
1186 
1187   // Copy over the argument to R0
1188   SDValue InFlag;
1189   Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, Hexagon::R0, Chain, InFlag);
1190   InFlag = Chain.getValue(1);
1191 
1192   unsigned Flags =
1193       static_cast<const HexagonSubtarget &>(DAG.getSubtarget()).useLongCalls()
1194           ? HexagonII::MO_GDPLT | HexagonII::HMOTF_ConstExtended
1195           : HexagonII::MO_GDPLT;
1196 
1197   return GetDynamicTLSAddr(DAG, Chain, GA, InFlag, PtrVT,
1198                            Hexagon::R0, Flags);
1199 }
1200 
1201 //
1202 // Lower TLS addresses.
1203 //
1204 // For now for dynamic models, we only support the general dynamic model.
1205 //
1206 SDValue
1207 HexagonTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1208       SelectionDAG &DAG) const {
1209   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1210 
1211   switch (HTM.getTLSModel(GA->getGlobal())) {
1212     case TLSModel::GeneralDynamic:
1213     case TLSModel::LocalDynamic:
1214       return LowerToTLSGeneralDynamicModel(GA, DAG);
1215     case TLSModel::InitialExec:
1216       return LowerToTLSInitialExecModel(GA, DAG);
1217     case TLSModel::LocalExec:
1218       return LowerToTLSLocalExecModel(GA, DAG);
1219   }
1220   llvm_unreachable("Bogus TLS model");
1221 }
1222 
1223 //===----------------------------------------------------------------------===//
1224 // TargetLowering Implementation
1225 //===----------------------------------------------------------------------===//
1226 
1227 HexagonTargetLowering::HexagonTargetLowering(const TargetMachine &TM,
1228                                              const HexagonSubtarget &ST)
1229     : TargetLowering(TM), HTM(static_cast<const HexagonTargetMachine&>(TM)),
1230       Subtarget(ST) {
1231   auto &HRI = *Subtarget.getRegisterInfo();
1232 
1233   setPrefLoopAlignment(4);
1234   setPrefFunctionAlignment(4);
1235   setMinFunctionAlignment(2);
1236   setStackPointerRegisterToSaveRestore(HRI.getStackRegister());
1237   setBooleanContents(TargetLoweringBase::UndefinedBooleanContent);
1238   setBooleanVectorContents(TargetLoweringBase::UndefinedBooleanContent);
1239 
1240   setMaxAtomicSizeInBitsSupported(64);
1241   setMinCmpXchgSizeInBits(32);
1242 
1243   if (EnableHexSDNodeSched)
1244     setSchedulingPreference(Sched::VLIW);
1245   else
1246     setSchedulingPreference(Sched::Source);
1247 
1248   // Limits for inline expansion of memcpy/memmove
1249   MaxStoresPerMemcpy = MaxStoresPerMemcpyCL;
1250   MaxStoresPerMemcpyOptSize = MaxStoresPerMemcpyOptSizeCL;
1251   MaxStoresPerMemmove = MaxStoresPerMemmoveCL;
1252   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmoveOptSizeCL;
1253   MaxStoresPerMemset = MaxStoresPerMemsetCL;
1254   MaxStoresPerMemsetOptSize = MaxStoresPerMemsetOptSizeCL;
1255 
1256   //
1257   // Set up register classes.
1258   //
1259 
1260   addRegisterClass(MVT::i1,    &Hexagon::PredRegsRegClass);
1261   addRegisterClass(MVT::v2i1,  &Hexagon::PredRegsRegClass);  // bbbbaaaa
1262   addRegisterClass(MVT::v4i1,  &Hexagon::PredRegsRegClass);  // ddccbbaa
1263   addRegisterClass(MVT::v8i1,  &Hexagon::PredRegsRegClass);  // hgfedcba
1264   addRegisterClass(MVT::i32,   &Hexagon::IntRegsRegClass);
1265   addRegisterClass(MVT::v2i16, &Hexagon::IntRegsRegClass);
1266   addRegisterClass(MVT::v4i8,  &Hexagon::IntRegsRegClass);
1267   addRegisterClass(MVT::i64,   &Hexagon::DoubleRegsRegClass);
1268   addRegisterClass(MVT::v8i8,  &Hexagon::DoubleRegsRegClass);
1269   addRegisterClass(MVT::v4i16, &Hexagon::DoubleRegsRegClass);
1270   addRegisterClass(MVT::v2i32, &Hexagon::DoubleRegsRegClass);
1271 
1272   addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
1273   addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
1274 
1275   //
1276   // Handling of scalar operations.
1277   //
1278   // All operations default to "legal", except:
1279   // - indexed loads and stores (pre-/post-incremented),
1280   // - ANY_EXTEND_VECTOR_INREG, ATOMIC_CMP_SWAP_WITH_SUCCESS, CONCAT_VECTORS,
1281   //   ConstantFP, DEBUGTRAP, FCEIL, FCOPYSIGN, FEXP, FEXP2, FFLOOR, FGETSIGN,
1282   //   FLOG, FLOG2, FLOG10, FMAXNUM, FMINNUM, FNEARBYINT, FRINT, FROUND, TRAP,
1283   //   FTRUNC, PREFETCH, SIGN_EXTEND_VECTOR_INREG, ZERO_EXTEND_VECTOR_INREG,
1284   // which default to "expand" for at least one type.
1285 
1286   // Misc operations.
1287   setOperationAction(ISD::ConstantFP,           MVT::f32,   Legal);
1288   setOperationAction(ISD::ConstantFP,           MVT::f64,   Legal);
1289   setOperationAction(ISD::TRAP,                 MVT::Other, Legal);
1290   setOperationAction(ISD::ConstantPool,         MVT::i32,   Custom);
1291   setOperationAction(ISD::JumpTable,            MVT::i32,   Custom);
1292   setOperationAction(ISD::BUILD_PAIR,           MVT::i64,   Expand);
1293   setOperationAction(ISD::SIGN_EXTEND_INREG,    MVT::i1,    Expand);
1294   setOperationAction(ISD::INLINEASM,            MVT::Other, Custom);
1295   setOperationAction(ISD::PREFETCH,             MVT::Other, Custom);
1296   setOperationAction(ISD::READCYCLECOUNTER,     MVT::i64,   Custom);
1297   setOperationAction(ISD::INTRINSIC_VOID,       MVT::Other, Custom);
1298   setOperationAction(ISD::EH_RETURN,            MVT::Other, Custom);
1299   setOperationAction(ISD::GLOBAL_OFFSET_TABLE,  MVT::i32,   Custom);
1300   setOperationAction(ISD::GlobalTLSAddress,     MVT::i32,   Custom);
1301   setOperationAction(ISD::ATOMIC_FENCE,         MVT::Other, Custom);
1302 
1303   // Custom legalize GlobalAddress nodes into CONST32.
1304   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1305   setOperationAction(ISD::GlobalAddress, MVT::i8,  Custom);
1306   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
1307 
1308   // Hexagon needs to optimize cases with negative constants.
1309   setOperationAction(ISD::SETCC, MVT::i8,    Custom);
1310   setOperationAction(ISD::SETCC, MVT::i16,   Custom);
1311   setOperationAction(ISD::SETCC, MVT::v4i8,  Custom);
1312   setOperationAction(ISD::SETCC, MVT::v2i16, Custom);
1313 
1314   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1315   setOperationAction(ISD::VASTART, MVT::Other, Custom);
1316   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
1317   setOperationAction(ISD::VAARG,   MVT::Other, Expand);
1318   setOperationAction(ISD::VACOPY,  MVT::Other, Expand);
1319 
1320   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1321   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1322   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1323 
1324   if (EmitJumpTables)
1325     setMinimumJumpTableEntries(MinimumJumpTables);
1326   else
1327     setMinimumJumpTableEntries(std::numeric_limits<int>::max());
1328   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1329 
1330   setOperationAction(ISD::ABS, MVT::i32, Legal);
1331   setOperationAction(ISD::ABS, MVT::i64, Legal);
1332 
1333   // Hexagon has A4_addp_c and A4_subp_c that take and generate a carry bit,
1334   // but they only operate on i64.
1335   for (MVT VT : MVT::integer_valuetypes()) {
1336     setOperationAction(ISD::UADDO,    VT, Expand);
1337     setOperationAction(ISD::USUBO,    VT, Expand);
1338     setOperationAction(ISD::SADDO,    VT, Expand);
1339     setOperationAction(ISD::SSUBO,    VT, Expand);
1340     setOperationAction(ISD::ADDCARRY, VT, Expand);
1341     setOperationAction(ISD::SUBCARRY, VT, Expand);
1342   }
1343   setOperationAction(ISD::ADDCARRY, MVT::i64, Custom);
1344   setOperationAction(ISD::SUBCARRY, MVT::i64, Custom);
1345 
1346   setOperationAction(ISD::CTLZ, MVT::i8,  Promote);
1347   setOperationAction(ISD::CTLZ, MVT::i16, Promote);
1348   setOperationAction(ISD::CTTZ, MVT::i8,  Promote);
1349   setOperationAction(ISD::CTTZ, MVT::i16, Promote);
1350 
1351   // Popcount can count # of 1s in i64 but returns i32.
1352   setOperationAction(ISD::CTPOP, MVT::i8,  Promote);
1353   setOperationAction(ISD::CTPOP, MVT::i16, Promote);
1354   setOperationAction(ISD::CTPOP, MVT::i32, Promote);
1355   setOperationAction(ISD::CTPOP, MVT::i64, Legal);
1356 
1357   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1358   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
1359   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
1360   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
1361 
1362   for (unsigned IntExpOp :
1363        {ISD::SDIV,      ISD::UDIV,      ISD::SREM,      ISD::UREM,
1364         ISD::SDIVREM,   ISD::UDIVREM,   ISD::ROTL,      ISD::ROTR,
1365         ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS,
1366         ISD::SMUL_LOHI, ISD::UMUL_LOHI}) {
1367     for (MVT VT : MVT::integer_valuetypes())
1368       setOperationAction(IntExpOp, VT, Expand);
1369   }
1370 
1371   for (unsigned FPExpOp :
1372        {ISD::FDIV, ISD::FREM, ISD::FSQRT, ISD::FSIN, ISD::FCOS, ISD::FSINCOS,
1373         ISD::FPOW, ISD::FCOPYSIGN}) {
1374     for (MVT VT : MVT::fp_valuetypes())
1375       setOperationAction(FPExpOp, VT, Expand);
1376   }
1377 
1378   // No extending loads from i32.
1379   for (MVT VT : MVT::integer_valuetypes()) {
1380     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
1381     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
1382     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i32, Expand);
1383   }
1384   // Turn FP truncstore into trunc + store.
1385   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1386   // Turn FP extload into load/fpextend.
1387   for (MVT VT : MVT::fp_valuetypes())
1388     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1389 
1390   // Expand BR_CC and SELECT_CC for all integer and fp types.
1391   for (MVT VT : MVT::integer_valuetypes()) {
1392     setOperationAction(ISD::BR_CC,     VT, Expand);
1393     setOperationAction(ISD::SELECT_CC, VT, Expand);
1394   }
1395   for (MVT VT : MVT::fp_valuetypes()) {
1396     setOperationAction(ISD::BR_CC,     VT, Expand);
1397     setOperationAction(ISD::SELECT_CC, VT, Expand);
1398   }
1399   setOperationAction(ISD::BR_CC, MVT::Other, Expand);
1400 
1401   //
1402   // Handling of vector operations.
1403   //
1404 
1405   // Set the action for vector operations to "expand", then override it with
1406   // either "custom" or "legal" for specific cases.
1407   static const unsigned VectExpOps[] = {
1408     // Integer arithmetic:
1409     ISD::ADD,     ISD::SUB,     ISD::MUL,     ISD::SDIV,      ISD::UDIV,
1410     ISD::SREM,    ISD::UREM,    ISD::SDIVREM, ISD::UDIVREM,   ISD::SADDO,
1411     ISD::UADDO,   ISD::SSUBO,   ISD::USUBO,   ISD::SMUL_LOHI, ISD::UMUL_LOHI,
1412     // Logical/bit:
1413     ISD::AND,     ISD::OR,      ISD::XOR,     ISD::ROTL,    ISD::ROTR,
1414     ISD::CTPOP,   ISD::CTLZ,    ISD::CTTZ,
1415     // Floating point arithmetic/math functions:
1416     ISD::FADD,    ISD::FSUB,    ISD::FMUL,    ISD::FMA,     ISD::FDIV,
1417     ISD::FREM,    ISD::FNEG,    ISD::FABS,    ISD::FSQRT,   ISD::FSIN,
1418     ISD::FCOS,    ISD::FPOW,    ISD::FLOG,    ISD::FLOG2,
1419     ISD::FLOG10,  ISD::FEXP,    ISD::FEXP2,   ISD::FCEIL,   ISD::FTRUNC,
1420     ISD::FRINT,   ISD::FNEARBYINT,            ISD::FROUND,  ISD::FFLOOR,
1421     ISD::FMINNUM, ISD::FMAXNUM, ISD::FSINCOS,
1422     // Misc:
1423     ISD::BR_CC,   ISD::SELECT_CC,             ISD::ConstantPool,
1424     // Vector:
1425     ISD::BUILD_VECTOR,          ISD::SCALAR_TO_VECTOR,
1426     ISD::EXTRACT_VECTOR_ELT,    ISD::INSERT_VECTOR_ELT,
1427     ISD::EXTRACT_SUBVECTOR,     ISD::INSERT_SUBVECTOR,
1428     ISD::CONCAT_VECTORS,        ISD::VECTOR_SHUFFLE
1429   };
1430 
1431   for (MVT VT : MVT::vector_valuetypes()) {
1432     for (unsigned VectExpOp : VectExpOps)
1433       setOperationAction(VectExpOp, VT, Expand);
1434 
1435     // Expand all extending loads and truncating stores:
1436     for (MVT TargetVT : MVT::vector_valuetypes()) {
1437       if (TargetVT == VT)
1438         continue;
1439       setLoadExtAction(ISD::EXTLOAD, TargetVT, VT, Expand);
1440       setLoadExtAction(ISD::ZEXTLOAD, TargetVT, VT, Expand);
1441       setLoadExtAction(ISD::SEXTLOAD, TargetVT, VT, Expand);
1442       setTruncStoreAction(VT, TargetVT, Expand);
1443     }
1444 
1445     // Normalize all inputs to SELECT to be vectors of i32.
1446     if (VT.getVectorElementType() != MVT::i32) {
1447       MVT VT32 = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
1448       setOperationAction(ISD::SELECT, VT, Promote);
1449       AddPromotedToType(ISD::SELECT, VT, VT32);
1450     }
1451     setOperationAction(ISD::SRA, VT, Custom);
1452     setOperationAction(ISD::SHL, VT, Custom);
1453     setOperationAction(ISD::SRL, VT, Custom);
1454   }
1455 
1456   // Extending loads from (native) vectors of i8 into (native) vectors of i16
1457   // are legal.
1458   setLoadExtAction(ISD::EXTLOAD,  MVT::v2i16, MVT::v2i8, Legal);
1459   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1460   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1461   setLoadExtAction(ISD::EXTLOAD,  MVT::v4i16, MVT::v4i8, Legal);
1462   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1463   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1464 
1465   // Types natively supported:
1466   for (MVT NativeVT : {MVT::v8i1, MVT::v4i1, MVT::v2i1, MVT::v4i8,
1467                        MVT::v8i8, MVT::v2i16, MVT::v4i16, MVT::v2i32}) {
1468     setOperationAction(ISD::BUILD_VECTOR,       NativeVT, Custom);
1469     setOperationAction(ISD::EXTRACT_VECTOR_ELT, NativeVT, Custom);
1470     setOperationAction(ISD::INSERT_VECTOR_ELT,  NativeVT, Custom);
1471     setOperationAction(ISD::EXTRACT_SUBVECTOR,  NativeVT, Custom);
1472     setOperationAction(ISD::INSERT_SUBVECTOR,   NativeVT, Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     NativeVT, Custom);
1474 
1475     setOperationAction(ISD::ADD, NativeVT, Legal);
1476     setOperationAction(ISD::SUB, NativeVT, Legal);
1477     setOperationAction(ISD::MUL, NativeVT, Legal);
1478     setOperationAction(ISD::AND, NativeVT, Legal);
1479     setOperationAction(ISD::OR,  NativeVT, Legal);
1480     setOperationAction(ISD::XOR, NativeVT, Legal);
1481   }
1482 
1483   // Custom lower unaligned loads.
1484   // Also, for both loads and stores, verify the alignment of the address
1485   // in case it is a compile-time constant. This is a usability feature to
1486   // provide a meaningful error message to users.
1487   for (MVT VT : {MVT::i16, MVT::i32, MVT::v4i8, MVT::i64, MVT::v8i8,
1488                  MVT::v2i16, MVT::v4i16, MVT::v2i32}) {
1489     setOperationAction(ISD::LOAD,  VT, Custom);
1490     setOperationAction(ISD::STORE, VT, Custom);
1491   }
1492 
1493   for (MVT VT : {MVT::v2i16, MVT::v4i8, MVT::v2i32, MVT::v4i16, MVT::v2i32}) {
1494     setCondCodeAction(ISD::SETLT,  VT, Expand);
1495     setCondCodeAction(ISD::SETLE,  VT, Expand);
1496     setCondCodeAction(ISD::SETULT, VT, Expand);
1497     setCondCodeAction(ISD::SETULE, VT, Expand);
1498   }
1499 
1500   // Custom-lower bitcasts from i8 to v8i1.
1501   setOperationAction(ISD::BITCAST,        MVT::i8,    Custom);
1502   setOperationAction(ISD::SETCC,          MVT::v2i16, Custom);
1503   setOperationAction(ISD::VSELECT,        MVT::v2i16, Custom);
1504   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i8,  Custom);
1505   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
1506   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8,  Custom);
1507 
1508   // Subtarget-specific operation actions.
1509   //
1510   if (Subtarget.hasV60Ops()) {
1511     setOperationAction(ISD::ROTL, MVT::i32, Custom);
1512     setOperationAction(ISD::ROTL, MVT::i64, Custom);
1513   }
1514 
1515   // V5+.
1516   setOperationAction(ISD::FMA,  MVT::f64, Expand);
1517   setOperationAction(ISD::FADD, MVT::f64, Expand);
1518   setOperationAction(ISD::FSUB, MVT::f64, Expand);
1519   setOperationAction(ISD::FMUL, MVT::f64, Expand);
1520 
1521   setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1522   setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1523 
1524   setOperationAction(ISD::FP_TO_UINT, MVT::i1,  Promote);
1525   setOperationAction(ISD::FP_TO_UINT, MVT::i8,  Promote);
1526   setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
1527   setOperationAction(ISD::FP_TO_SINT, MVT::i1,  Promote);
1528   setOperationAction(ISD::FP_TO_SINT, MVT::i8,  Promote);
1529   setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
1530   setOperationAction(ISD::UINT_TO_FP, MVT::i1,  Promote);
1531   setOperationAction(ISD::UINT_TO_FP, MVT::i8,  Promote);
1532   setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
1533   setOperationAction(ISD::SINT_TO_FP, MVT::i1,  Promote);
1534   setOperationAction(ISD::SINT_TO_FP, MVT::i8,  Promote);
1535   setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
1536 
1537   // Handling of indexed loads/stores: default is "expand".
1538   //
1539   for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64, MVT::f32, MVT::f64,
1540                  MVT::v2i16, MVT::v2i32, MVT::v4i8, MVT::v4i16, MVT::v8i8}) {
1541     setIndexedLoadAction(ISD::POST_INC, VT, Legal);
1542     setIndexedStoreAction(ISD::POST_INC, VT, Legal);
1543   }
1544 
1545   if (Subtarget.useHVXOps())
1546     initializeHVXLowering();
1547 
1548   computeRegisterProperties(&HRI);
1549 
1550   //
1551   // Library calls for unsupported operations
1552   //
1553   bool FastMath  = EnableFastMath;
1554 
1555   setLibcallName(RTLIB::SDIV_I32, "__hexagon_divsi3");
1556   setLibcallName(RTLIB::SDIV_I64, "__hexagon_divdi3");
1557   setLibcallName(RTLIB::UDIV_I32, "__hexagon_udivsi3");
1558   setLibcallName(RTLIB::UDIV_I64, "__hexagon_udivdi3");
1559   setLibcallName(RTLIB::SREM_I32, "__hexagon_modsi3");
1560   setLibcallName(RTLIB::SREM_I64, "__hexagon_moddi3");
1561   setLibcallName(RTLIB::UREM_I32, "__hexagon_umodsi3");
1562   setLibcallName(RTLIB::UREM_I64, "__hexagon_umoddi3");
1563 
1564   setLibcallName(RTLIB::SINTTOFP_I128_F64, "__hexagon_floattidf");
1565   setLibcallName(RTLIB::SINTTOFP_I128_F32, "__hexagon_floattisf");
1566   setLibcallName(RTLIB::FPTOUINT_F32_I128, "__hexagon_fixunssfti");
1567   setLibcallName(RTLIB::FPTOUINT_F64_I128, "__hexagon_fixunsdfti");
1568   setLibcallName(RTLIB::FPTOSINT_F32_I128, "__hexagon_fixsfti");
1569   setLibcallName(RTLIB::FPTOSINT_F64_I128, "__hexagon_fixdfti");
1570 
1571   // This is the only fast library function for sqrtd.
1572   if (FastMath)
1573     setLibcallName(RTLIB::SQRT_F64, "__hexagon_fast2_sqrtdf2");
1574 
1575   // Prefix is: nothing  for "slow-math",
1576   //            "fast2_" for V5+ fast-math double-precision
1577   // (actually, keep fast-math and fast-math2 separate for now)
1578   if (FastMath) {
1579     setLibcallName(RTLIB::ADD_F64, "__hexagon_fast_adddf3");
1580     setLibcallName(RTLIB::SUB_F64, "__hexagon_fast_subdf3");
1581     setLibcallName(RTLIB::MUL_F64, "__hexagon_fast_muldf3");
1582     setLibcallName(RTLIB::DIV_F64, "__hexagon_fast_divdf3");
1583     setLibcallName(RTLIB::DIV_F32, "__hexagon_fast_divsf3");
1584   } else {
1585     setLibcallName(RTLIB::ADD_F64, "__hexagon_adddf3");
1586     setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
1587     setLibcallName(RTLIB::MUL_F64, "__hexagon_muldf3");
1588     setLibcallName(RTLIB::DIV_F64, "__hexagon_divdf3");
1589     setLibcallName(RTLIB::DIV_F32, "__hexagon_divsf3");
1590   }
1591 
1592   if (FastMath)
1593     setLibcallName(RTLIB::SQRT_F32, "__hexagon_fast2_sqrtf");
1594   else
1595     setLibcallName(RTLIB::SQRT_F32, "__hexagon_sqrtf");
1596 
1597   // These cause problems when the shift amount is non-constant.
1598   setLibcallName(RTLIB::SHL_I128, nullptr);
1599   setLibcallName(RTLIB::SRL_I128, nullptr);
1600   setLibcallName(RTLIB::SRA_I128, nullptr);
1601 }
1602 
1603 const char* HexagonTargetLowering::getTargetNodeName(unsigned Opcode) const {
1604   switch ((HexagonISD::NodeType)Opcode) {
1605   case HexagonISD::ADDC:          return "HexagonISD::ADDC";
1606   case HexagonISD::SUBC:          return "HexagonISD::SUBC";
1607   case HexagonISD::ALLOCA:        return "HexagonISD::ALLOCA";
1608   case HexagonISD::AT_GOT:        return "HexagonISD::AT_GOT";
1609   case HexagonISD::AT_PCREL:      return "HexagonISD::AT_PCREL";
1610   case HexagonISD::BARRIER:       return "HexagonISD::BARRIER";
1611   case HexagonISD::CALL:          return "HexagonISD::CALL";
1612   case HexagonISD::CALLnr:        return "HexagonISD::CALLnr";
1613   case HexagonISD::CALLR:         return "HexagonISD::CALLR";
1614   case HexagonISD::COMBINE:       return "HexagonISD::COMBINE";
1615   case HexagonISD::CONST32_GP:    return "HexagonISD::CONST32_GP";
1616   case HexagonISD::CONST32:       return "HexagonISD::CONST32";
1617   case HexagonISD::CP:            return "HexagonISD::CP";
1618   case HexagonISD::DCFETCH:       return "HexagonISD::DCFETCH";
1619   case HexagonISD::EH_RETURN:     return "HexagonISD::EH_RETURN";
1620   case HexagonISD::TSTBIT:        return "HexagonISD::TSTBIT";
1621   case HexagonISD::EXTRACTU:      return "HexagonISD::EXTRACTU";
1622   case HexagonISD::INSERT:        return "HexagonISD::INSERT";
1623   case HexagonISD::JT:            return "HexagonISD::JT";
1624   case HexagonISD::RET_FLAG:      return "HexagonISD::RET_FLAG";
1625   case HexagonISD::TC_RETURN:     return "HexagonISD::TC_RETURN";
1626   case HexagonISD::VASL:          return "HexagonISD::VASL";
1627   case HexagonISD::VASR:          return "HexagonISD::VASR";
1628   case HexagonISD::VLSR:          return "HexagonISD::VLSR";
1629   case HexagonISD::VSPLAT:        return "HexagonISD::VSPLAT";
1630   case HexagonISD::VEXTRACTW:     return "HexagonISD::VEXTRACTW";
1631   case HexagonISD::VINSERTW0:     return "HexagonISD::VINSERTW0";
1632   case HexagonISD::VROR:          return "HexagonISD::VROR";
1633   case HexagonISD::READCYCLE:     return "HexagonISD::READCYCLE";
1634   case HexagonISD::VZERO:         return "HexagonISD::VZERO";
1635   case HexagonISD::VSPLATW:       return "HexagonISD::VSPLATW";
1636   case HexagonISD::D2P:           return "HexagonISD::D2P";
1637   case HexagonISD::P2D:           return "HexagonISD::P2D";
1638   case HexagonISD::V2Q:           return "HexagonISD::V2Q";
1639   case HexagonISD::Q2V:           return "HexagonISD::Q2V";
1640   case HexagonISD::QCAT:          return "HexagonISD::QCAT";
1641   case HexagonISD::QTRUE:         return "HexagonISD::QTRUE";
1642   case HexagonISD::QFALSE:        return "HexagonISD::QFALSE";
1643   case HexagonISD::TYPECAST:      return "HexagonISD::TYPECAST";
1644   case HexagonISD::VALIGN:        return "HexagonISD::VALIGN";
1645   case HexagonISD::VALIGNADDR:    return "HexagonISD::VALIGNADDR";
1646   case HexagonISD::OP_END:        break;
1647   }
1648   return nullptr;
1649 }
1650 
1651 void
1652 HexagonTargetLowering::validateConstPtrAlignment(SDValue Ptr, const SDLoc &dl,
1653       unsigned NeedAlign) const {
1654   auto *CA = dyn_cast<ConstantSDNode>(Ptr);
1655   if (!CA)
1656     return;
1657   unsigned Addr = CA->getZExtValue();
1658   unsigned HaveAlign = Addr != 0 ? 1u << countTrailingZeros(Addr) : NeedAlign;
1659   if (HaveAlign < NeedAlign) {
1660     std::string ErrMsg;
1661     raw_string_ostream O(ErrMsg);
1662     O << "Misaligned constant address: " << format_hex(Addr, 10)
1663       << " has alignment " << HaveAlign
1664       << ", but the memory access requires " << NeedAlign;
1665     if (DebugLoc DL = dl.getDebugLoc())
1666       DL.print(O << ", at ");
1667     report_fatal_error(O.str());
1668   }
1669 }
1670 
1671 // Bit-reverse Load Intrinsic: Check if the instruction is a bit reverse load
1672 // intrinsic.
1673 static bool isBrevLdIntrinsic(const Value *Inst) {
1674   unsigned ID = cast<IntrinsicInst>(Inst)->getIntrinsicID();
1675   return (ID == Intrinsic::hexagon_L2_loadrd_pbr ||
1676           ID == Intrinsic::hexagon_L2_loadri_pbr ||
1677           ID == Intrinsic::hexagon_L2_loadrh_pbr ||
1678           ID == Intrinsic::hexagon_L2_loadruh_pbr ||
1679           ID == Intrinsic::hexagon_L2_loadrb_pbr ||
1680           ID == Intrinsic::hexagon_L2_loadrub_pbr);
1681 }
1682 
1683 // Bit-reverse Load Intrinsic :Crawl up and figure out the object from previous
1684 // instruction. So far we only handle bitcast, extract value and bit reverse
1685 // load intrinsic instructions. Should we handle CGEP ?
1686 static Value *getBrevLdObject(Value *V) {
1687   if (Operator::getOpcode(V) == Instruction::ExtractValue ||
1688       Operator::getOpcode(V) == Instruction::BitCast)
1689     V = cast<Operator>(V)->getOperand(0);
1690   else if (isa<IntrinsicInst>(V) && isBrevLdIntrinsic(V))
1691     V = cast<Instruction>(V)->getOperand(0);
1692   return V;
1693 }
1694 
1695 // Bit-reverse Load Intrinsic: For a PHI Node return either an incoming edge or
1696 // a back edge. If the back edge comes from the intrinsic itself, the incoming
1697 // edge is returned.
1698 static Value *returnEdge(const PHINode *PN, Value *IntrBaseVal) {
1699   const BasicBlock *Parent = PN->getParent();
1700   int Idx = -1;
1701   for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1702     BasicBlock *Blk = PN->getIncomingBlock(i);
1703     // Determine if the back edge is originated from intrinsic.
1704     if (Blk == Parent) {
1705       Value *BackEdgeVal = PN->getIncomingValue(i);
1706       Value *BaseVal;
1707       // Loop over till we return the same Value or we hit the IntrBaseVal.
1708       do {
1709         BaseVal = BackEdgeVal;
1710         BackEdgeVal = getBrevLdObject(BackEdgeVal);
1711       } while ((BaseVal != BackEdgeVal) && (IntrBaseVal != BackEdgeVal));
1712       // If the getBrevLdObject returns IntrBaseVal, we should return the
1713       // incoming edge.
1714       if (IntrBaseVal == BackEdgeVal)
1715         continue;
1716       Idx = i;
1717       break;
1718     } else // Set the node to incoming edge.
1719       Idx = i;
1720   }
1721   assert(Idx >= 0 && "Unexpected index to incoming argument in PHI");
1722   return PN->getIncomingValue(Idx);
1723 }
1724 
1725 // Bit-reverse Load Intrinsic: Figure out the underlying object the base
1726 // pointer points to, for the bit-reverse load intrinsic. Setting this to
1727 // memoperand might help alias analysis to figure out the dependencies.
1728 static Value *getUnderLyingObjectForBrevLdIntr(Value *V) {
1729   Value *IntrBaseVal = V;
1730   Value *BaseVal;
1731   // Loop over till we return the same Value, implies we either figure out
1732   // the object or we hit a PHI
1733   do {
1734     BaseVal = V;
1735     V = getBrevLdObject(V);
1736   } while (BaseVal != V);
1737 
1738   // Identify the object from PHINode.
1739   if (const PHINode *PN = dyn_cast<PHINode>(V))
1740     return returnEdge(PN, IntrBaseVal);
1741   // For non PHI nodes, the object is the last value returned by getBrevLdObject
1742   else
1743     return V;
1744 }
1745 
1746 /// Given an intrinsic, checks if on the target the intrinsic will need to map
1747 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
1748 /// true and store the intrinsic information into the IntrinsicInfo that was
1749 /// passed to the function.
1750 bool HexagonTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1751                                                const CallInst &I,
1752                                                MachineFunction &MF,
1753                                                unsigned Intrinsic) const {
1754   switch (Intrinsic) {
1755   case Intrinsic::hexagon_L2_loadrd_pbr:
1756   case Intrinsic::hexagon_L2_loadri_pbr:
1757   case Intrinsic::hexagon_L2_loadrh_pbr:
1758   case Intrinsic::hexagon_L2_loadruh_pbr:
1759   case Intrinsic::hexagon_L2_loadrb_pbr:
1760   case Intrinsic::hexagon_L2_loadrub_pbr: {
1761     Info.opc = ISD::INTRINSIC_W_CHAIN;
1762     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
1763     auto &Cont = I.getCalledFunction()->getParent()->getContext();
1764     // The intrinsic function call is of the form { ElTy, i8* }
1765     // @llvm.hexagon.L2.loadXX.pbr(i8*, i32). The pointer and memory access type
1766     // should be derived from ElTy.
1767     PointerType *PtrTy = I.getCalledFunction()
1768                              ->getReturnType()
1769                              ->getContainedType(0)
1770                              ->getPointerTo();
1771     Info.memVT = MVT::getVT(PtrTy->getElementType());
1772     llvm::Value *BasePtrVal = I.getOperand(0);
1773     Info.ptrVal = getUnderLyingObjectForBrevLdIntr(BasePtrVal);
1774     // The offset value comes through Modifier register. For now, assume the
1775     // offset is 0.
1776     Info.offset = 0;
1777     Info.align = DL.getABITypeAlignment(Info.memVT.getTypeForEVT(Cont));
1778     Info.flags = MachineMemOperand::MOLoad;
1779     return true;
1780   }
1781   case Intrinsic::hexagon_V6_vgathermw:
1782   case Intrinsic::hexagon_V6_vgathermw_128B:
1783   case Intrinsic::hexagon_V6_vgathermh:
1784   case Intrinsic::hexagon_V6_vgathermh_128B:
1785   case Intrinsic::hexagon_V6_vgathermhw:
1786   case Intrinsic::hexagon_V6_vgathermhw_128B:
1787   case Intrinsic::hexagon_V6_vgathermwq:
1788   case Intrinsic::hexagon_V6_vgathermwq_128B:
1789   case Intrinsic::hexagon_V6_vgathermhq:
1790   case Intrinsic::hexagon_V6_vgathermhq_128B:
1791   case Intrinsic::hexagon_V6_vgathermhwq:
1792   case Intrinsic::hexagon_V6_vgathermhwq_128B: {
1793     const Module &M = *I.getParent()->getParent()->getParent();
1794     Info.opc = ISD::INTRINSIC_W_CHAIN;
1795     Type *VecTy = I.getArgOperand(1)->getType();
1796     Info.memVT = MVT::getVT(VecTy);
1797     Info.ptrVal = I.getArgOperand(0);
1798     Info.offset = 0;
1799     Info.align = M.getDataLayout().getTypeAllocSizeInBits(VecTy) / 8;
1800     Info.flags = MachineMemOperand::MOLoad |
1801                  MachineMemOperand::MOStore |
1802                  MachineMemOperand::MOVolatile;
1803     return true;
1804   }
1805   default:
1806     break;
1807   }
1808   return false;
1809 }
1810 
1811 bool HexagonTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
1812   return isTruncateFree(EVT::getEVT(Ty1), EVT::getEVT(Ty2));
1813 }
1814 
1815 bool HexagonTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1816   if (!VT1.isSimple() || !VT2.isSimple())
1817     return false;
1818   return VT1.getSimpleVT() == MVT::i64 && VT2.getSimpleVT() == MVT::i32;
1819 }
1820 
1821 bool HexagonTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
1822   return isOperationLegalOrCustom(ISD::FMA, VT);
1823 }
1824 
1825 // Should we expand the build vector with shuffles?
1826 bool HexagonTargetLowering::shouldExpandBuildVectorWithShuffles(EVT VT,
1827       unsigned DefinedValues) const {
1828   return false;
1829 }
1830 
1831 bool HexagonTargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask,
1832                                                EVT VT) const {
1833   return true;
1834 }
1835 
1836 TargetLoweringBase::LegalizeTypeAction
1837 HexagonTargetLowering::getPreferredVectorAction(EVT VT) const {
1838   if (VT.getVectorNumElements() == 1)
1839     return TargetLoweringBase::TypeScalarizeVector;
1840 
1841   // Always widen vectors of i1.
1842   MVT ElemTy = VT.getSimpleVT().getVectorElementType();
1843   if (ElemTy == MVT::i1)
1844     return TargetLoweringBase::TypeWidenVector;
1845 
1846   if (Subtarget.useHVXOps()) {
1847     // If the size of VT is at least half of the vector length,
1848     // widen the vector. Note: the threshold was not selected in
1849     // any scientific way.
1850     ArrayRef<MVT> Tys = Subtarget.getHVXElementTypes();
1851     if (llvm::find(Tys, ElemTy) != Tys.end()) {
1852       unsigned HwWidth = 8*Subtarget.getVectorLength();
1853       unsigned VecWidth = VT.getSizeInBits();
1854       if (VecWidth >= HwWidth/2 && VecWidth < HwWidth)
1855         return TargetLoweringBase::TypeWidenVector;
1856     }
1857   }
1858   return TargetLoweringBase::TypeSplitVector;
1859 }
1860 
1861 std::pair<SDValue, int>
1862 HexagonTargetLowering::getBaseAndOffset(SDValue Addr) const {
1863   if (Addr.getOpcode() == ISD::ADD) {
1864     SDValue Op1 = Addr.getOperand(1);
1865     if (auto *CN = dyn_cast<const ConstantSDNode>(Op1.getNode()))
1866       return { Addr.getOperand(0), CN->getSExtValue() };
1867   }
1868   return { Addr, 0 };
1869 }
1870 
1871 // Lower a vector shuffle (V1, V2, V3).  V1 and V2 are the two vectors
1872 // to select data from, V3 is the permutation.
1873 SDValue
1874 HexagonTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG)
1875       const {
1876   const auto *SVN = cast<ShuffleVectorSDNode>(Op);
1877   ArrayRef<int> AM = SVN->getMask();
1878   assert(AM.size() <= 8 && "Unexpected shuffle mask");
1879   unsigned VecLen = AM.size();
1880 
1881   MVT VecTy = ty(Op);
1882   assert(!Subtarget.isHVXVectorType(VecTy, true) &&
1883          "HVX shuffles should be legal");
1884   assert(VecTy.getSizeInBits() <= 64 && "Unexpected vector length");
1885 
1886   SDValue Op0 = Op.getOperand(0);
1887   SDValue Op1 = Op.getOperand(1);
1888   const SDLoc &dl(Op);
1889 
1890   // If the inputs are not the same as the output, bail. This is not an
1891   // error situation, but complicates the handling and the default expansion
1892   // (into BUILD_VECTOR) should be adequate.
1893   if (ty(Op0) != VecTy || ty(Op1) != VecTy)
1894     return SDValue();
1895 
1896   // Normalize the mask so that the first non-negative index comes from
1897   // the first operand.
1898   SmallVector<int,8> Mask(AM.begin(), AM.end());
1899   unsigned F = llvm::find_if(AM, [](int M) { return M >= 0; }) - AM.data();
1900   if (F == AM.size())
1901     return DAG.getUNDEF(VecTy);
1902   if (AM[F] >= int(VecLen)) {
1903     ShuffleVectorSDNode::commuteMask(Mask);
1904     std::swap(Op0, Op1);
1905   }
1906 
1907   // Express the shuffle mask in terms of bytes.
1908   SmallVector<int,8> ByteMask;
1909   unsigned ElemBytes = VecTy.getVectorElementType().getSizeInBits() / 8;
1910   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
1911     int M = Mask[i];
1912     if (M < 0) {
1913       for (unsigned j = 0; j != ElemBytes; ++j)
1914         ByteMask.push_back(-1);
1915     } else {
1916       for (unsigned j = 0; j != ElemBytes; ++j)
1917         ByteMask.push_back(M*ElemBytes + j);
1918     }
1919   }
1920   assert(ByteMask.size() <= 8);
1921 
1922   // All non-undef (non-negative) indexes are well within [0..127], so they
1923   // fit in a single byte. Build two 64-bit words:
1924   // - MaskIdx where each byte is the corresponding index (for non-negative
1925   //   indexes), and 0xFF for negative indexes, and
1926   // - MaskUnd that has 0xFF for each negative index.
1927   uint64_t MaskIdx = 0;
1928   uint64_t MaskUnd = 0;
1929   for (unsigned i = 0, e = ByteMask.size(); i != e; ++i) {
1930     unsigned S = 8*i;
1931     uint64_t M = ByteMask[i] & 0xFF;
1932     if (M == 0xFF)
1933       MaskUnd |= M << S;
1934     MaskIdx |= M << S;
1935   }
1936 
1937   if (ByteMask.size() == 4) {
1938     // Identity.
1939     if (MaskIdx == (0x03020100 | MaskUnd))
1940       return Op0;
1941     // Byte swap.
1942     if (MaskIdx == (0x00010203 | MaskUnd)) {
1943       SDValue T0 = DAG.getBitcast(MVT::i32, Op0);
1944       SDValue T1 = DAG.getNode(ISD::BSWAP, dl, MVT::i32, T0);
1945       return DAG.getBitcast(VecTy, T1);
1946     }
1947 
1948     // Byte packs.
1949     SDValue Concat10 = DAG.getNode(HexagonISD::COMBINE, dl,
1950                                    typeJoin({ty(Op1), ty(Op0)}), {Op1, Op0});
1951     if (MaskIdx == (0x06040200 | MaskUnd))
1952       return getInstr(Hexagon::S2_vtrunehb, dl, VecTy, {Concat10}, DAG);
1953     if (MaskIdx == (0x07050301 | MaskUnd))
1954       return getInstr(Hexagon::S2_vtrunohb, dl, VecTy, {Concat10}, DAG);
1955 
1956     SDValue Concat01 = DAG.getNode(HexagonISD::COMBINE, dl,
1957                                    typeJoin({ty(Op0), ty(Op1)}), {Op0, Op1});
1958     if (MaskIdx == (0x02000604 | MaskUnd))
1959       return getInstr(Hexagon::S2_vtrunehb, dl, VecTy, {Concat01}, DAG);
1960     if (MaskIdx == (0x03010705 | MaskUnd))
1961       return getInstr(Hexagon::S2_vtrunohb, dl, VecTy, {Concat01}, DAG);
1962   }
1963 
1964   if (ByteMask.size() == 8) {
1965     // Identity.
1966     if (MaskIdx == (0x0706050403020100ull | MaskUnd))
1967       return Op0;
1968     // Byte swap.
1969     if (MaskIdx == (0x0001020304050607ull | MaskUnd)) {
1970       SDValue T0 = DAG.getBitcast(MVT::i64, Op0);
1971       SDValue T1 = DAG.getNode(ISD::BSWAP, dl, MVT::i64, T0);
1972       return DAG.getBitcast(VecTy, T1);
1973     }
1974 
1975     // Halfword picks.
1976     if (MaskIdx == (0x0d0c050409080100ull | MaskUnd))
1977       return getInstr(Hexagon::S2_shuffeh, dl, VecTy, {Op1, Op0}, DAG);
1978     if (MaskIdx == (0x0f0e07060b0a0302ull | MaskUnd))
1979       return getInstr(Hexagon::S2_shuffoh, dl, VecTy, {Op1, Op0}, DAG);
1980     if (MaskIdx == (0x0d0c090805040100ull | MaskUnd))
1981       return getInstr(Hexagon::S2_vtrunewh, dl, VecTy, {Op1, Op0}, DAG);
1982     if (MaskIdx == (0x0f0e0b0a07060302ull | MaskUnd))
1983       return getInstr(Hexagon::S2_vtrunowh, dl, VecTy, {Op1, Op0}, DAG);
1984     if (MaskIdx == (0x0706030205040100ull | MaskUnd)) {
1985       VectorPair P = opSplit(Op0, dl, DAG);
1986       return getInstr(Hexagon::S2_packhl, dl, VecTy, {P.second, P.first}, DAG);
1987     }
1988 
1989     // Byte packs.
1990     if (MaskIdx == (0x0e060c040a020800ull | MaskUnd))
1991       return getInstr(Hexagon::S2_shuffeb, dl, VecTy, {Op1, Op0}, DAG);
1992     if (MaskIdx == (0x0f070d050b030901ull | MaskUnd))
1993       return getInstr(Hexagon::S2_shuffob, dl, VecTy, {Op1, Op0}, DAG);
1994   }
1995 
1996   return SDValue();
1997 }
1998 
1999 // Create a Hexagon-specific node for shifting a vector by an integer.
2000 SDValue
2001 HexagonTargetLowering::getVectorShiftByInt(SDValue Op, SelectionDAG &DAG)
2002       const {
2003   if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) {
2004     if (SDValue S = BVN->getSplatValue()) {
2005       unsigned NewOpc;
2006       switch (Op.getOpcode()) {
2007         case ISD::SHL:
2008           NewOpc = HexagonISD::VASL;
2009           break;
2010         case ISD::SRA:
2011           NewOpc = HexagonISD::VASR;
2012           break;
2013         case ISD::SRL:
2014           NewOpc = HexagonISD::VLSR;
2015           break;
2016         default:
2017           llvm_unreachable("Unexpected shift opcode");
2018       }
2019       return DAG.getNode(NewOpc, SDLoc(Op), ty(Op), Op.getOperand(0), S);
2020     }
2021   }
2022 
2023   return SDValue();
2024 }
2025 
2026 SDValue
2027 HexagonTargetLowering::LowerVECTOR_SHIFT(SDValue Op, SelectionDAG &DAG) const {
2028   return getVectorShiftByInt(Op, DAG);
2029 }
2030 
2031 SDValue
2032 HexagonTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
2033   if (isa<ConstantSDNode>(Op.getOperand(1).getNode()))
2034     return Op;
2035   return SDValue();
2036 }
2037 
2038 SDValue
2039 HexagonTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
2040   MVT ResTy = ty(Op);
2041   SDValue InpV = Op.getOperand(0);
2042   MVT InpTy = ty(InpV);
2043   assert(ResTy.getSizeInBits() == InpTy.getSizeInBits());
2044   const SDLoc &dl(Op);
2045 
2046   // Handle conversion from i8 to v8i1.
2047   if (ResTy == MVT::v8i1) {
2048     SDValue Sc = DAG.getBitcast(tyScalar(InpTy), InpV);
2049     SDValue Ext = DAG.getZExtOrTrunc(Sc, dl, MVT::i32);
2050     return getInstr(Hexagon::C2_tfrrp, dl, ResTy, Ext, DAG);
2051   }
2052 
2053   return SDValue();
2054 }
2055 
2056 bool
2057 HexagonTargetLowering::getBuildVectorConstInts(ArrayRef<SDValue> Values,
2058       MVT VecTy, SelectionDAG &DAG,
2059       MutableArrayRef<ConstantInt*> Consts) const {
2060   MVT ElemTy = VecTy.getVectorElementType();
2061   unsigned ElemWidth = ElemTy.getSizeInBits();
2062   IntegerType *IntTy = IntegerType::get(*DAG.getContext(), ElemWidth);
2063   bool AllConst = true;
2064 
2065   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2066     SDValue V = Values[i];
2067     if (V.isUndef()) {
2068       Consts[i] = ConstantInt::get(IntTy, 0);
2069       continue;
2070     }
2071     // Make sure to always cast to IntTy.
2072     if (auto *CN = dyn_cast<ConstantSDNode>(V.getNode())) {
2073       const ConstantInt *CI = CN->getConstantIntValue();
2074       Consts[i] = ConstantInt::get(IntTy, CI->getValue().getSExtValue());
2075     } else if (auto *CN = dyn_cast<ConstantFPSDNode>(V.getNode())) {
2076       const ConstantFP *CF = CN->getConstantFPValue();
2077       APInt A = CF->getValueAPF().bitcastToAPInt();
2078       Consts[i] = ConstantInt::get(IntTy, A.getZExtValue());
2079     } else {
2080       AllConst = false;
2081     }
2082   }
2083   return AllConst;
2084 }
2085 
2086 SDValue
2087 HexagonTargetLowering::buildVector32(ArrayRef<SDValue> Elem, const SDLoc &dl,
2088                                      MVT VecTy, SelectionDAG &DAG) const {
2089   MVT ElemTy = VecTy.getVectorElementType();
2090   assert(VecTy.getVectorNumElements() == Elem.size());
2091 
2092   SmallVector<ConstantInt*,4> Consts(Elem.size());
2093   bool AllConst = getBuildVectorConstInts(Elem, VecTy, DAG, Consts);
2094 
2095   unsigned First, Num = Elem.size();
2096   for (First = 0; First != Num; ++First)
2097     if (!isUndef(Elem[First]))
2098       break;
2099   if (First == Num)
2100     return DAG.getUNDEF(VecTy);
2101 
2102   if (AllConst &&
2103       llvm::all_of(Consts, [](ConstantInt *CI) { return CI->isZero(); }))
2104     return getZero(dl, VecTy, DAG);
2105 
2106   if (ElemTy == MVT::i16) {
2107     assert(Elem.size() == 2);
2108     if (AllConst) {
2109       uint32_t V = (Consts[0]->getZExtValue() & 0xFFFF) |
2110                    Consts[1]->getZExtValue() << 16;
2111       return DAG.getBitcast(MVT::v2i16, DAG.getConstant(V, dl, MVT::i32));
2112     }
2113     SDValue N = getInstr(Hexagon::A2_combine_ll, dl, MVT::i32,
2114                          {Elem[1], Elem[0]}, DAG);
2115     return DAG.getBitcast(MVT::v2i16, N);
2116   }
2117 
2118   if (ElemTy == MVT::i8) {
2119     // First try generating a constant.
2120     if (AllConst) {
2121       int32_t V = (Consts[0]->getZExtValue() & 0xFF) |
2122                   (Consts[1]->getZExtValue() & 0xFF) << 8 |
2123                   (Consts[1]->getZExtValue() & 0xFF) << 16 |
2124                   Consts[2]->getZExtValue() << 24;
2125       return DAG.getBitcast(MVT::v4i8, DAG.getConstant(V, dl, MVT::i32));
2126     }
2127 
2128     // Then try splat.
2129     bool IsSplat = true;
2130     for (unsigned i = 0; i != Num; ++i) {
2131       if (i == First)
2132         continue;
2133       if (Elem[i] == Elem[First] || isUndef(Elem[i]))
2134         continue;
2135       IsSplat = false;
2136       break;
2137     }
2138     if (IsSplat) {
2139       // Legalize the operand to VSPLAT.
2140       SDValue Ext = DAG.getZExtOrTrunc(Elem[First], dl, MVT::i32);
2141       return DAG.getNode(HexagonISD::VSPLAT, dl, VecTy, Ext);
2142     }
2143 
2144     // Generate
2145     //   (zxtb(Elem[0]) | (zxtb(Elem[1]) << 8)) |
2146     //   (zxtb(Elem[2]) | (zxtb(Elem[3]) << 8)) << 16
2147     assert(Elem.size() == 4);
2148     SDValue Vs[4];
2149     for (unsigned i = 0; i != 4; ++i) {
2150       Vs[i] = DAG.getZExtOrTrunc(Elem[i], dl, MVT::i32);
2151       Vs[i] = DAG.getZeroExtendInReg(Vs[i], dl, MVT::i8);
2152     }
2153     SDValue S8 = DAG.getConstant(8, dl, MVT::i32);
2154     SDValue T0 = DAG.getNode(ISD::SHL, dl, MVT::i32, {Vs[1], S8});
2155     SDValue T1 = DAG.getNode(ISD::SHL, dl, MVT::i32, {Vs[3], S8});
2156     SDValue B0 = DAG.getNode(ISD::OR, dl, MVT::i32, {Vs[0], T0});
2157     SDValue B1 = DAG.getNode(ISD::OR, dl, MVT::i32, {Vs[2], T1});
2158 
2159     SDValue R = getInstr(Hexagon::A2_combine_ll, dl, MVT::i32, {B1, B0}, DAG);
2160     return DAG.getBitcast(MVT::v4i8, R);
2161   }
2162 
2163 #ifndef NDEBUG
2164   dbgs() << "VecTy: " << EVT(VecTy).getEVTString() << '\n';
2165 #endif
2166   llvm_unreachable("Unexpected vector element type");
2167 }
2168 
2169 SDValue
2170 HexagonTargetLowering::buildVector64(ArrayRef<SDValue> Elem, const SDLoc &dl,
2171                                      MVT VecTy, SelectionDAG &DAG) const {
2172   MVT ElemTy = VecTy.getVectorElementType();
2173   assert(VecTy.getVectorNumElements() == Elem.size());
2174 
2175   SmallVector<ConstantInt*,8> Consts(Elem.size());
2176   bool AllConst = getBuildVectorConstInts(Elem, VecTy, DAG, Consts);
2177 
2178   unsigned First, Num = Elem.size();
2179   for (First = 0; First != Num; ++First)
2180     if (!isUndef(Elem[First]))
2181       break;
2182   if (First == Num)
2183     return DAG.getUNDEF(VecTy);
2184 
2185   if (AllConst &&
2186       llvm::all_of(Consts, [](ConstantInt *CI) { return CI->isZero(); }))
2187     return getZero(dl, VecTy, DAG);
2188 
2189   // First try splat if possible.
2190   if (ElemTy == MVT::i16) {
2191     bool IsSplat = true;
2192     for (unsigned i = 0; i != Num; ++i) {
2193       if (i == First)
2194         continue;
2195       if (Elem[i] == Elem[First] || isUndef(Elem[i]))
2196         continue;
2197       IsSplat = false;
2198       break;
2199     }
2200     if (IsSplat) {
2201       // Legalize the operand to VSPLAT.
2202       SDValue Ext = DAG.getZExtOrTrunc(Elem[First], dl, MVT::i32);
2203       return DAG.getNode(HexagonISD::VSPLAT, dl, VecTy, Ext);
2204     }
2205   }
2206 
2207   // Then try constant.
2208   if (AllConst) {
2209     uint64_t Val = 0;
2210     unsigned W = ElemTy.getSizeInBits();
2211     uint64_t Mask = (ElemTy == MVT::i8)  ? 0xFFull
2212                   : (ElemTy == MVT::i16) ? 0xFFFFull : 0xFFFFFFFFull;
2213     for (unsigned i = 0; i != Num; ++i)
2214       Val = (Val << W) | (Consts[Num-1-i]->getZExtValue() & Mask);
2215     SDValue V0 = DAG.getConstant(Val, dl, MVT::i64);
2216     return DAG.getBitcast(VecTy, V0);
2217   }
2218 
2219   // Build two 32-bit vectors and concatenate.
2220   MVT HalfTy = MVT::getVectorVT(ElemTy, Num/2);
2221   SDValue L = (ElemTy == MVT::i32)
2222                 ? Elem[0]
2223                 : buildVector32(Elem.take_front(Num/2), dl, HalfTy, DAG);
2224   SDValue H = (ElemTy == MVT::i32)
2225                 ? Elem[1]
2226                 : buildVector32(Elem.drop_front(Num/2), dl, HalfTy, DAG);
2227   return DAG.getNode(HexagonISD::COMBINE, dl, VecTy, {H, L});
2228 }
2229 
2230 SDValue
2231 HexagonTargetLowering::extractVector(SDValue VecV, SDValue IdxV,
2232                                      const SDLoc &dl, MVT ValTy, MVT ResTy,
2233                                      SelectionDAG &DAG) const {
2234   MVT VecTy = ty(VecV);
2235   assert(!ValTy.isVector() ||
2236          VecTy.getVectorElementType() == ValTy.getVectorElementType());
2237   unsigned VecWidth = VecTy.getSizeInBits();
2238   unsigned ValWidth = ValTy.getSizeInBits();
2239   unsigned ElemWidth = VecTy.getVectorElementType().getSizeInBits();
2240   assert((VecWidth % ElemWidth) == 0);
2241   auto *IdxN = dyn_cast<ConstantSDNode>(IdxV);
2242 
2243   // Special case for v{8,4,2}i1 (the only boolean vectors legal in Hexagon
2244   // without any coprocessors).
2245   if (ElemWidth == 1) {
2246     assert(VecWidth == VecTy.getVectorNumElements() && "Sanity failure");
2247     assert(VecWidth == 8 || VecWidth == 4 || VecWidth == 2);
2248     // Check if this is an extract of the lowest bit.
2249     if (IdxN) {
2250       // Extracting the lowest bit is a no-op, but it changes the type,
2251       // so it must be kept as an operation to avoid errors related to
2252       // type mismatches.
2253       if (IdxN->isNullValue() && ValTy.getSizeInBits() == 1)
2254         return DAG.getNode(HexagonISD::TYPECAST, dl, MVT::i1, VecV);
2255     }
2256 
2257     // If the value extracted is a single bit, use tstbit.
2258     if (ValWidth == 1) {
2259       SDValue A0 = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {VecV}, DAG);
2260       SDValue M0 = DAG.getConstant(8 / VecWidth, dl, MVT::i32);
2261       SDValue I0 = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, M0);
2262       return DAG.getNode(HexagonISD::TSTBIT, dl, MVT::i1, A0, I0);
2263     }
2264 
2265     // Each bool vector (v2i1, v4i1, v8i1) always occupies 8 bits in
2266     // a predicate register. The elements of the vector are repeated
2267     // in the register (if necessary) so that the total number is 8.
2268     // The extracted subvector will need to be expanded in such a way.
2269     unsigned Scale = VecWidth / ValWidth;
2270 
2271     // Generate (p2d VecV) >> 8*Idx to move the interesting bytes to
2272     // position 0.
2273     assert(ty(IdxV) == MVT::i32);
2274     unsigned VecRep = 8 / VecWidth;
2275     SDValue S0 = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2276                              DAG.getConstant(8*VecRep, dl, MVT::i32));
2277     SDValue T0 = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, VecV);
2278     SDValue T1 = DAG.getNode(ISD::SRL, dl, MVT::i64, T0, S0);
2279     while (Scale > 1) {
2280       // The longest possible subvector is at most 32 bits, so it is always
2281       // contained in the low subregister.
2282       T1 = DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::i32, T1);
2283       T1 = expandPredicate(T1, dl, DAG);
2284       Scale /= 2;
2285     }
2286 
2287     return DAG.getNode(HexagonISD::D2P, dl, ResTy, T1);
2288   }
2289 
2290   assert(VecWidth == 32 || VecWidth == 64);
2291 
2292   // Cast everything to scalar integer types.
2293   MVT ScalarTy = tyScalar(VecTy);
2294   VecV = DAG.getBitcast(ScalarTy, VecV);
2295 
2296   SDValue WidthV = DAG.getConstant(ValWidth, dl, MVT::i32);
2297   SDValue ExtV;
2298 
2299   if (IdxN) {
2300     unsigned Off = IdxN->getZExtValue() * ElemWidth;
2301     if (VecWidth == 64 && ValWidth == 32) {
2302       assert(Off == 0 || Off == 32);
2303       unsigned SubIdx = Off == 0 ? Hexagon::isub_lo : Hexagon::isub_hi;
2304       ExtV = DAG.getTargetExtractSubreg(SubIdx, dl, MVT::i32, VecV);
2305     } else if (Off == 0 && (ValWidth % 8) == 0) {
2306       ExtV = DAG.getZeroExtendInReg(VecV, dl, tyScalar(ValTy));
2307     } else {
2308       SDValue OffV = DAG.getConstant(Off, dl, MVT::i32);
2309       // The return type of EXTRACTU must be the same as the type of the
2310       // input vector.
2311       ExtV = DAG.getNode(HexagonISD::EXTRACTU, dl, ScalarTy,
2312                          {VecV, WidthV, OffV});
2313     }
2314   } else {
2315     if (ty(IdxV) != MVT::i32)
2316       IdxV = DAG.getZExtOrTrunc(IdxV, dl, MVT::i32);
2317     SDValue OffV = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2318                                DAG.getConstant(ElemWidth, dl, MVT::i32));
2319     ExtV = DAG.getNode(HexagonISD::EXTRACTU, dl, ScalarTy,
2320                        {VecV, WidthV, OffV});
2321   }
2322 
2323   // Cast ExtV to the requested result type.
2324   ExtV = DAG.getZExtOrTrunc(ExtV, dl, tyScalar(ResTy));
2325   ExtV = DAG.getBitcast(ResTy, ExtV);
2326   return ExtV;
2327 }
2328 
2329 SDValue
2330 HexagonTargetLowering::insertVector(SDValue VecV, SDValue ValV, SDValue IdxV,
2331                                     const SDLoc &dl, MVT ValTy,
2332                                     SelectionDAG &DAG) const {
2333   MVT VecTy = ty(VecV);
2334   if (VecTy.getVectorElementType() == MVT::i1) {
2335     MVT ValTy = ty(ValV);
2336     assert(ValTy.getVectorElementType() == MVT::i1);
2337     SDValue ValR = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, ValV);
2338     unsigned VecLen = VecTy.getVectorNumElements();
2339     unsigned Scale = VecLen / ValTy.getVectorNumElements();
2340     assert(Scale > 1);
2341 
2342     for (unsigned R = Scale; R > 1; R /= 2) {
2343       ValR = contractPredicate(ValR, dl, DAG);
2344       ValR = DAG.getNode(HexagonISD::COMBINE, dl, MVT::i64,
2345                          DAG.getUNDEF(MVT::i32), ValR);
2346     }
2347     // The longest possible subvector is at most 32 bits, so it is always
2348     // contained in the low subregister.
2349     ValR = DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::i32, ValR);
2350 
2351     unsigned ValBytes = 64 / Scale;
2352     SDValue Width = DAG.getConstant(ValBytes*8, dl, MVT::i32);
2353     SDValue Idx = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2354                               DAG.getConstant(8, dl, MVT::i32));
2355     SDValue VecR = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, VecV);
2356     SDValue Ins = DAG.getNode(HexagonISD::INSERT, dl, MVT::i32,
2357                               {VecR, ValR, Width, Idx});
2358     return DAG.getNode(HexagonISD::D2P, dl, VecTy, Ins);
2359   }
2360 
2361   unsigned VecWidth = VecTy.getSizeInBits();
2362   unsigned ValWidth = ValTy.getSizeInBits();
2363   assert(VecWidth == 32 || VecWidth == 64);
2364   assert((VecWidth % ValWidth) == 0);
2365 
2366   // Cast everything to scalar integer types.
2367   MVT ScalarTy = MVT::getIntegerVT(VecWidth);
2368   // The actual type of ValV may be different than ValTy (which is related
2369   // to the vector type).
2370   unsigned VW = ty(ValV).getSizeInBits();
2371   ValV = DAG.getBitcast(MVT::getIntegerVT(VW), ValV);
2372   VecV = DAG.getBitcast(ScalarTy, VecV);
2373   if (VW != VecWidth)
2374     ValV = DAG.getAnyExtOrTrunc(ValV, dl, ScalarTy);
2375 
2376   SDValue WidthV = DAG.getConstant(ValWidth, dl, MVT::i32);
2377   SDValue InsV;
2378 
2379   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(IdxV)) {
2380     unsigned W = C->getZExtValue() * ValWidth;
2381     SDValue OffV = DAG.getConstant(W, dl, MVT::i32);
2382     InsV = DAG.getNode(HexagonISD::INSERT, dl, ScalarTy,
2383                        {VecV, ValV, WidthV, OffV});
2384   } else {
2385     if (ty(IdxV) != MVT::i32)
2386       IdxV = DAG.getZExtOrTrunc(IdxV, dl, MVT::i32);
2387     SDValue OffV = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, WidthV);
2388     InsV = DAG.getNode(HexagonISD::INSERT, dl, ScalarTy,
2389                        {VecV, ValV, WidthV, OffV});
2390   }
2391 
2392   return DAG.getNode(ISD::BITCAST, dl, VecTy, InsV);
2393 }
2394 
2395 SDValue
2396 HexagonTargetLowering::expandPredicate(SDValue Vec32, const SDLoc &dl,
2397                                        SelectionDAG &DAG) const {
2398   assert(ty(Vec32).getSizeInBits() == 32);
2399   if (isUndef(Vec32))
2400     return DAG.getUNDEF(MVT::i64);
2401   return getInstr(Hexagon::S2_vsxtbh, dl, MVT::i64, {Vec32}, DAG);
2402 }
2403 
2404 SDValue
2405 HexagonTargetLowering::contractPredicate(SDValue Vec64, const SDLoc &dl,
2406                                          SelectionDAG &DAG) const {
2407   assert(ty(Vec64).getSizeInBits() == 64);
2408   if (isUndef(Vec64))
2409     return DAG.getUNDEF(MVT::i32);
2410   return getInstr(Hexagon::S2_vtrunehb, dl, MVT::i32, {Vec64}, DAG);
2411 }
2412 
2413 SDValue
2414 HexagonTargetLowering::getZero(const SDLoc &dl, MVT Ty, SelectionDAG &DAG)
2415       const {
2416   if (Ty.isVector()) {
2417     assert(Ty.isInteger() && "Only integer vectors are supported here");
2418     unsigned W = Ty.getSizeInBits();
2419     if (W <= 64)
2420       return DAG.getBitcast(Ty, DAG.getConstant(0, dl, MVT::getIntegerVT(W)));
2421     return DAG.getNode(HexagonISD::VZERO, dl, Ty);
2422   }
2423 
2424   if (Ty.isInteger())
2425     return DAG.getConstant(0, dl, Ty);
2426   if (Ty.isFloatingPoint())
2427     return DAG.getConstantFP(0.0, dl, Ty);
2428   llvm_unreachable("Invalid type for zero");
2429 }
2430 
2431 SDValue
2432 HexagonTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
2433   MVT VecTy = ty(Op);
2434   unsigned BW = VecTy.getSizeInBits();
2435   const SDLoc &dl(Op);
2436   SmallVector<SDValue,8> Ops;
2437   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i)
2438     Ops.push_back(Op.getOperand(i));
2439 
2440   if (BW == 32)
2441     return buildVector32(Ops, dl, VecTy, DAG);
2442   if (BW == 64)
2443     return buildVector64(Ops, dl, VecTy, DAG);
2444 
2445   if (VecTy == MVT::v8i1 || VecTy == MVT::v4i1 || VecTy == MVT::v2i1) {
2446     // For each i1 element in the resulting predicate register, put 1
2447     // shifted by the index of the element into a general-purpose register,
2448     // then or them together and transfer it back into a predicate register.
2449     SDValue Rs[8];
2450     SDValue Z = getZero(dl, MVT::i32, DAG);
2451     // Always produce 8 bits, repeat inputs if necessary.
2452     unsigned Rep = 8 / VecTy.getVectorNumElements();
2453     for (unsigned i = 0; i != 8; ++i) {
2454       SDValue S = DAG.getConstant(1ull << i, dl, MVT::i32);
2455       Rs[i] = DAG.getSelect(dl, MVT::i32, Ops[i/Rep], S, Z);
2456     }
2457     for (ArrayRef<SDValue> A(Rs); A.size() != 1; A = A.drop_back(A.size()/2)) {
2458       for (unsigned i = 0, e = A.size()/2; i != e; ++i)
2459         Rs[i] = DAG.getNode(ISD::OR, dl, MVT::i32, Rs[2*i], Rs[2*i+1]);
2460     }
2461     // Move the value directly to a predicate register.
2462     return getInstr(Hexagon::C2_tfrrp, dl, VecTy, {Rs[0]}, DAG);
2463   }
2464 
2465   return SDValue();
2466 }
2467 
2468 SDValue
2469 HexagonTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
2470                                            SelectionDAG &DAG) const {
2471   MVT VecTy = ty(Op);
2472   const SDLoc &dl(Op);
2473   if (VecTy.getSizeInBits() == 64) {
2474     assert(Op.getNumOperands() == 2);
2475     return DAG.getNode(HexagonISD::COMBINE, dl, VecTy, Op.getOperand(1),
2476                        Op.getOperand(0));
2477   }
2478 
2479   MVT ElemTy = VecTy.getVectorElementType();
2480   if (ElemTy == MVT::i1) {
2481     assert(VecTy == MVT::v2i1 || VecTy == MVT::v4i1 || VecTy == MVT::v8i1);
2482     MVT OpTy = ty(Op.getOperand(0));
2483     // Scale is how many times the operands need to be contracted to match
2484     // the representation in the target register.
2485     unsigned Scale = VecTy.getVectorNumElements() / OpTy.getVectorNumElements();
2486     assert(Scale == Op.getNumOperands() && Scale > 1);
2487 
2488     // First, convert all bool vectors to integers, then generate pairwise
2489     // inserts to form values of doubled length. Up until there are only
2490     // two values left to concatenate, all of these values will fit in a
2491     // 32-bit integer, so keep them as i32 to use 32-bit inserts.
2492     SmallVector<SDValue,4> Words[2];
2493     unsigned IdxW = 0;
2494 
2495     for (SDValue P : Op.getNode()->op_values()) {
2496       SDValue W = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, P);
2497       for (unsigned R = Scale; R > 1; R /= 2) {
2498         W = contractPredicate(W, dl, DAG);
2499         W = DAG.getNode(HexagonISD::COMBINE, dl, MVT::i64,
2500                         DAG.getUNDEF(MVT::i32), W);
2501       }
2502       W = DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::i32, W);
2503       Words[IdxW].push_back(W);
2504     }
2505 
2506     while (Scale > 2) {
2507       SDValue WidthV = DAG.getConstant(64 / Scale, dl, MVT::i32);
2508       Words[IdxW ^ 1].clear();
2509 
2510       for (unsigned i = 0, e = Words[IdxW].size(); i != e; i += 2) {
2511         SDValue W0 = Words[IdxW][i], W1 = Words[IdxW][i+1];
2512         // Insert W1 into W0 right next to the significant bits of W0.
2513         SDValue T = DAG.getNode(HexagonISD::INSERT, dl, MVT::i32,
2514                                 {W0, W1, WidthV, WidthV});
2515         Words[IdxW ^ 1].push_back(T);
2516       }
2517       IdxW ^= 1;
2518       Scale /= 2;
2519     }
2520 
2521     // Another sanity check. At this point there should only be two words
2522     // left, and Scale should be 2.
2523     assert(Scale == 2 && Words[IdxW].size() == 2);
2524 
2525     SDValue WW = DAG.getNode(HexagonISD::COMBINE, dl, MVT::i64,
2526                              Words[IdxW][1], Words[IdxW][0]);
2527     return DAG.getNode(HexagonISD::D2P, dl, VecTy, WW);
2528   }
2529 
2530   return SDValue();
2531 }
2532 
2533 SDValue
2534 HexagonTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
2535                                                SelectionDAG &DAG) const {
2536   SDValue Vec = Op.getOperand(0);
2537   MVT ElemTy = ty(Vec).getVectorElementType();
2538   return extractVector(Vec, Op.getOperand(1), SDLoc(Op), ElemTy, ty(Op), DAG);
2539 }
2540 
2541 SDValue
2542 HexagonTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
2543                                               SelectionDAG &DAG) const {
2544   return extractVector(Op.getOperand(0), Op.getOperand(1), SDLoc(Op),
2545                        ty(Op), ty(Op), DAG);
2546 }
2547 
2548 SDValue
2549 HexagonTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
2550                                               SelectionDAG &DAG) const {
2551   return insertVector(Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
2552                       SDLoc(Op), ty(Op).getVectorElementType(), DAG);
2553 }
2554 
2555 SDValue
2556 HexagonTargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
2557                                              SelectionDAG &DAG) const {
2558   SDValue ValV = Op.getOperand(1);
2559   return insertVector(Op.getOperand(0), ValV, Op.getOperand(2),
2560                       SDLoc(Op), ty(ValV), DAG);
2561 }
2562 
2563 bool
2564 HexagonTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
2565   // Assuming the caller does not have either a signext or zeroext modifier, and
2566   // only one value is accepted, any reasonable truncation is allowed.
2567   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
2568     return false;
2569 
2570   // FIXME: in principle up to 64-bit could be made safe, but it would be very
2571   // fragile at the moment: any support for multiple value returns would be
2572   // liable to disallow tail calls involving i64 -> iN truncation in many cases.
2573   return Ty1->getPrimitiveSizeInBits() <= 32;
2574 }
2575 
2576 SDValue
2577 HexagonTargetLowering::LowerLoad(SDValue Op, SelectionDAG &DAG) const {
2578   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
2579   unsigned ClaimAlign = LN->getAlignment();
2580   validateConstPtrAlignment(LN->getBasePtr(), SDLoc(Op), ClaimAlign);
2581   // Call LowerUnalignedLoad for all loads, it recognizes loads that
2582   // don't need extra aligning.
2583   return LowerUnalignedLoad(Op, DAG);
2584 }
2585 
2586 SDValue
2587 HexagonTargetLowering::LowerStore(SDValue Op, SelectionDAG &DAG) const {
2588   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
2589   unsigned ClaimAlign = SN->getAlignment();
2590   SDValue Ptr = SN->getBasePtr();
2591   const SDLoc &dl(Op);
2592   validateConstPtrAlignment(Ptr, dl, ClaimAlign);
2593 
2594   MVT StoreTy = SN->getMemoryVT().getSimpleVT();
2595   unsigned NeedAlign = Subtarget.getTypeAlignment(StoreTy);
2596   if (ClaimAlign < NeedAlign)
2597     return expandUnalignedStore(SN, DAG);
2598   return Op;
2599 }
2600 
2601 SDValue
2602 HexagonTargetLowering::LowerUnalignedLoad(SDValue Op, SelectionDAG &DAG)
2603       const {
2604   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
2605   MVT LoadTy = ty(Op);
2606   unsigned NeedAlign = Subtarget.getTypeAlignment(LoadTy);
2607   unsigned HaveAlign = LN->getAlignment();
2608   if (HaveAlign >= NeedAlign)
2609     return Op;
2610 
2611   const SDLoc &dl(Op);
2612   const DataLayout &DL = DAG.getDataLayout();
2613   LLVMContext &Ctx = *DAG.getContext();
2614   unsigned AS = LN->getAddressSpace();
2615 
2616   // If the load aligning is disabled or the load can be broken up into two
2617   // smaller legal loads, do the default (target-independent) expansion.
2618   bool DoDefault = false;
2619   // Handle it in the default way if this is an indexed load.
2620   if (!LN->isUnindexed())
2621     DoDefault = true;
2622 
2623   if (!AlignLoads) {
2624     if (allowsMemoryAccess(Ctx, DL, LN->getMemoryVT(), AS, HaveAlign))
2625       return Op;
2626     DoDefault = true;
2627   }
2628   if (!DoDefault && 2*HaveAlign == NeedAlign) {
2629     // The PartTy is the equivalent of "getLoadableTypeOfSize(HaveAlign)".
2630     MVT PartTy = HaveAlign <= 8 ? MVT::getIntegerVT(8*HaveAlign)
2631                                 : MVT::getVectorVT(MVT::i8, HaveAlign);
2632     DoDefault = allowsMemoryAccess(Ctx, DL, PartTy, AS, HaveAlign);
2633   }
2634   if (DoDefault) {
2635     std::pair<SDValue, SDValue> P = expandUnalignedLoad(LN, DAG);
2636     return DAG.getMergeValues({P.first, P.second}, dl);
2637   }
2638 
2639   // The code below generates two loads, both aligned as NeedAlign, and
2640   // with the distance of NeedAlign between them. For that to cover the
2641   // bits that need to be loaded (and without overlapping), the size of
2642   // the loads should be equal to NeedAlign. This is true for all loadable
2643   // types, but add an assertion in case something changes in the future.
2644   assert(LoadTy.getSizeInBits() == 8*NeedAlign);
2645 
2646   unsigned LoadLen = NeedAlign;
2647   SDValue Base = LN->getBasePtr();
2648   SDValue Chain = LN->getChain();
2649   auto BO = getBaseAndOffset(Base);
2650   unsigned BaseOpc = BO.first.getOpcode();
2651   if (BaseOpc == HexagonISD::VALIGNADDR && BO.second % LoadLen == 0)
2652     return Op;
2653 
2654   if (BO.second % LoadLen != 0) {
2655     BO.first = DAG.getNode(ISD::ADD, dl, MVT::i32, BO.first,
2656                            DAG.getConstant(BO.second % LoadLen, dl, MVT::i32));
2657     BO.second -= BO.second % LoadLen;
2658   }
2659   SDValue BaseNoOff = (BaseOpc != HexagonISD::VALIGNADDR)
2660       ? DAG.getNode(HexagonISD::VALIGNADDR, dl, MVT::i32, BO.first,
2661                     DAG.getConstant(NeedAlign, dl, MVT::i32))
2662       : BO.first;
2663   SDValue Base0 = DAG.getMemBasePlusOffset(BaseNoOff, BO.second, dl);
2664   SDValue Base1 = DAG.getMemBasePlusOffset(BaseNoOff, BO.second+LoadLen, dl);
2665 
2666   MachineMemOperand *WideMMO = nullptr;
2667   if (MachineMemOperand *MMO = LN->getMemOperand()) {
2668     MachineFunction &MF = DAG.getMachineFunction();
2669     WideMMO = MF.getMachineMemOperand(MMO->getPointerInfo(), MMO->getFlags(),
2670                     2*LoadLen, LoadLen, MMO->getAAInfo(), MMO->getRanges(),
2671                     MMO->getSyncScopeID(), MMO->getOrdering(),
2672                     MMO->getFailureOrdering());
2673   }
2674 
2675   SDValue Load0 = DAG.getLoad(LoadTy, dl, Chain, Base0, WideMMO);
2676   SDValue Load1 = DAG.getLoad(LoadTy, dl, Chain, Base1, WideMMO);
2677 
2678   SDValue Aligned = DAG.getNode(HexagonISD::VALIGN, dl, LoadTy,
2679                                 {Load1, Load0, BaseNoOff.getOperand(0)});
2680   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2681                                  Load0.getValue(1), Load1.getValue(1));
2682   SDValue M = DAG.getMergeValues({Aligned, NewChain}, dl);
2683   return M;
2684 }
2685 
2686 SDValue
2687 HexagonTargetLowering::LowerAddSubCarry(SDValue Op, SelectionDAG &DAG) const {
2688   const SDLoc &dl(Op);
2689   unsigned Opc = Op.getOpcode();
2690   SDValue X = Op.getOperand(0), Y = Op.getOperand(1), C = Op.getOperand(2);
2691 
2692   if (Opc == ISD::ADDCARRY)
2693     return DAG.getNode(HexagonISD::ADDC, dl, Op.getNode()->getVTList(),
2694                        { X, Y, C });
2695 
2696   EVT CarryTy = C.getValueType();
2697   SDValue SubC = DAG.getNode(HexagonISD::SUBC, dl, Op.getNode()->getVTList(),
2698                              { X, Y, DAG.getLogicalNOT(dl, C, CarryTy) });
2699   SDValue Out[] = { SubC.getValue(0),
2700                     DAG.getLogicalNOT(dl, SubC.getValue(1), CarryTy) };
2701   return DAG.getMergeValues(Out, dl);
2702 }
2703 
2704 SDValue
2705 HexagonTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
2706   SDValue Chain     = Op.getOperand(0);
2707   SDValue Offset    = Op.getOperand(1);
2708   SDValue Handler   = Op.getOperand(2);
2709   SDLoc dl(Op);
2710   auto PtrVT = getPointerTy(DAG.getDataLayout());
2711 
2712   // Mark function as containing a call to EH_RETURN.
2713   HexagonMachineFunctionInfo *FuncInfo =
2714     DAG.getMachineFunction().getInfo<HexagonMachineFunctionInfo>();
2715   FuncInfo->setHasEHReturn();
2716 
2717   unsigned OffsetReg = Hexagon::R28;
2718 
2719   SDValue StoreAddr =
2720       DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getRegister(Hexagon::R30, PtrVT),
2721                   DAG.getIntPtrConstant(4, dl));
2722   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
2723   Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
2724 
2725   // Not needed we already use it as explict input to EH_RETURN.
2726   // MF.getRegInfo().addLiveOut(OffsetReg);
2727 
2728   return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
2729 }
2730 
2731 SDValue
2732 HexagonTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2733   unsigned Opc = Op.getOpcode();
2734 
2735   // Handle INLINEASM first.
2736   if (Opc == ISD::INLINEASM)
2737     return LowerINLINEASM(Op, DAG);
2738 
2739   if (isHvxOperation(Op)) {
2740     // If HVX lowering returns nothing, try the default lowering.
2741     if (SDValue V = LowerHvxOperation(Op, DAG))
2742       return V;
2743   }
2744 
2745   switch (Opc) {
2746     default:
2747 #ifndef NDEBUG
2748       Op.getNode()->dumpr(&DAG);
2749       if (Opc > HexagonISD::OP_BEGIN && Opc < HexagonISD::OP_END)
2750         errs() << "Error: check for a non-legal type in this operation\n";
2751 #endif
2752       llvm_unreachable("Should not custom lower this!");
2753     case ISD::CONCAT_VECTORS:       return LowerCONCAT_VECTORS(Op, DAG);
2754     case ISD::INSERT_SUBVECTOR:     return LowerINSERT_SUBVECTOR(Op, DAG);
2755     case ISD::INSERT_VECTOR_ELT:    return LowerINSERT_VECTOR_ELT(Op, DAG);
2756     case ISD::EXTRACT_SUBVECTOR:    return LowerEXTRACT_SUBVECTOR(Op, DAG);
2757     case ISD::EXTRACT_VECTOR_ELT:   return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2758     case ISD::BUILD_VECTOR:         return LowerBUILD_VECTOR(Op, DAG);
2759     case ISD::VECTOR_SHUFFLE:       return LowerVECTOR_SHUFFLE(Op, DAG);
2760     case ISD::BITCAST:              return LowerBITCAST(Op, DAG);
2761     case ISD::LOAD:                 return LowerLoad(Op, DAG);
2762     case ISD::STORE:                return LowerStore(Op, DAG);
2763     case ISD::ADDCARRY:
2764     case ISD::SUBCARRY:             return LowerAddSubCarry(Op, DAG);
2765     case ISD::SRA:
2766     case ISD::SHL:
2767     case ISD::SRL:                  return LowerVECTOR_SHIFT(Op, DAG);
2768     case ISD::ROTL:                 return LowerROTL(Op, DAG);
2769     case ISD::ConstantPool:         return LowerConstantPool(Op, DAG);
2770     case ISD::JumpTable:            return LowerJumpTable(Op, DAG);
2771     case ISD::EH_RETURN:            return LowerEH_RETURN(Op, DAG);
2772     case ISD::RETURNADDR:           return LowerRETURNADDR(Op, DAG);
2773     case ISD::FRAMEADDR:            return LowerFRAMEADDR(Op, DAG);
2774     case ISD::GlobalTLSAddress:     return LowerGlobalTLSAddress(Op, DAG);
2775     case ISD::ATOMIC_FENCE:         return LowerATOMIC_FENCE(Op, DAG);
2776     case ISD::GlobalAddress:        return LowerGLOBALADDRESS(Op, DAG);
2777     case ISD::BlockAddress:         return LowerBlockAddress(Op, DAG);
2778     case ISD::GLOBAL_OFFSET_TABLE:  return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2779     case ISD::VASTART:              return LowerVASTART(Op, DAG);
2780     case ISD::DYNAMIC_STACKALLOC:   return LowerDYNAMIC_STACKALLOC(Op, DAG);
2781     case ISD::SETCC:                return LowerSETCC(Op, DAG);
2782     case ISD::VSELECT:              return LowerVSELECT(Op, DAG);
2783     case ISD::INTRINSIC_WO_CHAIN:   return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2784     case ISD::INTRINSIC_VOID:       return LowerINTRINSIC_VOID(Op, DAG);
2785     case ISD::PREFETCH:             return LowerPREFETCH(Op, DAG);
2786     case ISD::READCYCLECOUNTER:     return LowerREADCYCLECOUNTER(Op, DAG);
2787       break;
2788   }
2789 
2790   return SDValue();
2791 }
2792 
2793 void
2794 HexagonTargetLowering::LowerOperationWrapper(SDNode *N,
2795                                              SmallVectorImpl<SDValue> &Results,
2796                                              SelectionDAG &DAG) const {
2797   // We are only custom-lowering stores to verify the alignment of the
2798   // address if it is a compile-time constant. Since a store can be modified
2799   // during type-legalization (the value being stored may need legalization),
2800   // return empty Results here to indicate that we don't really make any
2801   // changes in the custom lowering.
2802   if (N->getOpcode() != ISD::STORE)
2803     return TargetLowering::LowerOperationWrapper(N, Results, DAG);
2804 }
2805 
2806 void
2807 HexagonTargetLowering::ReplaceNodeResults(SDNode *N,
2808                                           SmallVectorImpl<SDValue> &Results,
2809                                           SelectionDAG &DAG) const {
2810   const SDLoc &dl(N);
2811   switch (N->getOpcode()) {
2812     case ISD::SRL:
2813     case ISD::SRA:
2814     case ISD::SHL:
2815       return;
2816     case ISD::BITCAST:
2817       // Handle a bitcast from v8i1 to i8.
2818       if (N->getValueType(0) == MVT::i8) {
2819         SDValue P = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32,
2820                              N->getOperand(0), DAG);
2821         Results.push_back(P);
2822       }
2823       break;
2824   }
2825 }
2826 
2827 /// Returns relocation base for the given PIC jumptable.
2828 SDValue
2829 HexagonTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2830                                                 SelectionDAG &DAG) const {
2831   int Idx = cast<JumpTableSDNode>(Table)->getIndex();
2832   EVT VT = Table.getValueType();
2833   SDValue T = DAG.getTargetJumpTable(Idx, VT, HexagonII::MO_PCREL);
2834   return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Table), VT, T);
2835 }
2836 
2837 //===----------------------------------------------------------------------===//
2838 // Inline Assembly Support
2839 //===----------------------------------------------------------------------===//
2840 
2841 TargetLowering::ConstraintType
2842 HexagonTargetLowering::getConstraintType(StringRef Constraint) const {
2843   if (Constraint.size() == 1) {
2844     switch (Constraint[0]) {
2845       case 'q':
2846       case 'v':
2847         if (Subtarget.useHVXOps())
2848           return C_RegisterClass;
2849         break;
2850       case 'a':
2851         return C_RegisterClass;
2852       default:
2853         break;
2854     }
2855   }
2856   return TargetLowering::getConstraintType(Constraint);
2857 }
2858 
2859 std::pair<unsigned, const TargetRegisterClass*>
2860 HexagonTargetLowering::getRegForInlineAsmConstraint(
2861     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
2862 
2863   if (Constraint.size() == 1) {
2864     switch (Constraint[0]) {
2865     case 'r':   // R0-R31
2866       switch (VT.SimpleTy) {
2867       default:
2868         return {0u, nullptr};
2869       case MVT::i1:
2870       case MVT::i8:
2871       case MVT::i16:
2872       case MVT::i32:
2873       case MVT::f32:
2874         return {0u, &Hexagon::IntRegsRegClass};
2875       case MVT::i64:
2876       case MVT::f64:
2877         return {0u, &Hexagon::DoubleRegsRegClass};
2878       }
2879       break;
2880     case 'a': // M0-M1
2881       if (VT != MVT::i32)
2882         return {0u, nullptr};
2883       return {0u, &Hexagon::ModRegsRegClass};
2884     case 'q': // q0-q3
2885       switch (VT.getSizeInBits()) {
2886       default:
2887         return {0u, nullptr};
2888       case 512:
2889       case 1024:
2890         return {0u, &Hexagon::HvxQRRegClass};
2891       }
2892       break;
2893     case 'v': // V0-V31
2894       switch (VT.getSizeInBits()) {
2895       default:
2896         return {0u, nullptr};
2897       case 512:
2898         return {0u, &Hexagon::HvxVRRegClass};
2899       case 1024:
2900         if (Subtarget.hasV60Ops() && Subtarget.useHVX128BOps())
2901           return {0u, &Hexagon::HvxVRRegClass};
2902         return {0u, &Hexagon::HvxWRRegClass};
2903       case 2048:
2904         return {0u, &Hexagon::HvxWRRegClass};
2905       }
2906       break;
2907     default:
2908       return {0u, nullptr};
2909     }
2910   }
2911 
2912   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2913 }
2914 
2915 /// isFPImmLegal - Returns true if the target can instruction select the
2916 /// specified FP immediate natively. If false, the legalizer will
2917 /// materialize the FP immediate as a load from a constant pool.
2918 bool HexagonTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2919   return true;
2920 }
2921 
2922 /// isLegalAddressingMode - Return true if the addressing mode represented by
2923 /// AM is legal for this target, for a load/store of the specified type.
2924 bool HexagonTargetLowering::isLegalAddressingMode(const DataLayout &DL,
2925                                                   const AddrMode &AM, Type *Ty,
2926                                                   unsigned AS, Instruction *I) const {
2927   if (Ty->isSized()) {
2928     // When LSR detects uses of the same base address to access different
2929     // types (e.g. unions), it will assume a conservative type for these
2930     // uses:
2931     //   LSR Use: Kind=Address of void in addrspace(4294967295), ...
2932     // The type Ty passed here would then be "void". Skip the alignment
2933     // checks, but do not return false right away, since that confuses
2934     // LSR into crashing.
2935     unsigned A = DL.getABITypeAlignment(Ty);
2936     // The base offset must be a multiple of the alignment.
2937     if ((AM.BaseOffs % A) != 0)
2938       return false;
2939     // The shifted offset must fit in 11 bits.
2940     if (!isInt<11>(AM.BaseOffs >> Log2_32(A)))
2941       return false;
2942   }
2943 
2944   // No global is ever allowed as a base.
2945   if (AM.BaseGV)
2946     return false;
2947 
2948   int Scale = AM.Scale;
2949   if (Scale < 0)
2950     Scale = -Scale;
2951   switch (Scale) {
2952   case 0:  // No scale reg, "r+i", "r", or just "i".
2953     break;
2954   default: // No scaled addressing mode.
2955     return false;
2956   }
2957   return true;
2958 }
2959 
2960 /// Return true if folding a constant offset with the given GlobalAddress is
2961 /// legal.  It is frequently not legal in PIC relocation models.
2962 bool HexagonTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA)
2963       const {
2964   return HTM.getRelocationModel() == Reloc::Static;
2965 }
2966 
2967 /// isLegalICmpImmediate - Return true if the specified immediate is legal
2968 /// icmp immediate, that is the target has icmp instructions which can compare
2969 /// a register against the immediate without having to materialize the
2970 /// immediate into a register.
2971 bool HexagonTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
2972   return Imm >= -512 && Imm <= 511;
2973 }
2974 
2975 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2976 /// for tail call optimization. Targets which want to do tail call
2977 /// optimization should implement this function.
2978 bool HexagonTargetLowering::IsEligibleForTailCallOptimization(
2979                                  SDValue Callee,
2980                                  CallingConv::ID CalleeCC,
2981                                  bool IsVarArg,
2982                                  bool IsCalleeStructRet,
2983                                  bool IsCallerStructRet,
2984                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
2985                                  const SmallVectorImpl<SDValue> &OutVals,
2986                                  const SmallVectorImpl<ISD::InputArg> &Ins,
2987                                  SelectionDAG& DAG) const {
2988   const Function &CallerF = DAG.getMachineFunction().getFunction();
2989   CallingConv::ID CallerCC = CallerF.getCallingConv();
2990   bool CCMatch = CallerCC == CalleeCC;
2991 
2992   // ***************************************************************************
2993   //  Look for obvious safe cases to perform tail call optimization that do not
2994   //  require ABI changes.
2995   // ***************************************************************************
2996 
2997   // If this is a tail call via a function pointer, then don't do it!
2998   if (!isa<GlobalAddressSDNode>(Callee) &&
2999       !isa<ExternalSymbolSDNode>(Callee)) {
3000     return false;
3001   }
3002 
3003   // Do not optimize if the calling conventions do not match and the conventions
3004   // used are not C or Fast.
3005   if (!CCMatch) {
3006     bool R = (CallerCC == CallingConv::C || CallerCC == CallingConv::Fast);
3007     bool E = (CalleeCC == CallingConv::C || CalleeCC == CallingConv::Fast);
3008     // If R & E, then ok.
3009     if (!R || !E)
3010       return false;
3011   }
3012 
3013   // Do not tail call optimize vararg calls.
3014   if (IsVarArg)
3015     return false;
3016 
3017   // Also avoid tail call optimization if either caller or callee uses struct
3018   // return semantics.
3019   if (IsCalleeStructRet || IsCallerStructRet)
3020     return false;
3021 
3022   // In addition to the cases above, we also disable Tail Call Optimization if
3023   // the calling convention code that at least one outgoing argument needs to
3024   // go on the stack. We cannot check that here because at this point that
3025   // information is not available.
3026   return true;
3027 }
3028 
3029 /// Returns the target specific optimal type for load and store operations as
3030 /// a result of memset, memcpy, and memmove lowering.
3031 ///
3032 /// If DstAlign is zero that means it's safe to destination alignment can
3033 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
3034 /// a need to check it against alignment requirement, probably because the
3035 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
3036 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
3037 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
3038 /// does not need to be loaded.  It returns EVT::Other if the type should be
3039 /// determined using generic target-independent logic.
3040 EVT HexagonTargetLowering::getOptimalMemOpType(uint64_t Size,
3041       unsigned DstAlign, unsigned SrcAlign, bool IsMemset, bool ZeroMemset,
3042       bool MemcpyStrSrc, MachineFunction &MF) const {
3043 
3044   auto Aligned = [](unsigned GivenA, unsigned MinA) -> bool {
3045     return (GivenA % MinA) == 0;
3046   };
3047 
3048   if (Size >= 8 && Aligned(DstAlign, 8) && (IsMemset || Aligned(SrcAlign, 8)))
3049     return MVT::i64;
3050   if (Size >= 4 && Aligned(DstAlign, 4) && (IsMemset || Aligned(SrcAlign, 4)))
3051     return MVT::i32;
3052   if (Size >= 2 && Aligned(DstAlign, 2) && (IsMemset || Aligned(SrcAlign, 2)))
3053     return MVT::i16;
3054 
3055   return MVT::Other;
3056 }
3057 
3058 bool HexagonTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
3059       unsigned AS, unsigned Align, bool *Fast) const {
3060   if (Fast)
3061     *Fast = false;
3062   return Subtarget.isHVXVectorType(VT.getSimpleVT());
3063 }
3064 
3065 std::pair<const TargetRegisterClass*, uint8_t>
3066 HexagonTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
3067       MVT VT) const {
3068   if (Subtarget.isHVXVectorType(VT, true)) {
3069     unsigned BitWidth = VT.getSizeInBits();
3070     unsigned VecWidth = Subtarget.getVectorLength() * 8;
3071 
3072     if (VT.getVectorElementType() == MVT::i1)
3073       return std::make_pair(&Hexagon::HvxQRRegClass, 1);
3074     if (BitWidth == VecWidth)
3075       return std::make_pair(&Hexagon::HvxVRRegClass, 1);
3076     assert(BitWidth == 2 * VecWidth);
3077     return std::make_pair(&Hexagon::HvxWRRegClass, 1);
3078   }
3079 
3080   return TargetLowering::findRepresentativeClass(TRI, VT);
3081 }
3082 
3083 Value *HexagonTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
3084       AtomicOrdering Ord) const {
3085   BasicBlock *BB = Builder.GetInsertBlock();
3086   Module *M = BB->getParent()->getParent();
3087   Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
3088   unsigned SZ = Ty->getPrimitiveSizeInBits();
3089   assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic loads supported");
3090   Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_L2_loadw_locked
3091                                    : Intrinsic::hexagon_L4_loadd_locked;
3092   Value *Fn = Intrinsic::getDeclaration(M, IntID);
3093   return Builder.CreateCall(Fn, Addr, "larx");
3094 }
3095 
3096 /// Perform a store-conditional operation to Addr. Return the status of the
3097 /// store. This should be 0 if the store succeeded, non-zero otherwise.
3098 Value *HexagonTargetLowering::emitStoreConditional(IRBuilder<> &Builder,
3099       Value *Val, Value *Addr, AtomicOrdering Ord) const {
3100   BasicBlock *BB = Builder.GetInsertBlock();
3101   Module *M = BB->getParent()->getParent();
3102   Type *Ty = Val->getType();
3103   unsigned SZ = Ty->getPrimitiveSizeInBits();
3104   assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic stores supported");
3105   Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_S2_storew_locked
3106                                    : Intrinsic::hexagon_S4_stored_locked;
3107   Value *Fn = Intrinsic::getDeclaration(M, IntID);
3108   Value *Call = Builder.CreateCall(Fn, {Addr, Val}, "stcx");
3109   Value *Cmp = Builder.CreateICmpEQ(Call, Builder.getInt32(0), "");
3110   Value *Ext = Builder.CreateZExt(Cmp, Type::getInt32Ty(M->getContext()));
3111   return Ext;
3112 }
3113 
3114 TargetLowering::AtomicExpansionKind
3115 HexagonTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
3116   // Do not expand loads and stores that don't exceed 64 bits.
3117   return LI->getType()->getPrimitiveSizeInBits() > 64
3118              ? AtomicExpansionKind::LLOnly
3119              : AtomicExpansionKind::None;
3120 }
3121 
3122 bool HexagonTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
3123   // Do not expand loads and stores that don't exceed 64 bits.
3124   return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() > 64;
3125 }
3126 
3127 TargetLowering::AtomicExpansionKind
3128 HexagonTargetLowering::shouldExpandAtomicCmpXchgInIR(
3129     AtomicCmpXchgInst *AI) const {
3130   const DataLayout &DL = AI->getModule()->getDataLayout();
3131   unsigned Size = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
3132   if (Size >= 4 && Size <= 8)
3133     return AtomicExpansionKind::LLSC;
3134   return AtomicExpansionKind::None;
3135 }
3136