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