Coverage Report

Created: 2019-07-24 05:18

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