LLVM 24.0.0git
HexagonISelLowering.cpp
Go to the documentation of this file.
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"
17#include "HexagonRegisterInfo.h"
18#include "HexagonSubtarget.h"
21#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/ArrayRef.h"
33#include "llvm/IR/BasicBlock.h"
34#include "llvm/IR/CallingConv.h"
35#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/IRBuilder.h"
42#include "llvm/IR/InlineAsm.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/IntrinsicsHexagon.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/Type.h"
49#include "llvm/IR/Value.h"
53#include "llvm/Support/Debug.h"
58#include <algorithm>
59#include <cassert>
60#include <cstdint>
61#include <limits>
62#include <utility>
63
64using namespace llvm;
65
66#define DEBUG_TYPE "hexagon-lowering"
67
68static cl::opt<bool> EmitJumpTables("hexagon-emit-jump-tables",
69 cl::init(true), cl::Hidden,
70 cl::desc("Control jump table emission on Hexagon target"));
71
72static cl::opt<bool>
73 EnableHexSDNodeSched("enable-hexagon-sdnode-sched", cl::Hidden,
74 cl::desc("Enable Hexagon SDNode scheduling"));
75
76static cl::opt<int> MinimumJumpTables("minimum-jump-tables", cl::Hidden,
77 cl::init(5),
78 cl::desc("Set minimum jump tables"));
79
80static cl::opt<bool>
81 ConstantLoadsToImm("constant-loads-to-imm", cl::Hidden, cl::init(true),
82 cl::desc("Convert constant loads to immediate values."));
83
84static cl::opt<bool> AlignLoads("hexagon-align-loads",
85 cl::Hidden, cl::init(false),
86 cl::desc("Rewrite unaligned loads as a pair of aligned loads"));
87
88static cl::opt<bool>
89 DisableArgsMinAlignment("hexagon-disable-args-min-alignment", cl::Hidden,
90 cl::init(false),
91 cl::desc("Disable minimum alignment of 1 for "
92 "arguments passed by value on stack"));
93
94// Implement calling convention for Hexagon.
95
96static bool CC_SkipOdd(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
97 CCValAssign::LocInfo &LocInfo,
98 ISD::ArgFlagsTy &ArgFlags, CCState &State) {
99 static const MCPhysReg ArgRegs[] = {
100 Hexagon::R0, Hexagon::R1, Hexagon::R2,
101 Hexagon::R3, Hexagon::R4, Hexagon::R5
102 };
103 const unsigned NumArgRegs = std::size(ArgRegs);
104 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
105
106 // RegNum is an index into ArgRegs: skip a register if RegNum is odd.
107 if (RegNum != NumArgRegs && RegNum % 2 == 1)
108 State.AllocateReg(ArgRegs[RegNum]);
109
110 // Always return false here, as this function only makes sure that the first
111 // unallocated register has an even register number and does not actually
112 // allocate a register for the current argument.
113 return false;
114}
115
116// HLX vectors that do not fit in registers are passed on the VTCM stack.
117// CCState only tracks the scalar stack, so add a custom memory location here
118// and let assignVTCMStackOffsets set its offset.
119static bool CC_Hexagon_VTCM_Stack(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
120 CCValAssign::LocInfo &LocInfo,
121 ISD::ArgFlagsTy &ArgFlags, CCState &State) {
122 State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT, 0, LocVT, LocInfo));
123 return true;
124}
125
126// Assign VTCM stack offsets to the HLX arguments, in argument order, and
127// return the size of the VTCM argument area.
129 unsigned Size = 0;
130 for (CCValAssign &VA : ArgLocs) {
131 if (!VA.isMemLoc() || !VA.needsCustom())
132 continue;
133 VA.convertToMem(Size);
134 Size += VA.getLocVT().getStoreSize();
135 }
136 return Size;
137}
138
139#define GET_CALLING_CONV_IMPL
140#include "HexagonGenCallingConv.inc"
141
143 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
144 unsigned &NumIntermediates, MVT &RegisterVT) const {
145
146 bool isBoolVector = VT.getVectorElementType() == MVT::i1;
147 bool isPowerOf2 = VT.isPow2VectorType();
148 unsigned NumElts = VT.getVectorNumElements();
149
150 // Split vectors of type vXi1 into (X/8) vectors of type v8i1,
151 // where X is divisible by 8.
152 if (isBoolVector && !Subtarget.useHVXOps() && isPowerOf2 && NumElts >= 8) {
153 RegisterVT = MVT::v8i8;
154 IntermediateVT = MVT::v8i1;
155 NumIntermediates = NumElts / 8;
156 return NumIntermediates;
157 }
158
159 // In HVX 64-byte mode, vectors of type vXi1 are split into (X / 64) vectors
160 // of type v64i1, provided that X is divisible by 64.
161 if (isBoolVector && Subtarget.useHVX64BOps() && isPowerOf2 && NumElts >= 64) {
162 RegisterVT = MVT::v64i8;
163 IntermediateVT = MVT::v64i1;
164 NumIntermediates = NumElts / 64;
165 return NumIntermediates;
166 }
167
168 // In HVX 128-byte mode, vectors of type vXi1 are split into (X / 128) vectors
169 // of type v128i1, provided that X is divisible by 128.
170 if (isBoolVector && Subtarget.useHVX128BOps() && isPowerOf2 &&
171 NumElts >= 128) {
172 RegisterVT = MVT::v128i8;
173 IntermediateVT = MVT::v128i1;
174 NumIntermediates = NumElts / 128;
175 return NumIntermediates;
176 }
177
179 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
180}
181
182std::pair<MVT, unsigned>
184 const HexagonSubtarget &Subtarget, EVT VT) const {
185 assert(VT.getVectorElementType() == MVT::i1);
186
187 const unsigned NumElems = VT.getVectorNumElements();
188
189 if (!VT.isPow2VectorType())
191
192 if (!Subtarget.useHVXOps() && NumElems >= 8)
193 return {MVT::v8i8, NumElems / 8};
194
195 if (Subtarget.useHVX64BOps() && NumElems >= 64)
196 return {MVT::v64i8, NumElems / 64};
197
198 if (Subtarget.useHVX128BOps() && NumElems >= 128)
199 return {MVT::v128i8, NumElems / 128};
200
202}
203
206 EVT VT) const {
207
208 if (VT.isVectorOf(MVT::i1)) {
209 auto [RegisterVT, NumRegisters] =
211 if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
212 return RegisterVT;
213 }
214
216}
217
220 const {
221 unsigned IntNo = Op.getConstantOperandVal(0);
222 SDLoc dl(Op);
223 switch (IntNo) {
224 default:
225 return SDValue(); // Don't custom lower most intrinsics.
226 case Intrinsic::thread_pointer: {
227 EVT PtrVT = getPointerTy(DAG.getDataLayout());
228 return DAG.getNode(HexagonISD::THREAD_POINTER, dl, PtrVT);
229 }
230 }
231}
232
233/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
234/// by "Src" to address "Dst" of size "Size". Alignment information is
235/// specified by the specific parameter attribute. The copy will be passed as
236/// a byval function parameter. Sometimes what we are copying is the end of a
237/// larger object, the part that does not fit in registers.
239 SDValue Chain, ISD::ArgFlagsTy Flags,
240 SelectionDAG &DAG, const SDLoc &dl) {
241 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
242 Align Alignment = Flags.getNonZeroByValAlign();
243 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Alignment, Alignment,
244 /*isVolatile=*/false, /*AlwaysInline=*/false,
245 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(),
247}
248
249bool
251 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
253 LLVMContext &Context, const Type *RetTy) const {
255 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
256
257 return CCInfo.CheckReturn(Outs, RetCC_Hexagon);
258}
259
260// LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
261// passed by value, the function prototype is modified to return void and
262// the value is stored in memory pointed by a pointer passed by caller.
265 bool IsVarArg,
267 const SmallVectorImpl<SDValue> &OutVals,
268 const SDLoc &dl, SelectionDAG &DAG) const {
269 // CCValAssign - represent the assignment of the return value to locations.
271
272 // CCState - Info about the registers and stack slot.
273 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
274 *DAG.getContext());
275
276 // Analyze return values of ISD::RET
277 CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
278
279 SDValue Glue;
280 SmallVector<SDValue, 4> RetOps(1, Chain);
281
282 // Copy the result values into the output registers.
283 for (unsigned i = 0; i != RVLocs.size(); ++i) {
284 CCValAssign &VA = RVLocs[i];
285 SDValue Val = OutVals[i];
286
287 switch (VA.getLocInfo()) {
288 default:
289 // Loc info must be one of Full, BCvt, SExt, ZExt, or AExt.
290 llvm_unreachable("Unknown loc info!");
292 break;
294 Val = DAG.getBitcast(VA.getLocVT(), Val);
295 break;
297 Val = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Val);
298 break;
300 Val = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Val);
301 break;
303 Val = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Val);
304 break;
305 }
306
307 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Val, Glue);
308
309 // Guarantee that all emitted copies are stuck together with flags.
310 Glue = Chain.getValue(1);
311 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
312 }
313
314 RetOps[0] = Chain; // Update chain.
315
316 // Add the glue if we have it.
317 if (Glue.getNode())
318 RetOps.push_back(Glue);
319
320 return DAG.getNode(HexagonISD::RET_GLUE, dl, MVT::Other, RetOps);
321}
322
324 // If either no tail call or told not to tail call at all, don't.
325 return CI->isTailCall();
326}
327
329 const char* RegName, LLT VT, const MachineFunction &) const {
330 // Just support r19, the linux kernel uses it.
332 .Case("r0", Hexagon::R0)
333 .Case("r1", Hexagon::R1)
334 .Case("r2", Hexagon::R2)
335 .Case("r3", Hexagon::R3)
336 .Case("r4", Hexagon::R4)
337 .Case("r5", Hexagon::R5)
338 .Case("r6", Hexagon::R6)
339 .Case("r7", Hexagon::R7)
340 .Case("r8", Hexagon::R8)
341 .Case("r9", Hexagon::R9)
342 .Case("r10", Hexagon::R10)
343 .Case("r11", Hexagon::R11)
344 .Case("r12", Hexagon::R12)
345 .Case("r13", Hexagon::R13)
346 .Case("r14", Hexagon::R14)
347 .Case("r15", Hexagon::R15)
348 .Case("r16", Hexagon::R16)
349 .Case("r17", Hexagon::R17)
350 .Case("r18", Hexagon::R18)
351 .Case("r19", Hexagon::R19)
352 .Case("r20", Hexagon::R20)
353 .Case("r21", Hexagon::R21)
354 .Case("r22", Hexagon::R22)
355 .Case("r23", Hexagon::R23)
356 .Case("r24", Hexagon::R24)
357 .Case("r25", Hexagon::R25)
358 .Case("r26", Hexagon::R26)
359 .Case("r27", Hexagon::R27)
360 .Case("r28", Hexagon::R28)
361 .Case("r29", Hexagon::R29)
362 .Case("r30", Hexagon::R30)
363 .Case("r31", Hexagon::R31)
364 .Case("r1:0", Hexagon::D0)
365 .Case("r3:2", Hexagon::D1)
366 .Case("r5:4", Hexagon::D2)
367 .Case("r7:6", Hexagon::D3)
368 .Case("r9:8", Hexagon::D4)
369 .Case("r11:10", Hexagon::D5)
370 .Case("r13:12", Hexagon::D6)
371 .Case("r15:14", Hexagon::D7)
372 .Case("r17:16", Hexagon::D8)
373 .Case("r19:18", Hexagon::D9)
374 .Case("r21:20", Hexagon::D10)
375 .Case("r23:22", Hexagon::D11)
376 .Case("r25:24", Hexagon::D12)
377 .Case("r27:26", Hexagon::D13)
378 .Case("r29:28", Hexagon::D14)
379 .Case("r31:30", Hexagon::D15)
380 .Case("sp", Hexagon::R29)
381 .Case("fp", Hexagon::R30)
382 .Case("lr", Hexagon::R31)
383 .Case("p0", Hexagon::P0)
384 .Case("p1", Hexagon::P1)
385 .Case("p2", Hexagon::P2)
386 .Case("p3", Hexagon::P3)
387 .Case("sa0", Hexagon::SA0)
388 .Case("lc0", Hexagon::LC0)
389 .Case("sa1", Hexagon::SA1)
390 .Case("lc1", Hexagon::LC1)
391 .Case("m0", Hexagon::M0)
392 .Case("m1", Hexagon::M1)
393 .Case("usr", Hexagon::USR)
394 .Case("ugp", Hexagon::UGP)
395 .Case("cs0", Hexagon::CS0)
396 .Case("cs1", Hexagon::CS1)
397 .Default(Register());
398 return Reg;
399}
400
401/// LowerCallResult - Lower the result values of an ISD::CALL into the
402/// appropriate copies out of appropriate physical registers. This assumes that
403/// Chain/Glue are the input chain/glue to use, and that TheCall is the call
404/// being lowered. Returns a SDNode with the same number of values as the
405/// ISD::CALL.
407 SDValue Chain, SDValue Glue, CallingConv::ID CallConv, bool IsVarArg,
408 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
410 const SmallVectorImpl<SDValue> &OutVals, SDValue Callee) const {
411 // Assign locations to each value returned by this call.
413
414 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
415 *DAG.getContext());
416
417 CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
418
419 // Copy all of the result registers out of their specified physreg.
420 for (unsigned i = 0; i != RVLocs.size(); ++i) {
421 SDValue RetVal;
422 if (RVLocs[i].getValVT() == MVT::i1) {
423 // Return values of type MVT::i1 require special handling. The reason
424 // is that MVT::i1 is associated with the PredRegs register class, but
425 // values of that type are still returned in R0. Generate an explicit
426 // copy into a predicate register from R0, and treat the value of the
427 // predicate register as the call result.
428 auto &MRI = DAG.getMachineFunction().getRegInfo();
429 SDValue FR0 = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
430 MVT::i32, Glue);
431 // FR0 = (Value, Chain, Glue)
432 Register PredR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
433 SDValue TPR = DAG.getCopyToReg(FR0.getValue(1), dl, PredR,
434 FR0.getValue(0), FR0.getValue(2));
435 // TPR = (Chain, Glue)
436 // Don't glue this CopyFromReg, because it copies from a virtual
437 // register. If it is glued to the call, InstrEmitter will add it
438 // as an implicit def to the call (EmitMachineNode).
439 RetVal = DAG.getCopyFromReg(TPR.getValue(0), dl, PredR, MVT::i1);
440 Glue = TPR.getValue(1);
441 Chain = TPR.getValue(0);
442 } else {
443 RetVal = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
444 RVLocs[i].getValVT(), Glue);
445 Glue = RetVal.getValue(2);
446 Chain = RetVal.getValue(1);
447 }
448 InVals.push_back(RetVal.getValue(0));
449 }
450
451 return Chain;
452}
453
454/// LowerCall - Functions arguments are copied from virtual regs to
455/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
458 SmallVectorImpl<SDValue> &InVals) const {
459 SelectionDAG &DAG = CLI.DAG;
460 SDLoc &dl = CLI.DL;
462 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
464 SDValue Chain = CLI.Chain;
465 SDValue Callee = CLI.Callee;
466 CallingConv::ID CallConv = CLI.CallConv;
467 bool IsVarArg = CLI.IsVarArg;
468 bool DoesNotReturn = CLI.DoesNotReturn;
469
470 bool IsStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
472 MachineFrameInfo &MFI = MF.getFrameInfo();
473 auto PtrVT = getPointerTy(MF.getDataLayout());
474
476 Callee = DAG.getTargetGlobalAddress(GAN->getGlobal(), dl, MVT::i32);
477
478 // Linux ABI treats var-arg calls the same way as regular ones.
479 bool TreatAsVarArg = !Subtarget.isEnvironmentMusl() && IsVarArg;
480
481 // Analyze operands of the call, assigning locations to each operand.
483 CCState CCInfo(CallConv, TreatAsVarArg, MF, ArgLocs, *DAG.getContext());
484
486 CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_Legacy);
487 else
488 CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
489 unsigned NumVTCMBytes = assignVTCMStackOffsets(ArgLocs);
490
491 if (CLI.IsTailCall) {
492 bool StructAttrFlag = MF.getFunction().hasStructRetAttr();
493 CLI.IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
494 IsVarArg, IsStructRet, StructAttrFlag, Outs,
495 OutVals, Ins, DAG);
496 for (const CCValAssign &VA : ArgLocs) {
497 if (VA.isMemLoc()) {
498 CLI.IsTailCall = false;
499 break;
500 }
501 }
502 LLVM_DEBUG(dbgs() << (CLI.IsTailCall ? "Eligible for Tail Call\n"
503 : "Argument must be passed on stack. "
504 "Not eligible for Tail Call\n"));
505 }
506 // Get a count of how many bytes are to be pushed on the stack.
507 unsigned NumBytes = CCInfo.getStackSize();
509 SmallVector<SDValue, 8> MemOpChains;
510
511 const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
512 SDValue StackPtr =
513 DAG.getCopyFromReg(Chain, dl, HRI.getStackRegister(), PtrVT);
514 SDValue VTCMStackPtr;
515 if (NumVTCMBytes) {
516 VTCMStackPtr =
517 DAG.getCopyFromReg(Chain, dl, HRI.getVTCMStackRegister(), PtrVT);
518 MF.getInfo<HexagonMachineFunctionInfo>()->reserveVTCMCallFrame(
519 NumVTCMBytes);
520 }
521
522 bool NeedsArgAlign = false;
523 Align LargestAlignSeen;
524 // Walk the register/memloc assignments, inserting copies/loads.
525 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
526 CCValAssign &VA = ArgLocs[i];
527 SDValue Arg = OutVals[i];
528 ISD::ArgFlagsTy Flags = Outs[i].Flags;
529 // Record if we need > 8 byte alignment on an argument.
530 bool ArgAlign = Subtarget.isHVXVectorType(VA.getValVT());
531 NeedsArgAlign |= ArgAlign;
532
533 // Promote the value if needed.
534 switch (VA.getLocInfo()) {
535 default:
536 // Loc info must be one of Full, BCvt, SExt, ZExt, or AExt.
537 llvm_unreachable("Unknown loc info!");
539 break;
541 Arg = DAG.getBitcast(VA.getLocVT(), Arg);
542 break;
544 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
545 break;
547 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
548 break;
550 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
551 break;
552 }
553
554 if (VA.isMemLoc()) {
555 unsigned LocMemOffset = VA.getLocMemOffset();
556 SDValue BasePtr = VA.needsCustom() ? VTCMStackPtr : StackPtr;
557 SDValue MemAddr =
558 DAG.getConstant(LocMemOffset, dl, BasePtr.getValueType());
559 MemAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr, MemAddr);
560 if (ArgAlign)
561 LargestAlignSeen = std::max(
562 LargestAlignSeen, Align(VA.getLocVT().getStoreSizeInBits() / 8));
563 if (Flags.isByVal()) {
564 // The argument is a struct passed by value. According to LLVM, "Arg"
565 // is a pointer.
566 MemOpChains.push_back(CreateCopyOfByValArgument(Arg, MemAddr, Chain,
567 Flags, DAG, dl));
568 } else {
570 DAG.getMachineFunction(), LocMemOffset);
571 if (isHlxPairTy(VA.getLocVT())) {
572 splitHlxPairArgStore(DAG, dl, Chain, Arg, MemAddr, VA.getLocVT(),
573 LocPI, MemOpChains);
574 } else {
575 SDValue S = DAG.getStore(Chain, dl, Arg, MemAddr, LocPI);
576 MemOpChains.push_back(S);
577 }
578 }
579 continue;
580 }
581
582 // Arguments that can be passed on register must be kept at RegsToPass
583 // vector.
584 if (VA.isRegLoc())
585 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
586 }
587
588 if (NeedsArgAlign && Subtarget.hasV60Ops()) {
589 LLVM_DEBUG(dbgs() << "Function needs byte stack align due to call args\n");
590 Align VecAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
591 LargestAlignSeen = std::max(LargestAlignSeen, VecAlign);
592 MFI.ensureMaxAlignment(LargestAlignSeen);
593 }
594 // Transform all store nodes into one single node because all store
595 // nodes are independent of each other.
596 if (!MemOpChains.empty())
597 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
598
599 SDValue Glue;
600 if (!CLI.IsTailCall) {
601 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
602 Glue = Chain.getValue(1);
603 }
604
605 // Build a sequence of copy-to-reg nodes chained together with token
606 // chain and flag operands which copy the outgoing args into registers.
607 // The Glue is necessary since all emitted instructions must be
608 // stuck together.
609 if (!CLI.IsTailCall) {
610 for (const auto &R : RegsToPass) {
611 Chain = DAG.getCopyToReg(Chain, dl, R.first, R.second, Glue);
612 Glue = Chain.getValue(1);
613 }
614 } else {
615 // For tail calls lower the arguments to the 'real' stack slot.
616 //
617 // Force all the incoming stack arguments to be loaded from the stack
618 // before any new outgoing arguments are stored to the stack, because the
619 // outgoing stack slots may alias the incoming argument stack slots, and
620 // the alias isn't otherwise explicit. This is slightly more conservative
621 // than necessary, because it means that each store effectively depends
622 // on every argument instead of just those arguments it would clobber.
623 //
624 // Do not flag preceding copytoreg stuff together with the following stuff.
625 Glue = SDValue();
626 for (const auto &R : RegsToPass) {
627 Chain = DAG.getCopyToReg(Chain, dl, R.first, R.second, Glue);
628 Glue = Chain.getValue(1);
629 }
630 Glue = SDValue();
631 }
632
633 bool LongCalls = MF.getSubtarget<HexagonSubtarget>().useLongCalls();
634 unsigned Flags = LongCalls ? HexagonII::HMOTF_ConstExtended : 0;
635
636 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
637 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
638 // node so that legalize doesn't hack it.
640 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, PtrVT, 0, Flags);
641 } else if (ExternalSymbolSDNode *S =
643 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, Flags);
644 }
645
646 // Returns a chain & a flag for retval copy to use.
648 Ops.push_back(Chain);
649 Ops.push_back(Callee);
650
651 // Add argument registers to the end of the list so that they are
652 // known live into the call.
653 for (const auto &R : RegsToPass)
654 Ops.push_back(DAG.getRegister(R.first, R.second.getValueType()));
655
656 // Callees that take or return HLX values preserve L12-L15.
657 bool HasHLXLocs =
658 any_of(ArgLocs,
659 [](const CCValAssign &VA) {
660 return VA.isRegLoc() &&
661 (Hexagon::HlxLRRegClass.contains(VA.getLocReg()) ||
662 Hexagon::HlxLLRRegClass.contains(VA.getLocReg()));
663 }) ||
664 any_of(Ins, [this](const ISD::InputArg &In) {
665 return Subtarget.isHLXVectorType(In.VT);
666 });
667 const uint32_t *Mask = HasHLXLocs ? HRI.getHLXCallPreservedMask()
668 : HRI.getCallPreservedMask(MF, CallConv);
669 assert(Mask && "Missing call preserved mask for calling convention");
670 Ops.push_back(DAG.getRegisterMask(Mask));
671
672 if (Glue.getNode())
673 Ops.push_back(Glue);
674
675 if (CLI.IsTailCall) {
676 MFI.setHasTailCall();
677 return DAG.getNode(HexagonISD::TC_RETURN, dl, MVT::Other, Ops);
678 }
679
680 // Set this here because we need to know this for "hasFP" in frame lowering.
681 // The target-independent code calls getFrameRegister before setting it, and
682 // getFrameRegister uses hasFP to determine whether the function has FP.
683 MFI.setHasCalls(true);
684
685 unsigned OpCode = DoesNotReturn ? HexagonISD::CALLnr : HexagonISD::CALL;
686 Chain = DAG.getNode(OpCode, dl, {MVT::Other, MVT::Glue}, Ops);
687 if (CLI.CFIType)
688 Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
689 Glue = Chain.getValue(1);
690
691 // Create the CALLSEQ_END node.
692 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, dl);
693 Glue = Chain.getValue(1);
694
695 // Handle result values, copying them out of physregs into vregs that we
696 // return.
697 return LowerCallResult(Chain, Glue, CallConv, IsVarArg, Ins, dl, DAG,
698 InVals, OutVals, Callee);
699}
700
701/// Returns true by value, base pointer and offset pointer and addressing
702/// mode by reference if this node can be combined with a load / store to
703/// form a post-indexed load / store.
706 SelectionDAG &DAG) const {
708 if (!LSN)
709 return false;
710 EVT VT = LSN->getMemoryVT();
711 if (!VT.isSimple())
712 return false;
713 bool IsLegalType = VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 ||
714 VT == MVT::i64 || VT == MVT::f32 || VT == MVT::f64 ||
715 VT == MVT::v2i16 || VT == MVT::v2i32 || VT == MVT::v4i8 ||
716 VT == MVT::v4i16 || VT == MVT::v8i8 ||
717 Subtarget.isHVXVectorType(VT.getSimpleVT());
718 if (!IsLegalType)
719 return false;
720
721 if (Op->getOpcode() != ISD::ADD)
722 return false;
723 Base = Op->getOperand(0);
724 Offset = Op->getOperand(1);
725 if (!isa<ConstantSDNode>(Offset.getNode()))
726 return false;
727 AM = ISD::POST_INC;
728
729 int32_t V = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
730 return Subtarget.getInstrInfo()->isValidAutoIncImm(VT, V);
731}
732
735 return SDValue();
736 else
737 return Op;
738}
739
743 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
744 const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
745 unsigned LR = HRI.getRARegister();
746
747 if ((Op.getOpcode() != ISD::INLINEASM &&
748 Op.getOpcode() != ISD::INLINEASM_BR) || HMFI.hasClobberLR())
749 return Op;
750
751 unsigned NumOps = Op.getNumOperands();
752 if (Op.getOperand(NumOps-1).getValueType() == MVT::Glue)
753 --NumOps; // Ignore the flag operand.
754
755 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
756 const InlineAsm::Flag Flags(Op.getConstantOperandVal(i));
757 unsigned NumVals = Flags.getNumOperandRegisters();
758 ++i; // Skip the ID value.
759
760 switch (Flags.getKind()) {
761 default:
762 llvm_unreachable("Bad flags!");
766 i += NumVals;
767 break;
771 for (; NumVals; --NumVals, ++i) {
772 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
773 if (Reg != LR)
774 continue;
775 HMFI.setHasClobberLR(true);
776 return Op;
777 }
778 break;
779 }
780 }
781 }
782
783 return Op;
784}
785
786// Need to transform ISD::PREFETCH into something that doesn't inherit
787// all of the properties of ISD::PREFETCH, specifically SDNPMayLoad and
788// SDNPMayStore.
790 SelectionDAG &DAG) const {
791 SDValue Chain = Op.getOperand(0);
792 SDValue Addr = Op.getOperand(1);
793 // Lower it to DCFETCH($reg, #0). A "pat" will try to merge the offset in,
794 // if the "reg" is fed by an "add".
795 SDLoc DL(Op);
796 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
797 return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
798}
799
801 SelectionDAG &DAG) const {
802 SDValue Chain = Op.getOperand(0);
803 unsigned IntNo = Op.getConstantOperandVal(1);
804 // Lower the hexagon_prefetch builtin to DCFETCH, as above.
805 if (IntNo == Intrinsic::hexagon_prefetch) {
806 SDValue Addr = Op.getOperand(2);
807 SDLoc DL(Op);
808 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
809 return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
810 }
811 return SDValue();
812}
813
816 SelectionDAG &DAG) const {
817 SDValue Chain = Op.getOperand(0);
818 SDValue Size = Op.getOperand(1);
819 SDValue Align = Op.getOperand(2);
820 SDLoc dl(Op);
821
823 assert(AlignConst && "Non-constant Align in LowerDYNAMIC_STACKALLOC");
824
825 unsigned A = AlignConst->getSExtValue();
826 auto &HFI = *Subtarget.getFrameLowering();
827 // "Zero" means natural stack alignment.
828 if (A == 0)
829 A = HFI.getStackAlign().value();
830
831 LLVM_DEBUG({
832 dbgs () << __func__ << " Align: " << A << " Size: ";
833 Size.getNode()->dump(&DAG);
834 dbgs() << "\n";
835 });
836
837 SDValue AC = DAG.getConstant(A, dl, MVT::i32);
838 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
839 SDValue AA = DAG.getNode(HexagonISD::ALLOCA, dl, VTs, Chain, Size, AC);
840
842 return AA;
843}
844
846 SelectionDAG &DAG) const {
847 EVT OpVT = Op.getValueType();
848 MVT SimpleVT = OpVT.getSimpleVT();
849 SDLoc DL(Op);
850
851 // Check if any of the inputs are NaN. If so, propagate the NaN
852 // to the output, otherwise return the maximum/minimum of the inputs.
853 // We can safely use ISD::FMINNUM/ISD::FMAXNUM to run
854 // Hexagon's F2_sfmin/F2_sfmax, when no operand is NaN.
855 // Note: We cannot directly compare nodes against NaN node to find NaNs,
856 // because comparing NaN with anything always returns False (except for !=0
857 // which always return True). To work around that, we compare input operands
858 // with themselves under ISD::SETUO, which only returns true if the operand is
859 // NaN.
860
861 SDValue Op1 = Op.getOperand(0);
862 SDValue Op2 = Op.getOperand(1);
863 SDValue isOp1NaN = DAG.getSetCC(DL, MVT::i1, Op1, Op1, ISD::SETUO);
864 SDValue isOp2NaN = DAG.getSetCC(DL, MVT::i1, Op2, Op2, ISD::SETUO);
865
866 switch (Op.getOpcode()) {
867 case ISD::FMAXIMUM: {
868 SDValue FmaxNode = DAG.getNode(ISD::FMAXNUM, DL, SimpleVT, Op1, Op2);
869 SDValue result =
870 DAG.getNode(ISD::SELECT, DL, SimpleVT, isOp2NaN, Op2, FmaxNode);
871 return DAG.getNode(ISD::SELECT, DL, SimpleVT, isOp1NaN, Op1, result);
872 }
873 case ISD::FMINIMUM: {
874 SDValue FminNode = DAG.getNode(ISD::FMINNUM, DL, SimpleVT, Op1, Op2);
875 SDValue result =
876 DAG.getNode(ISD::SELECT, DL, SimpleVT, isOp2NaN, Op2, FminNode);
877 return DAG.getNode(ISD::SELECT, DL, SimpleVT, isOp1NaN, Op1, result);
878 }
879 default:
880 llvm_unreachable("Invalid opcode for LowerFMINFMAX");
881 }
882}
883
885 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
886 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
887 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
889 MachineFrameInfo &MFI = MF.getFrameInfo();
891
892 // Linux ABI treats var-arg calls the same way as regular ones.
893 bool TreatAsVarArg = !Subtarget.isEnvironmentMusl() && IsVarArg;
894
895 // Assign locations to all of the incoming arguments.
897 CCState CCInfo(CallConv, TreatAsVarArg, MF, ArgLocs, *DAG.getContext());
898
900 CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon_Legacy);
901 else
902 CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
903 assignVTCMStackOffsets(ArgLocs);
904
905 // For LLVM, in the case when returning a struct by value (>8byte),
906 // the first argument is a pointer that points to the location on caller's
907 // stack where the return value will be stored. For Hexagon, the location on
908 // caller's stack is passed only when the struct size is smaller than (and
909 // equal to) 8 bytes. If not, no address will be passed into callee and
910 // callee return the result directly through R0/R1.
911 auto NextSingleReg = [] (const TargetRegisterClass &RC, unsigned Reg) {
912 switch (RC.getID()) {
913 case Hexagon::IntRegsRegClassID:
914 return Reg - Hexagon::R0 + 1;
915 case Hexagon::DoubleRegsRegClassID:
916 return (Reg - Hexagon::D0 + 1) * 2;
917 case Hexagon::HvxVRRegClassID:
918 return Reg - Hexagon::V0 + 1;
919 case Hexagon::HvxWRRegClassID:
920 return (Reg - Hexagon::W0 + 1) * 2;
921 case Hexagon::HlxLRRegClassID:
922 return Reg - Hexagon::L0 + 1;
923 case Hexagon::HlxLLRRegClassID:
924 return (Reg - Hexagon::LL0 + 1) * 2;
925 }
926 llvm_unreachable("Unexpected register class");
927 };
928
929 auto &HFL = const_cast<HexagonFrameLowering&>(*Subtarget.getFrameLowering());
930 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
931 HFL.FirstVarArgSavedReg = 0;
933
934 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
935 CCValAssign &VA = ArgLocs[i];
936 ISD::ArgFlagsTy Flags = Ins[i].Flags;
937 bool ByVal = Flags.isByVal();
938
939 // Arguments passed in registers:
940 // 1. 32- and 64-bit values and HVX/HLX vectors are passed directly,
941 // 2. Large structs are passed via an address, and the address is
942 // passed in a register.
943 if (VA.isRegLoc() && ByVal && Flags.getByValSize() <= 8)
944 llvm_unreachable("ByValSize must be bigger than 8 bytes");
945
946 bool InReg = VA.isRegLoc() &&
947 (!ByVal || (ByVal && Flags.getByValSize() > 8));
948
949 if (InReg) {
950 MVT RegVT = VA.getLocVT();
951 if (VA.getLocInfo() == CCValAssign::BCvt)
952 RegVT = VA.getValVT();
953
954 const TargetRegisterClass *RC = getRegClassFor(RegVT);
955 Register VReg = MRI.createVirtualRegister(RC);
956 SDValue Copy = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
957
958 // Treat values of type MVT::i1 specially: they are passed in
959 // registers of type i32, but they need to remain as values of
960 // type i1 for consistency of the argument lowering.
961 if (VA.getValVT() == MVT::i1) {
962 assert(RegVT.getSizeInBits() <= 32);
963 SDValue T = DAG.getNode(ISD::AND, dl, RegVT,
964 Copy, DAG.getConstant(1, dl, RegVT));
965 Copy = DAG.getSetCC(dl, MVT::i1, T, DAG.getConstant(0, dl, RegVT),
966 ISD::SETNE);
967 } else {
968#ifndef NDEBUG
969 unsigned RegSize = RegVT.getSizeInBits();
970 assert(RegSize == 32 || RegSize == 64 ||
971 Subtarget.isHVXVectorType(RegVT) ||
972 Subtarget.isHLXVectorType(RegVT));
973#endif
974 }
975 InVals.push_back(Copy);
976 MRI.addLiveIn(VA.getLocReg(), VReg);
977 HFL.FirstVarArgSavedReg = NextSingleReg(*RC, VA.getLocReg());
978 } else {
979 assert(VA.isMemLoc() && "Argument should be passed in memory");
980
981 // If it's a byval parameter, then we need to compute the
982 // "real" size, not the size of the pointer.
983 unsigned ObjSize = Flags.isByVal()
984 ? Flags.getByValSize()
985 : VA.getLocVT().getStoreSizeInBits() / 8;
986
987 // Create the frame index object for this incoming parameter. HLX
988 // arguments are in the caller's VTCM argument area, not on the scalar
989 // stack. Mark them NoAlloc so that the scalar frame layout skips them;
990 // computeVTCMStackOffsets moves every NoAlloc fixed object to the VTCM
991 // frame. Hexagon uses NoAlloc only for these objects.
992 int Offset = VA.needsCustom() ? VA.getLocMemOffset()
994 int FI = MFI.CreateFixedObject(ObjSize, Offset, true);
995 if (VA.needsCustom())
997 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
998
999 if (Flags.isByVal()) {
1000 // If it's a pass-by-value aggregate, then do not dereference the stack
1001 // location. Instead, we should generate a reference to the stack
1002 // location.
1003 InVals.push_back(FIN);
1004 } else if (isHlxPairTy(VA.getValVT())) {
1005 InVals.push_back(
1006 splitHlxPairArgLoad(DAG, dl, Chain, FIN, VA.getValVT(),
1008 } else {
1009 SDValue L = DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1011 InVals.push_back(L);
1012 }
1013 }
1014 }
1015
1016 if (IsVarArg && Subtarget.isEnvironmentMusl()) {
1017 for (int i = HFL.FirstVarArgSavedReg; i < 6; i++)
1018 MRI.addLiveIn(Hexagon::R0+i);
1019 }
1020
1021 if (IsVarArg && Subtarget.isEnvironmentMusl()) {
1022 HMFI.setFirstNamedArgFrameIndex(HMFI.getFirstNamedArgFrameIndex() - 1);
1023 HMFI.setLastNamedArgFrameIndex(-int(MFI.getNumFixedObjects()));
1024
1025 // Create Frame index for the start of register saved area.
1026 int NumVarArgRegs = 6 - HFL.FirstVarArgSavedReg;
1027 bool RequiresPadding = (NumVarArgRegs & 1);
1028 int RegSaveAreaSizePlusPadding = RequiresPadding
1029 ? (NumVarArgRegs + 1) * 4
1030 : NumVarArgRegs * 4;
1031
1032 if (RegSaveAreaSizePlusPadding > 0) {
1033 // The offset to saved register area should be 8 byte aligned.
1034 int RegAreaStart = HEXAGON_LRFP_SIZE + CCInfo.getStackSize();
1035 if (!(RegAreaStart % 8))
1036 RegAreaStart = (RegAreaStart + 7) & -8;
1037
1038 int RegSaveAreaFrameIndex =
1039 MFI.CreateFixedObject(RegSaveAreaSizePlusPadding, RegAreaStart, true);
1040 HMFI.setRegSavedAreaStartFrameIndex(RegSaveAreaFrameIndex);
1041
1042 // This will point to the next argument passed via stack.
1043 int Offset = RegAreaStart + RegSaveAreaSizePlusPadding;
1044 int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
1045 HMFI.setVarArgsFrameIndex(FI);
1046 } else {
1047 // This will point to the next argument passed via stack, when
1048 // there is no saved register area.
1049 int Offset = HEXAGON_LRFP_SIZE + CCInfo.getStackSize();
1050 int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
1051 HMFI.setRegSavedAreaStartFrameIndex(FI);
1052 HMFI.setVarArgsFrameIndex(FI);
1053 }
1054 }
1055
1056
1057 if (IsVarArg && !Subtarget.isEnvironmentMusl()) {
1058 // This will point to the next argument passed via stack.
1059 int Offset = HEXAGON_LRFP_SIZE + CCInfo.getStackSize();
1060 int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
1061 HMFI.setVarArgsFrameIndex(FI);
1062 }
1063
1064 return Chain;
1065}
1066
1067SDValue
1069 // VASTART stores the address of the VarArgsFrameIndex slot into the
1070 // memory location argument.
1073 SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
1074 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1075
1076 if (!Subtarget.isEnvironmentMusl()) {
1077 return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr, Op.getOperand(1),
1078 MachinePointerInfo(SV));
1079 }
1080 auto &FuncInfo = *MF.getInfo<HexagonMachineFunctionInfo>();
1081 auto &HFL = *Subtarget.getFrameLowering();
1082 SDLoc DL(Op);
1084
1085 // Get frame index of va_list.
1086 SDValue FIN = Op.getOperand(1);
1087
1088 // If first Vararg register is odd, add 4 bytes to start of
1089 // saved register area to point to the first register location.
1090 // This is because the saved register area has to be 8 byte aligned.
1091 // In case of an odd start register, there will be 4 bytes of padding in
1092 // the beginning of saved register area. If all registers area used up,
1093 // the following condition will handle it correctly.
1094 SDValue SavedRegAreaStartFrameIndex =
1095 DAG.getFrameIndex(FuncInfo.getRegSavedAreaStartFrameIndex(), MVT::i32);
1096
1097 auto PtrVT = getPointerTy(DAG.getDataLayout());
1098
1099 if (HFL.FirstVarArgSavedReg & 1)
1100 SavedRegAreaStartFrameIndex =
1101 DAG.getNode(ISD::ADD, DL, PtrVT,
1102 DAG.getFrameIndex(FuncInfo.getRegSavedAreaStartFrameIndex(),
1103 MVT::i32),
1104 DAG.getIntPtrConstant(4, DL));
1105
1106 // Store the saved register area start pointer.
1107 SDValue Store =
1108 DAG.getStore(Op.getOperand(0), DL,
1109 SavedRegAreaStartFrameIndex,
1110 FIN, MachinePointerInfo(SV));
1111 MemOps.push_back(Store);
1112
1113 // Store saved register area end pointer.
1114 FIN = DAG.getNode(ISD::ADD, DL, PtrVT,
1115 FIN, DAG.getIntPtrConstant(4, DL));
1116 Store = DAG.getStore(Op.getOperand(0), DL,
1117 DAG.getFrameIndex(FuncInfo.getVarArgsFrameIndex(),
1118 PtrVT),
1119 FIN, MachinePointerInfo(SV, 4));
1120 MemOps.push_back(Store);
1121
1122 // Store overflow area pointer.
1123 FIN = DAG.getNode(ISD::ADD, DL, PtrVT,
1124 FIN, DAG.getIntPtrConstant(4, DL));
1125 Store = DAG.getStore(Op.getOperand(0), DL,
1126 DAG.getFrameIndex(FuncInfo.getVarArgsFrameIndex(),
1127 PtrVT),
1128 FIN, MachinePointerInfo(SV, 8));
1129 MemOps.push_back(Store);
1130
1131 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1132}
1133
1134SDValue
1136 // Assert that the linux ABI is enabled for the current compilation.
1137 assert(Subtarget.isEnvironmentMusl() && "Linux ABI should be enabled");
1138 SDValue Chain = Op.getOperand(0);
1139 SDValue DestPtr = Op.getOperand(1);
1140 SDValue SrcPtr = Op.getOperand(2);
1141 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
1142 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
1143 SDLoc DL(Op);
1144 // Size of the va_list is 12 bytes as it has 3 pointers. Therefore,
1145 // we need to memcopy 12 bytes from va_list to another similar list.
1146 return DAG.getMemcpy(Chain, DL, DestPtr, SrcPtr,
1147 DAG.getIntPtrConstant(12, DL), Align(4), Align(4),
1148 /*isVolatile*/ false, false, /*CI=*/nullptr,
1149 std::nullopt, MachinePointerInfo(DestSV),
1150 MachinePointerInfo(SrcSV));
1151}
1152
1154 const SDLoc &dl(Op);
1155 SDValue LHS = Op.getOperand(0);
1156 SDValue RHS = Op.getOperand(1);
1157 ISD::CondCode CC = Op.getOperandCondCode(2);
1158 MVT ResTy = ty(Op);
1159 MVT OpTy = ty(LHS);
1160
1161 if (OpTy == MVT::v2i16 || OpTy == MVT::v4i8) {
1162 assert(OpTy.getVectorElementType().isScalarInteger());
1163 MVT WideTy = OpTy.widenIntegerElementType();
1164 return DAG.getSetCC(dl, ResTy,
1165 DAG.getSExtOrTrunc(LHS, SDLoc(LHS), WideTy),
1166 DAG.getSExtOrTrunc(RHS, SDLoc(RHS), WideTy), CC);
1167 }
1168
1169 // Treat all other vector types as legal.
1170 if (ResTy.isVector())
1171 return Op;
1172
1173 // Equality comparisons of short integers should use sign-extend, not
1174 // zero-extend, since we can represent small negative values in the compare
1175 // instructions. The LLVM default is to use zero-extend arbitrarily in
1176 // these cases.
1177 auto isSExtFree = [this](SDValue N) {
1178 switch (N.getOpcode()) {
1179 case ISD::TRUNCATE: {
1180 // A sign-extend of a truncate of a sign-extend is free.
1181 SDValue Op = N.getOperand(0);
1182 if (Op.getOpcode() != ISD::AssertSext)
1183 return false;
1184 EVT OrigTy = cast<VTSDNode>(Op.getOperand(1))->getVT();
1185 unsigned ThisBW = ty(N).getSizeInBits();
1186 unsigned OrigBW = OrigTy.getSizeInBits();
1187 // The type that was sign-extended to get the AssertSext must be
1188 // narrower than the type of N (so that N has still the same value
1189 // as the original).
1190 return ThisBW >= OrigBW;
1191 }
1192 case ISD::LOAD:
1193 // We have sign-extended loads.
1194 return true;
1195 }
1196 return false;
1197 };
1198
1199 // Only do this for equality comparisons. Signed comparisons are already
1200 // sign-extended by the generic operand promotion, and for unsigned
1201 // comparisons a sign-extension is never profitable: it does not change the
1202 // result (sign-extension preserves the unsigned ordering of the values of
1203 // the narrower type), but it turns constants with the sign bit of the
1204 // narrower type set into large 32-bit values, which then have to be
1205 // materialized in a register or use a constant extender.
1206 if ((OpTy == MVT::i8 || OpTy == MVT::i16) && ISD::isIntEqualitySetCC(CC)) {
1208 bool IsNegative = C && C->getAPIntValue().isNegative();
1209 if (IsNegative || isSExtFree(LHS) || isSExtFree(RHS))
1210 return DAG.getSetCC(dl, ResTy,
1211 DAG.getSExtOrTrunc(LHS, SDLoc(LHS), MVT::i32),
1212 DAG.getSExtOrTrunc(RHS, SDLoc(RHS), MVT::i32), CC);
1213 }
1214
1215 return SDValue();
1216}
1217
1218SDValue
1220 SDValue PredOp = Op.getOperand(0);
1221 SDValue Op1 = Op.getOperand(1), Op2 = Op.getOperand(2);
1222 MVT OpTy = ty(Op1);
1223 const SDLoc &dl(Op);
1224
1225 if (OpTy == MVT::v2i16 || OpTy == MVT::v4i8) {
1226 assert(OpTy.getVectorElementType().isScalarInteger());
1227 MVT WideTy = OpTy.widenIntegerElementType();
1228 // Generate (trunc (select (_, sext, sext))).
1229 return DAG.getSExtOrTrunc(
1230 DAG.getSelect(dl, WideTy, PredOp,
1231 DAG.getSExtOrTrunc(Op1, dl, WideTy),
1232 DAG.getSExtOrTrunc(Op2, dl, WideTy)),
1233 dl, OpTy);
1234 }
1235
1236 return SDValue();
1237}
1238
1239SDValue
1241 EVT ValTy = Op.getValueType();
1243 Constant *CVal = nullptr;
1244 bool isVTi1Type = false;
1245 if (auto *CV = dyn_cast<ConstantVector>(CPN->getConstVal())) {
1246 if (cast<VectorType>(CV->getType())->getElementType()->isIntegerTy(1)) {
1248 unsigned VecLen = CV->getNumOperands();
1249 assert(isPowerOf2_32(VecLen) &&
1250 "conversion only supported for pow2 VectorSize");
1251 for (unsigned i = 0; i < VecLen; ++i)
1252 NewConst.push_back(ConstantInt::get(Type::getInt8Ty(CV->getContext()),
1253 CV->getOperand(i)->isNullValue()));
1254
1255 CVal = ConstantVector::get(NewConst);
1256 isVTi1Type = true;
1257 }
1258 }
1259 Align Alignment = CPN->getAlign();
1260 bool IsPositionIndependent = isPositionIndependent();
1261 unsigned char TF = IsPositionIndependent ? HexagonII::MO_PCREL : 0;
1262
1263 unsigned Offset = 0;
1264 SDValue T;
1265 if (CPN->isMachineConstantPoolEntry())
1266 T = DAG.getTargetConstantPool(CPN->getMachineCPVal(), ValTy, Alignment,
1267 Offset, TF);
1268 else if (isVTi1Type)
1269 T = DAG.getTargetConstantPool(CVal, ValTy, Alignment, Offset, TF);
1270 else
1271 T = DAG.getTargetConstantPool(CPN->getConstVal(), ValTy, Alignment, Offset,
1272 TF);
1273
1274 assert(cast<ConstantPoolSDNode>(T)->getTargetFlags() == TF &&
1275 "Inconsistent target flag encountered");
1276
1277 if (IsPositionIndependent)
1278 return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), ValTy, T);
1279 return DAG.getNode(HexagonISD::CP, SDLoc(Op), ValTy, T);
1280}
1281
1282SDValue
1284 EVT VT = Op.getValueType();
1285 int Idx = cast<JumpTableSDNode>(Op)->getIndex();
1286 if (isPositionIndependent()) {
1288 return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), VT, T);
1289 }
1290
1291 SDValue T = DAG.getTargetJumpTable(Idx, VT);
1292 return DAG.getNode(HexagonISD::JT, SDLoc(Op), VT, T);
1293}
1294
1295SDValue
1297 const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1299 MachineFrameInfo &MFI = MF.getFrameInfo();
1300 MFI.setReturnAddressIsTaken(true);
1301
1302 EVT VT = Op.getValueType();
1303 SDLoc dl(Op);
1304 unsigned Depth = Op.getConstantOperandVal(0);
1305 if (Depth) {
1306 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1307 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
1308 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
1309 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
1311 }
1312
1313 // Return LR, which contains the return address. Mark it an implicit live-in.
1314 Register Reg = MF.addLiveIn(HRI.getRARegister(), getRegClassFor(MVT::i32));
1315 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
1316}
1317
1318SDValue
1320 const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1322 MFI.setFrameAddressIsTaken(true);
1323
1324 EVT VT = Op.getValueType();
1325 SDLoc dl(Op);
1326 unsigned Depth = Op.getConstantOperandVal(0);
1327 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1328 HRI.getFrameRegister(), VT);
1329 while (Depth--)
1330 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1332 return FrameAddr;
1333}
1334
1335SDValue
1337 SDLoc dl(Op);
1338 return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
1339}
1340
1341SDValue
1343 SDLoc dl(Op);
1344 auto *GAN = cast<GlobalAddressSDNode>(Op);
1345 auto PtrVT = getPointerTy(DAG.getDataLayout());
1346 auto *GV = GAN->getGlobal();
1347 int64_t Offset = GAN->getOffset();
1348
1349 auto &HLOF = *HTM.getObjFileLowering();
1350 Reloc::Model RM = HTM.getRelocationModel();
1351
1352 if (RM == Reloc::Static) {
1353 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
1354 const GlobalObject *GO = GV->getAliaseeObject();
1355 if (GO && Subtarget.useSmallData() && HLOF.isGlobalInSmallSection(GO, HTM))
1356 return DAG.getNode(HexagonISD::CONST32_GP, dl, PtrVT, GA);
1357 return DAG.getNode(HexagonISD::CONST32, dl, PtrVT, GA);
1358 }
1359
1360 bool UsePCRel = getTargetMachine().shouldAssumeDSOLocal(GV);
1361 if (UsePCRel) {
1362 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset,
1364 return DAG.getNode(HexagonISD::AT_PCREL, dl, PtrVT, GA);
1365 }
1366
1367 // Use GOT index.
1368 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1369 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, HexagonII::MO_GOT);
1370 SDValue Off = DAG.getConstant(Offset, dl, MVT::i32);
1371 return DAG.getNode(HexagonISD::AT_GOT, dl, PtrVT, GOT, GA, Off);
1372}
1373
1374// Specifies that for loads and stores VT can be promoted to PromotedLdStVT.
1375SDValue
1377 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1378 SDLoc dl(Op);
1379 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1380
1381 Reloc::Model RM = HTM.getRelocationModel();
1382 if (RM == Reloc::Static) {
1383 SDValue A = DAG.getTargetBlockAddress(BA, PtrVT);
1384 return DAG.getNode(HexagonISD::CONST32_GP, dl, PtrVT, A);
1385 }
1386
1388 return DAG.getNode(HexagonISD::AT_PCREL, dl, PtrVT, A);
1389}
1390
1391SDValue
1393 const {
1394 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1397 return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), PtrVT, GOTSym);
1398}
1399
1400SDValue
1402 GlobalAddressSDNode *GA, SDValue Glue, EVT PtrVT, unsigned ReturnReg,
1403 unsigned char OperandFlags) const {
1405 MachineFrameInfo &MFI = MF.getFrameInfo();
1406 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1407 SDLoc dl(GA);
1408 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
1409 GA->getValueType(0),
1410 GA->getOffset(),
1411 OperandFlags);
1412 // Create Operands for the call.The Operands should have the following:
1413 // 1. Chain SDValue
1414 // 2. Callee which in this case is the Global address value.
1415 // 3. Registers live into the call.In this case its R0, as we
1416 // have just one argument to be passed.
1417 // 4. Glue.
1418 // Note: The order is important.
1419
1420 const auto &HRI = *Subtarget.getRegisterInfo();
1421 const uint32_t *Mask = HRI.getCallPreservedMask(MF, CallingConv::C);
1422 assert(Mask && "Missing call preserved mask for calling convention");
1423 SDValue Ops[] = { Chain, TGA, DAG.getRegister(Hexagon::R0, PtrVT),
1424 DAG.getRegisterMask(Mask), Glue };
1425 Chain = DAG.getNode(HexagonISD::CALL, dl, NodeTys, Ops);
1426
1427 // Inform MFI that function has calls.
1428 MFI.setAdjustsStack(true);
1429
1430 Glue = Chain.getValue(1);
1431 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
1432}
1433
1434//
1435// Lower using the initial executable model for TLS addresses
1436//
1437SDValue
1439 SelectionDAG &DAG) const {
1440 SDLoc dl(GA);
1441 int64_t Offset = GA->getOffset();
1442 auto PtrVT = getPointerTy(DAG.getDataLayout());
1443
1444 // Get the thread pointer.
1445 SDValue TP = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Hexagon::UGP, PtrVT);
1446
1447 bool IsPositionIndependent = isPositionIndependent();
1448 unsigned char TF =
1449 IsPositionIndependent ? HexagonII::MO_IEGOT : HexagonII::MO_IE;
1450
1451 // First generate the TLS symbol address
1452 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT,
1453 Offset, TF);
1454
1455 SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1456
1457 if (IsPositionIndependent) {
1458 // Generate the GOT pointer in case of position independent code
1459 SDValue GOT = LowerGLOBAL_OFFSET_TABLE(Sym, DAG);
1460
1461 // Add the TLS Symbol address to GOT pointer.This gives
1462 // GOT relative relocation for the symbol.
1463 Sym = DAG.getNode(ISD::ADD, dl, PtrVT, GOT, Sym);
1464 }
1465
1466 // Load the offset value for TLS symbol.This offset is relative to
1467 // thread pointer.
1468 SDValue LoadOffset =
1469 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Sym, MachinePointerInfo());
1470
1471 // Address of the thread local variable is the add of thread
1472 // pointer and the offset of the variable.
1473 return DAG.getNode(ISD::ADD, dl, PtrVT, TP, LoadOffset);
1474}
1475
1476//
1477// Lower using the local executable model for TLS addresses
1478//
1479SDValue
1481 SelectionDAG &DAG) const {
1482 SDLoc dl(GA);
1483 int64_t Offset = GA->getOffset();
1484 auto PtrVT = getPointerTy(DAG.getDataLayout());
1485
1486 // Get the thread pointer.
1487 SDValue TP = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Hexagon::UGP, PtrVT);
1488 // Generate the TLS symbol address
1489 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT, Offset,
1491 SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1492
1493 // Address of the thread local variable is the add of thread
1494 // pointer and the offset of the variable.
1495 return DAG.getNode(ISD::ADD, dl, PtrVT, TP, Sym);
1496}
1497
1498//
1499// Lower using the general dynamic model for TLS addresses
1500//
1501SDValue
1503 SelectionDAG &DAG) const {
1504 SDLoc dl(GA);
1505 int64_t Offset = GA->getOffset();
1506 auto PtrVT = getPointerTy(DAG.getDataLayout());
1507
1508 // First generate the TLS symbol address
1509 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT, Offset,
1511
1512 // Then, generate the GOT pointer
1513 SDValue GOT = LowerGLOBAL_OFFSET_TABLE(TGA, DAG);
1514
1515 // Add the TLS symbol and the GOT pointer
1516 SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1517 SDValue Chain = DAG.getNode(ISD::ADD, dl, PtrVT, GOT, Sym);
1518
1519 // Copy over the argument to R0
1520 SDValue InGlue;
1521 Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, Hexagon::R0, Chain, InGlue);
1522 InGlue = Chain.getValue(1);
1523
1524 unsigned Flags = DAG.getSubtarget<HexagonSubtarget>().useLongCalls()
1527
1528 return GetDynamicTLSAddr(DAG, Chain, GA, InGlue, PtrVT,
1529 Hexagon::R0, Flags);
1530}
1531
1532//
1533// Lower TLS addresses.
1534//
1535// For now for dynamic models, we only support the general dynamic model.
1536//
1537SDValue
1539 SelectionDAG &DAG) const {
1541
1542 switch (HTM.getTLSModel(GA->getGlobal())) {
1545 return LowerToTLSGeneralDynamicModel(GA, DAG);
1547 return LowerToTLSInitialExecModel(GA, DAG);
1549 return LowerToTLSLocalExecModel(GA, DAG);
1550 }
1551 llvm_unreachable("Bogus TLS model");
1552}
1553
1554//===----------------------------------------------------------------------===//
1555// TargetLowering Implementation
1556//===----------------------------------------------------------------------===//
1557
1559 const HexagonSubtarget &ST)
1560 : TargetLowering(TM, ST),
1561 HTM(static_cast<const HexagonTargetMachine &>(TM)), Subtarget(ST) {
1562 auto &HRI = *Subtarget.getRegisterInfo();
1563
1567 setStackPointerRegisterToSaveRestore(HRI.getStackRegister());
1570
1573
1576 else
1578
1579 // Limits for inline expansion of memcpy/memmove
1586
1588
1589 //
1590 // Set up register classes.
1591 //
1592
1593 addRegisterClass(MVT::i1, &Hexagon::PredRegsRegClass);
1594 addRegisterClass(MVT::v2i1, &Hexagon::PredRegsRegClass); // bbbbaaaa
1595 addRegisterClass(MVT::v4i1, &Hexagon::PredRegsRegClass); // ddccbbaa
1596 addRegisterClass(MVT::v8i1, &Hexagon::PredRegsRegClass); // hgfedcba
1597 addRegisterClass(MVT::i32, &Hexagon::IntRegsRegClass);
1598 addRegisterClass(MVT::v2i16, &Hexagon::IntRegsRegClass);
1599 addRegisterClass(MVT::v4i8, &Hexagon::IntRegsRegClass);
1600 addRegisterClass(MVT::i64, &Hexagon::DoubleRegsRegClass);
1601 addRegisterClass(MVT::v8i8, &Hexagon::DoubleRegsRegClass);
1602 addRegisterClass(MVT::v4i16, &Hexagon::DoubleRegsRegClass);
1603 addRegisterClass(MVT::v2i32, &Hexagon::DoubleRegsRegClass);
1604
1605 addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
1606 addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
1607
1608 //
1609 // Handling of scalar operations.
1610 //
1611 // All operations default to "legal", except:
1612 // - indexed loads and stores (pre-/post-incremented),
1613 // - ANY_EXTEND_VECTOR_INREG, ATOMIC_CMP_SWAP_WITH_SUCCESS, CONCAT_VECTORS,
1614 // ConstantFP, FCEIL, FCOPYSIGN, FEXP, FEXP2, FFLOOR, FGETSIGN,
1615 // FLOG, FLOG2, FLOG10, FMAXIMUMNUM, FMINIMUMNUM, FNEARBYINT, FRINT, FROUND,
1616 // TRAP, FTRUNC, PREFETCH, SIGN_EXTEND_VECTOR_INREG,
1617 // ZERO_EXTEND_VECTOR_INREG,
1618 // which default to "expand" for at least one type.
1619
1620 // Misc operations.
1623 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1641
1642 // Custom legalize GlobalAddress nodes into CONST32.
1646
1647 // Hexagon needs to optimize cases with negative constants.
1651 setOperationAction(ISD::SETCC, MVT::v2i16, Custom);
1652
1653 // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1655 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1656 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1657 if (Subtarget.isEnvironmentMusl())
1659 else
1661
1665
1666 if (EmitJumpTables)
1668 else
1669 setMinimumJumpTableEntries(std::numeric_limits<unsigned>::max());
1670 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1671
1672 for (unsigned LegalIntOp :
1674 setOperationAction(LegalIntOp, MVT::i32, Legal);
1675 setOperationAction(LegalIntOp, MVT::i64, Legal);
1676 }
1677
1678 // Hexagon has A4_addp_c and A4_subp_c that take and generate a carry bit,
1679 // but they only operate on i64.
1680 for (MVT VT : MVT::integer_valuetypes()) {
1687 }
1690
1695
1696 // Popcount can count # of 1s in i64 but returns i32.
1701
1706
1711
1712 for (unsigned IntExpOp :
1717 for (MVT VT : MVT::integer_valuetypes())
1718 setOperationAction(IntExpOp, VT, Expand);
1719 }
1720 for (MVT VT : MVT::fp_valuetypes()) {
1721 for (unsigned FPExpOp : {ISD::FDIV, ISD::FSQRT, ISD::FSIN, ISD::FCOS,
1723 setOperationAction(FPExpOp, VT, Expand);
1724
1726 }
1727
1728 // No extending loads from i32.
1729 for (MVT VT : MVT::integer_valuetypes()) {
1730 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
1731 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
1732 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
1733 }
1734 // Turn FP truncstore into trunc + store.
1735 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1736 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
1737 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
1738 // Turn FP extload into load/fpextend.
1739 for (MVT VT : MVT::fp_valuetypes())
1740 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1741
1742 // Expand BR_CC and SELECT_CC for all integer and fp types.
1743 for (MVT VT : MVT::integer_valuetypes()) {
1746 }
1747 for (MVT VT : MVT::fp_valuetypes()) {
1750 }
1751 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
1752
1753 //
1754 // Handling of vector operations.
1755 //
1756
1757 // Set the action for vector operations to "expand", then override it with
1758 // either "custom" or "legal" for specific cases.
1759 // clang-format off
1760 static const unsigned VectExpOps[] = {
1761 // Integer arithmetic:
1765 // Logical/bit:
1768 // Floating point arithmetic/math functions:
1776 // Misc:
1778 // Vector:
1784 };
1785 // clang-format on
1786
1788 for (unsigned VectExpOp : VectExpOps)
1789 setOperationAction(VectExpOp, VT, Expand);
1790
1791 // Expand all extending loads and truncating stores:
1792 for (MVT TargetVT : MVT::fixedlen_vector_valuetypes()) {
1793 if (TargetVT == VT)
1794 continue;
1795 setLoadExtAction(ISD::EXTLOAD, TargetVT, VT, Expand);
1796 setLoadExtAction(ISD::ZEXTLOAD, TargetVT, VT, Expand);
1797 setLoadExtAction(ISD::SEXTLOAD, TargetVT, VT, Expand);
1798 setTruncStoreAction(VT, TargetVT, Expand);
1799 }
1800
1801 // Normalize all inputs to SELECT to be vectors of i32.
1802 if (VT.getVectorElementType() != MVT::i32) {
1803 MVT VT32 = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
1805 AddPromotedToType(ISD::SELECT, VT, VT32);
1806 }
1810 }
1811
1814
1815 // Extending loads from (native) vectors of i8 into (native) vectors of i16
1816 // are legal.
1817 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1818 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1819 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1820 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1821 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1822 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1823
1827
1828 // Types natively supported:
1829 for (MVT NativeVT : {MVT::v8i1, MVT::v4i1, MVT::v2i1, MVT::v4i8,
1830 MVT::v8i8, MVT::v2i16, MVT::v4i16, MVT::v2i32}) {
1837
1838 setOperationAction(ISD::ADD, NativeVT, Legal);
1839 setOperationAction(ISD::SUB, NativeVT, Legal);
1840 setOperationAction(ISD::MUL, NativeVT, Legal);
1841 setOperationAction(ISD::AND, NativeVT, Legal);
1842 setOperationAction(ISD::OR, NativeVT, Legal);
1843 setOperationAction(ISD::XOR, NativeVT, Legal);
1844
1845 if (NativeVT.getVectorElementType() != MVT::i1) {
1849 }
1850 }
1851
1852 for (MVT VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32}) {
1857 }
1858
1859 // Custom lower unaligned loads.
1860 // Also, for both loads and stores, verify the alignment of the address
1861 // in case it is a compile-time constant. This is a usability feature to
1862 // provide a meaningful error message to users.
1863 for (MVT VT : {MVT::i16, MVT::i32, MVT::v4i8, MVT::i64, MVT::v8i8,
1864 MVT::v2i16, MVT::v4i16, MVT::v2i32}) {
1867 }
1868
1869 // Custom-lower load/stores of boolean vectors.
1870 for (MVT VT : {MVT::v2i1, MVT::v4i1, MVT::v8i1}) {
1873 }
1874
1875 // Normalize integer compares to EQ/GT/UGT
1876 for (MVT VT : {MVT::v2i16, MVT::v4i8, MVT::v8i8, MVT::v2i32, MVT::v4i16,
1877 MVT::v2i32}) {
1885 }
1886
1887 // Normalize boolean compares to [U]LE/[U]LT
1888 for (MVT VT : {MVT::i1, MVT::v2i1, MVT::v4i1, MVT::v8i1}) {
1893 }
1894
1895 // Custom-lower bitcasts from i8 to v8i1.
1897 setOperationAction(ISD::SETCC, MVT::v2i16, Custom);
1903
1904 // V5+.
1910
1919
1932
1933 // Special handling for half-precision floating point conversions.
1934 // Lower half float conversions into library calls.
1942
1943 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
1944 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
1945 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::bf16, Expand);
1946 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::bf16, Expand);
1947
1948 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1949 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1950
1951 // Handling of indexed loads/stores: default is "expand".
1952 //
1953 for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64, MVT::f32, MVT::f64,
1954 MVT::v2i16, MVT::v2i32, MVT::v4i8, MVT::v4i16, MVT::v8i8}) {
1957 }
1958
1959 // Subtarget-specific operation actions.
1960 //
1961 if (Subtarget.hasV60Ops()) {
1966 }
1967 if (Subtarget.hasV66Ops()) {
1970 }
1971 if (Subtarget.hasV67Ops()) {
1977 }
1978
1982
1983 if (Subtarget.useHVXOps())
1984 initializeHVXLowering();
1985
1986 if (Subtarget.useHLXOps())
1987 initializeHLXLowering();
1988
1990}
1991
1992bool
1993HexagonTargetLowering::validateConstPtrAlignment(SDValue Ptr, Align NeedAlign,
1994 const SDLoc &dl, SelectionDAG &DAG) const {
1995 auto *CA = dyn_cast<ConstantSDNode>(Ptr);
1996 if (!CA)
1997 return true;
1998 unsigned Addr = CA->getZExtValue();
1999 Align HaveAlign =
2000 Addr != 0 ? Align::fromLog2(llvm::countr_zero(Addr)) : NeedAlign;
2001 if (HaveAlign >= NeedAlign)
2002 return true;
2003
2004 static int DK_MisalignedTrap = llvm::getNextAvailablePluginDiagnosticKind();
2005
2006 struct DiagnosticInfoMisalignedTrap : public DiagnosticInfo {
2007 DiagnosticInfoMisalignedTrap(StringRef M)
2008 : DiagnosticInfo(DK_MisalignedTrap, DS_Remark), Msg(M) {}
2009 void print(DiagnosticPrinter &DP) const override {
2010 DP << Msg;
2011 }
2012 static bool classof(const DiagnosticInfo *DI) {
2013 return DI->getKind() == DK_MisalignedTrap;
2014 }
2015 StringRef Msg;
2016 };
2017
2018 std::string ErrMsg;
2019 raw_string_ostream O(ErrMsg);
2020 O << "Misaligned constant address: " << format_hex(Addr, 10)
2021 << " has alignment " << HaveAlign.value()
2022 << ", but the memory access requires " << NeedAlign.value();
2023 if (DebugLoc DL = dl.getDebugLoc())
2024 DL.print(O << ", at ");
2025 O << ". The instruction has been replaced with a trap.";
2026
2027 DAG.getContext()->diagnose(DiagnosticInfoMisalignedTrap(O.str()));
2028 return false;
2029}
2030
2031SDValue
2032HexagonTargetLowering::replaceMemWithUndef(SDValue Op, SelectionDAG &DAG)
2033 const {
2034 const SDLoc &dl(Op);
2035 auto *LS = cast<LSBaseSDNode>(Op.getNode());
2036 assert(!LS->isIndexed() && "Not expecting indexed ops on constant address");
2037
2038 SDValue Chain = LS->getChain();
2039 SDValue Trap = DAG.getNode(ISD::TRAP, dl, MVT::Other, Chain);
2040 if (LS->getOpcode() == ISD::LOAD)
2041 return DAG.getMergeValues({DAG.getUNDEF(ty(Op)), Trap}, dl);
2042 return Trap;
2043}
2044
2045// Bit-reverse Load Intrinsic: Check if the instruction is a bit reverse load
2046// intrinsic.
2047static bool isBrevLdIntrinsic(const Value *Inst) {
2048 unsigned ID = cast<IntrinsicInst>(Inst)->getIntrinsicID();
2049 return (ID == Intrinsic::hexagon_L2_loadrd_pbr ||
2050 ID == Intrinsic::hexagon_L2_loadri_pbr ||
2051 ID == Intrinsic::hexagon_L2_loadrh_pbr ||
2052 ID == Intrinsic::hexagon_L2_loadruh_pbr ||
2053 ID == Intrinsic::hexagon_L2_loadrb_pbr ||
2054 ID == Intrinsic::hexagon_L2_loadrub_pbr);
2055}
2056
2057// Bit-reverse Load Intrinsic :Crawl up and figure out the object from previous
2058// instruction. So far we only handle bitcast, extract value and bit reverse
2059// load intrinsic instructions. Should we handle CGEP ?
2061 if (Operator::getOpcode(V) == Instruction::ExtractValue ||
2062 Operator::getOpcode(V) == Instruction::BitCast)
2063 V = cast<Operator>(V)->getOperand(0);
2065 V = cast<Instruction>(V)->getOperand(0);
2066 return V;
2067}
2068
2069// Bit-reverse Load Intrinsic: For a PHI Node return either an incoming edge or
2070// a back edge. If the back edge comes from the intrinsic itself, the incoming
2071// edge is returned.
2072static Value *returnEdge(const PHINode *PN, Value *IntrBaseVal) {
2073 const BasicBlock *Parent = PN->getParent();
2074 int Idx = -1;
2075 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
2076 BasicBlock *Blk = PN->getIncomingBlock(i);
2077 // Determine if the back edge is originated from intrinsic.
2078 if (Blk == Parent) {
2079 Value *BackEdgeVal = PN->getIncomingValue(i);
2080 Value *BaseVal;
2081 // Loop over till we return the same Value or we hit the IntrBaseVal.
2082 do {
2083 BaseVal = BackEdgeVal;
2084 BackEdgeVal = getBrevLdObject(BackEdgeVal);
2085 } while ((BaseVal != BackEdgeVal) && (IntrBaseVal != BackEdgeVal));
2086 // If the getBrevLdObject returns IntrBaseVal, we should return the
2087 // incoming edge.
2088 if (IntrBaseVal == BackEdgeVal)
2089 continue;
2090 Idx = i;
2091 break;
2092 } else // Set the node to incoming edge.
2093 Idx = i;
2094 }
2095 assert(Idx >= 0 && "Unexpected index to incoming argument in PHI");
2096 return PN->getIncomingValue(Idx);
2097}
2098
2099// Bit-reverse Load Intrinsic: Figure out the underlying object the base
2100// pointer points to, for the bit-reverse load intrinsic. Setting this to
2101// memoperand might help alias analysis to figure out the dependencies.
2102// A bit-reverse load accesses the base pointer with its low 16 bits reversed,
2103// and post-increments the base pointer by the modifier value. For a chain of
2104// bit-reverse loads, the offset that a load accesses relative to the
2105// underlying object is the bit-reverse of the sum of the modifiers of the
2106// preceding loads in the chain. Offset is set to that value, and HasOffset is
2107// set to true, when the sum is known, that is when all of those modifiers are
2108// constants and the sum fits in 16 unsigned bits. Otherwise HasOffset is set
2109// to false and Offset is left unchanged.
2111 bool &HasOffset) {
2112 Value *IntrBaseVal = V;
2113 Value *BaseVal;
2114 int64_t Sum = 0;
2115 HasOffset = true;
2116 // Loop over till we return the same Value, implies we either figure out
2117 // the object or we hit a PHI
2118 do {
2119 BaseVal = V;
2120 V = getBrevLdObject(V);
2121 // Identify if this is part of a chain of bit-reverse loads, and accumulate
2122 // the modifier of the preceding load in the chain.
2123 if (HasOffset && BaseVal != V && isa<IntrinsicInst>(V) &&
2125 Value *Modifier = cast<IntrinsicInst>(V)->getOperand(1);
2126 if (auto *CN = dyn_cast<ConstantInt>(Modifier))
2127 Sum += CN->getSExtValue();
2128 else
2129 HasOffset = false;
2130 }
2131 } while (BaseVal != V);
2132
2133 // Only the low 16 bits of the base pointer take part in the bit-reverse. A
2134 // sum that does not fit in them would also change the remaining bits.
2135 if (HasOffset && Sum >= 0 && isUInt<16>(Sum))
2136 Offset = APInt(16, Sum).reverseBits().getZExtValue();
2137 else
2138 HasOffset = false;
2139
2140 // Identify the object from PHINode.
2141 if (const PHINode *PN = dyn_cast<PHINode>(V))
2142 return returnEdge(PN, IntrBaseVal);
2143 // For non PHI nodes, the object is the last value returned by getBrevLdObject
2144 else
2145 return V;
2146}
2147
2148/// Infer IntrinsicInfo for an HLX memory intrinsic from its IR signature.
2149/// Loads return a vector type; stores have a void return and pass the vector
2150/// as an argument.
2152 const HexagonSubtarget &ST,
2154 Type *RetTy = I.getCalledFunction()->getReturnType();
2155 bool IsLoad = RetTy->isVectorTy();
2156 Type *VecTy = IsLoad ? RetTy : I.getArgOperand(1)->getType();
2157 assert(VecTy->isVectorTy() && ST.isHLXVectorType(MVT::getVT(VecTy)) &&
2158 "Expected HLX vector type in HLX intrinsic");
2159
2160 Info.opc = IsLoad ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID;
2161 Info.memVT = MVT::getVT(VecTy);
2162 Info.ptrVal = I.getArgOperand(0);
2163 Info.offset = 0;
2164 Info.align = Align(ST.getHLXVectorLength());
2166}
2167
2168/// Given an intrinsic, checks if on the target the intrinsic will need to map
2169/// to a MemIntrinsicNode (touches memory). If this is the case, it stores
2170/// the intrinsic information into the Infos vector.
2173 MachineFunction &MF, unsigned Intrinsic) const {
2174 IntrinsicInfo Info;
2175 switch (Intrinsic) {
2176 case Intrinsic::hexagon_LX_L16b_tmp:
2177 case Intrinsic::hexagon_LX_LL16b_tmp:
2178 case Intrinsic::hexagon_LX_S16b_new:
2179 case Intrinsic::hexagon_LX_SS16b_new:
2180 getHlxMemIntrinsicInfo(I, Subtarget, Info);
2181 Infos.push_back(Info);
2182 return;
2183 case Intrinsic::hexagon_L2_loadrd_pbr:
2184 case Intrinsic::hexagon_L2_loadri_pbr:
2185 case Intrinsic::hexagon_L2_loadrh_pbr:
2186 case Intrinsic::hexagon_L2_loadruh_pbr:
2187 case Intrinsic::hexagon_L2_loadrb_pbr:
2188 case Intrinsic::hexagon_L2_loadrub_pbr: {
2189 Info.opc = ISD::INTRINSIC_W_CHAIN;
2190 auto &DL = I.getDataLayout();
2191 auto &Cont = I.getCalledFunction()->getParent()->getContext();
2192 // The intrinsic function call is of the form { ElTy, i8* }
2193 // @llvm.hexagon.L2.loadXX.pbr(i8*, i32). The pointer and memory access type
2194 // should be derived from ElTy.
2195 Type *ElTy = I.getCalledFunction()->getReturnType()->getStructElementType(0);
2196 Info.memVT = MVT::getVT(ElTy);
2197 llvm::Value *BasePtrVal = I.getOperand(0);
2198 // The offset value comes through the Modifier register. Determine the
2199 // offset that is going to be accessed relative to the underlying object.
2200 // If it cannot be determined, leave the pointer information out of the
2201 // memory operand, so that alias analysis stays conservative.
2202 bool HasOffset = false;
2203 Info.offset = 0;
2204 Value *UnderlyingObj =
2205 getUnderLyingObjectForBrevLdIntr(BasePtrVal, Info.offset, HasOffset);
2206 // The underlying object is unknown if the base pointer could not be traced
2207 // back to a pointer value. Also, unless the object is aligned to 64K, the
2208 // low 16 bits of the base pointer are not known, and reversing them can
2209 // produce an address anywhere in the surrounding 64K region, possibly
2210 // outside of the object.
2211 if (!UnderlyingObj->getType()->isPointerTy() ||
2212 UnderlyingObj->getPointerAlignment(DL) < Align(65536))
2213 HasOffset = false;
2214 if (HasOffset)
2215 Info.ptrVal = UnderlyingObj;
2216 Info.align = DL.getABITypeAlign(Info.memVT.getTypeForEVT(Cont));
2217 Info.flags = MachineMemOperand::MOLoad;
2218 Infos.push_back(Info);
2219 return;
2220 }
2221 case Intrinsic::hexagon_V6_vgathermw:
2222 case Intrinsic::hexagon_V6_vgathermw_128B:
2223 case Intrinsic::hexagon_V6_vgathermh:
2224 case Intrinsic::hexagon_V6_vgathermh_128B:
2225 case Intrinsic::hexagon_V6_vgathermhw:
2226 case Intrinsic::hexagon_V6_vgathermhw_128B:
2227 case Intrinsic::hexagon_V6_vgathermwq:
2228 case Intrinsic::hexagon_V6_vgathermwq_128B:
2229 case Intrinsic::hexagon_V6_vgathermhq:
2230 case Intrinsic::hexagon_V6_vgathermhq_128B:
2231 case Intrinsic::hexagon_V6_vgathermhwq:
2232 case Intrinsic::hexagon_V6_vgathermhwq_128B:
2233 case Intrinsic::hexagon_V6_vgather_vscattermh:
2234 case Intrinsic::hexagon_V6_vgather_vscattermh_128B: {
2235 const Module &M = *I.getParent()->getParent()->getParent();
2236 Info.opc = ISD::INTRINSIC_W_CHAIN;
2237 Type *VecTy = I.getArgOperand(I.arg_size() - 1)->getType();
2238 assert(VecTy->isVectorTy() && "Expected vector operand for vgather");
2239 Info.memVT = MVT::getVT(VecTy);
2240 Info.ptrVal = I.getArgOperand(0);
2241 Info.offset = 0;
2242 Info.align =
2243 MaybeAlign(M.getDataLayout().getTypeAllocSizeInBits(VecTy) / 8);
2246 Infos.push_back(Info);
2247 return;
2248 }
2249 default:
2250 break;
2251 }
2252}
2253
2255 return X.getValueType().isScalarInteger(); // 'tstbit'
2256}
2257
2259 return isTruncateFree(EVT::getEVT(Ty1), EVT::getEVT(Ty2));
2260}
2261
2263 if (!VT1.isSimple() || !VT2.isSimple())
2264 return false;
2265 return VT1.getSimpleVT() == MVT::i64 && VT2.getSimpleVT() == MVT::i32;
2266}
2267
2272
2273// Should we expand the build vector with shuffles?
2275 unsigned DefinedValues) const {
2276 return false;
2277}
2278
2281 unsigned Index) const {
2283 if (!ResVT.isSimple() || !SrcVT.isSimple())
2285
2286 MVT ResTy = ResVT.getSimpleVT(), SrcTy = SrcVT.getSimpleVT();
2287 if (ResTy.getVectorElementType() != MVT::i1)
2289
2290 // Non-HVX bool vectors are relatively cheap.
2291 if (SrcTy.getVectorNumElements() <= 8)
2294}
2295
2300
2302 EVT VT) const {
2303 return true;
2304}
2305
2308 unsigned VecLen = VT.getVectorMinNumElements();
2310
2311 if (VecLen == 1 || VT.isScalableVector())
2313
2314 if (Subtarget.useHVXOps()) {
2315 unsigned Action = getPreferredHvxVectorAction(VT);
2316 if (Action != ~0u)
2317 return static_cast<TargetLoweringBase::LegalizeTypeAction>(Action);
2318 }
2319
2320 // Always widen (remaining) vectors of i1.
2321 if (ElemTy == MVT::i1)
2323 // Widen non-power-of-2 vectors. Such types cannot be split right now,
2324 // and computeRegisterProperties will override "split" with "widen",
2325 // which can cause other issues.
2326 if (!isPowerOf2_32(VecLen))
2328
2330}
2331
2334 if (Subtarget.useHVXOps()) {
2335 unsigned Action = getCustomHvxOperationAction(Op);
2336 if (Action != ~0u)
2337 return static_cast<TargetLoweringBase::LegalizeAction>(Action);
2338 }
2340}
2341
2342std::pair<SDValue, int>
2343HexagonTargetLowering::getBaseAndOffset(SDValue Addr) const {
2344 if (Addr.getOpcode() == ISD::ADD) {
2345 SDValue Op1 = Addr.getOperand(1);
2346 if (auto *CN = dyn_cast<const ConstantSDNode>(Op1.getNode()))
2347 return { Addr.getOperand(0), CN->getSExtValue() };
2348 }
2349 return { Addr, 0 };
2350}
2351
2352// Lower a vector shuffle (V1, V2, V3). V1 and V2 are the two vectors
2353// to select data from, V3 is the permutation.
2354SDValue
2356 const {
2357 const auto *SVN = cast<ShuffleVectorSDNode>(Op);
2358 ArrayRef<int> AM = SVN->getMask();
2359 assert(AM.size() <= 8 && "Unexpected shuffle mask");
2360 unsigned VecLen = AM.size();
2361
2362 MVT VecTy = ty(Op);
2363 assert(!Subtarget.isHVXVectorType(VecTy, true) &&
2364 "HVX shuffles should be legal");
2365 assert(VecTy.getSizeInBits() <= 64 && "Unexpected vector length");
2366
2367 SDValue Op0 = Op.getOperand(0);
2368 SDValue Op1 = Op.getOperand(1);
2369 const SDLoc &dl(Op);
2370
2371 // If the inputs are not the same as the output, bail. This is not an
2372 // error situation, but complicates the handling and the default expansion
2373 // (into BUILD_VECTOR) should be adequate.
2374 if (ty(Op0) != VecTy || ty(Op1) != VecTy)
2375 return SDValue();
2376
2377 // Normalize the mask so that the first non-negative index comes from
2378 // the first operand.
2379 SmallVector<int, 8> Mask(AM);
2380 unsigned F = llvm::find_if(AM, [](int M) { return M >= 0; }) - AM.data();
2381 if (F == AM.size())
2382 return DAG.getUNDEF(VecTy);
2383 if (AM[F] >= int(VecLen)) {
2385 std::swap(Op0, Op1);
2386 }
2387
2388 // Express the shuffle mask in terms of bytes.
2389 SmallVector<int,8> ByteMask;
2390 unsigned ElemBytes = VecTy.getVectorElementType().getSizeInBits() / 8;
2391 for (int M : Mask) {
2392 if (M < 0) {
2393 for (unsigned j = 0; j != ElemBytes; ++j)
2394 ByteMask.push_back(-1);
2395 } else {
2396 for (unsigned j = 0; j != ElemBytes; ++j)
2397 ByteMask.push_back(M*ElemBytes + j);
2398 }
2399 }
2400 assert(ByteMask.size() <= 8);
2401
2402 // All non-undef (non-negative) indexes are well within [0..127], so they
2403 // fit in a single byte. Build two 64-bit words:
2404 // - MaskIdx where each byte is the corresponding index (for non-negative
2405 // indexes), and 0xFF for negative indexes, and
2406 // - MaskUnd that has 0xFF for each negative index.
2407 uint64_t MaskIdx = 0;
2408 uint64_t MaskUnd = 0;
2409 for (unsigned i = 0, e = ByteMask.size(); i != e; ++i) {
2410 unsigned S = 8*i;
2411 uint64_t M = ByteMask[i] & 0xFF;
2412 if (M == 0xFF)
2413 MaskUnd |= M << S;
2414 MaskIdx |= M << S;
2415 }
2416
2417 if (ByteMask.size() == 4) {
2418 // Identity.
2419 if (MaskIdx == (0x03020100 | MaskUnd))
2420 return Op0;
2421 // Byte swap.
2422 if (MaskIdx == (0x00010203 | MaskUnd)) {
2423 SDValue T0 = DAG.getBitcast(MVT::i32, Op0);
2424 SDValue T1 = DAG.getNode(ISD::BSWAP, dl, MVT::i32, T0);
2425 return DAG.getBitcast(VecTy, T1);
2426 }
2427
2428 // Byte packs.
2429 SDValue Concat10 =
2430 getCombine(Op1, Op0, dl, typeJoin({ty(Op1), ty(Op0)}), DAG);
2431 if (MaskIdx == (0x06040200 | MaskUnd))
2432 return getInstr(Hexagon::S2_vtrunehb, dl, VecTy, {Concat10}, DAG);
2433 if (MaskIdx == (0x07050301 | MaskUnd))
2434 return getInstr(Hexagon::S2_vtrunohb, dl, VecTy, {Concat10}, DAG);
2435
2436 SDValue Concat01 =
2437 getCombine(Op0, Op1, dl, typeJoin({ty(Op0), ty(Op1)}), DAG);
2438 if (MaskIdx == (0x02000604 | MaskUnd))
2439 return getInstr(Hexagon::S2_vtrunehb, dl, VecTy, {Concat01}, DAG);
2440 if (MaskIdx == (0x03010705 | MaskUnd))
2441 return getInstr(Hexagon::S2_vtrunohb, dl, VecTy, {Concat01}, DAG);
2442 }
2443
2444 if (ByteMask.size() == 8) {
2445 // Identity.
2446 if (MaskIdx == (0x0706050403020100ull | MaskUnd))
2447 return Op0;
2448 // Byte swap.
2449 if (MaskIdx == (0x0001020304050607ull | MaskUnd)) {
2450 SDValue T0 = DAG.getBitcast(MVT::i64, Op0);
2451 SDValue T1 = DAG.getNode(ISD::BSWAP, dl, MVT::i64, T0);
2452 return DAG.getBitcast(VecTy, T1);
2453 }
2454
2455 // Halfword picks.
2456 if (MaskIdx == (0x0d0c050409080100ull | MaskUnd))
2457 return getInstr(Hexagon::S2_shuffeh, dl, VecTy, {Op1, Op0}, DAG);
2458 if (MaskIdx == (0x0f0e07060b0a0302ull | MaskUnd))
2459 return getInstr(Hexagon::S2_shuffoh, dl, VecTy, {Op1, Op0}, DAG);
2460 if (MaskIdx == (0x0d0c090805040100ull | MaskUnd))
2461 return getInstr(Hexagon::S2_vtrunewh, dl, VecTy, {Op1, Op0}, DAG);
2462 if (MaskIdx == (0x0f0e0b0a07060302ull | MaskUnd))
2463 return getInstr(Hexagon::S2_vtrunowh, dl, VecTy, {Op1, Op0}, DAG);
2464 if (MaskIdx == (0x0706030205040100ull | MaskUnd)) {
2465 VectorPair P = opSplit(Op0, dl, DAG);
2466 return getInstr(Hexagon::S2_packhl, dl, VecTy, {P.second, P.first}, DAG);
2467 }
2468
2469 // Byte packs.
2470 if (MaskIdx == (0x0e060c040a020800ull | MaskUnd))
2471 return getInstr(Hexagon::S2_shuffeb, dl, VecTy, {Op1, Op0}, DAG);
2472 if (MaskIdx == (0x0f070d050b030901ull | MaskUnd))
2473 return getInstr(Hexagon::S2_shuffob, dl, VecTy, {Op1, Op0}, DAG);
2474 }
2475
2476 return SDValue();
2477}
2478
2479SDValue
2480HexagonTargetLowering::getSplatValue(SDValue Op, SelectionDAG &DAG) const {
2481 switch (Op.getOpcode()) {
2482 case ISD::BUILD_VECTOR:
2484 return S;
2485 break;
2486 case ISD::SPLAT_VECTOR:
2487 return Op.getOperand(0);
2488 }
2489 return SDValue();
2490}
2491
2492// Create a Hexagon-specific node for shifting a vector by an integer.
2493SDValue
2494HexagonTargetLowering::getVectorShiftByInt(SDValue Op, SelectionDAG &DAG)
2495 const {
2496 unsigned NewOpc;
2497 switch (Op.getOpcode()) {
2498 case ISD::SHL:
2499 NewOpc = HexagonISD::VASL;
2500 break;
2501 case ISD::SRA:
2502 NewOpc = HexagonISD::VASR;
2503 break;
2504 case ISD::SRL:
2505 NewOpc = HexagonISD::VLSR;
2506 break;
2507 default:
2508 llvm_unreachable("Unexpected shift opcode");
2509 }
2510 if (SDValue Sp = getSplatValue(Op.getOperand(1), DAG)) {
2511 const SDLoc dl(Op);
2512 // Canonicalize shift amount to i32 as required.
2513 SDValue Sh = Sp;
2514 if (Sh.getValueType() != MVT::i32)
2515 Sh = DAG.getZExtOrTrunc(Sh, dl, MVT::i32);
2516
2517 assert(Sh.getValueType() == MVT::i32 &&
2518 "Hexagon vector shift-by-int must use i32 shift operand");
2519 return DAG.getNode(NewOpc, dl, ty(Op), Op.getOperand(0), Sh);
2520 }
2521
2522 return SDValue();
2523}
2524
2525SDValue
2527 const SDLoc &dl(Op);
2528
2529 // First try to convert the shift (by vector) to a shift by a scalar.
2530 // If we first split the shift, the shift amount will become 'extract
2531 // subvector', and will no longer be recognized as scalar.
2532 SDValue Res = Op;
2533 if (SDValue S = getVectorShiftByInt(Op, DAG))
2534 Res = S;
2535
2536 unsigned Opc = Res.getOpcode();
2537 switch (Opc) {
2538 case HexagonISD::VASR:
2539 case HexagonISD::VLSR:
2540 case HexagonISD::VASL:
2541 break;
2542 default:
2543 // No instructions for shifts by non-scalars.
2544 return SDValue();
2545 }
2546
2547 MVT ResTy = ty(Res);
2548 if (ResTy.getVectorElementType() != MVT::i8)
2549 return Res;
2550
2551 // For shifts of i8, extend the inputs to i16, then truncate back to i8.
2552 assert(ResTy.getVectorElementType() == MVT::i8);
2553 SDValue Val = Res.getOperand(0), Amt = Res.getOperand(1);
2554
2555 auto ShiftPartI8 = [&dl, &DAG, this](unsigned Opc, SDValue V, SDValue A) {
2556 MVT Ty = ty(V);
2557 MVT ExtTy = MVT::getVectorVT(MVT::i16, Ty.getVectorNumElements());
2558 SDValue ExtV = Opc == HexagonISD::VASR ? DAG.getSExtOrTrunc(V, dl, ExtTy)
2559 : DAG.getZExtOrTrunc(V, dl, ExtTy);
2560 SDValue ExtS = DAG.getNode(Opc, dl, ExtTy, {ExtV, A});
2561 return DAG.getZExtOrTrunc(ExtS, dl, Ty);
2562 };
2563
2564 if (ResTy.getSizeInBits() == 32)
2565 return ShiftPartI8(Opc, Val, Amt);
2566
2567 auto [LoV, HiV] = opSplit(Val, dl, DAG);
2568 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy,
2569 {ShiftPartI8(Opc, LoV, Amt), ShiftPartI8(Opc, HiV, Amt)});
2570}
2571
2572SDValue
2574 if (isa<ConstantSDNode>(Op.getOperand(1).getNode()))
2575 return Op;
2576 return SDValue();
2577}
2578
2579SDValue
2581 MVT ResTy = ty(Op);
2582 SDValue InpV = Op.getOperand(0);
2583 MVT InpTy = ty(InpV);
2584 assert(ResTy.getSizeInBits() == InpTy.getSizeInBits());
2585 const SDLoc &dl(Op);
2586
2587 // Handle conversion from i8 to v8i1.
2588 if (InpTy == MVT::i8) {
2589 if (ResTy == MVT::v8i1) {
2590 SDValue Sc = DAG.getBitcast(tyScalar(InpTy), InpV);
2591 SDValue Ext = DAG.getZExtOrTrunc(Sc, dl, MVT::i32);
2592 return getInstr(Hexagon::C2_tfrrp, dl, ResTy, Ext, DAG);
2593 }
2594 return SDValue();
2595 }
2596
2597 return Op;
2598}
2599
2600bool
2601HexagonTargetLowering::getBuildVectorConstInts(ArrayRef<SDValue> Values,
2602 MVT VecTy, SelectionDAG &DAG,
2603 MutableArrayRef<ConstantInt*> Consts) const {
2605 unsigned ElemWidth = ElemTy.getSizeInBits();
2606 IntegerType *IntTy = IntegerType::get(*DAG.getContext(), ElemWidth);
2607 bool AllConst = true;
2608
2609 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2610 SDValue V = Values[i];
2611 if (V.isUndef()) {
2612 Consts[i] = ConstantInt::get(IntTy, 0);
2613 continue;
2614 }
2615 // Make sure to always cast to IntTy.
2616 if (auto *CN = dyn_cast<ConstantSDNode>(V.getNode())) {
2617 const ConstantInt *CI = CN->getConstantIntValue();
2618 Consts[i] = cast<ConstantInt>(
2619 ConstantInt::get(IntTy, CI->getValue().trunc(ElemWidth)));
2620 } else if (auto *CN = dyn_cast<ConstantFPSDNode>(V.getNode())) {
2621 const ConstantFP *CF = CN->getConstantFPValue();
2622 APInt A = CF->getValueAPF().bitcastToAPInt();
2623 Consts[i] = ConstantInt::get(IntTy, A.getZExtValue());
2624 } else {
2625 AllConst = false;
2626 }
2627 }
2628 return AllConst;
2629}
2630
2631SDValue
2632HexagonTargetLowering::buildVector32(ArrayRef<SDValue> Elem, const SDLoc &dl,
2633 MVT VecTy, SelectionDAG &DAG) const {
2634 MVT ElemTy = VecTy.getVectorElementType();
2635 assert(VecTy.getVectorNumElements() == Elem.size());
2636
2637 SmallVector<ConstantInt*,4> Consts(Elem.size());
2638 bool AllConst = getBuildVectorConstInts(Elem, VecTy, DAG, Consts);
2639
2640 unsigned First, Num = Elem.size();
2641 for (First = 0; First != Num; ++First) {
2642 if (!isUndef(Elem[First]))
2643 break;
2644 }
2645 if (First == Num)
2646 return DAG.getUNDEF(VecTy);
2647
2648 if (AllConst &&
2649 llvm::all_of(Consts, [](ConstantInt *CI) { return CI->isZero(); }))
2650 return getZero(dl, VecTy, DAG);
2651
2652 if (ElemTy == MVT::i16 || ElemTy == MVT::f16) {
2653 assert(Elem.size() == 2);
2654 if (AllConst) {
2655 // The 'Consts' array will have all values as integers regardless
2656 // of the vector element type.
2657 uint32_t V = (Consts[0]->getZExtValue() & 0xFFFF) |
2658 Consts[1]->getZExtValue() << 16;
2659 return DAG.getBitcast(VecTy, DAG.getConstant(V, dl, MVT::i32));
2660 }
2661 SDValue E0, E1;
2662 if (ElemTy == MVT::f16) {
2663 E0 = DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Elem[0]), dl, MVT::i32);
2664 E1 = DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Elem[1]), dl, MVT::i32);
2665 } else {
2666 E0 = Elem[0];
2667 E1 = Elem[1];
2668 }
2669 SDValue N = getInstr(Hexagon::A2_combine_ll, dl, MVT::i32, {E1, E0}, DAG);
2670 return DAG.getBitcast(VecTy, N);
2671 }
2672
2673 if (ElemTy == MVT::i8) {
2674 // First try generating a constant.
2675 if (AllConst) {
2676 uint32_t V = (Consts[0]->getZExtValue() & 0xFF) |
2677 (Consts[1]->getZExtValue() & 0xFF) << 8 |
2678 (Consts[2]->getZExtValue() & 0xFF) << 16 |
2679 Consts[3]->getZExtValue() << 24;
2680 return DAG.getBitcast(MVT::v4i8, DAG.getConstant(V, dl, MVT::i32));
2681 }
2682
2683 // Then try splat.
2684 bool IsSplat = true;
2685 for (unsigned i = First+1; i != Num; ++i) {
2686 if (Elem[i] == Elem[First] || isUndef(Elem[i]))
2687 continue;
2688 IsSplat = false;
2689 break;
2690 }
2691 if (IsSplat) {
2692 // Legalize the operand of SPLAT_VECTOR.
2693 SDValue Ext = DAG.getZExtOrTrunc(Elem[First], dl, MVT::i32);
2694 return DAG.getNode(ISD::SPLAT_VECTOR, dl, VecTy, Ext);
2695 }
2696
2697 // Generate
2698 // (zxtb(Elem[0]) | (zxtb(Elem[1]) << 8)) |
2699 // (zxtb(Elem[2]) | (zxtb(Elem[3]) << 8)) << 16
2700 assert(Elem.size() == 4);
2701 SDValue Vs[4];
2702 for (unsigned i = 0; i != 4; ++i) {
2703 Vs[i] = DAG.getZExtOrTrunc(Elem[i], dl, MVT::i32);
2704 Vs[i] = DAG.getZeroExtendInReg(Vs[i], dl, MVT::i8);
2705 }
2706 SDValue S8 = DAG.getConstant(8, dl, MVT::i32);
2707 SDValue T0 = DAG.getNode(ISD::SHL, dl, MVT::i32, {Vs[1], S8});
2708 SDValue T1 = DAG.getNode(ISD::SHL, dl, MVT::i32, {Vs[3], S8});
2709 SDValue B0 = DAG.getNode(ISD::OR, dl, MVT::i32, {Vs[0], T0});
2710 SDValue B1 = DAG.getNode(ISD::OR, dl, MVT::i32, {Vs[2], T1});
2711
2712 SDValue R = getInstr(Hexagon::A2_combine_ll, dl, MVT::i32, {B1, B0}, DAG);
2713 return DAG.getBitcast(MVT::v4i8, R);
2714 }
2715
2716#ifndef NDEBUG
2717 dbgs() << "VecTy: " << VecTy << '\n';
2718#endif
2719 llvm_unreachable("Unexpected vector element type");
2720}
2721
2722SDValue
2723HexagonTargetLowering::buildVector64(ArrayRef<SDValue> Elem, const SDLoc &dl,
2724 MVT VecTy, SelectionDAG &DAG) const {
2725 MVT ElemTy = VecTy.getVectorElementType();
2726 assert(VecTy.getVectorNumElements() == Elem.size());
2727
2728 SmallVector<ConstantInt*,8> Consts(Elem.size());
2729 bool AllConst = getBuildVectorConstInts(Elem, VecTy, DAG, Consts);
2730
2731 unsigned First, Num = Elem.size();
2732 for (First = 0; First != Num; ++First) {
2733 if (!isUndef(Elem[First]))
2734 break;
2735 }
2736 if (First == Num)
2737 return DAG.getUNDEF(VecTy);
2738
2739 if (AllConst &&
2740 llvm::all_of(Consts, [](ConstantInt *CI) { return CI->isZero(); }))
2741 return getZero(dl, VecTy, DAG);
2742
2743 // First try splat if possible.
2744 if (ElemTy == MVT::i16 || ElemTy == MVT::f16) {
2745 bool IsSplat = true;
2746 for (unsigned i = First+1; i != Num; ++i) {
2747 if (Elem[i] == Elem[First] || isUndef(Elem[i]))
2748 continue;
2749 IsSplat = false;
2750 break;
2751 }
2752 if (IsSplat) {
2753 // Legalize the operand of SPLAT_VECTOR
2754 SDValue S = ElemTy == MVT::f16 ? DAG.getBitcast(MVT::i16, Elem[First])
2755 : Elem[First];
2756 SDValue Ext = DAG.getZExtOrTrunc(S, dl, MVT::i32);
2757 return DAG.getNode(ISD::SPLAT_VECTOR, dl, VecTy, Ext);
2758 }
2759 }
2760
2761 // Then try constant.
2762 if (AllConst) {
2763 uint64_t Val = 0;
2764 unsigned W = ElemTy.getSizeInBits();
2765 uint64_t Mask = (1ull << W) - 1;
2766 for (unsigned i = 0; i != Num; ++i)
2767 Val = (Val << W) | (Consts[Num-1-i]->getZExtValue() & Mask);
2768 SDValue V0 = DAG.getConstant(Val, dl, MVT::i64);
2769 return DAG.getBitcast(VecTy, V0);
2770 }
2771
2772 // Build two 32-bit vectors and concatenate.
2773 MVT HalfTy = MVT::getVectorVT(ElemTy, Num/2);
2774 SDValue L = (ElemTy == MVT::i32)
2775 ? Elem[0]
2776 : buildVector32(Elem.take_front(Num/2), dl, HalfTy, DAG);
2777 SDValue H = (ElemTy == MVT::i32)
2778 ? Elem[1]
2779 : buildVector32(Elem.drop_front(Num/2), dl, HalfTy, DAG);
2780 return getCombine(H, L, dl, VecTy, DAG);
2781}
2782
2783SDValue
2784HexagonTargetLowering::extractVector(SDValue VecV, SDValue IdxV,
2785 const SDLoc &dl, MVT ValTy, MVT ResTy,
2786 SelectionDAG &DAG) const {
2787 MVT VecTy = ty(VecV);
2788 assert(!ValTy.isVector() ||
2789 VecTy.getVectorElementType() == ValTy.getVectorElementType());
2790 if (VecTy.getVectorElementType() == MVT::i1)
2791 return extractVectorPred(VecV, IdxV, dl, ValTy, ResTy, DAG);
2792
2793 unsigned VecWidth = VecTy.getSizeInBits();
2794 unsigned ValWidth = ValTy.getSizeInBits();
2795 unsigned ElemWidth = VecTy.getVectorElementType().getSizeInBits();
2796 assert((VecWidth % ElemWidth) == 0);
2797 assert(VecWidth == 32 || VecWidth == 64);
2798
2799 // Cast everything to scalar integer types.
2800 MVT ScalarTy = tyScalar(VecTy);
2801 VecV = DAG.getBitcast(ScalarTy, VecV);
2802
2803 SDValue WidthV = DAG.getConstant(ValWidth, dl, MVT::i32);
2804 SDValue ExtV;
2805
2806 if (auto *IdxN = dyn_cast<ConstantSDNode>(IdxV)) {
2807 unsigned Off = IdxN->getZExtValue() * ElemWidth;
2808 if (VecWidth == 64 && ValWidth == 32) {
2809 assert(Off == 0 || Off == 32);
2810 ExtV = Off == 0 ? LoHalf(VecV, DAG) : HiHalf(VecV, DAG);
2811 } else if (Off == 0 && (ValWidth % 8) == 0) {
2812 ExtV = DAG.getZeroExtendInReg(VecV, dl, tyScalar(ValTy));
2813 } else {
2814 SDValue OffV = DAG.getConstant(Off, dl, MVT::i32);
2815 // The return type of EXTRACTU must be the same as the type of the
2816 // input vector.
2817 ExtV = DAG.getNode(HexagonISD::EXTRACTU, dl, ScalarTy,
2818 {VecV, WidthV, OffV});
2819 }
2820 } else {
2821 if (ty(IdxV) != MVT::i32)
2822 IdxV = DAG.getZExtOrTrunc(IdxV, dl, MVT::i32);
2823 SDValue OffV = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2824 DAG.getConstant(ElemWidth, dl, MVT::i32));
2825 ExtV = DAG.getNode(HexagonISD::EXTRACTU, dl, ScalarTy,
2826 {VecV, WidthV, OffV});
2827 }
2828
2829 // Cast ExtV to the requested result type.
2830 ExtV = DAG.getZExtOrTrunc(ExtV, dl, tyScalar(ResTy));
2831 ExtV = DAG.getBitcast(ResTy, ExtV);
2832 return ExtV;
2833}
2834
2835SDValue
2836HexagonTargetLowering::extractVectorPred(SDValue VecV, SDValue IdxV,
2837 const SDLoc &dl, MVT ValTy, MVT ResTy,
2838 SelectionDAG &DAG) const {
2839 // Special case for v{8,4,2}i1 (the only boolean vectors legal in Hexagon
2840 // without any coprocessors).
2841 MVT VecTy = ty(VecV);
2842 unsigned VecWidth = VecTy.getSizeInBits();
2843 unsigned ValWidth = ValTy.getSizeInBits();
2844 assert(VecWidth == VecTy.getVectorNumElements() &&
2845 "Vector elements should equal vector width size");
2846 assert(VecWidth == 8 || VecWidth == 4 || VecWidth == 2);
2847
2848 // Check if this is an extract of the lowest bit.
2849 if (isNullConstant(IdxV) && ValTy.getSizeInBits() == 1) {
2850 // Extracting the lowest bit is a no-op, but it changes the type,
2851 // so it must be kept as an operation to avoid errors related to
2852 // type mismatches.
2853 return DAG.getNode(HexagonISD::TYPECAST, dl, MVT::i1, VecV);
2854 }
2855
2856 // If the value extracted is a single bit, use tstbit.
2857 if (ValWidth == 1) {
2858 SDValue A0 = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {VecV}, DAG);
2859 SDValue M0 = DAG.getConstant(8 / VecWidth, dl, MVT::i32);
2860 SDValue I0 = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, M0);
2861 return DAG.getNode(HexagonISD::TSTBIT, dl, MVT::i1, A0, I0);
2862 }
2863
2864 // Each bool vector (v2i1, v4i1, v8i1) always occupies 8 bits in
2865 // a predicate register. The elements of the vector are repeated
2866 // in the register (if necessary) so that the total number is 8.
2867 // The extracted subvector will need to be expanded in such a way.
2868 unsigned Scale = VecWidth / ValWidth;
2869
2870 // Generate (p2d VecV) >> 8*Idx to move the interesting bytes to
2871 // position 0.
2872 assert(ty(IdxV) == MVT::i32);
2873 unsigned VecRep = 8 / VecWidth;
2874 SDValue S0 = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2875 DAG.getConstant(8*VecRep, dl, MVT::i32));
2876 SDValue T0 = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, VecV);
2877 SDValue T1 = DAG.getNode(ISD::SRL, dl, MVT::i64, T0, S0);
2878 while (Scale > 1) {
2879 // The longest possible subvector is at most 32 bits, so it is always
2880 // contained in the low subregister.
2881 T1 = LoHalf(T1, DAG);
2882 T1 = expandPredicate(T1, dl, DAG);
2883 Scale /= 2;
2884 }
2885
2886 return DAG.getNode(HexagonISD::D2P, dl, ResTy, T1);
2887}
2888
2889SDValue
2890HexagonTargetLowering::insertVector(SDValue VecV, SDValue ValV, SDValue IdxV,
2891 const SDLoc &dl, MVT ValTy,
2892 SelectionDAG &DAG) const {
2893 MVT VecTy = ty(VecV);
2894 if (VecTy.getVectorElementType() == MVT::i1)
2895 return insertVectorPred(VecV, ValV, IdxV, dl, ValTy, DAG);
2896
2897 unsigned VecWidth = VecTy.getSizeInBits();
2898 unsigned ValWidth = ValTy.getSizeInBits();
2899 assert(VecWidth == 32 || VecWidth == 64);
2900 assert((VecWidth % ValWidth) == 0);
2901
2902 // Cast everything to scalar integer types.
2903 MVT ScalarTy = MVT::getIntegerVT(VecWidth);
2904 // The actual type of ValV may be different than ValTy (which is related
2905 // to the vector type).
2906 unsigned VW = ty(ValV).getSizeInBits();
2907 ValV = DAG.getBitcast(MVT::getIntegerVT(VW), ValV);
2908 VecV = DAG.getBitcast(ScalarTy, VecV);
2909 if (VW != VecWidth)
2910 ValV = DAG.getAnyExtOrTrunc(ValV, dl, ScalarTy);
2911
2912 SDValue WidthV = DAG.getConstant(ValWidth, dl, MVT::i32);
2913 SDValue InsV;
2914
2915 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(IdxV)) {
2916 unsigned W = C->getZExtValue() * ValWidth;
2917 SDValue OffV = DAG.getConstant(W, dl, MVT::i32);
2918 InsV = DAG.getNode(HexagonISD::INSERT, dl, ScalarTy,
2919 {VecV, ValV, WidthV, OffV});
2920 } else {
2921 if (ty(IdxV) != MVT::i32)
2922 IdxV = DAG.getZExtOrTrunc(IdxV, dl, MVT::i32);
2923 SDValue OffV = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, WidthV);
2924 InsV = DAG.getNode(HexagonISD::INSERT, dl, ScalarTy,
2925 {VecV, ValV, WidthV, OffV});
2926 }
2927
2928 return DAG.getNode(ISD::BITCAST, dl, VecTy, InsV);
2929}
2930
2931SDValue
2932HexagonTargetLowering::insertVectorPred(SDValue VecV, SDValue ValV,
2933 SDValue IdxV, const SDLoc &dl,
2934 MVT ValTy, SelectionDAG &DAG) const {
2935 MVT VecTy = ty(VecV);
2936 unsigned VecLen = VecTy.getVectorNumElements();
2937
2938 if (ValTy == MVT::i1) {
2939 SDValue ToReg = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {VecV}, DAG);
2940 SDValue Ext = DAG.getSExtOrTrunc(ValV, dl, MVT::i32);
2941 SDValue Width = DAG.getConstant(8 / VecLen, dl, MVT::i32);
2942 SDValue Idx = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, Width);
2943 SDValue Ins =
2944 DAG.getNode(HexagonISD::INSERT, dl, MVT::i32, {ToReg, Ext, Width, Idx});
2945 return getInstr(Hexagon::C2_tfrrp, dl, VecTy, {Ins}, DAG);
2946 }
2947
2948 assert(ValTy.getVectorElementType() == MVT::i1);
2949 SDValue ValR = ValTy.isVector()
2950 ? DAG.getNode(HexagonISD::P2D, dl, MVT::i64, ValV)
2951 : DAG.getSExtOrTrunc(ValV, dl, MVT::i64);
2952
2953 unsigned Scale = VecLen / ValTy.getVectorNumElements();
2954 assert(Scale > 1);
2955
2956 for (unsigned R = Scale; R > 1; R /= 2) {
2957 ValR = contractPredicate(ValR, dl, DAG);
2958 ValR = getCombine(DAG.getUNDEF(MVT::i32), ValR, dl, MVT::i64, DAG);
2959 }
2960
2961 SDValue Width = DAG.getConstant(64 / Scale, dl, MVT::i32);
2962 SDValue Idx = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, Width);
2963 SDValue VecR = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, VecV);
2964 SDValue Ins =
2965 DAG.getNode(HexagonISD::INSERT, dl, MVT::i64, {VecR, ValR, Width, Idx});
2966 return DAG.getNode(HexagonISD::D2P, dl, VecTy, Ins);
2967}
2968
2969SDValue
2970HexagonTargetLowering::expandPredicate(SDValue Vec32, const SDLoc &dl,
2971 SelectionDAG &DAG) const {
2972 assert(ty(Vec32).getSizeInBits() == 32);
2973 if (isUndef(Vec32))
2974 return DAG.getUNDEF(MVT::i64);
2975 SDValue P = DAG.getBitcast(MVT::v4i8, Vec32);
2976 SDValue X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i16, P);
2977 return DAG.getBitcast(MVT::i64, X);
2978}
2979
2980SDValue
2981HexagonTargetLowering::contractPredicate(SDValue Vec64, const SDLoc &dl,
2982 SelectionDAG &DAG) const {
2983 assert(ty(Vec64).getSizeInBits() == 64);
2984 if (isUndef(Vec64))
2985 return DAG.getUNDEF(MVT::i32);
2986 // Collect even bytes:
2987 SDValue A = DAG.getBitcast(MVT::v8i8, Vec64);
2988 SDValue S = DAG.getVectorShuffle(MVT::v8i8, dl, A, DAG.getUNDEF(MVT::v8i8),
2989 {0, 2, 4, 6, 1, 3, 5, 7});
2990 return extractVector(S, DAG.getConstant(0, dl, MVT::i32), dl, MVT::v4i8,
2991 MVT::i32, DAG);
2992}
2993
2994SDValue
2995HexagonTargetLowering::getZero(const SDLoc &dl, MVT Ty, SelectionDAG &DAG)
2996 const {
2997 if (Ty.isVector()) {
2998 unsigned W = Ty.getSizeInBits();
2999 if (W <= 64)
3000 return DAG.getBitcast(Ty, DAG.getConstant(0, dl, MVT::getIntegerVT(W)));
3001 return DAG.getNode(ISD::SPLAT_VECTOR, dl, Ty, getZero(dl, MVT::i32, DAG));
3002 }
3003
3004 if (Ty.isInteger())
3005 return DAG.getConstant(0, dl, Ty);
3006 if (Ty.isFloatingPoint())
3007 return DAG.getConstantFP(0.0, dl, Ty);
3008 llvm_unreachable("Invalid type for zero");
3009}
3010
3011SDValue
3012HexagonTargetLowering::appendUndef(SDValue Val, MVT ResTy, SelectionDAG &DAG)
3013 const {
3014 MVT ValTy = ty(Val);
3016
3017 unsigned ValLen = ValTy.getVectorNumElements();
3018 unsigned ResLen = ResTy.getVectorNumElements();
3019 if (ValLen == ResLen)
3020 return Val;
3021
3022 const SDLoc &dl(Val);
3023 assert(ValLen < ResLen);
3024 assert(ResLen % ValLen == 0);
3025
3026 SmallVector<SDValue, 4> Concats = {Val};
3027 for (unsigned i = 1, e = ResLen / ValLen; i < e; ++i)
3028 Concats.push_back(DAG.getUNDEF(ValTy));
3029
3030 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy, Concats);
3031}
3032
3033SDValue
3034HexagonTargetLowering::getCombine(SDValue Hi, SDValue Lo, const SDLoc &dl,
3035 MVT ResTy, SelectionDAG &DAG) const {
3036 MVT ElemTy = ty(Hi);
3037 assert(ElemTy == ty(Lo));
3038
3039 if (!ElemTy.isVector()) {
3040 assert(ElemTy.isScalarInteger());
3041 MVT PairTy = ElemTy.widenIntegerElementType();
3042 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, PairTy, Lo, Hi);
3043 return DAG.getBitcast(ResTy, Pair);
3044 }
3045
3046 unsigned Width = ElemTy.getSizeInBits();
3047 MVT IntTy = MVT::getIntegerVT(Width);
3048 SDValue Pair =
3050 {DAG.getBitcast(IntTy, Lo), DAG.getBitcast(IntTy, Hi)});
3051 return DAG.getBitcast(ResTy, Pair);
3052}
3053
3054SDValue
3056 MVT VecTy = ty(Op);
3057 unsigned BW = VecTy.getSizeInBits();
3058 const SDLoc &dl(Op);
3060 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i)
3061 Ops.push_back(Op.getOperand(i));
3062
3063 if (BW == 32)
3064 return buildVector32(Ops, dl, VecTy, DAG);
3065 if (BW == 64)
3066 return buildVector64(Ops, dl, VecTy, DAG);
3067
3068 if (VecTy == MVT::v8i1 || VecTy == MVT::v4i1 || VecTy == MVT::v2i1) {
3069 // Check if this is a special case or all-0 or all-1.
3070 bool All0 = true, All1 = true;
3071 for (SDValue P : Ops) {
3072 auto *CN = dyn_cast<ConstantSDNode>(P.getNode());
3073 if (CN == nullptr) {
3074 All0 = All1 = false;
3075 break;
3076 }
3077 uint32_t C = CN->getZExtValue();
3078 All0 &= (C == 0);
3079 All1 &= (C == 1);
3080 }
3081 if (All0)
3082 return DAG.getNode(HexagonISD::PFALSE, dl, VecTy);
3083 if (All1)
3084 return DAG.getNode(HexagonISD::PTRUE, dl, VecTy);
3085
3086 // For each i1 element in the resulting predicate register, put 1
3087 // shifted by the index of the element into a general-purpose register,
3088 // then or them together and transfer it back into a predicate register.
3089 SDValue Rs[8];
3090 SDValue Z = getZero(dl, MVT::i32, DAG);
3091 // Always produce 8 bits, repeat inputs if necessary.
3092 unsigned Rep = 8 / VecTy.getVectorNumElements();
3093 for (unsigned i = 0; i != 8; ++i) {
3094 SDValue S = DAG.getConstant(1ull << i, dl, MVT::i32);
3095 Rs[i] = DAG.getSelect(dl, MVT::i32, Ops[i/Rep], S, Z);
3096 }
3097 for (ArrayRef<SDValue> A(Rs); A.size() != 1; A = A.drop_back(A.size()/2)) {
3098 for (unsigned i = 0, e = A.size()/2; i != e; ++i)
3099 Rs[i] = DAG.getNode(ISD::OR, dl, MVT::i32, Rs[2*i], Rs[2*i+1]);
3100 }
3101 // Move the value directly to a predicate register.
3102 return getInstr(Hexagon::C2_tfrrp, dl, VecTy, {Rs[0]}, DAG);
3103 }
3104
3105 return SDValue();
3106}
3107
3108SDValue
3110 SelectionDAG &DAG) const {
3111 MVT VecTy = ty(Op);
3112 const SDLoc &dl(Op);
3113 if (VecTy.getSizeInBits() == 64) {
3114 assert(Op.getNumOperands() == 2);
3115 return getCombine(Op.getOperand(1), Op.getOperand(0), dl, VecTy, DAG);
3116 }
3117
3119 if (ElemTy == MVT::i1) {
3120 assert(VecTy == MVT::v2i1 || VecTy == MVT::v4i1 || VecTy == MVT::v8i1);
3121 MVT OpTy = ty(Op.getOperand(0));
3122 // Scale is how many times the operands need to be contracted to match
3123 // the representation in the target register.
3124 unsigned Scale = VecTy.getVectorNumElements() / OpTy.getVectorNumElements();
3125 assert(Scale == Op.getNumOperands() && Scale > 1);
3126
3127 // First, convert all bool vectors to integers, then generate pairwise
3128 // inserts to form values of doubled length. Up until there are only
3129 // two values left to concatenate, all of these values will fit in a
3130 // 32-bit integer, so keep them as i32 to use 32-bit inserts.
3131 SmallVector<SDValue,4> Words[2];
3132 unsigned IdxW = 0;
3133
3134 for (SDValue P : Op.getNode()->op_values()) {
3135 SDValue W = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, P);
3136 for (unsigned R = Scale; R > 1; R /= 2) {
3137 W = contractPredicate(W, dl, DAG);
3138 W = getCombine(DAG.getUNDEF(MVT::i32), W, dl, MVT::i64, DAG);
3139 }
3140 W = LoHalf(W, DAG);
3141 Words[IdxW].push_back(W);
3142 }
3143
3144 while (Scale > 2) {
3145 SDValue WidthV = DAG.getConstant(64 / Scale, dl, MVT::i32);
3146 Words[IdxW ^ 1].clear();
3147
3148 for (unsigned i = 0, e = Words[IdxW].size(); i != e; i += 2) {
3149 SDValue W0 = Words[IdxW][i], W1 = Words[IdxW][i+1];
3150 // Insert W1 into W0 right next to the significant bits of W0.
3151 SDValue T = DAG.getNode(HexagonISD::INSERT, dl, MVT::i32,
3152 {W0, W1, WidthV, WidthV});
3153 Words[IdxW ^ 1].push_back(T);
3154 }
3155 IdxW ^= 1;
3156 Scale /= 2;
3157 }
3158
3159 // At this point there should only be two words left, and Scale should be 2.
3160 assert(Scale == 2 && Words[IdxW].size() == 2);
3161
3162 SDValue WW = getCombine(Words[IdxW][1], Words[IdxW][0], dl, MVT::i64, DAG);
3163 return DAG.getNode(HexagonISD::D2P, dl, VecTy, WW);
3164 }
3165
3166 return SDValue();
3167}
3168
3169SDValue
3171 SelectionDAG &DAG) const {
3172 SDValue Vec = Op.getOperand(0);
3173 MVT ElemTy = ty(Vec).getVectorElementType();
3174 return extractVector(Vec, Op.getOperand(1), SDLoc(Op), ElemTy, ty(Op), DAG);
3175}
3176
3177SDValue
3179 SelectionDAG &DAG) const {
3180 return extractVector(Op.getOperand(0), Op.getOperand(1), SDLoc(Op),
3181 ty(Op), ty(Op), DAG);
3182}
3183
3184SDValue
3186 SelectionDAG &DAG) const {
3187 return insertVector(Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
3188 SDLoc(Op), ty(Op).getVectorElementType(), DAG);
3189}
3190
3191SDValue
3193 SelectionDAG &DAG) const {
3194 SDValue ValV = Op.getOperand(1);
3195 return insertVector(Op.getOperand(0), ValV, Op.getOperand(2),
3196 SDLoc(Op), ty(ValV), DAG);
3197}
3198
3199bool
3201 // Assuming the caller does not have either a signext or zeroext modifier, and
3202 // only one value is accepted, any reasonable truncation is allowed.
3203 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
3204 return false;
3205
3206 // FIXME: in principle up to 64-bit could be made safe, but it would be very
3207 // fragile at the moment: any support for multiple value returns would be
3208 // liable to disallow tail calls involving i64 -> iN truncation in many cases.
3209 return Ty1->getPrimitiveSizeInBits() <= 32;
3210}
3211
3212SDValue
3214 MVT Ty = ty(Op);
3215 const SDLoc &dl(Op);
3216 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
3217 MVT MemTy = LN->getMemoryVT().getSimpleVT();
3219
3220 bool LoadPred = MemTy == MVT::v2i1 || MemTy == MVT::v4i1 || MemTy == MVT::v8i1;
3221 if (LoadPred) {
3222 SDValue NL = DAG.getLoad(
3223 LN->getAddressingMode(), ISD::ZEXTLOAD, MVT::i32, dl, LN->getChain(),
3224 LN->getBasePtr(), LN->getOffset(), LN->getPointerInfo(),
3225 /*MemoryVT*/ MVT::i8, LN->getAlign(), LN->getMemOperand()->getFlags(),
3226 MMOMetadata(LN->getAAInfo(), LN->getRanges()));
3227 LN = cast<LoadSDNode>(NL.getNode());
3228 }
3229
3230 Align ClaimAlign = LN->getAlign();
3231 if (!validateConstPtrAlignment(LN->getBasePtr(), ClaimAlign, dl, DAG))
3232 return replaceMemWithUndef(Op, DAG);
3233
3234 // Call LowerUnalignedLoad for all loads, it recognizes loads that
3235 // don't need extra aligning.
3236 SDValue LU = LowerUnalignedLoad(SDValue(LN, 0), DAG);
3237 if (LoadPred) {
3238 SDValue TP = getInstr(Hexagon::C2_tfrrp, dl, MemTy, {LU}, DAG);
3239 if (ET == ISD::SEXTLOAD) {
3240 TP = DAG.getSExtOrTrunc(TP, dl, Ty);
3241 } else if (ET != ISD::NON_EXTLOAD) {
3242 TP = DAG.getZExtOrTrunc(TP, dl, Ty);
3243 }
3244 SDValue Ch = cast<LoadSDNode>(LU.getNode())->getChain();
3245 return DAG.getMergeValues({TP, Ch}, dl);
3246 }
3247 return LU;
3248}
3249
3250SDValue
3252 const SDLoc &dl(Op);
3253 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
3254 SDValue Val = SN->getValue();
3255 MVT Ty = ty(Val);
3256
3257 if (Ty == MVT::v2i1 || Ty == MVT::v4i1 || Ty == MVT::v8i1) {
3258 // Store the exact predicate (all bits).
3259 SDValue TR = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {Val}, DAG);
3260 SDValue NS = DAG.getTruncStore(SN->getChain(), dl, TR, SN->getBasePtr(),
3261 MVT::i8, SN->getMemOperand());
3262 if (SN->isIndexed()) {
3263 NS = DAG.getIndexedStore(NS, dl, SN->getBasePtr(), SN->getOffset(),
3264 SN->getAddressingMode());
3265 }
3266 SN = cast<StoreSDNode>(NS.getNode());
3267 }
3268
3269 Align ClaimAlign = SN->getAlign();
3270 if (!validateConstPtrAlignment(SN->getBasePtr(), ClaimAlign, dl, DAG))
3271 return replaceMemWithUndef(Op, DAG);
3272
3273 MVT StoreTy = SN->getMemoryVT().getSimpleVT();
3274 Align NeedAlign = Subtarget.getTypeAlignment(StoreTy);
3275 if (ClaimAlign < NeedAlign)
3276 return expandUnalignedStore(SN, DAG);
3277 return SDValue(SN, 0);
3278}
3279
3280SDValue
3282 const {
3283 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
3284 MVT LoadTy = ty(Op);
3285 unsigned NeedAlign = Subtarget.getTypeAlignment(LoadTy).value();
3286 unsigned HaveAlign = LN->getAlign().value();
3287 if (HaveAlign >= NeedAlign)
3288 return Op;
3289
3290 const SDLoc &dl(Op);
3291 const DataLayout &DL = DAG.getDataLayout();
3292 LLVMContext &Ctx = *DAG.getContext();
3293
3294 // If the load aligning is disabled or the load can be broken up into two
3295 // smaller legal loads, do the default (target-independent) expansion.
3296 bool DoDefault = false;
3297 // Handle it in the default way if this is an indexed load.
3298 if (!LN->isUnindexed())
3299 DoDefault = true;
3300
3301 if (!AlignLoads) {
3303 *LN->getMemOperand()))
3304 return Op;
3305 DoDefault = true;
3306 }
3307 if (!DoDefault && (2 * HaveAlign) == NeedAlign) {
3308 // The PartTy is the equivalent of "getLoadableTypeOfSize(HaveAlign)".
3309 MVT PartTy = HaveAlign <= 8 ? MVT::getIntegerVT(8 * HaveAlign)
3310 : MVT::getVectorVT(MVT::i8, HaveAlign);
3311 DoDefault =
3312 allowsMemoryAccessForAlignment(Ctx, DL, PartTy, *LN->getMemOperand());
3313 }
3314 if (DoDefault) {
3315 std::pair<SDValue, SDValue> P = expandUnalignedLoad(LN, DAG);
3316 return DAG.getMergeValues({P.first, P.second}, dl);
3317 }
3318
3319 // The code below generates two loads, both aligned as NeedAlign, and
3320 // with the distance of NeedAlign between them. For that to cover the
3321 // bits that need to be loaded (and without overlapping), the size of
3322 // the loads should be equal to NeedAlign. This is true for all loadable
3323 // types, but add an assertion in case something changes in the future.
3324 assert(LoadTy.getSizeInBits() == 8*NeedAlign);
3325
3326 unsigned LoadLen = NeedAlign;
3327 SDValue Base = LN->getBasePtr();
3328 SDValue Chain = LN->getChain();
3329 auto BO = getBaseAndOffset(Base);
3330 unsigned BaseOpc = BO.first.getOpcode();
3331 if (BaseOpc == HexagonISD::VALIGNADDR && BO.second % LoadLen == 0)
3332 return Op;
3333
3334 if (BO.second % LoadLen != 0) {
3335 BO.first = DAG.getNode(ISD::ADD, dl, MVT::i32, BO.first,
3336 DAG.getConstant(BO.second % LoadLen, dl, MVT::i32));
3337 BO.second -= BO.second % LoadLen;
3338 }
3339 SDValue BaseNoOff = (BaseOpc != HexagonISD::VALIGNADDR)
3340 ? DAG.getNode(HexagonISD::VALIGNADDR, dl, MVT::i32, BO.first,
3341 DAG.getConstant(NeedAlign, dl, MVT::i32))
3342 : BO.first;
3343 SDValue Base0 =
3344 DAG.getMemBasePlusOffset(BaseNoOff, TypeSize::getFixed(BO.second), dl);
3345 SDValue Base1 = DAG.getMemBasePlusOffset(
3346 BaseNoOff, TypeSize::getFixed(BO.second + LoadLen), dl);
3347
3348 MachineMemOperand *WideMMO = nullptr;
3349 if (MachineMemOperand *MMO = LN->getMemOperand()) {
3351 WideMMO = MF.getMachineMemOperand(
3352 MMO->getPointerInfo(), MMO->getFlags(), 2 * LoadLen, Align(LoadLen),
3353 MMOMetadata(MMO->getAAInfo(), MMO->getRanges()), MMO->getSyncScopeID(),
3354 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
3355 }
3356
3357 SDValue Load0 = DAG.getLoad(LoadTy, dl, Chain, Base0, WideMMO);
3358 SDValue Load1 = DAG.getLoad(LoadTy, dl, Chain, Base1, WideMMO);
3359
3360 SDValue Aligned = DAG.getNode(HexagonISD::VALIGN, dl, LoadTy,
3361 {Load1, Load0, BaseNoOff.getOperand(0)});
3362 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3363 Load0.getValue(1), Load1.getValue(1));
3364 SDValue M = DAG.getMergeValues({Aligned, NewChain}, dl);
3365 return M;
3366}
3367
3368SDValue
3370 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
3371 auto *CY = dyn_cast<ConstantSDNode>(Y);
3372 if (!CY)
3373 return SDValue();
3374
3375 const SDLoc &dl(Op);
3376 SDVTList VTs = Op.getNode()->getVTList();
3377 assert(VTs.NumVTs == 2);
3378 assert(VTs.VTs[1] == MVT::i1);
3379 unsigned Opc = Op.getOpcode();
3380
3381 if (CY) {
3382 uint64_t VY = CY->getZExtValue();
3383 assert(VY != 0 && "This should have been folded");
3384 // X +/- 1
3385 if (VY != 1)
3386 return SDValue();
3387
3388 if (Opc == ISD::UADDO) {
3389 SDValue Op = DAG.getNode(ISD::ADD, dl, VTs.VTs[0], {X, Y});
3390 SDValue Ov = DAG.getSetCC(dl, MVT::i1, Op, getZero(dl, ty(Op), DAG),
3391 ISD::SETEQ);
3392 return DAG.getMergeValues({Op, Ov}, dl);
3393 }
3394 if (Opc == ISD::USUBO) {
3395 SDValue Op = DAG.getNode(ISD::SUB, dl, VTs.VTs[0], {X, Y});
3396 SDValue Ov = DAG.getSetCC(dl, MVT::i1, Op,
3397 DAG.getAllOnesConstant(dl, ty(Op)), ISD::SETEQ);
3398 return DAG.getMergeValues({Op, Ov}, dl);
3399 }
3400 }
3401
3402 return SDValue();
3403}
3404
3406 SelectionDAG &DAG) const {
3407 const SDLoc &dl(Op);
3408 unsigned Opc = Op.getOpcode();
3409 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), C = Op.getOperand(2);
3410
3411 if (Opc == ISD::UADDO_CARRY)
3412 return DAG.getNode(HexagonISD::ADDC, dl, Op.getNode()->getVTList(),
3413 { X, Y, C });
3414
3415 EVT CarryTy = C.getValueType();
3416 SDValue SubC = DAG.getNode(HexagonISD::SUBC, dl, Op.getNode()->getVTList(),
3417 { X, Y, DAG.getLogicalNOT(dl, C, CarryTy) });
3418 SDValue Out[] = { SubC.getValue(0),
3419 DAG.getLogicalNOT(dl, SubC.getValue(1), CarryTy) };
3420 return DAG.getMergeValues(Out, dl);
3421}
3422
3423SDValue
3425 SDValue Chain = Op.getOperand(0);
3426 SDValue Offset = Op.getOperand(1);
3427 SDValue Handler = Op.getOperand(2);
3428 SDLoc dl(Op);
3429 auto PtrVT = getPointerTy(DAG.getDataLayout());
3430
3431 // Mark function as containing a call to EH_RETURN.
3432 HexagonMachineFunctionInfo *FuncInfo =
3434 FuncInfo->setHasEHReturn();
3435
3436 unsigned OffsetReg = Hexagon::R28;
3437
3438 SDValue StoreAddr =
3439 DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getRegister(Hexagon::R30, PtrVT),
3440 DAG.getIntPtrConstant(4, dl));
3441 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
3442 Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
3443
3444 // Not needed we already use it as explicit input to EH_RETURN.
3445 // MF.getRegInfo().addLiveOut(OffsetReg);
3446
3447 return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
3448}
3449
3450SDValue
3452 unsigned Opc = Op.getOpcode();
3453 // Handle INLINEASM first.
3455 return LowerINLINEASM(Op, DAG);
3456
3457 if (isHlxOperation(Op.getNode(), DAG)) {
3458 // If HLX lowering returns nothing, try the default lowering.
3459 if (SDValue V = LowerHlxOperation(Op, DAG))
3460 return V;
3461 } else if (isHvxOperation(Op.getNode(), DAG)) {
3462 // If HVX lowering returns nothing, try the default lowering.
3463 if (SDValue V = LowerHvxOperation(Op, DAG))
3464 return V;
3465 }
3466
3467 switch (Opc) {
3468 default:
3469#ifndef NDEBUG
3470 Op.getNode()->dumpr(&DAG);
3471#endif
3472 llvm_unreachable("Should not custom lower this!");
3473
3474 case ISD::FDIV:
3475 return LowerFDIV(Op, DAG);
3476 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
3481 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
3482 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
3483 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
3484 case ISD::LOAD: return LowerLoad(Op, DAG);
3485 case ISD::STORE: return LowerStore(Op, DAG);
3486 case ISD::UADDO:
3487 case ISD::USUBO: return LowerUAddSubO(Op, DAG);
3488 case ISD::UADDO_CARRY:
3489 case ISD::USUBO_CARRY: return LowerUAddSubOCarry(Op, DAG);
3490 case ISD::SRA:
3491 case ISD::SHL:
3492 case ISD::SRL: return LowerVECTOR_SHIFT(Op, DAG);
3493 case ISD::ROTL: return LowerROTL(Op, DAG);
3494 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
3495 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
3496 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
3497 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3498 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
3500 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
3501 case ISD::GlobalAddress: return LowerGLOBALADDRESS(Op, DAG);
3502 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
3504 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
3505 case ISD::VASTART: return LowerVASTART(Op, DAG);
3507 case ISD::SETCC: return LowerSETCC(Op, DAG);
3508 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
3510 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3511 // INTRINSIC_W_CHAIN is marked Custom only so HLX memory intrinsics can be
3512 // lowered (handled above via LowerHlxOperation). Any other W_CHAIN
3513 // intrinsic is left unchanged for normal instruction selection.
3515 return Op;
3516 case ISD::PREFETCH:
3517 return LowerPREFETCH(Op, DAG);
3518 case ISD::FMAXIMUM:
3519 case ISD::FMINIMUM:
3520 return LowerFMINFMAX(Op, DAG);
3521 break;
3522 }
3523
3524 return SDValue();
3525}
3526
3527void
3530 SelectionDAG &DAG) const {
3531 if (isHvxOperation(N, DAG)) {
3532 LowerHvxOperationWrapper(N, Results, DAG);
3533 if (!Results.empty())
3534 return;
3535 }
3536
3537 SDValue Op(N, 0);
3538 unsigned Opc = N->getOpcode();
3539
3540 switch (Opc) {
3541 case HexagonISD::SSAT:
3542 case HexagonISD::USAT:
3543 Results.push_back(opJoin(SplitVectorOp(Op, DAG), SDLoc(Op), DAG));
3544 break;
3545 case ISD::STORE:
3546 // We are only custom-lowering stores to verify the alignment of the
3547 // address if it is a compile-time constant. Since a store can be
3548 // modified during type-legalization (the value being stored may need
3549 // legalization), return empty Results here to indicate that we don't
3550 // really make any changes in the custom lowering.
3551 return;
3552 default:
3554 break;
3555 }
3556}
3557
3558void
3561 SelectionDAG &DAG) const {
3562 if (isHvxOperation(N, DAG)) {
3563 ReplaceHvxNodeResults(N, Results, DAG);
3564 if (!Results.empty())
3565 return;
3566 }
3567
3568 const SDLoc &dl(N);
3569 switch (N->getOpcode()) {
3570 case ISD::SRL:
3571 case ISD::SRA:
3572 case ISD::SHL:
3573 return;
3574 case ISD::BITCAST:
3575 // Handle a bitcast from v8i1 to i8.
3576 if (N->getValueType(0) == MVT::i8) {
3577 if (N->getOperand(0).getValueType() == MVT::v8i1) {
3578 SDValue P = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32,
3579 N->getOperand(0), DAG);
3580 SDValue T = DAG.getAnyExtOrTrunc(P, dl, MVT::i8);
3581 Results.push_back(T);
3582 }
3583 }
3584 break;
3585 }
3586}
3587
3588SDValue
3590 DAGCombinerInfo &DCI) const {
3591 SDValue Op(N, 0);
3592 const SDLoc &dl(Op);
3593 unsigned Opc = Op.getOpcode();
3594
3595 // Combining transformations applicable for arbitrary vector sizes.
3596 if (DCI.isBeforeLegalizeOps()) {
3597 switch (Opc) {
3598 case ISD::VECREDUCE_ADD:
3599 if (SDValue V = splitVecReduceAdd(N, DCI.DAG))
3600 return V;
3601 if (SDValue V = expandVecReduceAdd(N, DCI.DAG))
3602 return V;
3603 return SDValue();
3607 if (SDValue V = splitExtendingPartialReduceMLA(N, DCI.DAG))
3608 return V;
3609 return SDValue();
3610 }
3611 } else {
3612 switch (Opc) {
3613 case ISD::VSELECT: {
3614 // (vselect (xor x, ptrue), v0, v1) -> (vselect x, v1, v0)
3615 SDValue Cond = Op.getOperand(0);
3616 if (Cond->getOpcode() == ISD::XOR) {
3617 SDValue C0 = Cond.getOperand(0), C1 = Cond.getOperand(1);
3618 if (C1->getOpcode() == HexagonISD::PTRUE) {
3619 SDValue VSel = DCI.DAG.getNode(ISD::VSELECT, dl, ty(Op), C0,
3620 Op.getOperand(2), Op.getOperand(1));
3621 return VSel;
3622 }
3623 }
3624 return SDValue();
3625 }
3626 }
3627 }
3628
3629 if (isHvxOperation(N, DCI.DAG)) {
3630 if (SDValue V = PerformHvxDAGCombine(N, DCI))
3631 return V;
3632 return SDValue();
3633 }
3634
3635 if (Opc == ISD::TRUNCATE) {
3636 SDValue Op0 = Op.getOperand(0);
3637 // fold (truncate (build pair x, y)) -> (truncate x) or x
3638 if (Op0.getOpcode() == ISD::BUILD_PAIR) {
3639 EVT TruncTy = Op.getValueType();
3640 SDValue Elem0 = Op0.getOperand(0);
3641 // if we match the low element of the pair, just return it.
3642 if (Elem0.getValueType() == TruncTy)
3643 return Elem0;
3644 // otherwise, if the low part is still too large, apply the truncate.
3645 if (Elem0.getValueType().bitsGT(TruncTy))
3646 return DCI.DAG.getNode(ISD::TRUNCATE, dl, TruncTy, Elem0);
3647 }
3648 }
3649
3650 if (DCI.isBeforeLegalizeOps())
3651 return SDValue();
3652
3653 switch (Opc) {
3654 case HexagonISD::P2D: {
3655 SDValue P = Op.getOperand(0);
3656 switch (P.getOpcode()) {
3657 case HexagonISD::PTRUE:
3658 return DCI.DAG.getAllOnesConstant(dl, ty(Op));
3659 case HexagonISD::PFALSE:
3660 return getZero(dl, ty(Op), DCI.DAG);
3661 default:
3662 break;
3663 }
3664 break;
3665 }
3666 case ISD::TRUNCATE: {
3667 SDValue Op0 = Op.getOperand(0);
3668 // fold (truncate (build pair x, y)) -> (truncate x) or x
3669 if (Op0.getOpcode() == ISD::BUILD_PAIR) {
3670 MVT TruncTy = ty(Op);
3671 SDValue Elem0 = Op0.getOperand(0);
3672 // if we match the low element of the pair, just return it.
3673 if (ty(Elem0) == TruncTy)
3674 return Elem0;
3675 // otherwise, if the low part is still too large, apply the truncate.
3676 if (ty(Elem0).bitsGT(TruncTy))
3677 return DCI.DAG.getNode(ISD::TRUNCATE, dl, TruncTy, Elem0);
3678 }
3679 break;
3680 }
3681 case ISD::OR: {
3682 // fold (or (shl xx, s), (zext y)) -> (COMBINE (shl xx, s-32), y)
3683 // if s >= 32
3684 auto fold0 = [&, this](SDValue Op) {
3685 if (ty(Op) != MVT::i64)
3686 return SDValue();
3687 SDValue Shl = Op.getOperand(0);
3688 SDValue Zxt = Op.getOperand(1);
3689 if (Shl.getOpcode() != ISD::SHL)
3690 std::swap(Shl, Zxt);
3691
3692 if (Shl.getOpcode() != ISD::SHL || Zxt.getOpcode() != ISD::ZERO_EXTEND)
3693 return SDValue();
3694
3695 SDValue Z = Zxt.getOperand(0);
3696 auto *Amt = dyn_cast<ConstantSDNode>(Shl.getOperand(1));
3697 if (Amt && Amt->getZExtValue() >= 32 && ty(Z).getSizeInBits() <= 32) {
3698 unsigned A = Amt->getZExtValue();
3699 SDValue S = Shl.getOperand(0);
3700 SDValue T0 = DCI.DAG.getNode(ISD::SHL, dl, ty(S), S,
3701 DCI.DAG.getConstant(A - 32, dl, MVT::i32));
3702 SDValue T1 = DCI.DAG.getZExtOrTrunc(T0, dl, MVT::i32);
3703 SDValue T2 = DCI.DAG.getZExtOrTrunc(Z, dl, MVT::i32);
3704 return DCI.DAG.getNode(HexagonISD::COMBINE, dl, MVT::i64, {T1, T2});
3705 }
3706 return SDValue();
3707 };
3708
3709 if (SDValue R = fold0(Op))
3710 return R;
3711 break;
3712 }
3713 }
3714
3715 return SDValue();
3716}
3717
3718/// Returns relocation base for the given PIC jumptable.
3719SDValue
3721 SelectionDAG &DAG) const {
3722 int Idx = cast<JumpTableSDNode>(Table)->getIndex();
3723 EVT VT = Table.getValueType();
3725 return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Table), VT, T);
3726}
3727
3728//===----------------------------------------------------------------------===//
3729// Inline Assembly Support
3730//===----------------------------------------------------------------------===//
3731
3734 if (Constraint.size() == 1) {
3735 switch (Constraint[0]) {
3736 case 'q':
3737 case 'v':
3738 if (Subtarget.useHVXOps())
3739 return C_RegisterClass;
3740 break;
3741 case 'a':
3742 return C_RegisterClass;
3743 default:
3744 break;
3745 }
3746 }
3747 return TargetLowering::getConstraintType(Constraint);
3748}
3749
3750std::pair<unsigned, const TargetRegisterClass*>
3752 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
3753
3754 if (Constraint.size() == 1) {
3755 switch (Constraint[0]) {
3756 case 'r': // R0-R31
3757 switch (VT.SimpleTy) {
3758 default:
3759 return {0u, nullptr};
3760 case MVT::i1:
3761 case MVT::i8:
3762 case MVT::i16:
3763 case MVT::i32:
3764 case MVT::f32:
3765 return {0u, &Hexagon::IntRegsRegClass};
3766 case MVT::i64:
3767 case MVT::f64:
3768 return {0u, &Hexagon::DoubleRegsRegClass};
3769 }
3770 break;
3771 case 'a': // M0-M1
3772 if (VT != MVT::i32)
3773 return {0u, nullptr};
3774 return {0u, &Hexagon::ModRegsRegClass};
3775 case 'q': // q0-q3
3776 switch (VT.getSizeInBits()) {
3777 default:
3778 return {0u, nullptr};
3779 case 64:
3780 case 128:
3781 return {0u, &Hexagon::HvxQRRegClass};
3782 }
3783 break;
3784 case 'v': // V0-V31
3785 switch (VT.getSizeInBits()) {
3786 default:
3787 return {0u, nullptr};
3788 case 512:
3789 return {0u, &Hexagon::HvxVRRegClass};
3790 case 1024:
3791 if (Subtarget.hasV60Ops() && Subtarget.useHVX128BOps())
3792 return {0u, &Hexagon::HvxVRRegClass};
3793 return {0u, &Hexagon::HvxWRRegClass};
3794 case 2048:
3795 return {0u, &Hexagon::HvxWRRegClass};
3796 }
3797 break;
3798 default:
3799 return {0u, nullptr};
3800 }
3801 }
3802
3803 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3804}
3805
3806/// Returns how to materialize the specified FP immediate.
3809 bool ForCodeSize) const {
3810 return FPImmAction::Legal;
3811}
3812
3813/// Returns true if it is beneficial to convert a load of a constant
3814/// to just the constant itself.
3816 Type *Ty) const {
3817 if (!ConstantLoadsToImm)
3818 return false;
3819
3820 assert(Ty->isIntegerTy());
3821 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3822 return (BitSize > 0 && BitSize <= 64);
3823}
3824
3825/// isLegalAddressingMode - Return true if the addressing mode represented by
3826/// AM is legal for this target, for a load/store of the specified type.
3828 const AddrMode &AM, Type *Ty,
3829 unsigned AS, Instruction *I) const {
3830 if (Ty->isSized()) {
3831 // When LSR detects uses of the same base address to access different
3832 // types (e.g. unions), it will assume a conservative type for these
3833 // uses:
3834 // LSR Use: Kind=Address of void in addrspace(4294967295), ...
3835 // The type Ty passed here would then be "void". Skip the alignment
3836 // checks, but do not return false right away, since that confuses
3837 // LSR into crashing.
3838 Align A = DL.getABITypeAlign(Ty);
3839 // The base offset must be a multiple of the alignment.
3840 if (!isAligned(A, AM.BaseOffs))
3841 return false;
3842 // The shifted offset must fit in 11 bits.
3843 if (!isInt<11>(AM.BaseOffs >> Log2(A)))
3844 return false;
3845 }
3846
3847 // No global is ever allowed as a base.
3848 if (AM.BaseGV)
3849 return false;
3850
3851 int Scale = AM.Scale;
3852 if (Scale < 0)
3853 Scale = -Scale;
3854 switch (Scale) {
3855 case 0: // No scale reg, "r+i", "r", or just "i".
3856 break;
3857 default: // No scaled addressing mode.
3858 return false;
3859 }
3860 return true;
3861}
3862
3863/// Return true if folding a constant offset with the given GlobalAddress is
3864/// legal. It is frequently not legal in PIC relocation models.
3866 const {
3867 return HTM.getRelocationModel() == Reloc::Static;
3868}
3869
3870/// isLegalICmpImmediate - Return true if the specified immediate is legal
3871/// icmp immediate, that is the target has icmp instructions which can compare
3872/// a register against the immediate without having to materialize the
3873/// immediate into a register.
3875 return Imm >= -512 && Imm <= 511;
3876}
3877
3878/// IsEligibleForTailCallOptimization - Check whether the call is eligible
3879/// for tail call optimization. Targets which want to do tail call
3880/// optimization should implement this function.
3882 SDValue Callee,
3883 CallingConv::ID CalleeCC,
3884 bool IsVarArg,
3885 bool IsCalleeStructRet,
3886 bool IsCallerStructRet,
3888 const SmallVectorImpl<SDValue> &OutVals,
3890 SelectionDAG& DAG) const {
3891 const Function &CallerF = DAG.getMachineFunction().getFunction();
3892 CallingConv::ID CallerCC = CallerF.getCallingConv();
3893 bool CCMatch = CallerCC == CalleeCC;
3894
3895 // ***************************************************************************
3896 // Look for obvious safe cases to perform tail call optimization that do not
3897 // require ABI changes.
3898 // ***************************************************************************
3899
3900 // If this is a tail call via a function pointer, then don't do it!
3901 if (!isa<GlobalAddressSDNode>(Callee) &&
3902 !isa<ExternalSymbolSDNode>(Callee)) {
3903 return false;
3904 }
3905
3906 // Do not optimize if the calling conventions do not match and the conventions
3907 // used are not C or Fast.
3908 if (!CCMatch) {
3909 bool R = (CallerCC == CallingConv::C || CallerCC == CallingConv::Fast);
3910 bool E = (CalleeCC == CallingConv::C || CalleeCC == CallingConv::Fast);
3911 // If R & E, then ok.
3912 if (!R || !E)
3913 return false;
3914 }
3915
3916 // Do not tail call optimize vararg calls.
3917 if (IsVarArg)
3918 return false;
3919
3920 // Also avoid tail call optimization if either caller or callee uses struct
3921 // return semantics.
3922 if (IsCalleeStructRet || IsCallerStructRet)
3923 return false;
3924
3925 // In addition to the cases above, we also disable Tail Call Optimization if
3926 // the calling convention code that at least one outgoing argument needs to
3927 // go on the stack. We cannot check that here because at this point that
3928 // information is not available.
3929 return true;
3930}
3931
3932/// Returns the target specific optimal type for load and store operations as
3933/// a result of memset, memcpy, and memmove lowering.
3934///
3935/// If DstAlign is zero that means it's safe to destination alignment can
3936/// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
3937/// a need to check it against alignment requirement, probably because the
3938/// source does not need to be loaded. If 'IsMemset' is true, that means it's
3939/// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
3940/// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
3941/// does not need to be loaded. It returns EVT::Other if the type should be
3942/// determined using generic target-independent logic.
3944 LLVMContext &Context, const MemOp &Op,
3945 const AttributeList &FuncAttributes) const {
3946 if (Op.size() >= 8 && Op.isAligned(Align(8)))
3947 return MVT::i64;
3948 if (Op.size() >= 4 && Op.isAligned(Align(4)))
3949 return MVT::i32;
3950 if (Op.size() >= 2 && Op.isAligned(Align(2)))
3951 return MVT::i16;
3952 return MVT::Other;
3953}
3954
3955// The helpers below are versions of llvm::getShuffleReduction and
3956// llvm::getOrderedReduction, adapted to use during DAG passes and simplified as
3957// follows:
3958// - ICmp and FCmp are not handled;
3959// - in every step in getShuffleReduction, the input is split into halves (not
3960// pairwise).
3961
3963 SelectionDAG &DAG) {
3964 assert(Op != Instruction::ICmp && Op != Instruction::FCmp);
3965
3966 EVT VT = Vec.getValueType();
3967 EVT EltT = VT.getVectorElementType();
3968 unsigned VF = VT.getVectorNumElements();
3969 assert(VF > 0 &&
3970 "Reduction emission only supported for non-zero length vectors!");
3971
3972 SDLoc DL(Vec);
3973 SDValue Result = DAG.getExtractVectorElt(DL, EltT, Vec, 0);
3974 for (unsigned ExtractIdx = 1; ExtractIdx < VF; ++ExtractIdx) {
3975 SDValue Ext = DAG.getExtractVectorElt(DL, EltT, Vec, ExtractIdx);
3976 Result = DAG.getNode(Op, DL, EltT, {Result, Ext});
3977 }
3978
3979 return Result;
3980}
3981
3983 SelectionDAG &DAG) {
3984 assert(Op != Instruction::ICmp && Op != Instruction::FCmp);
3985
3986 EVT VT = Vec.getValueType();
3987 unsigned VF = VT.getVectorNumElements();
3988 if (VF == 0)
3989 llvm_unreachable("Vector must be non-zero length");
3990 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3991 // and vector ops, reducing the set of values being computed by half each
3992 // round.
3993 assert(isPowerOf2_32(VF) &&
3994 "Reduction emission only supported for pow2 vectors!");
3995
3996 SDLoc DL(Vec);
3997 // TODO: Is it correct to create double-vector shuffle and fill 3/4 of it with
3998 // undefs?
3999 SmallVector<int, 32> ShuffleMask(VF);
4000 for (unsigned i = VF; i > 1; i >>= 1) {
4001 // Move the upper half of the vector to the lower half.
4002 for (unsigned j = 0; j != i / 2; ++j)
4003 ShuffleMask[j] = i / 2 + j;
4004 // Fill the rest of the mask with undef.
4005 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
4006
4007 SDValue Shuf =
4008 DAG.getVectorShuffle(VT, DL, Vec, DAG.getUNDEF(VT), ShuffleMask);
4009
4010 Vec = DAG.getNode(Op, DL, VT, {Vec, Shuf});
4011 }
4012 // The result is in the first element of the vector.
4013 return DAG.getExtractVectorElt(DL, VT.getVectorElementType(), Vec, 0);
4014}
4015
4016SDValue HexagonTargetLowering::expandVecReduceAdd(SDNode *N,
4017 SelectionDAG &DAG) const {
4018 // Since we disabled automatic reduction expansion, generate log2 ladder code
4019 // if the vector is of a power-of-two length.
4020 SDValue Input = N->getOperand(0);
4021 if (isPowerOf2_32(Input.getValueType().getVectorNumElements()))
4022 return getShuffleReduction(Input, ISD::ADD, DAG);
4023 // Otherwise, reduction will be scalarized.
4024 return getOrderedReduction(Input, ISD::ADD, DAG);
4025}
4026
4028 LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
4029 Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const {
4030 if (!VT.isSimple())
4031 return false;
4032 MVT SVT = VT.getSimpleVT();
4033 if (Subtarget.isHLXVectorType(SVT))
4034 return allowsHlxMemoryAccess(SVT, Flags, Fast);
4035 if (Subtarget.isHVXVectorType(SVT, true))
4036 return allowsHvxMemoryAccess(SVT, Flags, Fast);
4038 Context, DL, VT, AddrSpace, Alignment, Flags, Fast);
4039}
4040
4042 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
4043 unsigned *Fast) const {
4044 if (!VT.isSimple())
4045 return false;
4046 MVT SVT = VT.getSimpleVT();
4047 if (Subtarget.isHVXVectorType(SVT, true))
4048 return allowsHvxMisalignedMemoryAccesses(SVT, Flags, Fast);
4049 if (Fast)
4050 *Fast = 0;
4051 return false;
4052}
4053
4054std::pair<const TargetRegisterClass*, uint8_t>
4055HexagonTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
4056 MVT VT) const {
4057 if (Subtarget.isHVXVectorType(VT, true)) {
4058 unsigned BitWidth = VT.getSizeInBits();
4059 unsigned VecWidth = Subtarget.getVectorLength() * 8;
4060
4061 if (VT.getVectorElementType() == MVT::i1)
4062 return std::make_pair(&Hexagon::HvxQRRegClass, 1);
4063 if (BitWidth == VecWidth)
4064 return std::make_pair(&Hexagon::HvxVRRegClass, 1);
4065 assert(BitWidth == 2 * VecWidth);
4066 return std::make_pair(&Hexagon::HvxWRRegClass, 1);
4067 }
4068
4070}
4071
4073 SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT,
4074 std::optional<unsigned> ByteOffset) const {
4075 // TODO: This may be worth removing. Check regression tests for diffs.
4077 ByteOffset))
4078 return false;
4079
4080 auto *L = cast<LoadSDNode>(Load);
4081 std::pair<SDValue, int> BO = getBaseAndOffset(L->getBasePtr());
4082 // Small-data object, do not shrink.
4083 if (BO.first.getOpcode() == HexagonISD::CONST32_GP)
4084 return false;
4086 auto &HTM = static_cast<const HexagonTargetMachine &>(getTargetMachine());
4087 const auto *GO = dyn_cast_or_null<const GlobalObject>(GA->getGlobal());
4088 return !GO || !HTM.getObjFileLowering()->isGlobalInSmallSection(GO, HTM);
4089 }
4090 return true;
4091}
4092
4094 SDNode *Node) const {
4095 AdjustHvxInstrPostInstrSelection(MI, Node);
4096}
4097
4099 Type *ValueTy, Value *Addr,
4100 AtomicOrdering Ord) const {
4101 unsigned SZ = ValueTy->getPrimitiveSizeInBits();
4102 assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic loads supported");
4103 Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_L2_loadw_locked
4104 : Intrinsic::hexagon_L4_loadd_locked;
4105
4106 Value *Call =
4107 Builder.CreateIntrinsic(IntID, Addr, /*FMFSource=*/nullptr, "larx");
4108
4109 return Builder.CreateBitCast(Call, ValueTy);
4110}
4111
4112/// Perform a store-conditional operation to Addr. Return the status of the
4113/// store. This should be 0 if the store succeeded, non-zero otherwise.
4115 Value *Val, Value *Addr,
4116 AtomicOrdering Ord) const {
4117 BasicBlock *BB = Builder.GetInsertBlock();
4118 Module *M = BB->getParent()->getParent();
4119 Type *Ty = Val->getType();
4120 unsigned SZ = Ty->getPrimitiveSizeInBits();
4121
4122 Type *CastTy = Builder.getIntNTy(SZ);
4123 assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic stores supported");
4124 Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_S2_storew_locked
4125 : Intrinsic::hexagon_S4_stored_locked;
4126
4127 Val = Builder.CreateBitCast(Val, CastTy);
4128
4129 Value *Call = Builder.CreateIntrinsic(IntID, {Addr, Val},
4130 /*FMFSource=*/nullptr, "stcx");
4131 Value *Cmp = Builder.CreateICmpEQ(Call, Builder.getInt32(0), "");
4132 Value *Ext = Builder.CreateZExt(Cmp, Type::getInt32Ty(M->getContext()));
4133 return Ext;
4134}
4135
4138 // Do not expand loads and stores that don't exceed 64 bits.
4139 return LI->getType()->getPrimitiveSizeInBits() > 64
4142}
4143
4146 // Do not expand loads and stores that don't exceed 64 bits.
4147 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() > 64
4150}
4151
4157
4159 MachineInstr &MI, MachineBasicBlock *BB) const {
4160 switch (MI.getOpcode()) {
4161 case TargetOpcode::PATCHABLE_EVENT_CALL:
4162 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
4163 // These are lowered in the AsmPrinter.
4164 return BB;
4165 default:
4166 llvm_unreachable("Unexpected instruction with custom inserter");
4167 }
4168}
4169
4173 const TargetInstrInfo *TII) const {
4174 assert(MBBI->isCall() && MBBI->getCFIType() &&
4175 "Invalid call instruction for a KCFI check");
4176
4177 switch (MBBI->getOpcode()) {
4178 case Hexagon::J2_callr:
4179 case Hexagon::PS_callr_nr:
4180 break;
4181 default:
4182 llvm_unreachable("Unexpected CFI call opcode");
4183 }
4184
4185 MachineOperand &Target = MBBI->getOperand(0);
4186 assert(Target.isReg() && "Invalid target operand for an indirect call");
4187 Target.setIsRenamable(false);
4188
4189 return BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(Hexagon::KCFI_CHECK))
4190 .addReg(Target.getReg())
4191 .addImm(MBBI->getCFIType())
4192 .getInstr();
4193}
4194
4196 const Instruction &AndI) const {
4197 // Only sink 'and' mask to cmp use block if it is masking a single bit since
4198 // this will fold the and/cmp/br into a single tstbit instruction.
4200 if (!Mask)
4201 return false;
4202 return Mask->getValue().isPowerOf2();
4203}
4204
4205// Check if the result of the node is only used as a return value, as
4206// otherwise we can't perform a tail-call.
4208 SDValue &Chain) const {
4209 if (N->getNumValues() != 1)
4210 return false;
4211 if (!N->hasNUsesOfValue(1, 0))
4212 return false;
4213
4214 SDNode *Copy = *N->user_begin();
4215
4216 if (Copy->getOpcode() == ISD::BITCAST) {
4217 return isUsedByReturnOnly(Copy, Chain);
4218 }
4219
4220 if (Copy->getOpcode() != ISD::CopyToReg) {
4221 return false;
4222 }
4223
4224 // If the ISD::CopyToReg has a glue operand, we conservatively assume it
4225 // isn't safe to perform a tail call.
4226 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == MVT::Glue)
4227 return false;
4228
4229 // The copy must be used by a HexagonISD::RET_GLUE, and nothing else.
4230 bool HasRet = false;
4231 for (SDNode *Node : Copy->users()) {
4232 if (Node->getOpcode() != HexagonISD::RET_GLUE)
4233 return false;
4234 HasRet = true;
4235 }
4236 if (!HasRet)
4237 return false;
4238
4239 Chain = Copy->getOperand(0);
4240 return true;
4241}
4242
4244 const MachineFunction &MF) const {
4245 if (MF.getFunction().hasFnAttribute("probe-stack"))
4246 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
4247 "inline-asm";
4248 return false;
4249}
4250
4252 Align StackAlign) const {
4253 const Function &Fn = MF.getFunction();
4254 unsigned StackProbeSize =
4255 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
4256 // Round down to the stack alignment.
4257 StackProbeSize = alignDown(StackProbeSize, StackAlign.value());
4258 return StackProbeSize ? StackProbeSize : StackAlign.value();
4259}
return SDValue()
const AArch64Subtarget & Subtarget
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
uint64_t Imm
constexpr LLT S8
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis Results
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
const HexagonInstrInfo * TII
static cl::opt< bool > ConstantLoadsToImm("constant-loads-to-imm", cl::Hidden, cl::init(true), cl::desc("Convert constant loads to immediate values."))
static bool CC_SkipOdd(unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, ISD::ArgFlagsTy &ArgFlags, CCState &State)
static void getHlxMemIntrinsicInfo(const CallBase &I, const HexagonSubtarget &ST, TargetLowering::IntrinsicInfo &Info)
Infer IntrinsicInfo for an HLX memory intrinsic from its IR signature.
static cl::opt< bool > AlignLoads("hexagon-align-loads", cl::Hidden, cl::init(false), cl::desc("Rewrite unaligned loads as a pair of aligned loads"))
static bool isBrevLdIntrinsic(const Value *Inst)
static Value * getUnderLyingObjectForBrevLdIntr(Value *V, int &Offset, bool &HasOffset)
static Value * getBrevLdObject(Value *V)
static cl::opt< bool > DisableArgsMinAlignment("hexagon-disable-args-min-alignment", cl::Hidden, cl::init(false), cl::desc("Disable minimum alignment of 1 for " "arguments passed by value on stack"))
static Value * returnEdge(const PHINode *PN, Value *IntrBaseVal)
static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, const SDLoc &dl)
CreateCopyOfByValArgument - Make a copy of an aggregate at address specified by "Src" to address "Dst...
static cl::opt< bool > EmitJumpTables("hexagon-emit-jump-tables", cl::init(true), cl::Hidden, cl::desc("Control jump table emission on Hexagon target"))
static unsigned assignVTCMStackOffsets(SmallVectorImpl< CCValAssign > &ArgLocs)
static cl::opt< int > MinimumJumpTables("minimum-jump-tables", cl::Hidden, cl::init(5), cl::desc("Set minimum jump tables"))
static cl::opt< bool > EnableHexSDNodeSched("enable-hexagon-sdnode-sched", cl::Hidden, cl::desc("Enable Hexagon SDNode scheduling"))
static bool CC_Hexagon_VTCM_Stack(unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, ISD::ArgFlagsTy &ArgFlags, CCState &State)
#define Hexagon_PointerSize
#define HEXAGON_LRFP_SIZE
#define HEXAGON_GOT_SYM_NAME
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
std::pair< MCSymbol *, MachineModuleInfoImpl::StubValueTy > PairTy
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
#define T1
#define P(N)
SmallVector< MachineOperand, 4 > Cond
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
int64_t C0
const char * Msg
This file defines the SmallVector class.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static llvm::Type * getVectorElementType(llvm::Type *Ty)
APInt bitcastToAPInt() const
Definition APFloat.h:1504
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
An instruction that atomically checks whether a specified value is in a memory location,...
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
The address of a basic block.
Definition Constants.h:1088
CCState - This class holds information needed while lowering arguments and return values.
LLVM_ABI void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
LLVM_ABI bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
LLVM_ABI void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool needsCustom() const
int64_t getLocMemOffset() const
static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
int64_t getSExtValue() const
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
This is the base abstract class for diagnostic reporting in the backend.
Interface for custom diagnostic printing.
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:708
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:778
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasStructRetAttr() const
Determine if the function returns a structure through first or second pointer argument.
Definition Function.h:673
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
const GlobalValue * getGlobal() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
Hexagon target-specific information for each MachineFunction.
const uint32_t * getHLXCallPreservedMask() const
Mask for calls that pass or return values in HLX registers.
Register getFrameRegister(const MachineFunction &MF) const override
const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const override
SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const override
Returns relocation base for the given PIC jumptable.
SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const
SDValue LowerFMINFMAX(SDValue Op, SelectionDAG &DAG) const
MachineInstr * EmitKCFICheck(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator &MBBI, const TargetInstrInfo *TII) const override
SDValue LowerGLOBAL_OFFSET_TABLE(SDValue Op, SelectionDAG &DAG) const
bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const override
Return if the target supports combining a chain like:
SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const
void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const override
This method should be implemented by targets that mark instructions with the 'hasPostISelHook' flag.
bool isTargetCanonicalConstantNode(SDValue Op) const override
Returns true if the given Opc is considered a canonical constant for the target, which should not be ...
ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
bool isTruncateFree(Type *Ty1, Type *Ty2) const override
Return true if it's free to truncate a value of type FromTy to type ToTy.
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
unsigned getStackProbeSize(const MachineFunction &MF, Align StackAlign) const
SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) const
SDValue LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const
ExtractSubvectorCost getExtractSubvectorCost(EVT ResVT, EVT SrcVT, unsigned Index) const override
Return the cost of extracting a subvector of type ResVT from a vector of type SrcVT,...
SDValue LowerUAddSubO(SDValue Op, SelectionDAG &DAG) const
Value * emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy, Value *Addr, AtomicOrdering Ord) const override
Perform a load-linked operation on Addr, returning a "Value *" with the corresponding pointee type.
bool isLegalICmpImmediate(int64_t Imm) const override
isLegalICmpImmediate - Return true if the specified immediate is legal icmp immediate,...
bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT, std::optional< unsigned > ByteOffset) const override
Return true if it is profitable to reduce a load to a smaller type.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
isLegalAddressingMode - Return true if the addressing mode represented by AM is legal for this target...
SDValue LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const
AtomicExpansionKind shouldExpandAtomicStoreInIR(StoreInst *SI) const override
Returns how the given (atomic) store should be expanded by the IR-level AtomicExpand pass into.
SDValue GetDynamicTLSAddr(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, SDValue InGlue, EVT PtrVT, unsigned ReturnReg, unsigned char OperandGlues) const
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &dl, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
bool getPostIndexedAddressParts(SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
Returns true by value, base pointer and offset pointer and addressing mode by reference if this node ...
SDValue LowerUnalignedLoad(SDValue Op, SelectionDAG &DAG) const
SDValue LowerFDIV(SDValue Op, SelectionDAG &DAG) const
SDValue LowerVACOPY(SDValue Op, SelectionDAG &DAG) const
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
bool mayBeEmittedAsTailCall(const CallInst *CI) const override
Return true if the target may be able emit the call instruction as a tail call.
AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const override
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass.
bool isUsedByReturnOnly(SDNode *N, SDValue &Chain) const override
Return true if result of the specified node is used by a return node only.
SDValue LowerCallResult(SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals, const SmallVectorImpl< SDValue > &OutVals, SDValue Callee) const
LowerCallResult - Lower the result values of an ISD::CALL into the appropriate copies out of appropri...
SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
SDValue LowerToTLSInitialExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG) const
SDValue LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG) const
bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const override
Return true if the target supports a memory access of this type for the given address space and align...
SDValue LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
SDValue LowerROTL(SDValue Op, SelectionDAG &DAG) const
SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const
SDValue LowerLoad(SDValue Op, SelectionDAG &DAG) const
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
bool isShuffleMaskLegal(ArrayRef< int > Mask, EVT VT) const override
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
LegalizeAction getCustomOperationAction(SDNode &Op) const override
How to legalize this custom operation?
SDValue LowerToTLSLocalExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG) const
SDValue LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
bool allowTruncateForTailCall(Type *Ty1, Type *Ty2) const override
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
SDValue LowerUAddSubOCarry(SDValue Op, SelectionDAG &DAG) const
bool shouldExpandBuildVectorWithShuffles(EVT VT, unsigned DefinedValues) const override
bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const override
Returns true if it is beneficial to convert a load of a constant to just the constant itself.
SDValue LowerSETCC(SDValue Op, SelectionDAG &DAG) const
SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
LowerCall - Functions arguments are copied from virtual regs to (physical regs)/(stack frame),...
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const override
Determine if the target supports unaligned memory accesses.
SDValue LowerStore(SDValue Op, SelectionDAG &DAG) const
SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) const
bool hasInlineStackProbe(const MachineFunction &MF) const override
SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
Value * emitStoreConditional(IRBuilderBase &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const override
Perform a store-conditional operation to Addr.
bool hasBitTest(SDValue X, SDValue Y) const override
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
HexagonTargetLowering(const TargetMachine &TM, const HexagonSubtarget &ST)
SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
bool IsEligibleForTailCallOptimization(SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, bool isCalleeStructRet, bool isCallerStructRet, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SmallVectorImpl< ISD::InputArg > &Ins, SelectionDAG &DAG) const
IsEligibleForTailCallOptimization - Check whether the call is eligible for tail call optimization.
SDValue LowerVSELECT(SDValue Op, SelectionDAG &DAG) const
void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const
SDValue LowerVECTOR_SHIFT(SDValue Op, SelectionDAG &DAG) const
SDValue LowerINTRINSIC_VOID(SDValue Op, SelectionDAG &DAG) const
SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const
FPImmAction getFPImmAction(const APFloat &Imm, EVT VT, bool ForCodeSize) const override
Returns how to materialize the specified FP immediate.
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) const
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &, EVT) const override
Return true if an FMA operation is faster than a pair of mul and add instructions.
SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset,...
SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const
LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
SDValue LowerGLOBALADDRESS(SDValue Op, SelectionDAG &DAG) const
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *AI) const override
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
std::pair< MVT, unsigned > handleMaskRegisterForCallingConv(const HexagonSubtarget &Subtarget, EVT VT) const
SDValue LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Base class for LoadSDNode and StoreSDNode.
ISD::MemIndexedMode getAddressingMode() const
Return the addressing mode for this load or store: unindexed, pre-inc, pre-dec, post-inc,...
bool isUnindexed() const
Return true if this is NOT a pre/post inc/dec load/store.
bool isIndexed() const
Return true if this is a pre/post inc/dec load/store.
An instruction for reading from memory.
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
const SDValue & getOffset() const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
unsigned getID() const
getID() - Return the register class ID number.
Machine Value Type.
@ INVALID_SIMPLE_VALUE_TYPE
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
SimpleValueType SimpleTy
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
bool isScalableVector() const
Return true if this is a vector value type where the runtime length is machine dependent.
static LLVM_ABI MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT widenIntegerElementType() const
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
TypeSize getStoreSizeInBits() const
Return the number of bits overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
MVT getVectorElementType() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
LLVM_ABI void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
Instructions::iterator instr_iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
LLVM_ABI void ensureMaxAlignment(Align Alignment)
Make sure the function's frame is at least Align bytes aligned.
void setFrameAddressIsTaken(bool T)
void setStackID(int ObjectIdx, uint8_t ID)
void setHasTailCall(bool V=true)
void setReturnAddressIsTaken(bool s)
unsigned getNumFixedObjects() const
Return the number of fixed objects.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const MDNode * getRanges() const
Returns the Ranges that describes the dereference.
Align getAlign() const
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
Represents one node in the SelectionDAG.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
void setCFIType(uint32_t Type)
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
const SDValue & getOperand(unsigned i) const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a logical NOT operation as (XOR Val, BooleanOne).
static void commuteMask(MutableArrayRef< int > Mask)
Change values in a shuffle permute mask assuming the two vector operands have swapped position.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
const SDValue & getBasePtr() const
const SDValue & getOffset() const
const SDValue & getValue() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT, std::optional< unsigned > ByteOffset=std::nullopt) const
Return true if it is profitable to reduce a load to a smaller type.
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
void setPrefLoopAlignment(Align Alignment)
Set the target's preferred loop alignment.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
ExtractSubvectorCost
Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
void setMinimumJumpTableEntries(unsigned Val)
Indicate the minimum number of blocks to generate jump tables.
FPImmAction
How the legalizer should materialize a floating-point immediate.
@ Legal
The target can instruction select the immediate natively.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn't supported on the target and indicate what to d...
virtual std::pair< const TargetRegisterClass *, uint8_t > findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const
Return the largest legal super-reg register class of the register class for the specified type and it...
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
bool allowsMemoryAccessForAlignment(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
This function returns true if the memory access is aligned or if the target allows this specific unal...
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
virtual bool isTargetCanonicalConstantNode(SDValue Op) const
Returns true if the given Opc is considered a canonical constant for the target, which should not be ...
SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const
Expands an unaligned store to 2 half-size stores for integer values, and possibly more for vectors.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
std::pair< SDValue, SDValue > expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Expands an unaligned load to 2 half-size loads for an integer, and possibly more for vectors.
bool isPositionIndependent() const
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
Primary interface to the complete machine description for the target machine.
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Target - Wrapper for Target specific information.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ MO_PCREL
MO_PCREL - On a symbol operand, indicates a PC-relative relocation Used for computing a global addres...
@ MO_GOT
MO_GOT - Indicates a GOT-relative relocation.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:158
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ READSTEADYCOUNTER
READSTEADYCOUNTER - This corresponds to the readfixedcounter intrinsic.
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:688
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ GLOBAL_OFFSET_TABLE
The address of the GOT.
Definition ISDOpcodes.h:105
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isIntEqualitySetCC(CondCode Code)
Return true if this is a setcc instruction that performs an equality comparison when used with intege...
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
initializer< Ty > init(const Ty &Val)
constexpr double e
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Value * getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op, TargetTransformInfo::ReductionShuffle RS, RecurKind MinMaxKind=RecurKind::None)
Generates a vector reduction using shufflevectors to reduce the value.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition Format.h:164
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
DWARFExpression::Operation Op
LLVM_ABI int getNextAvailablePluginDiagnosticKind()
Get the next available kind ID for a plugin diagnostic.
unsigned M0(unsigned Val)
Definition VE.h:393
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI Value * getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src, unsigned Op, RecurKind MinMaxKind=RecurKind::None)
Generates an ordered vector reduction using extracts to reduce the value.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73
Extended Value Type.
Definition ValueTypes.h:35
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:516
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:196
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
unsigned int NumVTs
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
SmallVector< ISD::OutputArg, 32 > Outs