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"
52#include "llvm/Support/Debug.h"
57#include <algorithm>
58#include <cassert>
59#include <cstdint>
60#include <limits>
61#include <utility>
62
63using namespace llvm;
64
65#define DEBUG_TYPE "hexagon-lowering"
66
67// Implement calling convention for Hexagon.
68
69static bool CC_SkipOdd(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
70 CCValAssign::LocInfo &LocInfo,
71 ISD::ArgFlagsTy &ArgFlags, CCState &State) {
72 static const MCPhysReg ArgRegs[] = {
73 Hexagon::R0, Hexagon::R1, Hexagon::R2,
74 Hexagon::R3, Hexagon::R4, Hexagon::R5
75 };
76 const unsigned NumArgRegs = std::size(ArgRegs);
77 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
78
79 // RegNum is an index into ArgRegs: skip a register if RegNum is odd.
80 if (RegNum != NumArgRegs && RegNum % 2 == 1)
81 State.AllocateReg(ArgRegs[RegNum]);
82
83 // Always return false here, as this function only makes sure that the first
84 // unallocated register has an even register number and does not actually
85 // allocate a register for the current argument.
86 return false;
87}
88
89// HLX vectors that do not fit in registers are passed on the VTCM stack.
90// CCState only tracks the scalar stack, so add a custom memory location here
91// and let assignVTCMStackOffsets set its offset.
92static bool CC_Hexagon_VTCM_Stack(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
93 CCValAssign::LocInfo &LocInfo,
94 ISD::ArgFlagsTy &ArgFlags, CCState &State) {
95 State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT, 0, LocVT, LocInfo));
96 return true;
97}
98
99// Assign VTCM stack offsets to the HLX arguments, in argument order, and
100// return the size of the VTCM argument area.
102 unsigned Size = 0;
103 for (CCValAssign &VA : ArgLocs) {
104 if (!VA.isMemLoc() || !VA.needsCustom())
105 continue;
106 VA.convertToMem(Size);
107 Size += VA.getLocVT().getStoreSize();
108 }
109 return Size;
110}
111
112#define GET_CALLING_CONV_IMPL
113#include "HexagonGenCallingConv.inc"
114
116 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
117 unsigned &NumIntermediates, MVT &RegisterVT) const {
118
119 bool isBoolVector = VT.getVectorElementType() == MVT::i1;
120 bool isPowerOf2 = VT.isPow2VectorType();
121 unsigned NumElts = VT.getVectorNumElements();
122
123 // Split vectors of type vXi1 into (X/8) vectors of type v8i1,
124 // where X is divisible by 8.
125 if (isBoolVector && !Subtarget.useHVXOps() && isPowerOf2 && NumElts >= 8) {
126 RegisterVT = MVT::v8i8;
127 IntermediateVT = MVT::v8i1;
128 NumIntermediates = NumElts / 8;
129 return NumIntermediates;
130 }
131
132 // In HVX 64-byte mode, vectors of type vXi1 are split into (X / 64) vectors
133 // of type v64i1, provided that X is divisible by 64.
134 if (isBoolVector && Subtarget.useHVX64BOps() && isPowerOf2 && NumElts >= 64) {
135 RegisterVT = MVT::v64i8;
136 IntermediateVT = MVT::v64i1;
137 NumIntermediates = NumElts / 64;
138 return NumIntermediates;
139 }
140
141 // In HVX 128-byte mode, vectors of type vXi1 are split into (X / 128) vectors
142 // of type v128i1, provided that X is divisible by 128.
143 if (isBoolVector && Subtarget.useHVX128BOps() && isPowerOf2 &&
144 NumElts >= 128) {
145 RegisterVT = MVT::v128i8;
146 IntermediateVT = MVT::v128i1;
147 NumIntermediates = NumElts / 128;
148 return NumIntermediates;
149 }
150
152 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
153}
154
155std::pair<MVT, unsigned>
157 const HexagonSubtarget &Subtarget, EVT VT) const {
158 assert(VT.getVectorElementType() == MVT::i1);
159
160 const unsigned NumElems = VT.getVectorNumElements();
161
162 if (!VT.isPow2VectorType())
164
165 if (!Subtarget.useHVXOps() && NumElems >= 8)
166 return {MVT::v8i8, NumElems / 8};
167
168 if (Subtarget.useHVX64BOps() && NumElems >= 64)
169 return {MVT::v64i8, NumElems / 64};
170
171 if (Subtarget.useHVX128BOps() && NumElems >= 128)
172 return {MVT::v128i8, NumElems / 128};
173
175}
176
179 EVT VT) const {
180
181 if (VT.isVectorOf(MVT::i1)) {
182 auto [RegisterVT, NumRegisters] =
184 if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
185 return RegisterVT;
186 }
187
189}
190
193 const {
194 unsigned IntNo = Op.getConstantOperandVal(0);
195 SDLoc dl(Op);
196 switch (IntNo) {
197 default:
198 return SDValue(); // Don't custom lower most intrinsics.
199 case Intrinsic::thread_pointer: {
200 EVT PtrVT = getPointerTy(DAG.getDataLayout());
201 return DAG.getNode(HexagonISD::THREAD_POINTER, dl, PtrVT);
202 }
203 }
204}
205
206/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
207/// by "Src" to address "Dst" of size "Size". Alignment information is
208/// specified by the specific parameter attribute. The copy will be passed as
209/// a byval function parameter. Sometimes what we are copying is the end of a
210/// larger object, the part that does not fit in registers.
212 SDValue Chain, ISD::ArgFlagsTy Flags,
213 SelectionDAG &DAG, const SDLoc &dl) {
214 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
215 Align Alignment = Flags.getNonZeroByValAlign();
216 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Alignment, Alignment,
217 /*isVolatile=*/false, /*AlwaysInline=*/false,
218 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(),
220}
221
222bool
224 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
226 LLVMContext &Context, const Type *RetTy) const {
228 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
229
230 return CCInfo.CheckReturn(Outs, RetCC_Hexagon);
231}
232
233// LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
234// passed by value, the function prototype is modified to return void and
235// the value is stored in memory pointed by a pointer passed by caller.
238 bool IsVarArg,
240 const SmallVectorImpl<SDValue> &OutVals,
241 const SDLoc &dl, SelectionDAG &DAG) const {
242 // CCValAssign - represent the assignment of the return value to locations.
244
245 // CCState - Info about the registers and stack slot.
246 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
247 *DAG.getContext());
248
249 // Analyze return values of ISD::RET
250 CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
251
252 SDValue Glue;
253 SmallVector<SDValue, 4> RetOps(1, Chain);
254
255 // Copy the result values into the output registers.
256 for (unsigned i = 0; i != RVLocs.size(); ++i) {
257 CCValAssign &VA = RVLocs[i];
258 SDValue Val = OutVals[i];
259
260 switch (VA.getLocInfo()) {
261 default:
262 // Loc info must be one of Full, BCvt, SExt, ZExt, or AExt.
263 llvm_unreachable("Unknown loc info!");
265 break;
267 Val = DAG.getBitcast(VA.getLocVT(), Val);
268 break;
270 Val = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Val);
271 break;
273 Val = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Val);
274 break;
276 Val = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Val);
277 break;
278 }
279
280 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Val, Glue);
281
282 // Guarantee that all emitted copies are stuck together with flags.
283 Glue = Chain.getValue(1);
284 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
285 }
286
287 RetOps[0] = Chain; // Update chain.
288
289 // Add the glue if we have it.
290 if (Glue.getNode())
291 RetOps.push_back(Glue);
292
293 return DAG.getNode(HexagonISD::RET_GLUE, dl, MVT::Other, RetOps);
294}
295
297 // If either no tail call or told not to tail call at all, don't.
298 return CI->isTailCall();
299}
300
302 const char* RegName, LLT VT, const MachineFunction &) const {
303 // Just support r19, the linux kernel uses it.
305 .Case("r0", Hexagon::R0)
306 .Case("r1", Hexagon::R1)
307 .Case("r2", Hexagon::R2)
308 .Case("r3", Hexagon::R3)
309 .Case("r4", Hexagon::R4)
310 .Case("r5", Hexagon::R5)
311 .Case("r6", Hexagon::R6)
312 .Case("r7", Hexagon::R7)
313 .Case("r8", Hexagon::R8)
314 .Case("r9", Hexagon::R9)
315 .Case("r10", Hexagon::R10)
316 .Case("r11", Hexagon::R11)
317 .Case("r12", Hexagon::R12)
318 .Case("r13", Hexagon::R13)
319 .Case("r14", Hexagon::R14)
320 .Case("r15", Hexagon::R15)
321 .Case("r16", Hexagon::R16)
322 .Case("r17", Hexagon::R17)
323 .Case("r18", Hexagon::R18)
324 .Case("r19", Hexagon::R19)
325 .Case("r20", Hexagon::R20)
326 .Case("r21", Hexagon::R21)
327 .Case("r22", Hexagon::R22)
328 .Case("r23", Hexagon::R23)
329 .Case("r24", Hexagon::R24)
330 .Case("r25", Hexagon::R25)
331 .Case("r26", Hexagon::R26)
332 .Case("r27", Hexagon::R27)
333 .Case("r28", Hexagon::R28)
334 .Case("r29", Hexagon::R29)
335 .Case("r30", Hexagon::R30)
336 .Case("r31", Hexagon::R31)
337 .Case("r1:0", Hexagon::D0)
338 .Case("r3:2", Hexagon::D1)
339 .Case("r5:4", Hexagon::D2)
340 .Case("r7:6", Hexagon::D3)
341 .Case("r9:8", Hexagon::D4)
342 .Case("r11:10", Hexagon::D5)
343 .Case("r13:12", Hexagon::D6)
344 .Case("r15:14", Hexagon::D7)
345 .Case("r17:16", Hexagon::D8)
346 .Case("r19:18", Hexagon::D9)
347 .Case("r21:20", Hexagon::D10)
348 .Case("r23:22", Hexagon::D11)
349 .Case("r25:24", Hexagon::D12)
350 .Case("r27:26", Hexagon::D13)
351 .Case("r29:28", Hexagon::D14)
352 .Case("r31:30", Hexagon::D15)
353 .Case("sp", Hexagon::R29)
354 .Case("fp", Hexagon::R30)
355 .Case("lr", Hexagon::R31)
356 .Case("p0", Hexagon::P0)
357 .Case("p1", Hexagon::P1)
358 .Case("p2", Hexagon::P2)
359 .Case("p3", Hexagon::P3)
360 .Case("sa0", Hexagon::SA0)
361 .Case("lc0", Hexagon::LC0)
362 .Case("sa1", Hexagon::SA1)
363 .Case("lc1", Hexagon::LC1)
364 .Case("m0", Hexagon::M0)
365 .Case("m1", Hexagon::M1)
366 .Case("usr", Hexagon::USR)
367 .Case("ugp", Hexagon::UGP)
368 .Case("cs0", Hexagon::CS0)
369 .Case("cs1", Hexagon::CS1)
370 .Default(Register());
371 return Reg;
372}
373
374/// LowerCallResult - Lower the result values of an ISD::CALL into the
375/// appropriate copies out of appropriate physical registers. This assumes that
376/// Chain/Glue are the input chain/glue to use, and that TheCall is the call
377/// being lowered. Returns a SDNode with the same number of values as the
378/// ISD::CALL.
380 SDValue Chain, SDValue Glue, CallingConv::ID CallConv, bool IsVarArg,
381 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
383 const SmallVectorImpl<SDValue> &OutVals, SDValue Callee) const {
384 // Assign locations to each value returned by this call.
386
387 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
388 *DAG.getContext());
389
390 CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
391
392 // Copy all of the result registers out of their specified physreg.
393 for (unsigned i = 0; i != RVLocs.size(); ++i) {
394 SDValue RetVal;
395 if (RVLocs[i].getValVT() == MVT::i1) {
396 // Return values of type MVT::i1 require special handling. The reason
397 // is that MVT::i1 is associated with the PredRegs register class, but
398 // values of that type are still returned in R0. Generate an explicit
399 // copy into a predicate register from R0, and treat the value of the
400 // predicate register as the call result.
401 auto &MRI = DAG.getMachineFunction().getRegInfo();
402 SDValue FR0 = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
403 MVT::i32, Glue);
404 // FR0 = (Value, Chain, Glue)
405 Register PredR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
406 SDValue TPR = DAG.getCopyToReg(FR0.getValue(1), dl, PredR,
407 FR0.getValue(0), FR0.getValue(2));
408 // TPR = (Chain, Glue)
409 // Don't glue this CopyFromReg, because it copies from a virtual
410 // register. If it is glued to the call, InstrEmitter will add it
411 // as an implicit def to the call (EmitMachineNode).
412 RetVal = DAG.getCopyFromReg(TPR.getValue(0), dl, PredR, MVT::i1);
413 Glue = TPR.getValue(1);
414 Chain = TPR.getValue(0);
415 } else {
416 RetVal = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
417 RVLocs[i].getValVT(), Glue);
418 Glue = RetVal.getValue(2);
419 Chain = RetVal.getValue(1);
420 }
421 InVals.push_back(RetVal.getValue(0));
422 }
423
424 return Chain;
425}
426
427/// LowerCall - Functions arguments are copied from virtual regs to
428/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
431 SmallVectorImpl<SDValue> &InVals) const {
432 SelectionDAG &DAG = CLI.DAG;
433 SDLoc &dl = CLI.DL;
435 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
437 SDValue Chain = CLI.Chain;
438 SDValue Callee = CLI.Callee;
439 CallingConv::ID CallConv = CLI.CallConv;
440 bool IsVarArg = CLI.IsVarArg;
441 bool DoesNotReturn = CLI.DoesNotReturn;
442
443 bool IsStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
445 MachineFrameInfo &MFI = MF.getFrameInfo();
446 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
447 auto PtrVT = getPointerTy(MF.getDataLayout());
448
450 Callee = DAG.getTargetGlobalAddress(GAN->getGlobal(), dl, MVT::i32);
451
452 // Linux ABI treats var-arg calls the same way as regular ones.
453 bool TreatAsVarArg = !Subtarget.isEnvironmentMusl() && IsVarArg;
454
455 // Analyze operands of the call, assigning locations to each operand.
457 CCState CCInfo(CallConv, TreatAsVarArg, MF, ArgLocs, *DAG.getContext());
458
459 if (!Subtarget.getCLOpts().args_min_alignment)
460 CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_Legacy);
461 else
462 CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
463 unsigned NumVTCMBytes = assignVTCMStackOffsets(ArgLocs);
464
465 if (CLI.IsTailCall) {
466 bool StructAttrFlag = MF.getFunction().hasStructRetAttr();
467 CLI.IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
468 IsVarArg, IsStructRet, StructAttrFlag, Outs,
469 OutVals, Ins, DAG);
470 for (const CCValAssign &VA : ArgLocs) {
471 if (VA.isMemLoc()) {
472 CLI.IsTailCall = false;
473 break;
474 }
475 }
476 LLVM_DEBUG(dbgs() << (CLI.IsTailCall ? "Eligible for Tail Call\n"
477 : "Argument must be passed on stack. "
478 "Not eligible for Tail Call\n"));
479 }
480 // Get a count of how many bytes are to be pushed on the stack.
481 unsigned NumBytes = CCInfo.getStackSize();
483 SmallVector<SDValue, 8> MemOpChains;
484
485 const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
486 SDValue StackPtr =
487 DAG.getCopyFromReg(Chain, dl, HRI.getStackRegister(), PtrVT);
488 SDValue VTCMStackPtr;
489 if (NumVTCMBytes) {
490 VTCMStackPtr =
491 DAG.getCopyFromReg(Chain, dl, HRI.getVTCMStackRegister(), PtrVT);
492 HMFI.reserveVTCMCallFrame(NumVTCMBytes);
493 }
494
495 bool NeedsArgAlign = false;
496 Align LargestAlignSeen;
497 // Walk the register/memloc assignments, inserting copies/loads.
498 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
499 CCValAssign &VA = ArgLocs[i];
500 SDValue Arg = OutVals[i];
501 ISD::ArgFlagsTy Flags = Outs[i].Flags;
502 // Record if we need > 8 byte alignment on an argument.
503 bool ArgAlign = Subtarget.isHVXVectorType(VA.getValVT());
504 NeedsArgAlign |= ArgAlign;
505
506 // Promote the value if needed.
507 switch (VA.getLocInfo()) {
508 default:
509 // Loc info must be one of Full, BCvt, SExt, ZExt, or AExt.
510 llvm_unreachable("Unknown loc info!");
512 break;
514 Arg = DAG.getBitcast(VA.getLocVT(), Arg);
515 break;
517 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
518 break;
520 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
521 break;
523 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
524 break;
525 }
526
527 if (VA.isMemLoc()) {
528 unsigned LocMemOffset = VA.getLocMemOffset();
529 SDValue BasePtr = VA.needsCustom() ? VTCMStackPtr : StackPtr;
530 SDValue MemAddr =
531 DAG.getConstant(LocMemOffset, dl, BasePtr.getValueType());
532 MemAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr, MemAddr);
533 if (ArgAlign)
534 LargestAlignSeen = std::max(
535 LargestAlignSeen, Align(VA.getLocVT().getStoreSizeInBits() / 8));
536 if (Flags.isByVal()) {
537 HMFI.ensureOutgoingArgAlign(Flags.getNonZeroByValAlign());
538 // The argument is a struct passed by value. According to LLVM, "Arg"
539 // is a pointer.
540 MemOpChains.push_back(CreateCopyOfByValArgument(Arg, MemAddr, Chain,
541 Flags, DAG, dl));
542 } else {
544 DAG.getMachineFunction(), LocMemOffset);
545 if (isHlxPairTy(VA.getLocVT())) {
546 splitHlxPairArgStore(DAG, dl, Chain, Arg, MemAddr, VA.getLocVT(),
547 LocPI, MemOpChains);
548 } else {
549 SDValue S = DAG.getStore(Chain, dl, Arg, MemAddr, LocPI);
550 MemOpChains.push_back(S);
551 }
552 }
553 continue;
554 }
555
556 // Arguments that can be passed on register must be kept at RegsToPass
557 // vector.
558 if (VA.isRegLoc())
559 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
560 }
561
562 if (NeedsArgAlign && Subtarget.hasV60Ops()) {
563 LLVM_DEBUG(dbgs() << "Function needs byte stack align due to call args\n");
564 Align VecAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
565 LargestAlignSeen = std::max(LargestAlignSeen, VecAlign);
566 MFI.ensureMaxAlignment(LargestAlignSeen);
567 HMFI.ensureOutgoingArgAlign(LargestAlignSeen);
568 }
569 // Transform all store nodes into one single node because all store
570 // nodes are independent of each other.
571 if (!MemOpChains.empty())
572 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
573
574 SDValue Glue;
575 if (!CLI.IsTailCall) {
576 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
577 Glue = Chain.getValue(1);
578 }
579
580 // Build a sequence of copy-to-reg nodes chained together with token
581 // chain and flag operands which copy the outgoing args into registers.
582 // The Glue is necessary since all emitted instructions must be
583 // stuck together.
584 if (!CLI.IsTailCall) {
585 for (const auto &R : RegsToPass) {
586 Chain = DAG.getCopyToReg(Chain, dl, R.first, R.second, Glue);
587 Glue = Chain.getValue(1);
588 }
589 } else {
590 // For tail calls lower the arguments to the 'real' stack slot.
591 //
592 // Force all the incoming stack arguments to be loaded from the stack
593 // before any new outgoing arguments are stored to the stack, because the
594 // outgoing stack slots may alias the incoming argument stack slots, and
595 // the alias isn't otherwise explicit. This is slightly more conservative
596 // than necessary, because it means that each store effectively depends
597 // on every argument instead of just those arguments it would clobber.
598 //
599 // Do not flag preceding copytoreg stuff together with the following stuff.
600 Glue = SDValue();
601 for (const auto &R : RegsToPass) {
602 Chain = DAG.getCopyToReg(Chain, dl, R.first, R.second, Glue);
603 Glue = Chain.getValue(1);
604 }
605 Glue = SDValue();
606 }
607
608 bool LongCalls = MF.getSubtarget<HexagonSubtarget>().useLongCalls();
609 unsigned Flags = LongCalls ? HexagonII::HMOTF_ConstExtended : 0;
610
611 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
612 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
613 // node so that legalize doesn't hack it.
615 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, PtrVT, 0, Flags);
616 } else if (ExternalSymbolSDNode *S =
618 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, Flags);
619 }
620
621 // Returns a chain & a flag for retval copy to use.
623 Ops.push_back(Chain);
624 Ops.push_back(Callee);
625
626 // Add argument registers to the end of the list so that they are
627 // known live into the call.
628 for (const auto &R : RegsToPass)
629 Ops.push_back(DAG.getRegister(R.first, R.second.getValueType()));
630
631 // Callees that take or return HLX values preserve L12-L15.
632 bool HasHLXLocs =
633 any_of(ArgLocs,
634 [](const CCValAssign &VA) {
635 return VA.isRegLoc() &&
636 (Hexagon::HlxLRRegClass.contains(VA.getLocReg()) ||
637 Hexagon::HlxLLRRegClass.contains(VA.getLocReg()));
638 }) ||
639 any_of(Ins, [this](const ISD::InputArg &In) {
640 return Subtarget.isHLXVectorType(In.VT);
641 });
642 const uint32_t *Mask = HasHLXLocs ? HRI.getHLXCallPreservedMask()
643 : HRI.getCallPreservedMask(MF, CallConv);
644 assert(Mask && "Missing call preserved mask for calling convention");
645 Ops.push_back(DAG.getRegisterMask(Mask));
646
647 if (Glue.getNode())
648 Ops.push_back(Glue);
649
650 if (CLI.IsTailCall) {
651 MFI.setHasTailCall();
652 return DAG.getNode(HexagonISD::TC_RETURN, dl, MVT::Other, Ops);
653 }
654
655 // Set this here because we need to know this for "hasFP" in frame lowering.
656 // The target-independent code calls getFrameRegister before setting it, and
657 // getFrameRegister uses hasFP to determine whether the function has FP.
658 MFI.setHasCalls(true);
659
660 unsigned OpCode = DoesNotReturn ? HexagonISD::CALLnr : HexagonISD::CALL;
661 Chain = DAG.getNode(OpCode, dl, {MVT::Other, MVT::Glue}, Ops);
662 if (CLI.CFIType)
663 Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
664 Glue = Chain.getValue(1);
665
666 // Create the CALLSEQ_END node.
667 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, dl);
668 Glue = Chain.getValue(1);
669
670 // Handle result values, copying them out of physregs into vregs that we
671 // return.
672 return LowerCallResult(Chain, Glue, CallConv, IsVarArg, Ins, dl, DAG,
673 InVals, OutVals, Callee);
674}
675
676/// Returns true by value, base pointer and offset pointer and addressing
677/// mode by reference if this node can be combined with a load / store to
678/// form a post-indexed load / store.
681 SelectionDAG &DAG) const {
683 if (!LSN)
684 return false;
685 EVT VT = LSN->getMemoryVT();
686 if (!VT.isSimple())
687 return false;
688 bool IsLegalType = VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 ||
689 VT == MVT::i64 || VT == MVT::f32 || VT == MVT::f64 ||
690 VT == MVT::v2i16 || VT == MVT::v2i32 || VT == MVT::v4i8 ||
691 VT == MVT::v4i16 || VT == MVT::v8i8 ||
692 Subtarget.isHVXVectorType(VT.getSimpleVT());
693 if (!IsLegalType)
694 return false;
695
696 if (Op->getOpcode() != ISD::ADD)
697 return false;
698 Base = Op->getOperand(0);
699 Offset = Op->getOperand(1);
700 if (!isa<ConstantSDNode>(Offset.getNode()))
701 return false;
702 AM = ISD::POST_INC;
703
704 int32_t V = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
705 return Subtarget.getInstrInfo()->isValidAutoIncImm(VT, V);
706}
707
710 return SDValue();
711 else
712 return Op;
713}
714
718 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
719 const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
720 unsigned LR = HRI.getRARegister();
721
722 if ((Op.getOpcode() != ISD::INLINEASM &&
723 Op.getOpcode() != ISD::INLINEASM_BR) || HMFI.hasClobberLR())
724 return Op;
725
726 unsigned NumOps = Op.getNumOperands();
727 if (Op.getOperand(NumOps-1).getValueType() == MVT::Glue)
728 --NumOps; // Ignore the flag operand.
729
730 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
731 const InlineAsm::Flag Flags(Op.getConstantOperandVal(i));
732 unsigned NumVals = Flags.getNumOperandRegisters();
733 ++i; // Skip the ID value.
734
735 switch (Flags.getKind()) {
736 default:
737 llvm_unreachable("Bad flags!");
741 i += NumVals;
742 break;
746 for (; NumVals; --NumVals, ++i) {
747 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
748 if (Reg != LR)
749 continue;
750 HMFI.setHasClobberLR(true);
751 return Op;
752 }
753 break;
754 }
755 }
756 }
757
758 return Op;
759}
760
761// Need to transform ISD::PREFETCH into something that doesn't inherit
762// all of the properties of ISD::PREFETCH, specifically SDNPMayLoad and
763// SDNPMayStore.
765 SelectionDAG &DAG) const {
766 SDValue Chain = Op.getOperand(0);
767 SDValue Addr = Op.getOperand(1);
768 // Lower it to DCFETCH($reg, #0). A "pat" will try to merge the offset in,
769 // if the "reg" is fed by an "add".
770 SDLoc DL(Op);
771 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
772 return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
773}
774
776 SelectionDAG &DAG) const {
777 SDValue Chain = Op.getOperand(0);
778 unsigned IntNo = Op.getConstantOperandVal(1);
779 // Lower the hexagon_prefetch builtin to DCFETCH, as above.
780 if (IntNo == Intrinsic::hexagon_prefetch) {
781 SDValue Addr = Op.getOperand(2);
782 SDLoc DL(Op);
783 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
784 return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
785 }
786 return SDValue();
787}
788
791 SelectionDAG &DAG) const {
792 SDValue Chain = Op.getOperand(0);
793 SDValue Size = Op.getOperand(1);
794 SDValue Align = Op.getOperand(2);
795 SDLoc dl(Op);
796
798 assert(AlignConst && "Non-constant Align in LowerDYNAMIC_STACKALLOC");
799
800 unsigned A = AlignConst->getSExtValue();
801 auto &HFI = *Subtarget.getFrameLowering();
802 // "Zero" means natural stack alignment.
803 if (A == 0)
804 A = HFI.getStackAlign().value();
805
806 LLVM_DEBUG({
807 dbgs () << __func__ << " Align: " << A << " Size: ";
808 Size.getNode()->dump(&DAG);
809 dbgs() << "\n";
810 });
811
812 SDValue AC = DAG.getConstant(A, dl, MVT::i32);
813 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
814 SDValue AA = DAG.getNode(HexagonISD::ALLOCA, dl, VTs, Chain, Size, AC);
815
817 return AA;
818}
819
821 SelectionDAG &DAG) const {
822 EVT OpVT = Op.getValueType();
823 MVT SimpleVT = OpVT.getSimpleVT();
824 SDLoc DL(Op);
825
826 // Check if any of the inputs are NaN. If so, propagate the NaN
827 // to the output, otherwise return the maximum/minimum of the inputs.
828 // We can safely use ISD::FMINNUM/ISD::FMAXNUM to run
829 // Hexagon's F2_sfmin/F2_sfmax, when no operand is NaN.
830 // Note: We cannot directly compare nodes against NaN node to find NaNs,
831 // because comparing NaN with anything always returns False (except for !=0
832 // which always return True). To work around that, we compare input operands
833 // with themselves under ISD::SETUO, which only returns true if the operand is
834 // NaN.
835
836 SDValue Op1 = Op.getOperand(0);
837 SDValue Op2 = Op.getOperand(1);
838 SDValue isOp1NaN = DAG.getSetCC(DL, MVT::i1, Op1, Op1, ISD::SETUO);
839 SDValue isOp2NaN = DAG.getSetCC(DL, MVT::i1, Op2, Op2, ISD::SETUO);
840
841 switch (Op.getOpcode()) {
842 case ISD::FMAXIMUM: {
843 SDValue FmaxNode = DAG.getNode(ISD::FMAXNUM, DL, SimpleVT, Op1, Op2);
844 SDValue result =
845 DAG.getNode(ISD::SELECT, DL, SimpleVT, isOp2NaN, Op2, FmaxNode);
846 return DAG.getNode(ISD::SELECT, DL, SimpleVT, isOp1NaN, Op1, result);
847 }
848 case ISD::FMINIMUM: {
849 SDValue FminNode = DAG.getNode(ISD::FMINNUM, DL, SimpleVT, Op1, Op2);
850 SDValue result =
851 DAG.getNode(ISD::SELECT, DL, SimpleVT, isOp2NaN, Op2, FminNode);
852 return DAG.getNode(ISD::SELECT, DL, SimpleVT, isOp1NaN, Op1, result);
853 }
854 default:
855 llvm_unreachable("Invalid opcode for LowerFMINFMAX");
856 }
857}
858
860 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
861 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
862 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
864 MachineFrameInfo &MFI = MF.getFrameInfo();
866
867 // Linux ABI treats var-arg calls the same way as regular ones.
868 bool TreatAsVarArg = !Subtarget.isEnvironmentMusl() && IsVarArg;
869
870 // Assign locations to all of the incoming arguments.
872 CCState CCInfo(CallConv, TreatAsVarArg, MF, ArgLocs, *DAG.getContext());
873
874 if (!Subtarget.getCLOpts().args_min_alignment)
875 CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon_Legacy);
876 else
877 CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
878 assignVTCMStackOffsets(ArgLocs);
879
880 // For LLVM, in the case when returning a struct by value (>8byte),
881 // the first argument is a pointer that points to the location on caller's
882 // stack where the return value will be stored. For Hexagon, the location on
883 // caller's stack is passed only when the struct size is smaller than (and
884 // equal to) 8 bytes. If not, no address will be passed into callee and
885 // callee return the result directly through R0/R1.
886 auto NextSingleReg = [] (const TargetRegisterClass &RC, unsigned Reg) {
887 switch (RC.getID()) {
888 case Hexagon::IntRegsRegClassID:
889 return Reg - Hexagon::R0 + 1;
890 case Hexagon::DoubleRegsRegClassID:
891 return (Reg - Hexagon::D0 + 1) * 2;
892 case Hexagon::HvxVRRegClassID:
893 return Reg - Hexagon::V0 + 1;
894 case Hexagon::HvxWRRegClassID:
895 return (Reg - Hexagon::W0 + 1) * 2;
896 case Hexagon::HlxLRRegClassID:
897 return Reg - Hexagon::L0 + 1;
898 case Hexagon::HlxLLRRegClassID:
899 return (Reg - Hexagon::LL0 + 1) * 2;
900 }
901 llvm_unreachable("Unexpected register class");
902 };
903
904 auto &HFL = const_cast<HexagonFrameLowering&>(*Subtarget.getFrameLowering());
905 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
906 HFL.FirstVarArgSavedReg = 0;
908
909 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
910 CCValAssign &VA = ArgLocs[i];
911 ISD::ArgFlagsTy Flags = Ins[i].Flags;
912 bool ByVal = Flags.isByVal();
913
914 // Arguments passed in registers:
915 // 1. 32- and 64-bit values and HVX/HLX vectors are passed directly,
916 // 2. Large structs are passed via an address, and the address is
917 // passed in a register.
918 if (VA.isRegLoc() && ByVal && Flags.getByValSize() <= 8)
919 llvm_unreachable("ByValSize must be bigger than 8 bytes");
920
921 bool InReg = VA.isRegLoc() &&
922 (!ByVal || (ByVal && Flags.getByValSize() > 8));
923
924 if (InReg) {
925 MVT RegVT = VA.getLocVT();
926 if (VA.getLocInfo() == CCValAssign::BCvt)
927 RegVT = VA.getValVT();
928
929 const TargetRegisterClass *RC = getRegClassFor(RegVT);
930 Register VReg = MRI.createVirtualRegister(RC);
931 SDValue Copy = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
932
933 // Treat values of type MVT::i1 specially: they are passed in
934 // registers of type i32, but they need to remain as values of
935 // type i1 for consistency of the argument lowering.
936 if (VA.getValVT() == MVT::i1) {
937 assert(RegVT.getSizeInBits() <= 32);
938 SDValue T = DAG.getNode(ISD::AND, dl, RegVT,
939 Copy, DAG.getConstant(1, dl, RegVT));
940 Copy = DAG.getSetCC(dl, MVT::i1, T, DAG.getConstant(0, dl, RegVT),
941 ISD::SETNE);
942 } else {
943#ifndef NDEBUG
944 unsigned RegSize = RegVT.getSizeInBits();
945 assert(RegSize == 32 || RegSize == 64 ||
946 Subtarget.isHVXVectorType(RegVT) ||
947 Subtarget.isHLXVectorType(RegVT));
948#endif
949 }
950 InVals.push_back(Copy);
951 MRI.addLiveIn(VA.getLocReg(), VReg);
952 HFL.FirstVarArgSavedReg = NextSingleReg(*RC, VA.getLocReg());
953 } else {
954 assert(VA.isMemLoc() && "Argument should be passed in memory");
955
956 // If it's a byval parameter, then we need to compute the
957 // "real" size, not the size of the pointer.
958 unsigned ObjSize = Flags.isByVal()
959 ? Flags.getByValSize()
960 : VA.getLocVT().getStoreSizeInBits() / 8;
961
962 // Create the frame index object for this incoming parameter. HLX
963 // arguments are in the caller's VTCM argument area, not on the scalar
964 // stack. Mark them NoAlloc so that the scalar frame layout skips them;
965 // computeVTCMStackOffsets moves every NoAlloc fixed object to the VTCM
966 // frame. Hexagon uses NoAlloc only for these objects.
967 int Offset = VA.needsCustom() ? VA.getLocMemOffset()
969 int FI = MFI.CreateFixedObject(ObjSize, Offset, true);
970 if (VA.needsCustom())
972 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
973
974 if (Flags.isByVal()) {
975 // If it's a pass-by-value aggregate, then do not dereference the stack
976 // location. Instead, we should generate a reference to the stack
977 // location.
978 InVals.push_back(FIN);
979 } else if (isHlxPairTy(VA.getValVT())) {
980 InVals.push_back(
981 splitHlxPairArgLoad(DAG, dl, Chain, FIN, VA.getValVT(),
983 } else {
984 SDValue L = DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
986 InVals.push_back(L);
987 }
988 }
989 }
990
991 if (IsVarArg && Subtarget.isEnvironmentMusl()) {
992 for (int i = HFL.FirstVarArgSavedReg; i < 6; i++)
993 MRI.addLiveIn(Hexagon::R0+i);
994 }
995
996 if (IsVarArg && Subtarget.isEnvironmentMusl()) {
997 HMFI.setFirstNamedArgFrameIndex(HMFI.getFirstNamedArgFrameIndex() - 1);
998 HMFI.setLastNamedArgFrameIndex(-int(MFI.getNumFixedObjects()));
999
1000 // Create Frame index for the start of register saved area.
1001 int NumVarArgRegs = 6 - HFL.FirstVarArgSavedReg;
1002 bool RequiresPadding = (NumVarArgRegs & 1);
1003 int RegSaveAreaSizePlusPadding = RequiresPadding
1004 ? (NumVarArgRegs + 1) * 4
1005 : NumVarArgRegs * 4;
1006
1007 if (RegSaveAreaSizePlusPadding > 0) {
1008 // The offset to saved register area should be 8 byte aligned.
1009 int RegAreaStart = HEXAGON_LRFP_SIZE + CCInfo.getStackSize();
1010 if (!(RegAreaStart % 8))
1011 RegAreaStart = (RegAreaStart + 7) & -8;
1012
1013 int RegSaveAreaFrameIndex =
1014 MFI.CreateFixedObject(RegSaveAreaSizePlusPadding, RegAreaStart, true);
1015 HMFI.setRegSavedAreaStartFrameIndex(RegSaveAreaFrameIndex);
1016
1017 // This will point to the next argument passed via stack.
1018 int Offset = RegAreaStart + RegSaveAreaSizePlusPadding;
1019 int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
1020 HMFI.setVarArgsFrameIndex(FI);
1021 } else {
1022 // This will point to the next argument passed via stack, when
1023 // there is no saved register area.
1024 int Offset = HEXAGON_LRFP_SIZE + CCInfo.getStackSize();
1025 int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
1026 HMFI.setRegSavedAreaStartFrameIndex(FI);
1027 HMFI.setVarArgsFrameIndex(FI);
1028 }
1029 }
1030
1031
1032 if (IsVarArg && !Subtarget.isEnvironmentMusl()) {
1033 // This will point to the next argument passed via stack.
1034 int Offset = HEXAGON_LRFP_SIZE + CCInfo.getStackSize();
1035 int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
1036 HMFI.setVarArgsFrameIndex(FI);
1037 }
1038
1039 return Chain;
1040}
1041
1042SDValue
1044 // VASTART stores the address of the VarArgsFrameIndex slot into the
1045 // memory location argument.
1048 SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
1049 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1050
1051 if (!Subtarget.isEnvironmentMusl()) {
1052 return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr, Op.getOperand(1),
1053 MachinePointerInfo(SV));
1054 }
1055 auto &FuncInfo = *MF.getInfo<HexagonMachineFunctionInfo>();
1056 auto &HFL = *Subtarget.getFrameLowering();
1057 SDLoc DL(Op);
1059
1060 // Get frame index of va_list.
1061 SDValue FIN = Op.getOperand(1);
1062
1063 // If first Vararg register is odd, add 4 bytes to start of
1064 // saved register area to point to the first register location.
1065 // This is because the saved register area has to be 8 byte aligned.
1066 // In case of an odd start register, there will be 4 bytes of padding in
1067 // the beginning of saved register area. If all registers area used up,
1068 // the following condition will handle it correctly.
1069 SDValue SavedRegAreaStartFrameIndex =
1070 DAG.getFrameIndex(FuncInfo.getRegSavedAreaStartFrameIndex(), MVT::i32);
1071
1072 auto PtrVT = getPointerTy(DAG.getDataLayout());
1073
1074 if (HFL.FirstVarArgSavedReg & 1)
1075 SavedRegAreaStartFrameIndex =
1076 DAG.getNode(ISD::ADD, DL, PtrVT,
1077 DAG.getFrameIndex(FuncInfo.getRegSavedAreaStartFrameIndex(),
1078 MVT::i32),
1079 DAG.getIntPtrConstant(4, DL));
1080
1081 // Store the saved register area start pointer.
1082 SDValue Store =
1083 DAG.getStore(Op.getOperand(0), DL,
1084 SavedRegAreaStartFrameIndex,
1085 FIN, MachinePointerInfo(SV));
1086 MemOps.push_back(Store);
1087
1088 // Store saved register area end pointer.
1089 FIN = DAG.getNode(ISD::ADD, DL, PtrVT,
1090 FIN, DAG.getIntPtrConstant(4, DL));
1091 Store = DAG.getStore(Op.getOperand(0), DL,
1092 DAG.getFrameIndex(FuncInfo.getVarArgsFrameIndex(),
1093 PtrVT),
1094 FIN, MachinePointerInfo(SV, 4));
1095 MemOps.push_back(Store);
1096
1097 // Store overflow area pointer.
1098 FIN = DAG.getNode(ISD::ADD, DL, PtrVT,
1099 FIN, DAG.getIntPtrConstant(4, DL));
1100 Store = DAG.getStore(Op.getOperand(0), DL,
1101 DAG.getFrameIndex(FuncInfo.getVarArgsFrameIndex(),
1102 PtrVT),
1103 FIN, MachinePointerInfo(SV, 8));
1104 MemOps.push_back(Store);
1105
1106 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1107}
1108
1109SDValue
1111 // Assert that the linux ABI is enabled for the current compilation.
1112 assert(Subtarget.isEnvironmentMusl() && "Linux ABI should be enabled");
1113 SDValue Chain = Op.getOperand(0);
1114 SDValue DestPtr = Op.getOperand(1);
1115 SDValue SrcPtr = Op.getOperand(2);
1116 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
1117 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
1118 SDLoc DL(Op);
1119 // Size of the va_list is 12 bytes as it has 3 pointers. Therefore,
1120 // we need to memcopy 12 bytes from va_list to another similar list.
1121 return DAG.getMemcpy(Chain, DL, DestPtr, SrcPtr,
1122 DAG.getIntPtrConstant(12, DL), Align(4), Align(4),
1123 /*isVolatile*/ false, false, /*CI=*/nullptr,
1124 std::nullopt, MachinePointerInfo(DestSV),
1125 MachinePointerInfo(SrcSV));
1126}
1127
1129 const SDLoc &dl(Op);
1130 SDValue LHS = Op.getOperand(0);
1131 SDValue RHS = Op.getOperand(1);
1132 ISD::CondCode CC = Op.getOperandCondCode(2);
1133 MVT ResTy = ty(Op);
1134 MVT OpTy = ty(LHS);
1135
1136 if (OpTy == MVT::v2i16 || OpTy == MVT::v4i8) {
1137 assert(OpTy.getVectorElementType().isScalarInteger());
1138 MVT WideTy = OpTy.widenIntegerElementType();
1139 return DAG.getSetCC(dl, ResTy,
1140 DAG.getSExtOrTrunc(LHS, SDLoc(LHS), WideTy),
1141 DAG.getSExtOrTrunc(RHS, SDLoc(RHS), WideTy), CC);
1142 }
1143
1144 // Treat all other vector types as legal.
1145 if (ResTy.isVector())
1146 return Op;
1147
1148 // Equality comparisons of short integers should use sign-extend, not
1149 // zero-extend, since we can represent small negative values in the compare
1150 // instructions. The LLVM default is to use zero-extend arbitrarily in
1151 // these cases.
1152 auto isSExtFree = [this](SDValue N) {
1153 switch (N.getOpcode()) {
1154 case ISD::TRUNCATE: {
1155 // A sign-extend of a truncate of a sign-extend is free.
1156 SDValue Op = N.getOperand(0);
1157 if (Op.getOpcode() != ISD::AssertSext)
1158 return false;
1159 EVT OrigTy = cast<VTSDNode>(Op.getOperand(1))->getVT();
1160 unsigned ThisBW = ty(N).getSizeInBits();
1161 unsigned OrigBW = OrigTy.getSizeInBits();
1162 // The type that was sign-extended to get the AssertSext must be
1163 // narrower than the type of N (so that N has still the same value
1164 // as the original).
1165 return ThisBW >= OrigBW;
1166 }
1167 case ISD::LOAD:
1168 // We have sign-extended loads.
1169 return true;
1170 }
1171 return false;
1172 };
1173
1174 // Only do this for equality comparisons. Signed comparisons are already
1175 // sign-extended by the generic operand promotion, and for unsigned
1176 // comparisons a sign-extension is never profitable: it does not change the
1177 // result (sign-extension preserves the unsigned ordering of the values of
1178 // the narrower type), but it turns constants with the sign bit of the
1179 // narrower type set into large 32-bit values, which then have to be
1180 // materialized in a register or use a constant extender.
1181 if ((OpTy == MVT::i8 || OpTy == MVT::i16) && ISD::isIntEqualitySetCC(CC)) {
1183 bool IsNegative = C && C->getAPIntValue().isNegative();
1184 if (IsNegative || isSExtFree(LHS) || isSExtFree(RHS))
1185 return DAG.getSetCC(dl, ResTy,
1186 DAG.getSExtOrTrunc(LHS, SDLoc(LHS), MVT::i32),
1187 DAG.getSExtOrTrunc(RHS, SDLoc(RHS), MVT::i32), CC);
1188 }
1189
1190 return SDValue();
1191}
1192
1193SDValue
1195 SDValue PredOp = Op.getOperand(0);
1196 SDValue Op1 = Op.getOperand(1), Op2 = Op.getOperand(2);
1197 MVT OpTy = ty(Op1);
1198 const SDLoc &dl(Op);
1199
1200 if (OpTy == MVT::v2i16 || OpTy == MVT::v4i8) {
1201 assert(OpTy.getVectorElementType().isScalarInteger());
1202 MVT WideTy = OpTy.widenIntegerElementType();
1203 // Generate (trunc (select (_, sext, sext))).
1204 return DAG.getSExtOrTrunc(
1205 DAG.getSelect(dl, WideTy, PredOp,
1206 DAG.getSExtOrTrunc(Op1, dl, WideTy),
1207 DAG.getSExtOrTrunc(Op2, dl, WideTy)),
1208 dl, OpTy);
1209 }
1210
1211 return SDValue();
1212}
1213
1214// Lower SELECT with a scalar condition and a predicate-vector result.
1215// Such a vector cannot be promoted to a vector of i32 the way the wider vector
1216// types are, because v2i1/v4i1/v8i1 are only 2/4/8 bits wide.
1218 SelectionDAG &DAG) const {
1219 MVT ResTy = ty(Op);
1220 if (ResTy != MVT::v2i1 && ResTy != MVT::v4i1 && ResTy != MVT::v8i1)
1221 return SDValue();
1222
1223 const SDLoc &dl(Op);
1224 // Each of these vectors occupies all 8 bits of a predicate register, with
1225 // every element repeated over 8/NumElts of them (see extractVectorPred).
1226 // The condition is a scalar, so the same source is picked for every element
1227 // and the whole 8-bit pattern can be selected at once -- no per-element mask
1228 // arithmetic is needed here, unlike in LowerBUILD_VECTOR. Move both
1229 // predicates into general-purpose registers, select there, and move the
1230 // result back, as insertVectorPred does.
1231 SDValue T =
1232 getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {Op.getOperand(1)}, DAG);
1233 SDValue F =
1234 getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {Op.getOperand(2)}, DAG);
1235 SDValue S = DAG.getSelect(dl, MVT::i32, Op.getOperand(0), T, F);
1236 return getInstr(Hexagon::C2_tfrrp, dl, ResTy, {S}, DAG);
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
1574 if (ST.getCLOpts().sdnode_sched)
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 (ST.getCLOpts().emit_jump_tables)
1667 setMinimumJumpTableEntries(ST.getCLOpts().minimum_jump_tables);
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 inputs to SELECT to be vectors of i32 if the vector is an
1802 // exact, non-zero multiple of 32 bits wide. For anything narrower the
1803 // element count below truncates to zero and MVT::getVectorVT would
1804 // build an invalid type. The types that actually reach this are the
1805 // vXi1 predicate vectors (v2i1/v4i1/v8i1); they are given a Custom
1806 // action further down.
1807 if (VT.getVectorElementType() != MVT::i32) {
1808 unsigned Width = VT.getSizeInBits();
1809 if (Width >= 32 && Width % 32 == 0) {
1810 MVT VT32 = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
1812 AddPromotedToType(ISD::SELECT, VT, VT32);
1813 } else {
1815 }
1816 }
1820 }
1821
1824
1825 // Extending loads from (native) vectors of i8 into (native) vectors of i16
1826 // are legal.
1827 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1828 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1829 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1830 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1831 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1832 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1833
1837
1838 // Types natively supported:
1839 for (MVT NativeVT : {MVT::v8i1, MVT::v4i1, MVT::v2i1, MVT::v4i8,
1840 MVT::v8i8, MVT::v2i16, MVT::v4i16, MVT::v2i32}) {
1847
1848 setOperationAction(ISD::ADD, NativeVT, Legal);
1849 setOperationAction(ISD::SUB, NativeVT, Legal);
1850 setOperationAction(ISD::MUL, NativeVT, Legal);
1851 setOperationAction(ISD::AND, NativeVT, Legal);
1852 setOperationAction(ISD::OR, NativeVT, Legal);
1853 setOperationAction(ISD::XOR, NativeVT, Legal);
1854
1855 if (NativeVT.getVectorElementType() != MVT::i1) {
1859 } else {
1860 // A predicate vector is too narrow to promote SELECT to a vector of i32
1861 // (see above), so lower it directly.
1863 }
1864 }
1865
1866 for (MVT VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32}) {
1871 }
1872
1873 // Custom lower unaligned loads.
1874 // Also, for both loads and stores, verify the alignment of the address
1875 // in case it is a compile-time constant. This is a usability feature to
1876 // provide a meaningful error message to users.
1877 for (MVT VT : {MVT::i16, MVT::i32, MVT::v4i8, MVT::i64, MVT::v8i8,
1878 MVT::v2i16, MVT::v4i16, MVT::v2i32}) {
1881 }
1882
1883 // Custom-lower load/stores of boolean vectors.
1884 for (MVT VT : {MVT::v2i1, MVT::v4i1, MVT::v8i1}) {
1887 }
1888
1889 // Normalize integer compares to EQ/GT/UGT
1890 for (MVT VT : {MVT::v2i16, MVT::v4i8, MVT::v8i8, MVT::v2i32, MVT::v4i16,
1891 MVT::v2i32}) {
1899 }
1900
1901 // Normalize boolean compares to [U]LE/[U]LT
1902 for (MVT VT : {MVT::i1, MVT::v2i1, MVT::v4i1, MVT::v8i1}) {
1907 }
1908
1909 // Custom-lower bitcasts from i8 to v8i1.
1911 setOperationAction(ISD::SETCC, MVT::v2i16, Custom);
1917
1918 // V5+.
1924
1933
1946
1947 // Special handling for half-precision floating point conversions.
1948 // Lower half float conversions into library calls.
1956
1957 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
1958 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
1959 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::bf16, Expand);
1960 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::bf16, Expand);
1961
1962 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1963 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1964
1965 // Handling of indexed loads/stores: default is "expand".
1966 //
1967 for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64, MVT::f32, MVT::f64,
1968 MVT::v2i16, MVT::v2i32, MVT::v4i8, MVT::v4i16, MVT::v8i8}) {
1971 }
1972
1973 // Subtarget-specific operation actions.
1974 //
1975 if (Subtarget.hasV60Ops()) {
1980 }
1981 if (Subtarget.hasV66Ops()) {
1984 }
1985 if (Subtarget.hasV67Ops()) {
1991 }
1992
1996
1997 if (Subtarget.useHVXOps())
1998 initializeHVXLowering();
1999
2000 if (Subtarget.useHLXOps())
2001 initializeHLXLowering();
2002
2004}
2005
2006bool
2007HexagonTargetLowering::validateConstPtrAlignment(SDValue Ptr, Align NeedAlign,
2008 const SDLoc &dl, SelectionDAG &DAG) const {
2009 auto *CA = dyn_cast<ConstantSDNode>(Ptr);
2010 if (!CA)
2011 return true;
2012 unsigned Addr = CA->getZExtValue();
2013 Align HaveAlign =
2014 Addr != 0 ? Align::fromLog2(llvm::countr_zero(Addr)) : NeedAlign;
2015 if (HaveAlign >= NeedAlign)
2016 return true;
2017
2018 static int DK_MisalignedTrap = llvm::getNextAvailablePluginDiagnosticKind();
2019
2020 struct DiagnosticInfoMisalignedTrap : public DiagnosticInfo {
2021 DiagnosticInfoMisalignedTrap(StringRef M)
2022 : DiagnosticInfo(DK_MisalignedTrap, DS_Remark), Msg(M) {}
2023 void print(DiagnosticPrinter &DP) const override {
2024 DP << Msg;
2025 }
2026 static bool classof(const DiagnosticInfo *DI) {
2027 return DI->getKind() == DK_MisalignedTrap;
2028 }
2029 StringRef Msg;
2030 };
2031
2032 std::string ErrMsg;
2033 raw_string_ostream O(ErrMsg);
2034 O << "Misaligned constant address: " << format_hex(Addr, 10)
2035 << " has alignment " << HaveAlign.value()
2036 << ", but the memory access requires " << NeedAlign.value();
2037 if (DebugLoc DL = dl.getDebugLoc())
2038 DL.print(O << ", at ");
2039 O << ". The instruction has been replaced with a trap.";
2040
2041 DAG.getContext()->diagnose(DiagnosticInfoMisalignedTrap(O.str()));
2042 return false;
2043}
2044
2045SDValue
2046HexagonTargetLowering::replaceMemWithUndef(SDValue Op, SelectionDAG &DAG)
2047 const {
2048 const SDLoc &dl(Op);
2049 auto *LS = cast<LSBaseSDNode>(Op.getNode());
2050 assert(!LS->isIndexed() && "Not expecting indexed ops on constant address");
2051
2052 SDValue Chain = LS->getChain();
2053 SDValue Trap = DAG.getNode(ISD::TRAP, dl, MVT::Other, Chain);
2054 if (LS->getOpcode() == ISD::LOAD)
2055 return DAG.getMergeValues({DAG.getUNDEF(ty(Op)), Trap}, dl);
2056 return Trap;
2057}
2058
2059// Bit-reverse Load Intrinsic: Check if the instruction is a bit reverse load
2060// intrinsic.
2061static bool isBrevLdIntrinsic(const Value *Inst) {
2062 unsigned ID = cast<IntrinsicInst>(Inst)->getIntrinsicID();
2063 return (ID == Intrinsic::hexagon_L2_loadrd_pbr ||
2064 ID == Intrinsic::hexagon_L2_loadri_pbr ||
2065 ID == Intrinsic::hexagon_L2_loadrh_pbr ||
2066 ID == Intrinsic::hexagon_L2_loadruh_pbr ||
2067 ID == Intrinsic::hexagon_L2_loadrb_pbr ||
2068 ID == Intrinsic::hexagon_L2_loadrub_pbr);
2069}
2070
2071// Bit-reverse Load Intrinsic :Crawl up and figure out the object from previous
2072// instruction. So far we only handle bitcast, extract value and bit reverse
2073// load intrinsic instructions. Should we handle CGEP ?
2075 if (Operator::getOpcode(V) == Instruction::ExtractValue ||
2076 Operator::getOpcode(V) == Instruction::BitCast)
2077 V = cast<Operator>(V)->getOperand(0);
2079 V = cast<Instruction>(V)->getOperand(0);
2080 return V;
2081}
2082
2083// Bit-reverse Load Intrinsic: For a PHI Node return either an incoming edge or
2084// a back edge. If the back edge comes from the intrinsic itself, the incoming
2085// edge is returned.
2086static Value *returnEdge(const PHINode *PN, Value *IntrBaseVal) {
2087 const BasicBlock *Parent = PN->getParent();
2088 int Idx = -1;
2089 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
2090 BasicBlock *Blk = PN->getIncomingBlock(i);
2091 // Determine if the back edge is originated from intrinsic.
2092 if (Blk == Parent) {
2093 Value *BackEdgeVal = PN->getIncomingValue(i);
2094 Value *BaseVal;
2095 // Loop over till we return the same Value or we hit the IntrBaseVal.
2096 do {
2097 BaseVal = BackEdgeVal;
2098 BackEdgeVal = getBrevLdObject(BackEdgeVal);
2099 } while ((BaseVal != BackEdgeVal) && (IntrBaseVal != BackEdgeVal));
2100 // If the getBrevLdObject returns IntrBaseVal, we should return the
2101 // incoming edge.
2102 if (IntrBaseVal == BackEdgeVal)
2103 continue;
2104 Idx = i;
2105 break;
2106 } else // Set the node to incoming edge.
2107 Idx = i;
2108 }
2109 assert(Idx >= 0 && "Unexpected index to incoming argument in PHI");
2110 return PN->getIncomingValue(Idx);
2111}
2112
2113// Bit-reverse Load Intrinsic: Figure out the underlying object the base
2114// pointer points to, for the bit-reverse load intrinsic. Setting this to
2115// memoperand might help alias analysis to figure out the dependencies.
2116// A bit-reverse load accesses the base pointer with its low 16 bits reversed,
2117// and post-increments the base pointer by the modifier value. For a chain of
2118// bit-reverse loads, the offset that a load accesses relative to the
2119// underlying object is the bit-reverse of the sum of the modifiers of the
2120// preceding loads in the chain. Offset is set to that value, and HasOffset is
2121// set to true, when the sum is known, that is when all of those modifiers are
2122// constants and the sum fits in 16 unsigned bits. Otherwise HasOffset is set
2123// to false and Offset is left unchanged.
2125 bool &HasOffset) {
2126 Value *IntrBaseVal = V;
2127 Value *BaseVal;
2128 int64_t Sum = 0;
2129 HasOffset = true;
2130 // Loop over till we return the same Value, implies we either figure out
2131 // the object or we hit a PHI
2132 do {
2133 BaseVal = V;
2134 V = getBrevLdObject(V);
2135 // Identify if this is part of a chain of bit-reverse loads, and accumulate
2136 // the modifier of the preceding load in the chain.
2137 if (HasOffset && BaseVal != V && isa<IntrinsicInst>(V) &&
2139 Value *Modifier = cast<IntrinsicInst>(V)->getOperand(1);
2140 if (auto *CN = dyn_cast<ConstantInt>(Modifier))
2141 Sum += CN->getSExtValue();
2142 else
2143 HasOffset = false;
2144 }
2145 } while (BaseVal != V);
2146
2147 // Only the low 16 bits of the base pointer take part in the bit-reverse. A
2148 // sum that does not fit in them would also change the remaining bits.
2149 if (HasOffset && Sum >= 0 && isUInt<16>(Sum))
2150 Offset = APInt(16, Sum).reverseBits().getZExtValue();
2151 else
2152 HasOffset = false;
2153
2154 // Identify the object from PHINode.
2155 if (const PHINode *PN = dyn_cast<PHINode>(V))
2156 return returnEdge(PN, IntrBaseVal);
2157 // For non PHI nodes, the object is the last value returned by getBrevLdObject
2158 else
2159 return V;
2160}
2161
2162/// Infer IntrinsicInfo for an HLX memory intrinsic from its IR signature.
2163/// Loads return a vector type; stores have a void return and pass the vector
2164/// as an argument.
2166 const HexagonSubtarget &ST,
2168 Type *RetTy = I.getCalledFunction()->getReturnType();
2169 bool IsLoad = RetTy->isVectorTy();
2170 Type *VecTy = IsLoad ? RetTy : I.getArgOperand(1)->getType();
2171 assert(VecTy->isVectorTy() && ST.isHLXVectorType(MVT::getVT(VecTy)) &&
2172 "Expected HLX vector type in HLX intrinsic");
2173
2174 Info.opc = IsLoad ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID;
2175 Info.memVT = MVT::getVT(VecTy);
2176 Info.ptrVal = I.getArgOperand(0);
2177 Info.offset = 0;
2178 Info.align = Align(ST.getHLXVectorLength());
2180}
2181
2182/// Given an intrinsic, checks if on the target the intrinsic will need to map
2183/// to a MemIntrinsicNode (touches memory). If this is the case, it stores
2184/// the intrinsic information into the Infos vector.
2187 MachineFunction &MF, unsigned Intrinsic) const {
2188 IntrinsicInfo Info;
2189 switch (Intrinsic) {
2190 case Intrinsic::hexagon_LX_L16b_tmp:
2191 case Intrinsic::hexagon_LX_LL16b_tmp:
2192 case Intrinsic::hexagon_LX_S16b_new:
2193 case Intrinsic::hexagon_LX_SS16b_new:
2194 getHlxMemIntrinsicInfo(I, Subtarget, Info);
2195 Infos.push_back(Info);
2196 return;
2197 case Intrinsic::hexagon_L2_loadrd_pbr:
2198 case Intrinsic::hexagon_L2_loadri_pbr:
2199 case Intrinsic::hexagon_L2_loadrh_pbr:
2200 case Intrinsic::hexagon_L2_loadruh_pbr:
2201 case Intrinsic::hexagon_L2_loadrb_pbr:
2202 case Intrinsic::hexagon_L2_loadrub_pbr: {
2203 Info.opc = ISD::INTRINSIC_W_CHAIN;
2204 auto &DL = I.getDataLayout();
2205 auto &Cont = I.getCalledFunction()->getParent()->getContext();
2206 // The intrinsic function call is of the form { ElTy, i8* }
2207 // @llvm.hexagon.L2.loadXX.pbr(i8*, i32). The pointer and memory access type
2208 // should be derived from ElTy.
2209 Type *ElTy = I.getCalledFunction()->getReturnType()->getStructElementType(0);
2210 Info.memVT = MVT::getVT(ElTy);
2211 llvm::Value *BasePtrVal = I.getOperand(0);
2212 // The offset value comes through the Modifier register. Determine the
2213 // offset that is going to be accessed relative to the underlying object.
2214 // If it cannot be determined, leave the pointer information out of the
2215 // memory operand, so that alias analysis stays conservative.
2216 bool HasOffset = false;
2217 Info.offset = 0;
2218 Value *UnderlyingObj =
2219 getUnderLyingObjectForBrevLdIntr(BasePtrVal, Info.offset, HasOffset);
2220 // The underlying object is unknown if the base pointer could not be traced
2221 // back to a pointer value. Also, unless the object is aligned to 64K, the
2222 // low 16 bits of the base pointer are not known, and reversing them can
2223 // produce an address anywhere in the surrounding 64K region, possibly
2224 // outside of the object.
2225 if (!UnderlyingObj->getType()->isPointerTy() ||
2226 UnderlyingObj->getPointerAlignment(DL) < Align(65536))
2227 HasOffset = false;
2228 if (HasOffset)
2229 Info.ptrVal = UnderlyingObj;
2230 Info.align = DL.getABITypeAlign(Info.memVT.getTypeForEVT(Cont));
2231 Info.flags = MachineMemOperand::MOLoad;
2232 Infos.push_back(Info);
2233 return;
2234 }
2235 case Intrinsic::hexagon_V6_vgathermw:
2236 case Intrinsic::hexagon_V6_vgathermw_128B:
2237 case Intrinsic::hexagon_V6_vgathermh:
2238 case Intrinsic::hexagon_V6_vgathermh_128B:
2239 case Intrinsic::hexagon_V6_vgathermhw:
2240 case Intrinsic::hexagon_V6_vgathermhw_128B:
2241 case Intrinsic::hexagon_V6_vgathermwq:
2242 case Intrinsic::hexagon_V6_vgathermwq_128B:
2243 case Intrinsic::hexagon_V6_vgathermhq:
2244 case Intrinsic::hexagon_V6_vgathermhq_128B:
2245 case Intrinsic::hexagon_V6_vgathermhwq:
2246 case Intrinsic::hexagon_V6_vgathermhwq_128B:
2247 case Intrinsic::hexagon_V6_vgather_vscattermh:
2248 case Intrinsic::hexagon_V6_vgather_vscattermh_128B: {
2249 const Module &M = *I.getParent()->getParent()->getParent();
2250 Info.opc = ISD::INTRINSIC_W_CHAIN;
2251 Type *VecTy = I.getArgOperand(I.arg_size() - 1)->getType();
2252 assert(VecTy->isVectorTy() && "Expected vector operand for vgather");
2253 Info.memVT = MVT::getVT(VecTy);
2254 Info.ptrVal = I.getArgOperand(0);
2255 Info.offset = 0;
2256 Info.align =
2257 MaybeAlign(M.getDataLayout().getTypeAllocSizeInBits(VecTy) / 8);
2260 Infos.push_back(Info);
2261 return;
2262 }
2263 default:
2264 break;
2265 }
2266}
2267
2269 return X.getValueType().isScalarInteger(); // 'tstbit'
2270}
2271
2273 return isTruncateFree(EVT::getEVT(Ty1), EVT::getEVT(Ty2));
2274}
2275
2277 if (!VT1.isSimple() || !VT2.isSimple())
2278 return false;
2279 return VT1.getSimpleVT() == MVT::i64 && VT2.getSimpleVT() == MVT::i32;
2280}
2281
2286
2287// Should we expand the build vector with shuffles?
2289 unsigned DefinedValues) const {
2290 return false;
2291}
2292
2295 unsigned Index) const {
2297 if (!ResVT.isSimple() || !SrcVT.isSimple())
2299
2300 MVT ResTy = ResVT.getSimpleVT(), SrcTy = SrcVT.getSimpleVT();
2301 if (ResTy.getVectorElementType() != MVT::i1)
2303
2304 // Non-HVX bool vectors are relatively cheap.
2305 if (SrcTy.getVectorNumElements() <= 8)
2308}
2309
2314
2316 EVT VT) const {
2317 return true;
2318}
2319
2322 unsigned VecLen = VT.getVectorMinNumElements();
2324
2325 if (VecLen == 1 || VT.isScalableVector())
2327
2328 if (Subtarget.useHVXOps()) {
2329 unsigned Action = getPreferredHvxVectorAction(VT);
2330 if (Action != ~0u)
2331 return static_cast<TargetLoweringBase::LegalizeTypeAction>(Action);
2332 }
2333
2334 // Always widen (remaining) vectors of i1.
2335 if (ElemTy == MVT::i1)
2337 // Widen non-power-of-2 vectors. Such types cannot be split right now,
2338 // and computeRegisterProperties will override "split" with "widen",
2339 // which can cause other issues.
2340 if (!isPowerOf2_32(VecLen))
2342
2344}
2345
2348 if (Subtarget.useHVXOps()) {
2349 unsigned Action = getCustomHvxOperationAction(Op);
2350 if (Action != ~0u)
2351 return static_cast<TargetLoweringBase::LegalizeAction>(Action);
2352 }
2354}
2355
2356std::pair<SDValue, int>
2357HexagonTargetLowering::getBaseAndOffset(SDValue Addr) const {
2358 if (Addr.getOpcode() == ISD::ADD) {
2359 SDValue Op1 = Addr.getOperand(1);
2360 if (auto *CN = dyn_cast<const ConstantSDNode>(Op1.getNode()))
2361 return { Addr.getOperand(0), CN->getSExtValue() };
2362 }
2363 return { Addr, 0 };
2364}
2365
2366// Lower a vector shuffle (V1, V2, V3). V1 and V2 are the two vectors
2367// to select data from, V3 is the permutation.
2368SDValue
2370 const {
2371 const auto *SVN = cast<ShuffleVectorSDNode>(Op);
2372 ArrayRef<int> AM = SVN->getMask();
2373 assert(AM.size() <= 8 && "Unexpected shuffle mask");
2374 unsigned VecLen = AM.size();
2375
2376 MVT VecTy = ty(Op);
2377 assert(!Subtarget.isHVXVectorType(VecTy, true) &&
2378 "HVX shuffles should be legal");
2379 assert(VecTy.getSizeInBits() <= 64 && "Unexpected vector length");
2380
2381 SDValue Op0 = Op.getOperand(0);
2382 SDValue Op1 = Op.getOperand(1);
2383 const SDLoc &dl(Op);
2384
2385 // If the inputs are not the same as the output, bail. This is not an
2386 // error situation, but complicates the handling and the default expansion
2387 // (into BUILD_VECTOR) should be adequate.
2388 if (ty(Op0) != VecTy || ty(Op1) != VecTy)
2389 return SDValue();
2390
2391 // Normalize the mask so that the first non-negative index comes from
2392 // the first operand.
2393 SmallVector<int, 8> Mask(AM);
2394 unsigned F = llvm::find_if(AM, [](int M) { return M >= 0; }) - AM.data();
2395 if (F == AM.size())
2396 return DAG.getUNDEF(VecTy);
2397 if (AM[F] >= int(VecLen)) {
2399 std::swap(Op0, Op1);
2400 }
2401
2402 // Express the shuffle mask in terms of bytes.
2403 SmallVector<int,8> ByteMask;
2404 unsigned ElemBytes = VecTy.getVectorElementType().getSizeInBits() / 8;
2405 for (int M : Mask) {
2406 if (M < 0) {
2407 for (unsigned j = 0; j != ElemBytes; ++j)
2408 ByteMask.push_back(-1);
2409 } else {
2410 for (unsigned j = 0; j != ElemBytes; ++j)
2411 ByteMask.push_back(M*ElemBytes + j);
2412 }
2413 }
2414 assert(ByteMask.size() <= 8);
2415
2416 // All non-undef (non-negative) indexes are well within [0..127], so they
2417 // fit in a single byte. Build two 64-bit words:
2418 // - MaskIdx where each byte is the corresponding index (for non-negative
2419 // indexes), and 0xFF for negative indexes, and
2420 // - MaskUnd that has 0xFF for each negative index.
2421 uint64_t MaskIdx = 0;
2422 uint64_t MaskUnd = 0;
2423 for (unsigned i = 0, e = ByteMask.size(); i != e; ++i) {
2424 unsigned S = 8*i;
2425 uint64_t M = ByteMask[i] & 0xFF;
2426 if (M == 0xFF)
2427 MaskUnd |= M << S;
2428 MaskIdx |= M << S;
2429 }
2430
2431 if (ByteMask.size() == 4) {
2432 // Identity.
2433 if (MaskIdx == (0x03020100 | MaskUnd))
2434 return Op0;
2435 // Byte swap.
2436 if (MaskIdx == (0x00010203 | MaskUnd)) {
2437 SDValue T0 = DAG.getBitcast(MVT::i32, Op0);
2438 SDValue T1 = DAG.getNode(ISD::BSWAP, dl, MVT::i32, T0);
2439 return DAG.getBitcast(VecTy, T1);
2440 }
2441
2442 // Byte packs.
2443 SDValue Concat10 =
2444 getCombine(Op1, Op0, dl, typeJoin({ty(Op1), ty(Op0)}), DAG);
2445 if (MaskIdx == (0x06040200 | MaskUnd))
2446 return getInstr(Hexagon::S2_vtrunehb, dl, VecTy, {Concat10}, DAG);
2447 if (MaskIdx == (0x07050301 | MaskUnd))
2448 return getInstr(Hexagon::S2_vtrunohb, dl, VecTy, {Concat10}, DAG);
2449
2450 SDValue Concat01 =
2451 getCombine(Op0, Op1, dl, typeJoin({ty(Op0), ty(Op1)}), DAG);
2452 if (MaskIdx == (0x02000604 | MaskUnd))
2453 return getInstr(Hexagon::S2_vtrunehb, dl, VecTy, {Concat01}, DAG);
2454 if (MaskIdx == (0x03010705 | MaskUnd))
2455 return getInstr(Hexagon::S2_vtrunohb, dl, VecTy, {Concat01}, DAG);
2456 }
2457
2458 if (ByteMask.size() == 8) {
2459 // Identity.
2460 if (MaskIdx == (0x0706050403020100ull | MaskUnd))
2461 return Op0;
2462 // Byte swap.
2463 if (MaskIdx == (0x0001020304050607ull | MaskUnd)) {
2464 SDValue T0 = DAG.getBitcast(MVT::i64, Op0);
2465 SDValue T1 = DAG.getNode(ISD::BSWAP, dl, MVT::i64, T0);
2466 return DAG.getBitcast(VecTy, T1);
2467 }
2468
2469 // Halfword picks.
2470 if (MaskIdx == (0x0d0c050409080100ull | MaskUnd))
2471 return getInstr(Hexagon::S2_shuffeh, dl, VecTy, {Op1, Op0}, DAG);
2472 if (MaskIdx == (0x0f0e07060b0a0302ull | MaskUnd))
2473 return getInstr(Hexagon::S2_shuffoh, dl, VecTy, {Op1, Op0}, DAG);
2474 if (MaskIdx == (0x0d0c090805040100ull | MaskUnd))
2475 return getInstr(Hexagon::S2_vtrunewh, dl, VecTy, {Op1, Op0}, DAG);
2476 if (MaskIdx == (0x0f0e0b0a07060302ull | MaskUnd))
2477 return getInstr(Hexagon::S2_vtrunowh, dl, VecTy, {Op1, Op0}, DAG);
2478 if (MaskIdx == (0x0706030205040100ull | MaskUnd)) {
2479 VectorPair P = opSplit(Op0, dl, DAG);
2480 return getInstr(Hexagon::S2_packhl, dl, VecTy, {P.second, P.first}, DAG);
2481 }
2482
2483 // Byte packs.
2484 if (MaskIdx == (0x0e060c040a020800ull | MaskUnd))
2485 return getInstr(Hexagon::S2_shuffeb, dl, VecTy, {Op1, Op0}, DAG);
2486 if (MaskIdx == (0x0f070d050b030901ull | MaskUnd))
2487 return getInstr(Hexagon::S2_shuffob, dl, VecTy, {Op1, Op0}, DAG);
2488 }
2489
2490 return SDValue();
2491}
2492
2493SDValue
2494HexagonTargetLowering::getSplatValue(SDValue Op, SelectionDAG &DAG) const {
2495 switch (Op.getOpcode()) {
2496 case ISD::BUILD_VECTOR:
2498 return S;
2499 break;
2500 case ISD::SPLAT_VECTOR:
2501 return Op.getOperand(0);
2502 }
2503 return SDValue();
2504}
2505
2506// Create a Hexagon-specific node for shifting a vector by an integer.
2507SDValue
2508HexagonTargetLowering::getVectorShiftByInt(SDValue Op, SelectionDAG &DAG)
2509 const {
2510 unsigned NewOpc;
2511 switch (Op.getOpcode()) {
2512 case ISD::SHL:
2513 NewOpc = HexagonISD::VASL;
2514 break;
2515 case ISD::SRA:
2516 NewOpc = HexagonISD::VASR;
2517 break;
2518 case ISD::SRL:
2519 NewOpc = HexagonISD::VLSR;
2520 break;
2521 default:
2522 llvm_unreachable("Unexpected shift opcode");
2523 }
2524 if (SDValue Sp = getSplatValue(Op.getOperand(1), DAG)) {
2525 const SDLoc dl(Op);
2526 // Canonicalize shift amount to i32 as required.
2527 SDValue Sh = Sp;
2528 if (Sh.getValueType() != MVT::i32)
2529 Sh = DAG.getZExtOrTrunc(Sh, dl, MVT::i32);
2530
2531 assert(Sh.getValueType() == MVT::i32 &&
2532 "Hexagon vector shift-by-int must use i32 shift operand");
2533 return DAG.getNode(NewOpc, dl, ty(Op), Op.getOperand(0), Sh);
2534 }
2535
2536 return SDValue();
2537}
2538
2539SDValue
2541 const SDLoc &dl(Op);
2542
2543 // First try to convert the shift (by vector) to a shift by a scalar.
2544 // If we first split the shift, the shift amount will become 'extract
2545 // subvector', and will no longer be recognized as scalar.
2546 SDValue Res = Op;
2547 if (SDValue S = getVectorShiftByInt(Op, DAG))
2548 Res = S;
2549
2550 unsigned Opc = Res.getOpcode();
2551 switch (Opc) {
2552 case HexagonISD::VASR:
2553 case HexagonISD::VLSR:
2554 case HexagonISD::VASL:
2555 break;
2556 default:
2557 // No instructions for shifts by non-scalars.
2558 return SDValue();
2559 }
2560
2561 MVT ResTy = ty(Res);
2562 if (ResTy.getVectorElementType() != MVT::i8)
2563 return Res;
2564
2565 // For shifts of i8, extend the inputs to i16, then truncate back to i8.
2566 assert(ResTy.getVectorElementType() == MVT::i8);
2567 SDValue Val = Res.getOperand(0), Amt = Res.getOperand(1);
2568
2569 auto ShiftPartI8 = [&dl, &DAG, this](unsigned Opc, SDValue V, SDValue A) {
2570 MVT Ty = ty(V);
2571 MVT ExtTy = MVT::getVectorVT(MVT::i16, Ty.getVectorNumElements());
2572 SDValue ExtV = Opc == HexagonISD::VASR ? DAG.getSExtOrTrunc(V, dl, ExtTy)
2573 : DAG.getZExtOrTrunc(V, dl, ExtTy);
2574 SDValue ExtS = DAG.getNode(Opc, dl, ExtTy, {ExtV, A});
2575 return DAG.getZExtOrTrunc(ExtS, dl, Ty);
2576 };
2577
2578 if (ResTy.getSizeInBits() == 32)
2579 return ShiftPartI8(Opc, Val, Amt);
2580
2581 auto [LoV, HiV] = opSplit(Val, dl, DAG);
2582 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy,
2583 {ShiftPartI8(Opc, LoV, Amt), ShiftPartI8(Opc, HiV, Amt)});
2584}
2585
2586SDValue
2588 if (isa<ConstantSDNode>(Op.getOperand(1).getNode()))
2589 return Op;
2590 return SDValue();
2591}
2592
2593SDValue
2595 MVT ResTy = ty(Op);
2596 SDValue InpV = Op.getOperand(0);
2597 MVT InpTy = ty(InpV);
2598 assert(ResTy.getSizeInBits() == InpTy.getSizeInBits());
2599 const SDLoc &dl(Op);
2600
2601 // Handle conversion from i8 to v8i1.
2602 if (InpTy == MVT::i8) {
2603 if (ResTy == MVT::v8i1) {
2604 SDValue Sc = DAG.getBitcast(tyScalar(InpTy), InpV);
2605 SDValue Ext = DAG.getZExtOrTrunc(Sc, dl, MVT::i32);
2606 return getInstr(Hexagon::C2_tfrrp, dl, ResTy, Ext, DAG);
2607 }
2608 return SDValue();
2609 }
2610
2611 return Op;
2612}
2613
2614bool
2615HexagonTargetLowering::getBuildVectorConstInts(ArrayRef<SDValue> Values,
2616 MVT VecTy, SelectionDAG &DAG,
2617 MutableArrayRef<ConstantInt*> Consts) const {
2619 unsigned ElemWidth = ElemTy.getSizeInBits();
2620 IntegerType *IntTy = IntegerType::get(*DAG.getContext(), ElemWidth);
2621 bool AllConst = true;
2622
2623 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2624 SDValue V = Values[i];
2625 if (V.isUndef()) {
2626 Consts[i] = ConstantInt::get(IntTy, 0);
2627 continue;
2628 }
2629 // Make sure to always cast to IntTy.
2630 if (auto *CN = dyn_cast<ConstantSDNode>(V.getNode())) {
2631 const ConstantInt *CI = CN->getConstantIntValue();
2632 Consts[i] = cast<ConstantInt>(
2633 ConstantInt::get(IntTy, CI->getValue().trunc(ElemWidth)));
2634 } else if (auto *CN = dyn_cast<ConstantFPSDNode>(V.getNode())) {
2635 const ConstantFP *CF = CN->getConstantFPValue();
2636 APInt A = CF->getValueAPF().bitcastToAPInt();
2637 Consts[i] = ConstantInt::get(IntTy, A.getZExtValue());
2638 } else {
2639 AllConst = false;
2640 }
2641 }
2642 return AllConst;
2643}
2644
2645SDValue
2646HexagonTargetLowering::buildVector32(ArrayRef<SDValue> Elem, const SDLoc &dl,
2647 MVT VecTy, SelectionDAG &DAG) const {
2648 MVT ElemTy = VecTy.getVectorElementType();
2649 assert(VecTy.getVectorNumElements() == Elem.size());
2650
2651 SmallVector<ConstantInt*,4> Consts(Elem.size());
2652 bool AllConst = getBuildVectorConstInts(Elem, VecTy, DAG, Consts);
2653
2654 unsigned First, Num = Elem.size();
2655 for (First = 0; First != Num; ++First) {
2656 if (!isUndef(Elem[First]))
2657 break;
2658 }
2659 if (First == Num)
2660 return DAG.getUNDEF(VecTy);
2661
2662 if (AllConst &&
2663 llvm::all_of(Consts, [](ConstantInt *CI) { return CI->isZero(); }))
2664 return getZero(dl, VecTy, DAG);
2665
2666 if (ElemTy == MVT::i16 || ElemTy == MVT::f16) {
2667 assert(Elem.size() == 2);
2668 if (AllConst) {
2669 // The 'Consts' array will have all values as integers regardless
2670 // of the vector element type.
2671 uint32_t V = (Consts[0]->getZExtValue() & 0xFFFF) |
2672 Consts[1]->getZExtValue() << 16;
2673 return DAG.getBitcast(VecTy, DAG.getConstant(V, dl, MVT::i32));
2674 }
2675 SDValue E0, E1;
2676 if (ElemTy == MVT::f16) {
2677 E0 = DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Elem[0]), dl, MVT::i32);
2678 E1 = DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Elem[1]), dl, MVT::i32);
2679 } else {
2680 E0 = Elem[0];
2681 E1 = Elem[1];
2682 }
2683 SDValue N = getInstr(Hexagon::A2_combine_ll, dl, MVT::i32, {E1, E0}, DAG);
2684 return DAG.getBitcast(VecTy, N);
2685 }
2686
2687 if (ElemTy == MVT::i8) {
2688 // First try generating a constant.
2689 if (AllConst) {
2690 uint32_t V = (Consts[0]->getZExtValue() & 0xFF) |
2691 (Consts[1]->getZExtValue() & 0xFF) << 8 |
2692 (Consts[2]->getZExtValue() & 0xFF) << 16 |
2693 Consts[3]->getZExtValue() << 24;
2694 return DAG.getBitcast(MVT::v4i8, DAG.getConstant(V, dl, MVT::i32));
2695 }
2696
2697 // Then try splat.
2698 bool IsSplat = true;
2699 for (unsigned i = First+1; i != Num; ++i) {
2700 if (Elem[i] == Elem[First] || isUndef(Elem[i]))
2701 continue;
2702 IsSplat = false;
2703 break;
2704 }
2705 if (IsSplat) {
2706 // Legalize the operand of SPLAT_VECTOR.
2707 SDValue Ext = DAG.getZExtOrTrunc(Elem[First], dl, MVT::i32);
2708 return DAG.getNode(ISD::SPLAT_VECTOR, dl, VecTy, Ext);
2709 }
2710
2711 // Generate
2712 // (zxtb(Elem[0]) | (zxtb(Elem[1]) << 8)) |
2713 // (zxtb(Elem[2]) | (zxtb(Elem[3]) << 8)) << 16
2714 assert(Elem.size() == 4);
2715 SDValue Vs[4];
2716 for (unsigned i = 0; i != 4; ++i) {
2717 Vs[i] = DAG.getZExtOrTrunc(Elem[i], dl, MVT::i32);
2718 Vs[i] = DAG.getZeroExtendInReg(Vs[i], dl, MVT::i8);
2719 }
2720 SDValue S8 = DAG.getConstant(8, dl, MVT::i32);
2721 SDValue T0 = DAG.getNode(ISD::SHL, dl, MVT::i32, {Vs[1], S8});
2722 SDValue T1 = DAG.getNode(ISD::SHL, dl, MVT::i32, {Vs[3], S8});
2723 SDValue B0 = DAG.getNode(ISD::OR, dl, MVT::i32, {Vs[0], T0});
2724 SDValue B1 = DAG.getNode(ISD::OR, dl, MVT::i32, {Vs[2], T1});
2725
2726 SDValue R = getInstr(Hexagon::A2_combine_ll, dl, MVT::i32, {B1, B0}, DAG);
2727 return DAG.getBitcast(MVT::v4i8, R);
2728 }
2729
2730#ifndef NDEBUG
2731 dbgs() << "VecTy: " << VecTy << '\n';
2732#endif
2733 llvm_unreachable("Unexpected vector element type");
2734}
2735
2736SDValue
2737HexagonTargetLowering::buildVector64(ArrayRef<SDValue> Elem, const SDLoc &dl,
2738 MVT VecTy, SelectionDAG &DAG) const {
2739 MVT ElemTy = VecTy.getVectorElementType();
2740 assert(VecTy.getVectorNumElements() == Elem.size());
2741
2742 SmallVector<ConstantInt*,8> Consts(Elem.size());
2743 bool AllConst = getBuildVectorConstInts(Elem, VecTy, DAG, Consts);
2744
2745 unsigned First, Num = Elem.size();
2746 for (First = 0; First != Num; ++First) {
2747 if (!isUndef(Elem[First]))
2748 break;
2749 }
2750 if (First == Num)
2751 return DAG.getUNDEF(VecTy);
2752
2753 if (AllConst &&
2754 llvm::all_of(Consts, [](ConstantInt *CI) { return CI->isZero(); }))
2755 return getZero(dl, VecTy, DAG);
2756
2757 // First try splat if possible.
2758 if (ElemTy == MVT::i16 || ElemTy == MVT::f16) {
2759 bool IsSplat = true;
2760 for (unsigned i = First+1; i != Num; ++i) {
2761 if (Elem[i] == Elem[First] || isUndef(Elem[i]))
2762 continue;
2763 IsSplat = false;
2764 break;
2765 }
2766 if (IsSplat) {
2767 // Legalize the operand of SPLAT_VECTOR
2768 SDValue S = ElemTy == MVT::f16 ? DAG.getBitcast(MVT::i16, Elem[First])
2769 : Elem[First];
2770 SDValue Ext = DAG.getZExtOrTrunc(S, dl, MVT::i32);
2771 return DAG.getNode(ISD::SPLAT_VECTOR, dl, VecTy, Ext);
2772 }
2773 }
2774
2775 // Then try constant.
2776 if (AllConst) {
2777 uint64_t Val = 0;
2778 unsigned W = ElemTy.getSizeInBits();
2779 uint64_t Mask = (1ull << W) - 1;
2780 for (unsigned i = 0; i != Num; ++i)
2781 Val = (Val << W) | (Consts[Num-1-i]->getZExtValue() & Mask);
2782 SDValue V0 = DAG.getConstant(Val, dl, MVT::i64);
2783 return DAG.getBitcast(VecTy, V0);
2784 }
2785
2786 // Build two 32-bit vectors and concatenate.
2787 MVT HalfTy = MVT::getVectorVT(ElemTy, Num/2);
2788 SDValue L = (ElemTy == MVT::i32)
2789 ? Elem[0]
2790 : buildVector32(Elem.take_front(Num/2), dl, HalfTy, DAG);
2791 SDValue H = (ElemTy == MVT::i32)
2792 ? Elem[1]
2793 : buildVector32(Elem.drop_front(Num/2), dl, HalfTy, DAG);
2794 return getCombine(H, L, dl, VecTy, DAG);
2795}
2796
2797SDValue
2798HexagonTargetLowering::extractVector(SDValue VecV, SDValue IdxV,
2799 const SDLoc &dl, MVT ValTy, MVT ResTy,
2800 SelectionDAG &DAG) const {
2801 MVT VecTy = ty(VecV);
2802 assert(!ValTy.isVector() ||
2803 VecTy.getVectorElementType() == ValTy.getVectorElementType());
2804 if (VecTy.getVectorElementType() == MVT::i1)
2805 return extractVectorPred(VecV, IdxV, dl, ValTy, ResTy, DAG);
2806
2807 unsigned VecWidth = VecTy.getSizeInBits();
2808 unsigned ValWidth = ValTy.getSizeInBits();
2809 unsigned ElemWidth = VecTy.getVectorElementType().getSizeInBits();
2810 assert((VecWidth % ElemWidth) == 0);
2811 assert(VecWidth == 32 || VecWidth == 64);
2812
2813 // Cast everything to scalar integer types.
2814 MVT ScalarTy = tyScalar(VecTy);
2815 VecV = DAG.getBitcast(ScalarTy, VecV);
2816
2817 SDValue WidthV = DAG.getConstant(ValWidth, dl, MVT::i32);
2818 SDValue ExtV;
2819
2820 if (auto *IdxN = dyn_cast<ConstantSDNode>(IdxV)) {
2821 unsigned Off = IdxN->getZExtValue() * ElemWidth;
2822 if (VecWidth == 64 && ValWidth == 32) {
2823 assert(Off == 0 || Off == 32);
2824 ExtV = Off == 0 ? LoHalf(VecV, DAG) : HiHalf(VecV, DAG);
2825 } else if (Off == 0 && (ValWidth % 8) == 0) {
2826 ExtV = DAG.getZeroExtendInReg(VecV, dl, tyScalar(ValTy));
2827 } else {
2828 SDValue OffV = DAG.getConstant(Off, dl, MVT::i32);
2829 // The return type of EXTRACTU must be the same as the type of the
2830 // input vector.
2831 ExtV = DAG.getNode(HexagonISD::EXTRACTU, dl, ScalarTy,
2832 {VecV, WidthV, OffV});
2833 }
2834 } else {
2835 if (ty(IdxV) != MVT::i32)
2836 IdxV = DAG.getZExtOrTrunc(IdxV, dl, MVT::i32);
2837 SDValue OffV = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2838 DAG.getConstant(ElemWidth, dl, MVT::i32));
2839 ExtV = DAG.getNode(HexagonISD::EXTRACTU, dl, ScalarTy,
2840 {VecV, WidthV, OffV});
2841 }
2842
2843 // Cast ExtV to the requested result type.
2844 ExtV = DAG.getZExtOrTrunc(ExtV, dl, tyScalar(ResTy));
2845 ExtV = DAG.getBitcast(ResTy, ExtV);
2846 return ExtV;
2847}
2848
2849SDValue
2850HexagonTargetLowering::extractVectorPred(SDValue VecV, SDValue IdxV,
2851 const SDLoc &dl, MVT ValTy, MVT ResTy,
2852 SelectionDAG &DAG) const {
2853 // Special case for v{8,4,2}i1 (the only boolean vectors legal in Hexagon
2854 // without any coprocessors).
2855 MVT VecTy = ty(VecV);
2856 unsigned VecWidth = VecTy.getSizeInBits();
2857 unsigned ValWidth = ValTy.getSizeInBits();
2858 assert(VecWidth == VecTy.getVectorNumElements() &&
2859 "Vector elements should equal vector width size");
2860 assert(VecWidth == 8 || VecWidth == 4 || VecWidth == 2);
2861
2862 // Check if this is an extract of the lowest bit.
2863 if (isNullConstant(IdxV) && ValTy.getSizeInBits() == 1) {
2864 // Extracting the lowest bit is a no-op, but it changes the type,
2865 // so it must be kept as an operation to avoid errors related to
2866 // type mismatches.
2867 return DAG.getNode(HexagonISD::TYPECAST, dl, MVT::i1, VecV);
2868 }
2869
2870 // If the value extracted is a single bit, use tstbit.
2871 if (ValWidth == 1) {
2872 SDValue A0 = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {VecV}, DAG);
2873 SDValue M0 = DAG.getConstant(8 / VecWidth, dl, MVT::i32);
2874 SDValue I0 = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, M0);
2875 return DAG.getNode(HexagonISD::TSTBIT, dl, MVT::i1, A0, I0);
2876 }
2877
2878 // Each bool vector (v2i1, v4i1, v8i1) always occupies 8 bits in
2879 // a predicate register. The elements of the vector are repeated
2880 // in the register (if necessary) so that the total number is 8.
2881 // The extracted subvector will need to be expanded in such a way.
2882 unsigned Scale = VecWidth / ValWidth;
2883
2884 // Generate (p2d VecV) >> 8*Idx to move the interesting bytes to
2885 // position 0.
2886 assert(ty(IdxV) == MVT::i32);
2887 unsigned VecRep = 8 / VecWidth;
2888 SDValue S0 = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2889 DAG.getConstant(8*VecRep, dl, MVT::i32));
2890 SDValue T0 = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, VecV);
2891 SDValue T1 = DAG.getNode(ISD::SRL, dl, MVT::i64, T0, S0);
2892 while (Scale > 1) {
2893 // The longest possible subvector is at most 32 bits, so it is always
2894 // contained in the low subregister.
2895 T1 = LoHalf(T1, DAG);
2896 T1 = expandPredicate(T1, dl, DAG);
2897 Scale /= 2;
2898 }
2899
2900 return DAG.getNode(HexagonISD::D2P, dl, ResTy, T1);
2901}
2902
2903SDValue
2904HexagonTargetLowering::insertVector(SDValue VecV, SDValue ValV, SDValue IdxV,
2905 const SDLoc &dl, MVT ValTy,
2906 SelectionDAG &DAG) const {
2907 MVT VecTy = ty(VecV);
2908 if (VecTy.getVectorElementType() == MVT::i1)
2909 return insertVectorPred(VecV, ValV, IdxV, dl, ValTy, DAG);
2910
2911 unsigned VecWidth = VecTy.getSizeInBits();
2912 unsigned ValWidth = ValTy.getSizeInBits();
2913 assert(VecWidth == 32 || VecWidth == 64);
2914 assert((VecWidth % ValWidth) == 0);
2915
2916 // Cast everything to scalar integer types.
2917 MVT ScalarTy = MVT::getIntegerVT(VecWidth);
2918 // The actual type of ValV may be different than ValTy (which is related
2919 // to the vector type).
2920 unsigned VW = ty(ValV).getSizeInBits();
2921 ValV = DAG.getBitcast(MVT::getIntegerVT(VW), ValV);
2922 VecV = DAG.getBitcast(ScalarTy, VecV);
2923 if (VW != VecWidth)
2924 ValV = DAG.getAnyExtOrTrunc(ValV, dl, ScalarTy);
2925
2926 SDValue WidthV = DAG.getConstant(ValWidth, dl, MVT::i32);
2927 SDValue InsV;
2928
2929 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(IdxV)) {
2930 unsigned W = C->getZExtValue() * ValWidth;
2931 SDValue OffV = DAG.getConstant(W, dl, MVT::i32);
2932 InsV = DAG.getNode(HexagonISD::INSERT, dl, ScalarTy,
2933 {VecV, ValV, WidthV, OffV});
2934 } else {
2935 if (ty(IdxV) != MVT::i32)
2936 IdxV = DAG.getZExtOrTrunc(IdxV, dl, MVT::i32);
2937 SDValue OffV = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, WidthV);
2938 InsV = DAG.getNode(HexagonISD::INSERT, dl, ScalarTy,
2939 {VecV, ValV, WidthV, OffV});
2940 }
2941
2942 return DAG.getNode(ISD::BITCAST, dl, VecTy, InsV);
2943}
2944
2945SDValue
2946HexagonTargetLowering::insertVectorPred(SDValue VecV, SDValue ValV,
2947 SDValue IdxV, const SDLoc &dl,
2948 MVT ValTy, SelectionDAG &DAG) const {
2949 MVT VecTy = ty(VecV);
2950 unsigned VecLen = VecTy.getVectorNumElements();
2951
2952 if (ValTy == MVT::i1) {
2953 SDValue ToReg = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {VecV}, DAG);
2954 SDValue Ext = DAG.getSExtOrTrunc(ValV, dl, MVT::i32);
2955 SDValue Width = DAG.getConstant(8 / VecLen, dl, MVT::i32);
2956 SDValue Idx = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, Width);
2957 SDValue Ins =
2958 DAG.getNode(HexagonISD::INSERT, dl, MVT::i32, {ToReg, Ext, Width, Idx});
2959 return getInstr(Hexagon::C2_tfrrp, dl, VecTy, {Ins}, DAG);
2960 }
2961
2962 assert(ValTy.getVectorElementType() == MVT::i1);
2963 SDValue ValR = ValTy.isVector()
2964 ? DAG.getNode(HexagonISD::P2D, dl, MVT::i64, ValV)
2965 : DAG.getSExtOrTrunc(ValV, dl, MVT::i64);
2966
2967 unsigned Scale = VecLen / ValTy.getVectorNumElements();
2968 assert(Scale > 1);
2969
2970 for (unsigned R = Scale; R > 1; R /= 2) {
2971 ValR = contractPredicate(ValR, dl, DAG);
2972 ValR = getCombine(DAG.getUNDEF(MVT::i32), ValR, dl, MVT::i64, DAG);
2973 }
2974
2975 SDValue Width = DAG.getConstant(64 / Scale, dl, MVT::i32);
2976 SDValue Idx = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, Width);
2977 SDValue VecR = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, VecV);
2978 SDValue Ins =
2979 DAG.getNode(HexagonISD::INSERT, dl, MVT::i64, {VecR, ValR, Width, Idx});
2980 return DAG.getNode(HexagonISD::D2P, dl, VecTy, Ins);
2981}
2982
2983SDValue
2984HexagonTargetLowering::expandPredicate(SDValue Vec32, const SDLoc &dl,
2985 SelectionDAG &DAG) const {
2986 assert(ty(Vec32).getSizeInBits() == 32);
2987 if (isUndef(Vec32))
2988 return DAG.getUNDEF(MVT::i64);
2989 SDValue P = DAG.getBitcast(MVT::v4i8, Vec32);
2990 SDValue X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i16, P);
2991 return DAG.getBitcast(MVT::i64, X);
2992}
2993
2994SDValue
2995HexagonTargetLowering::contractPredicate(SDValue Vec64, const SDLoc &dl,
2996 SelectionDAG &DAG) const {
2997 assert(ty(Vec64).getSizeInBits() == 64);
2998 if (isUndef(Vec64))
2999 return DAG.getUNDEF(MVT::i32);
3000 // Collect even bytes:
3001 SDValue A = DAG.getBitcast(MVT::v8i8, Vec64);
3002 SDValue S = DAG.getVectorShuffle(MVT::v8i8, dl, A, DAG.getUNDEF(MVT::v8i8),
3003 {0, 2, 4, 6, 1, 3, 5, 7});
3004 return extractVector(S, DAG.getConstant(0, dl, MVT::i32), dl, MVT::v4i8,
3005 MVT::i32, DAG);
3006}
3007
3008SDValue
3009HexagonTargetLowering::getZero(const SDLoc &dl, MVT Ty, SelectionDAG &DAG)
3010 const {
3011 if (Ty.isVector()) {
3012 unsigned W = Ty.getSizeInBits();
3013 if (W <= 64)
3014 return DAG.getBitcast(Ty, DAG.getConstant(0, dl, MVT::getIntegerVT(W)));
3015 return DAG.getNode(ISD::SPLAT_VECTOR, dl, Ty, getZero(dl, MVT::i32, DAG));
3016 }
3017
3018 if (Ty.isInteger())
3019 return DAG.getConstant(0, dl, Ty);
3020 if (Ty.isFloatingPoint())
3021 return DAG.getConstantFP(0.0, dl, Ty);
3022 llvm_unreachable("Invalid type for zero");
3023}
3024
3025SDValue
3026HexagonTargetLowering::appendUndef(SDValue Val, MVT ResTy, SelectionDAG &DAG)
3027 const {
3028 MVT ValTy = ty(Val);
3030
3031 unsigned ValLen = ValTy.getVectorNumElements();
3032 unsigned ResLen = ResTy.getVectorNumElements();
3033 if (ValLen == ResLen)
3034 return Val;
3035
3036 const SDLoc &dl(Val);
3037 assert(ValLen < ResLen);
3038 assert(ResLen % ValLen == 0);
3039
3040 SmallVector<SDValue, 4> Concats = {Val};
3041 for (unsigned i = 1, e = ResLen / ValLen; i < e; ++i)
3042 Concats.push_back(DAG.getUNDEF(ValTy));
3043
3044 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy, Concats);
3045}
3046
3047SDValue
3048HexagonTargetLowering::getCombine(SDValue Hi, SDValue Lo, const SDLoc &dl,
3049 MVT ResTy, SelectionDAG &DAG) const {
3050 MVT ElemTy = ty(Hi);
3051 assert(ElemTy == ty(Lo));
3052
3053 if (!ElemTy.isVector()) {
3054 assert(ElemTy.isScalarInteger());
3055 MVT PairTy = ElemTy.widenIntegerElementType();
3056 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, PairTy, Lo, Hi);
3057 return DAG.getBitcast(ResTy, Pair);
3058 }
3059
3060 unsigned Width = ElemTy.getSizeInBits();
3061 MVT IntTy = MVT::getIntegerVT(Width);
3062 SDValue Pair =
3064 {DAG.getBitcast(IntTy, Lo), DAG.getBitcast(IntTy, Hi)});
3065 return DAG.getBitcast(ResTy, Pair);
3066}
3067
3068SDValue
3070 MVT VecTy = ty(Op);
3071 unsigned BW = VecTy.getSizeInBits();
3072 const SDLoc &dl(Op);
3074 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i)
3075 Ops.push_back(Op.getOperand(i));
3076
3077 if (BW == 32)
3078 return buildVector32(Ops, dl, VecTy, DAG);
3079 if (BW == 64)
3080 return buildVector64(Ops, dl, VecTy, DAG);
3081
3082 if (VecTy == MVT::v8i1 || VecTy == MVT::v4i1 || VecTy == MVT::v2i1) {
3083 // Check if this is a special case or all-0 or all-1.
3084 bool All0 = true, All1 = true;
3085 for (SDValue P : Ops) {
3086 auto *CN = dyn_cast<ConstantSDNode>(P.getNode());
3087 if (CN == nullptr) {
3088 All0 = All1 = false;
3089 break;
3090 }
3091 uint32_t C = CN->getZExtValue();
3092 All0 &= (C == 0);
3093 All1 &= (C == 1);
3094 }
3095 if (All0)
3096 return DAG.getNode(HexagonISD::PFALSE, dl, VecTy);
3097 if (All1)
3098 return DAG.getNode(HexagonISD::PTRUE, dl, VecTy);
3099
3100 // For each i1 element in the resulting predicate register, put 1
3101 // shifted by the index of the element into a general-purpose register,
3102 // then or them together and transfer it back into a predicate register.
3103 SDValue Rs[8];
3104 SDValue Z = getZero(dl, MVT::i32, DAG);
3105 // Always produce 8 bits, repeat inputs if necessary.
3106 unsigned Rep = 8 / VecTy.getVectorNumElements();
3107 for (unsigned i = 0; i != 8; ++i) {
3108 SDValue S = DAG.getConstant(1ull << i, dl, MVT::i32);
3109 Rs[i] = DAG.getSelect(dl, MVT::i32, Ops[i/Rep], S, Z);
3110 }
3111 for (ArrayRef<SDValue> A(Rs); A.size() != 1; A = A.drop_back(A.size()/2)) {
3112 for (unsigned i = 0, e = A.size()/2; i != e; ++i)
3113 Rs[i] = DAG.getNode(ISD::OR, dl, MVT::i32, Rs[2*i], Rs[2*i+1]);
3114 }
3115 // Move the value directly to a predicate register.
3116 return getInstr(Hexagon::C2_tfrrp, dl, VecTy, {Rs[0]}, DAG);
3117 }
3118
3119 return SDValue();
3120}
3121
3122SDValue
3124 SelectionDAG &DAG) const {
3125 MVT VecTy = ty(Op);
3126 const SDLoc &dl(Op);
3127 if (VecTy.getSizeInBits() == 64) {
3128 assert(Op.getNumOperands() == 2);
3129 return getCombine(Op.getOperand(1), Op.getOperand(0), dl, VecTy, DAG);
3130 }
3131
3133 if (ElemTy == MVT::i1) {
3134 assert(VecTy == MVT::v2i1 || VecTy == MVT::v4i1 || VecTy == MVT::v8i1);
3135 MVT OpTy = ty(Op.getOperand(0));
3136 // Scale is how many times the operands need to be contracted to match
3137 // the representation in the target register.
3138 unsigned Scale = VecTy.getVectorNumElements() / OpTy.getVectorNumElements();
3139 assert(Scale == Op.getNumOperands() && Scale > 1);
3140
3141 // First, convert all bool vectors to integers, then generate pairwise
3142 // inserts to form values of doubled length. Up until there are only
3143 // two values left to concatenate, all of these values will fit in a
3144 // 32-bit integer, so keep them as i32 to use 32-bit inserts.
3145 SmallVector<SDValue,4> Words[2];
3146 unsigned IdxW = 0;
3147
3148 for (SDValue P : Op.getNode()->op_values()) {
3149 SDValue W = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, P);
3150 for (unsigned R = Scale; R > 1; R /= 2) {
3151 W = contractPredicate(W, dl, DAG);
3152 W = getCombine(DAG.getUNDEF(MVT::i32), W, dl, MVT::i64, DAG);
3153 }
3154 W = LoHalf(W, DAG);
3155 Words[IdxW].push_back(W);
3156 }
3157
3158 while (Scale > 2) {
3159 SDValue WidthV = DAG.getConstant(64 / Scale, dl, MVT::i32);
3160 Words[IdxW ^ 1].clear();
3161
3162 for (unsigned i = 0, e = Words[IdxW].size(); i != e; i += 2) {
3163 SDValue W0 = Words[IdxW][i], W1 = Words[IdxW][i+1];
3164 // Insert W1 into W0 right next to the significant bits of W0.
3165 SDValue T = DAG.getNode(HexagonISD::INSERT, dl, MVT::i32,
3166 {W0, W1, WidthV, WidthV});
3167 Words[IdxW ^ 1].push_back(T);
3168 }
3169 IdxW ^= 1;
3170 Scale /= 2;
3171 }
3172
3173 // At this point there should only be two words left, and Scale should be 2.
3174 assert(Scale == 2 && Words[IdxW].size() == 2);
3175
3176 SDValue WW = getCombine(Words[IdxW][1], Words[IdxW][0], dl, MVT::i64, DAG);
3177 return DAG.getNode(HexagonISD::D2P, dl, VecTy, WW);
3178 }
3179
3180 return SDValue();
3181}
3182
3183SDValue
3185 SelectionDAG &DAG) const {
3186 SDValue Vec = Op.getOperand(0);
3187 MVT ElemTy = ty(Vec).getVectorElementType();
3188 return extractVector(Vec, Op.getOperand(1), SDLoc(Op), ElemTy, ty(Op), DAG);
3189}
3190
3191SDValue
3193 SelectionDAG &DAG) const {
3194 return extractVector(Op.getOperand(0), Op.getOperand(1), SDLoc(Op),
3195 ty(Op), ty(Op), DAG);
3196}
3197
3198SDValue
3200 SelectionDAG &DAG) const {
3201 return insertVector(Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
3202 SDLoc(Op), ty(Op).getVectorElementType(), DAG);
3203}
3204
3205SDValue
3207 SelectionDAG &DAG) const {
3208 SDValue ValV = Op.getOperand(1);
3209 return insertVector(Op.getOperand(0), ValV, Op.getOperand(2),
3210 SDLoc(Op), ty(ValV), DAG);
3211}
3212
3213bool
3215 // Assuming the caller does not have either a signext or zeroext modifier, and
3216 // only one value is accepted, any reasonable truncation is allowed.
3217 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
3218 return false;
3219
3220 // FIXME: in principle up to 64-bit could be made safe, but it would be very
3221 // fragile at the moment: any support for multiple value returns would be
3222 // liable to disallow tail calls involving i64 -> iN truncation in many cases.
3223 return Ty1->getPrimitiveSizeInBits() <= 32;
3224}
3225
3226SDValue
3228 MVT Ty = ty(Op);
3229 const SDLoc &dl(Op);
3230 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
3231 MVT MemTy = LN->getMemoryVT().getSimpleVT();
3233
3234 bool LoadPred = MemTy == MVT::v2i1 || MemTy == MVT::v4i1 || MemTy == MVT::v8i1;
3235 if (LoadPred) {
3236 SDValue NL = DAG.getLoad(
3237 LN->getAddressingMode(), ISD::ZEXTLOAD, MVT::i32, dl, LN->getChain(),
3238 LN->getBasePtr(), LN->getOffset(), LN->getPointerInfo(),
3239 /*MemoryVT*/ MVT::i8, LN->getAlign(), LN->getMemOperand()->getFlags(),
3240 MMOMetadata(LN->getAAInfo(), LN->getRanges()));
3241 LN = cast<LoadSDNode>(NL.getNode());
3242 }
3243
3244 Align ClaimAlign = LN->getAlign();
3245 if (!validateConstPtrAlignment(LN->getBasePtr(), ClaimAlign, dl, DAG))
3246 return replaceMemWithUndef(Op, DAG);
3247
3248 // Call LowerUnalignedLoad for all loads, it recognizes loads that
3249 // don't need extra aligning.
3250 SDValue LU = LowerUnalignedLoad(SDValue(LN, 0), DAG);
3251 if (LoadPred) {
3252 SDValue TP = getInstr(Hexagon::C2_tfrrp, dl, MemTy, {LU}, DAG);
3253 if (ET == ISD::SEXTLOAD) {
3254 TP = DAG.getSExtOrTrunc(TP, dl, Ty);
3255 } else if (ET != ISD::NON_EXTLOAD) {
3256 TP = DAG.getZExtOrTrunc(TP, dl, Ty);
3257 }
3258 SDValue Ch = cast<LoadSDNode>(LU.getNode())->getChain();
3259 return DAG.getMergeValues({TP, Ch}, dl);
3260 }
3261 return LU;
3262}
3263
3264SDValue
3266 const SDLoc &dl(Op);
3267 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
3268 SDValue Val = SN->getValue();
3269 MVT Ty = ty(Val);
3270
3271 if (Ty == MVT::v2i1 || Ty == MVT::v4i1 || Ty == MVT::v8i1) {
3272 // Store the exact predicate (all bits).
3273 SDValue TR = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {Val}, DAG);
3274 SDValue NS = DAG.getTruncStore(SN->getChain(), dl, TR, SN->getBasePtr(),
3275 MVT::i8, SN->getMemOperand());
3276 if (SN->isIndexed()) {
3277 NS = DAG.getIndexedStore(NS, dl, SN->getBasePtr(), SN->getOffset(),
3278 SN->getAddressingMode());
3279 }
3280 SN = cast<StoreSDNode>(NS.getNode());
3281 }
3282
3283 Align ClaimAlign = SN->getAlign();
3284 if (!validateConstPtrAlignment(SN->getBasePtr(), ClaimAlign, dl, DAG))
3285 return replaceMemWithUndef(Op, DAG);
3286
3287 MVT StoreTy = SN->getMemoryVT().getSimpleVT();
3288 Align NeedAlign = Subtarget.getTypeAlignment(StoreTy);
3289 if (ClaimAlign < NeedAlign)
3290 return expandUnalignedStore(SN, DAG);
3291 return SDValue(SN, 0);
3292}
3293
3294SDValue
3296 const {
3297 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
3298 MVT LoadTy = ty(Op);
3299 unsigned NeedAlign = Subtarget.getTypeAlignment(LoadTy).value();
3300 unsigned HaveAlign = LN->getAlign().value();
3301 if (HaveAlign >= NeedAlign)
3302 return Op;
3303
3304 const SDLoc &dl(Op);
3305 const DataLayout &DL = DAG.getDataLayout();
3306 LLVMContext &Ctx = *DAG.getContext();
3307
3308 // If the load aligning is disabled or the load can be broken up into two
3309 // smaller legal loads, do the default (target-independent) expansion.
3310 bool DoDefault = false;
3311 // Handle it in the default way if this is an indexed load.
3312 if (!LN->isUnindexed())
3313 DoDefault = true;
3314
3315 if (!Subtarget.getCLOpts().align_loads) {
3317 *LN->getMemOperand()))
3318 return Op;
3319 DoDefault = true;
3320 }
3321 if (!DoDefault && (2 * HaveAlign) == NeedAlign) {
3322 // The PartTy is the equivalent of "getLoadableTypeOfSize(HaveAlign)".
3323 MVT PartTy = HaveAlign <= 8 ? MVT::getIntegerVT(8 * HaveAlign)
3324 : MVT::getVectorVT(MVT::i8, HaveAlign);
3325 DoDefault =
3326 allowsMemoryAccessForAlignment(Ctx, DL, PartTy, *LN->getMemOperand());
3327 }
3328 if (DoDefault) {
3329 std::pair<SDValue, SDValue> P = expandUnalignedLoad(LN, DAG);
3330 return DAG.getMergeValues({P.first, P.second}, dl);
3331 }
3332
3333 // The code below generates two loads, both aligned as NeedAlign, and
3334 // with the distance of NeedAlign between them. For that to cover the
3335 // bits that need to be loaded (and without overlapping), the size of
3336 // the loads should be equal to NeedAlign. This is true for all loadable
3337 // types, but add an assertion in case something changes in the future.
3338 assert(LoadTy.getSizeInBits() == 8*NeedAlign);
3339
3340 unsigned LoadLen = NeedAlign;
3341 SDValue Base = LN->getBasePtr();
3342 SDValue Chain = LN->getChain();
3343 auto BO = getBaseAndOffset(Base);
3344 unsigned BaseOpc = BO.first.getOpcode();
3345 if (BaseOpc == HexagonISD::VALIGNADDR && BO.second % LoadLen == 0)
3346 return Op;
3347
3348 if (BO.second % LoadLen != 0) {
3349 BO.first = DAG.getNode(ISD::ADD, dl, MVT::i32, BO.first,
3350 DAG.getConstant(BO.second % LoadLen, dl, MVT::i32));
3351 BO.second -= BO.second % LoadLen;
3352 }
3353 SDValue BaseNoOff = (BaseOpc != HexagonISD::VALIGNADDR)
3354 ? DAG.getNode(HexagonISD::VALIGNADDR, dl, MVT::i32, BO.first,
3355 DAG.getConstant(NeedAlign, dl, MVT::i32))
3356 : BO.first;
3357 SDValue Base0 =
3358 DAG.getMemBasePlusOffset(BaseNoOff, TypeSize::getFixed(BO.second), dl);
3359 SDValue Base1 = DAG.getMemBasePlusOffset(
3360 BaseNoOff, TypeSize::getFixed(BO.second + LoadLen), dl);
3361
3362 MachineMemOperand *WideMMO = nullptr;
3363 if (MachineMemOperand *MMO = LN->getMemOperand()) {
3365 WideMMO = MF.getMachineMemOperand(
3366 MMO->getPointerInfo(), MMO->getFlags(), 2 * LoadLen, Align(LoadLen),
3367 MMOMetadata(MMO->getAAInfo(), MMO->getRanges()), MMO->getSyncScopeID(),
3368 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
3369 }
3370
3371 SDValue Load0 = DAG.getLoad(LoadTy, dl, Chain, Base0, WideMMO);
3372 SDValue Load1 = DAG.getLoad(LoadTy, dl, Chain, Base1, WideMMO);
3373
3374 SDValue Aligned = DAG.getNode(HexagonISD::VALIGN, dl, LoadTy,
3375 {Load1, Load0, BaseNoOff.getOperand(0)});
3376 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3377 Load0.getValue(1), Load1.getValue(1));
3378 SDValue M = DAG.getMergeValues({Aligned, NewChain}, dl);
3379 return M;
3380}
3381
3382SDValue
3384 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
3385 auto *CY = dyn_cast<ConstantSDNode>(Y);
3386 if (!CY)
3387 return SDValue();
3388
3389 const SDLoc &dl(Op);
3390 SDVTList VTs = Op.getNode()->getVTList();
3391 assert(VTs.NumVTs == 2);
3392 assert(VTs.VTs[1] == MVT::i1);
3393 unsigned Opc = Op.getOpcode();
3394
3395 if (CY) {
3396 uint64_t VY = CY->getZExtValue();
3397 assert(VY != 0 && "This should have been folded");
3398 // X +/- 1
3399 if (VY != 1)
3400 return SDValue();
3401
3402 if (Opc == ISD::UADDO) {
3403 SDValue Op = DAG.getNode(ISD::ADD, dl, VTs.VTs[0], {X, Y});
3404 SDValue Ov = DAG.getSetCC(dl, MVT::i1, Op, getZero(dl, ty(Op), DAG),
3405 ISD::SETEQ);
3406 return DAG.getMergeValues({Op, Ov}, dl);
3407 }
3408 if (Opc == ISD::USUBO) {
3409 SDValue Op = DAG.getNode(ISD::SUB, dl, VTs.VTs[0], {X, Y});
3410 SDValue Ov = DAG.getSetCC(dl, MVT::i1, Op,
3411 DAG.getAllOnesConstant(dl, ty(Op)), ISD::SETEQ);
3412 return DAG.getMergeValues({Op, Ov}, dl);
3413 }
3414 }
3415
3416 return SDValue();
3417}
3418
3420 SelectionDAG &DAG) const {
3421 const SDLoc &dl(Op);
3422 unsigned Opc = Op.getOpcode();
3423 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), C = Op.getOperand(2);
3424
3425 if (Opc == ISD::UADDO_CARRY)
3426 return DAG.getNode(HexagonISD::ADDC, dl, Op.getNode()->getVTList(),
3427 { X, Y, C });
3428
3429 EVT CarryTy = C.getValueType();
3430 SDValue SubC = DAG.getNode(HexagonISD::SUBC, dl, Op.getNode()->getVTList(),
3431 { X, Y, DAG.getLogicalNOT(dl, C, CarryTy) });
3432 SDValue Out[] = { SubC.getValue(0),
3433 DAG.getLogicalNOT(dl, SubC.getValue(1), CarryTy) };
3434 return DAG.getMergeValues(Out, dl);
3435}
3436
3437SDValue
3439 SDValue Chain = Op.getOperand(0);
3440 SDValue Offset = Op.getOperand(1);
3441 SDValue Handler = Op.getOperand(2);
3442 SDLoc dl(Op);
3443 auto PtrVT = getPointerTy(DAG.getDataLayout());
3444
3445 // Mark function as containing a call to EH_RETURN.
3446 HexagonMachineFunctionInfo *FuncInfo =
3448 FuncInfo->setHasEHReturn();
3449
3450 unsigned OffsetReg = Hexagon::R28;
3451
3452 SDValue StoreAddr =
3453 DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getRegister(Hexagon::R30, PtrVT),
3454 DAG.getIntPtrConstant(4, dl));
3455 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
3456 Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
3457
3458 // Not needed we already use it as explicit input to EH_RETURN.
3459 // MF.getRegInfo().addLiveOut(OffsetReg);
3460
3461 return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
3462}
3463
3464SDValue
3466 unsigned Opc = Op.getOpcode();
3467 // Handle INLINEASM first.
3469 return LowerINLINEASM(Op, DAG);
3470
3471 if (isHlxOperation(Op.getNode(), DAG)) {
3472 // If HLX lowering returns nothing, try the default lowering.
3473 if (SDValue V = LowerHlxOperation(Op, DAG))
3474 return V;
3475 } else if (isHvxOperation(Op.getNode(), DAG)) {
3476 // If HVX lowering returns nothing, try the default lowering.
3477 if (SDValue V = LowerHvxOperation(Op, DAG))
3478 return V;
3479 }
3480
3481 switch (Opc) {
3482 default:
3483#ifndef NDEBUG
3484 Op.getNode()->dumpr(&DAG);
3485#endif
3486 llvm_unreachable("Should not custom lower this!");
3487
3488 case ISD::FDIV:
3489 return LowerFDIV(Op, DAG);
3490 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
3495 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
3496 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
3497 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
3498 case ISD::LOAD: return LowerLoad(Op, DAG);
3499 case ISD::STORE: return LowerStore(Op, DAG);
3500 case ISD::UADDO:
3501 case ISD::USUBO: return LowerUAddSubO(Op, DAG);
3502 case ISD::UADDO_CARRY:
3503 case ISD::USUBO_CARRY: return LowerUAddSubOCarry(Op, DAG);
3504 case ISD::SRA:
3505 case ISD::SHL:
3506 case ISD::SRL: return LowerVECTOR_SHIFT(Op, DAG);
3507 case ISD::ROTL: return LowerROTL(Op, DAG);
3508 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
3509 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
3510 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
3511 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3512 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
3514 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
3515 case ISD::GlobalAddress: return LowerGLOBALADDRESS(Op, DAG);
3516 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
3518 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
3519 case ISD::VASTART: return LowerVASTART(Op, DAG);
3521 case ISD::SETCC: return LowerSETCC(Op, DAG);
3522 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
3523 case ISD::SELECT:
3524 return LowerBoolVectorSelect(Op, DAG);
3526 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3527 // INTRINSIC_W_CHAIN is marked Custom only so HLX memory intrinsics can be
3528 // lowered (handled above via LowerHlxOperation). Any other W_CHAIN
3529 // intrinsic is left unchanged for normal instruction selection.
3531 return Op;
3532 case ISD::PREFETCH:
3533 return LowerPREFETCH(Op, DAG);
3534 case ISD::FMAXIMUM:
3535 case ISD::FMINIMUM:
3536 return LowerFMINFMAX(Op, DAG);
3537 break;
3538 }
3539
3540 return SDValue();
3541}
3542
3543void
3546 SelectionDAG &DAG) const {
3547 if (isHvxOperation(N, DAG)) {
3548 LowerHvxOperationWrapper(N, Results, DAG);
3549 if (!Results.empty())
3550 return;
3551 }
3552
3553 SDValue Op(N, 0);
3554 unsigned Opc = N->getOpcode();
3555
3556 switch (Opc) {
3557 case HexagonISD::SSAT:
3558 case HexagonISD::USAT:
3559 Results.push_back(opJoin(SplitVectorOp(Op, DAG), SDLoc(Op), DAG));
3560 break;
3561 case ISD::STORE:
3562 // We are only custom-lowering stores to verify the alignment of the
3563 // address if it is a compile-time constant. Since a store can be
3564 // modified during type-legalization (the value being stored may need
3565 // legalization), return empty Results here to indicate that we don't
3566 // really make any changes in the custom lowering.
3567 return;
3568 default:
3570 break;
3571 }
3572}
3573
3574void
3577 SelectionDAG &DAG) const {
3578 if (isHvxOperation(N, DAG)) {
3579 ReplaceHvxNodeResults(N, Results, DAG);
3580 if (!Results.empty())
3581 return;
3582 }
3583
3584 const SDLoc &dl(N);
3585 switch (N->getOpcode()) {
3586 case ISD::SRL:
3587 case ISD::SRA:
3588 case ISD::SHL:
3589 return;
3590 case ISD::BITCAST:
3591 // Handle a bitcast from v8i1 to i8.
3592 if (N->getValueType(0) == MVT::i8) {
3593 if (N->getOperand(0).getValueType() == MVT::v8i1) {
3594 SDValue P = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32,
3595 N->getOperand(0), DAG);
3596 SDValue T = DAG.getAnyExtOrTrunc(P, dl, MVT::i8);
3597 Results.push_back(T);
3598 }
3599 }
3600 break;
3601 }
3602}
3603
3604SDValue
3606 DAGCombinerInfo &DCI) const {
3607 SDValue Op(N, 0);
3608 const SDLoc &dl(Op);
3609 unsigned Opc = Op.getOpcode();
3610
3611 // Combining transformations applicable for arbitrary vector sizes.
3612 if (DCI.isBeforeLegalizeOps()) {
3613 switch (Opc) {
3614 case ISD::VECREDUCE_ADD:
3615 if (SDValue V = splitVecReduceAdd(N, DCI.DAG))
3616 return V;
3617 if (SDValue V = expandVecReduceAdd(N, DCI.DAG))
3618 return V;
3619 return SDValue();
3623 if (SDValue V = splitExtendingPartialReduceMLA(N, DCI.DAG))
3624 return V;
3625 return SDValue();
3626 }
3627 } else {
3628 switch (Opc) {
3629 case ISD::VSELECT: {
3630 // (vselect (xor x, ptrue), v0, v1) -> (vselect x, v1, v0)
3631 SDValue Cond = Op.getOperand(0);
3632 if (Cond->getOpcode() == ISD::XOR) {
3633 SDValue C0 = Cond.getOperand(0), C1 = Cond.getOperand(1);
3634 if (C1->getOpcode() == HexagonISD::PTRUE) {
3635 SDValue VSel = DCI.DAG.getNode(ISD::VSELECT, dl, ty(Op), C0,
3636 Op.getOperand(2), Op.getOperand(1));
3637 return VSel;
3638 }
3639 }
3640 return SDValue();
3641 }
3642 }
3643 }
3644
3645 if (isHvxOperation(N, DCI.DAG)) {
3646 if (SDValue V = PerformHvxDAGCombine(N, DCI))
3647 return V;
3648 return SDValue();
3649 }
3650
3651 if (Opc == ISD::TRUNCATE) {
3652 SDValue Op0 = Op.getOperand(0);
3653 // fold (truncate (build pair x, y)) -> (truncate x) or x
3654 if (Op0.getOpcode() == ISD::BUILD_PAIR) {
3655 EVT TruncTy = Op.getValueType();
3656 SDValue Elem0 = Op0.getOperand(0);
3657 // if we match the low element of the pair, just return it.
3658 if (Elem0.getValueType() == TruncTy)
3659 return Elem0;
3660 // otherwise, if the low part is still too large, apply the truncate.
3661 if (Elem0.getValueType().bitsGT(TruncTy))
3662 return DCI.DAG.getNode(ISD::TRUNCATE, dl, TruncTy, Elem0);
3663 }
3664 }
3665
3666 if (DCI.isBeforeLegalizeOps())
3667 return SDValue();
3668
3669 switch (Opc) {
3670 case HexagonISD::P2D: {
3671 SDValue P = Op.getOperand(0);
3672 switch (P.getOpcode()) {
3673 case HexagonISD::PTRUE:
3674 return DCI.DAG.getAllOnesConstant(dl, ty(Op));
3675 case HexagonISD::PFALSE:
3676 return getZero(dl, ty(Op), DCI.DAG);
3677 default:
3678 break;
3679 }
3680 break;
3681 }
3682 case ISD::TRUNCATE: {
3683 SDValue Op0 = Op.getOperand(0);
3684 // fold (truncate (build pair x, y)) -> (truncate x) or x
3685 if (Op0.getOpcode() == ISD::BUILD_PAIR) {
3686 MVT TruncTy = ty(Op);
3687 SDValue Elem0 = Op0.getOperand(0);
3688 // if we match the low element of the pair, just return it.
3689 if (ty(Elem0) == TruncTy)
3690 return Elem0;
3691 // otherwise, if the low part is still too large, apply the truncate.
3692 if (ty(Elem0).bitsGT(TruncTy))
3693 return DCI.DAG.getNode(ISD::TRUNCATE, dl, TruncTy, Elem0);
3694 }
3695 break;
3696 }
3697 case ISD::OR: {
3698 // fold (or (shl xx, s), (zext y)) -> (COMBINE (shl xx, s-32), y)
3699 // if s >= 32
3700 auto fold0 = [&, this](SDValue Op) {
3701 if (ty(Op) != MVT::i64)
3702 return SDValue();
3703 SDValue Shl = Op.getOperand(0);
3704 SDValue Zxt = Op.getOperand(1);
3705 if (Shl.getOpcode() != ISD::SHL)
3706 std::swap(Shl, Zxt);
3707
3708 if (Shl.getOpcode() != ISD::SHL || Zxt.getOpcode() != ISD::ZERO_EXTEND)
3709 return SDValue();
3710
3711 SDValue Z = Zxt.getOperand(0);
3712 auto *Amt = dyn_cast<ConstantSDNode>(Shl.getOperand(1));
3713 if (Amt && Amt->getZExtValue() >= 32 && ty(Z).getSizeInBits() <= 32) {
3714 unsigned A = Amt->getZExtValue();
3715 SDValue S = Shl.getOperand(0);
3716 SDValue T0 = DCI.DAG.getNode(ISD::SHL, dl, ty(S), S,
3717 DCI.DAG.getConstant(A - 32, dl, MVT::i32));
3718 SDValue T1 = DCI.DAG.getZExtOrTrunc(T0, dl, MVT::i32);
3719 SDValue T2 = DCI.DAG.getZExtOrTrunc(Z, dl, MVT::i32);
3720 return DCI.DAG.getNode(HexagonISD::COMBINE, dl, MVT::i64, {T1, T2});
3721 }
3722 return SDValue();
3723 };
3724
3725 if (SDValue R = fold0(Op))
3726 return R;
3727 break;
3728 }
3729 }
3730
3731 return SDValue();
3732}
3733
3734/// Returns relocation base for the given PIC jumptable.
3735SDValue
3737 SelectionDAG &DAG) const {
3738 int Idx = cast<JumpTableSDNode>(Table)->getIndex();
3739 EVT VT = Table.getValueType();
3741 return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Table), VT, T);
3742}
3743
3744//===----------------------------------------------------------------------===//
3745// Inline Assembly Support
3746//===----------------------------------------------------------------------===//
3747
3750 if (Constraint.size() == 1) {
3751 switch (Constraint[0]) {
3752 case 'q':
3753 case 'v':
3754 if (Subtarget.useHVXOps())
3755 return C_RegisterClass;
3756 break;
3757 case 'a':
3758 return C_RegisterClass;
3759 default:
3760 break;
3761 }
3762 }
3763 return TargetLowering::getConstraintType(Constraint);
3764}
3765
3766std::pair<unsigned, const TargetRegisterClass*>
3768 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
3769
3770 if (Constraint.size() == 1) {
3771 switch (Constraint[0]) {
3772 case 'r': // R0-R31
3773 switch (VT.SimpleTy) {
3774 default:
3775 return {0u, nullptr};
3776 case MVT::i1:
3777 case MVT::i8:
3778 case MVT::i16:
3779 case MVT::i32:
3780 case MVT::f32:
3781 return {0u, &Hexagon::IntRegsRegClass};
3782 case MVT::i64:
3783 case MVT::f64:
3784 return {0u, &Hexagon::DoubleRegsRegClass};
3785 }
3786 break;
3787 case 'a': // M0-M1
3788 if (VT != MVT::i32)
3789 return {0u, nullptr};
3790 return {0u, &Hexagon::ModRegsRegClass};
3791 case 'q': // q0-q3
3792 switch (VT.getSizeInBits()) {
3793 default:
3794 return {0u, nullptr};
3795 case 64:
3796 case 128:
3797 return {0u, &Hexagon::HvxQRRegClass};
3798 }
3799 break;
3800 case 'v': // V0-V31
3801 switch (VT.getSizeInBits()) {
3802 default:
3803 return {0u, nullptr};
3804 case 512:
3805 return {0u, &Hexagon::HvxVRRegClass};
3806 case 1024:
3807 if (Subtarget.hasV60Ops() && Subtarget.useHVX128BOps())
3808 return {0u, &Hexagon::HvxVRRegClass};
3809 return {0u, &Hexagon::HvxWRRegClass};
3810 case 2048:
3811 return {0u, &Hexagon::HvxWRRegClass};
3812 }
3813 break;
3814 default:
3815 return {0u, nullptr};
3816 }
3817 }
3818
3819 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3820}
3821
3822/// Returns how to materialize the specified FP immediate.
3825 bool ForCodeSize) const {
3826 return FPImmAction::Legal;
3827}
3828
3829/// Returns true if it is beneficial to convert a load of a constant
3830/// to just the constant itself.
3832 Type *Ty) const {
3833 if (!Subtarget.getCLOpts().constant_loads_to_imm)
3834 return false;
3835
3836 assert(Ty->isIntegerTy());
3837 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3838 return (BitSize > 0 && BitSize <= 64);
3839}
3840
3841/// isLegalAddressingMode - Return true if the addressing mode represented by
3842/// AM is legal for this target, for a load/store of the specified type.
3844 const AddrMode &AM, Type *Ty,
3845 unsigned AS, Instruction *I) const {
3846 if (Ty->isSized()) {
3847 // When LSR detects uses of the same base address to access different
3848 // types (e.g. unions), it will assume a conservative type for these
3849 // uses:
3850 // LSR Use: Kind=Address of void in addrspace(4294967295), ...
3851 // The type Ty passed here would then be "void". Skip the alignment
3852 // checks, but do not return false right away, since that confuses
3853 // LSR into crashing.
3854 Align A = DL.getABITypeAlign(Ty);
3855 // The base offset must be a multiple of the alignment.
3856 if (!isAligned(A, AM.BaseOffs))
3857 return false;
3858 // The shifted offset must fit in 11 bits.
3859 if (!isInt<11>(AM.BaseOffs >> Log2(A)))
3860 return false;
3861 }
3862
3863 // No global is ever allowed as a base.
3864 if (AM.BaseGV)
3865 return false;
3866
3867 int Scale = AM.Scale;
3868 if (Scale < 0)
3869 Scale = -Scale;
3870 switch (Scale) {
3871 case 0: // No scale reg, "r+i", "r", or just "i".
3872 break;
3873 default: // No scaled addressing mode.
3874 return false;
3875 }
3876 return true;
3877}
3878
3879/// Return true if folding a constant offset with the given GlobalAddress is
3880/// legal. It is frequently not legal in PIC relocation models.
3882 const {
3883 return HTM.getRelocationModel() == Reloc::Static;
3884}
3885
3886/// isLegalICmpImmediate - Return true if the specified immediate is legal
3887/// icmp immediate, that is the target has icmp instructions which can compare
3888/// a register against the immediate without having to materialize the
3889/// immediate into a register.
3891 return Imm >= -512 && Imm <= 511;
3892}
3893
3894/// IsEligibleForTailCallOptimization - Check whether the call is eligible
3895/// for tail call optimization. Targets which want to do tail call
3896/// optimization should implement this function.
3898 SDValue Callee,
3899 CallingConv::ID CalleeCC,
3900 bool IsVarArg,
3901 bool IsCalleeStructRet,
3902 bool IsCallerStructRet,
3904 const SmallVectorImpl<SDValue> &OutVals,
3906 SelectionDAG& DAG) const {
3907 const Function &CallerF = DAG.getMachineFunction().getFunction();
3908 CallingConv::ID CallerCC = CallerF.getCallingConv();
3909 bool CCMatch = CallerCC == CalleeCC;
3910
3911 // ***************************************************************************
3912 // Look for obvious safe cases to perform tail call optimization that do not
3913 // require ABI changes.
3914 // ***************************************************************************
3915
3916 // If this is a tail call via a function pointer, then don't do it!
3917 if (!isa<GlobalAddressSDNode>(Callee) &&
3918 !isa<ExternalSymbolSDNode>(Callee)) {
3919 return false;
3920 }
3921
3922 // Do not optimize if the calling conventions do not match and the conventions
3923 // used are not C or Fast.
3924 if (!CCMatch) {
3925 bool R = (CallerCC == CallingConv::C || CallerCC == CallingConv::Fast);
3926 bool E = (CalleeCC == CallingConv::C || CalleeCC == CallingConv::Fast);
3927 // If R & E, then ok.
3928 if (!R || !E)
3929 return false;
3930 }
3931
3932 // Do not tail call optimize vararg calls.
3933 if (IsVarArg)
3934 return false;
3935
3936 // Also avoid tail call optimization if either caller or callee uses struct
3937 // return semantics.
3938 if (IsCalleeStructRet || IsCallerStructRet)
3939 return false;
3940
3941 // In addition to the cases above, we also disable Tail Call Optimization if
3942 // the calling convention code that at least one outgoing argument needs to
3943 // go on the stack. We cannot check that here because at this point that
3944 // information is not available.
3945 return true;
3946}
3947
3948/// Returns the target specific optimal type for load and store operations as
3949/// a result of memset, memcpy, and memmove lowering.
3950///
3951/// If DstAlign is zero that means it's safe to destination alignment can
3952/// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
3953/// a need to check it against alignment requirement, probably because the
3954/// source does not need to be loaded. If 'IsMemset' is true, that means it's
3955/// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
3956/// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
3957/// does not need to be loaded. It returns EVT::Other if the type should be
3958/// determined using generic target-independent logic.
3960 LLVMContext &Context, const MemOp &Op,
3961 const AttributeList &FuncAttributes) const {
3962 if (Op.size() >= 8 && Op.isAligned(Align(8)))
3963 return MVT::i64;
3964 if (Op.size() >= 4 && Op.isAligned(Align(4)))
3965 return MVT::i32;
3966 if (Op.size() >= 2 && Op.isAligned(Align(2)))
3967 return MVT::i16;
3968 return MVT::Other;
3969}
3970
3971// The helpers below are versions of llvm::getShuffleReduction and
3972// llvm::getOrderedReduction, adapted to use during DAG passes and simplified as
3973// follows:
3974// - ICmp and FCmp are not handled;
3975// - in every step in getShuffleReduction, the input is split into halves (not
3976// pairwise).
3977
3979 SelectionDAG &DAG) {
3980 assert(Op != Instruction::ICmp && Op != Instruction::FCmp);
3981
3982 EVT VT = Vec.getValueType();
3983 EVT EltT = VT.getVectorElementType();
3984 unsigned VF = VT.getVectorNumElements();
3985 assert(VF > 0 &&
3986 "Reduction emission only supported for non-zero length vectors!");
3987
3988 SDLoc DL(Vec);
3989 SDValue Result = DAG.getExtractVectorElt(DL, EltT, Vec, 0);
3990 for (unsigned ExtractIdx = 1; ExtractIdx < VF; ++ExtractIdx) {
3991 SDValue Ext = DAG.getExtractVectorElt(DL, EltT, Vec, ExtractIdx);
3992 Result = DAG.getNode(Op, DL, EltT, {Result, Ext});
3993 }
3994
3995 return Result;
3996}
3997
3999 SelectionDAG &DAG) {
4000 assert(Op != Instruction::ICmp && Op != Instruction::FCmp);
4001
4002 EVT VT = Vec.getValueType();
4003 unsigned VF = VT.getVectorNumElements();
4004 if (VF == 0)
4005 llvm_unreachable("Vector must be non-zero length");
4006 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
4007 // and vector ops, reducing the set of values being computed by half each
4008 // round.
4009 assert(isPowerOf2_32(VF) &&
4010 "Reduction emission only supported for pow2 vectors!");
4011
4012 SDLoc DL(Vec);
4013 // TODO: Is it correct to create double-vector shuffle and fill 3/4 of it with
4014 // undefs?
4015 SmallVector<int, 32> ShuffleMask(VF);
4016 for (unsigned i = VF; i > 1; i >>= 1) {
4017 // Move the upper half of the vector to the lower half.
4018 for (unsigned j = 0; j != i / 2; ++j)
4019 ShuffleMask[j] = i / 2 + j;
4020 // Fill the rest of the mask with undef.
4021 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
4022
4023 SDValue Shuf =
4024 DAG.getVectorShuffle(VT, DL, Vec, DAG.getUNDEF(VT), ShuffleMask);
4025
4026 Vec = DAG.getNode(Op, DL, VT, {Vec, Shuf});
4027 }
4028 // The result is in the first element of the vector.
4029 return DAG.getExtractVectorElt(DL, VT.getVectorElementType(), Vec, 0);
4030}
4031
4032SDValue HexagonTargetLowering::expandVecReduceAdd(SDNode *N,
4033 SelectionDAG &DAG) const {
4034 // Since we disabled automatic reduction expansion, generate log2 ladder code
4035 // if the vector is of a power-of-two length.
4036 SDValue Input = N->getOperand(0);
4037 if (isPowerOf2_32(Input.getValueType().getVectorNumElements()))
4038 return getShuffleReduction(Input, ISD::ADD, DAG);
4039 // Otherwise, reduction will be scalarized.
4040 return getOrderedReduction(Input, ISD::ADD, DAG);
4041}
4042
4044 LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
4045 Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const {
4046 if (!VT.isSimple())
4047 return false;
4048 MVT SVT = VT.getSimpleVT();
4049 if (Subtarget.isHLXVectorType(SVT))
4050 return allowsHlxMemoryAccess(SVT, Flags, Fast);
4051 if (Subtarget.isHVXVectorType(SVT, true))
4052 return allowsHvxMemoryAccess(SVT, Flags, Fast);
4054 Context, DL, VT, AddrSpace, Alignment, Flags, Fast);
4055}
4056
4058 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
4059 unsigned *Fast) const {
4060 if (!VT.isSimple())
4061 return false;
4062 MVT SVT = VT.getSimpleVT();
4063 if (Subtarget.isHVXVectorType(SVT, true))
4064 return allowsHvxMisalignedMemoryAccesses(SVT, Flags, Fast);
4065 if (Fast)
4066 *Fast = 0;
4067 return false;
4068}
4069
4070std::pair<const TargetRegisterClass*, uint8_t>
4071HexagonTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
4072 MVT VT) const {
4073 if (Subtarget.isHVXVectorType(VT, true)) {
4074 unsigned BitWidth = VT.getSizeInBits();
4075 unsigned VecWidth = Subtarget.getVectorLength() * 8;
4076
4077 if (VT.getVectorElementType() == MVT::i1)
4078 return std::make_pair(&Hexagon::HvxQRRegClass, 1);
4079 if (BitWidth == VecWidth)
4080 return std::make_pair(&Hexagon::HvxVRRegClass, 1);
4081 assert(BitWidth == 2 * VecWidth);
4082 return std::make_pair(&Hexagon::HvxWRRegClass, 1);
4083 }
4084
4086}
4087
4089 SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT,
4090 std::optional<unsigned> ByteOffset) const {
4091 // TODO: This may be worth removing. Check regression tests for diffs.
4093 ByteOffset))
4094 return false;
4095
4096 auto *L = cast<LoadSDNode>(Load);
4097 std::pair<SDValue, int> BO = getBaseAndOffset(L->getBasePtr());
4098 // Small-data object, do not shrink.
4099 if (BO.first.getOpcode() == HexagonISD::CONST32_GP)
4100 return false;
4102 auto &HTM = static_cast<const HexagonTargetMachine &>(getTargetMachine());
4103 const auto *GO = dyn_cast_or_null<const GlobalObject>(GA->getGlobal());
4104 return !GO || !HTM.getObjFileLowering()->isGlobalInSmallSection(GO, HTM);
4105 }
4106 return true;
4107}
4108
4110 SDNode *Node) const {
4111 AdjustHvxInstrPostInstrSelection(MI, Node);
4112}
4113
4115 Type *ValueTy, Value *Addr,
4116 AtomicOrdering Ord) const {
4117 unsigned SZ = ValueTy->getPrimitiveSizeInBits();
4118 assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic loads supported");
4119 Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_L2_loadw_locked
4120 : Intrinsic::hexagon_L4_loadd_locked;
4121
4122 Value *Call =
4123 Builder.CreateIntrinsic(IntID, Addr, /*FMFSource=*/nullptr, "larx");
4124
4125 return Builder.CreateBitCast(Call, ValueTy);
4126}
4127
4128/// Perform a store-conditional operation to Addr. Return the status of the
4129/// store. This should be 0 if the store succeeded, non-zero otherwise.
4131 Value *Val, Value *Addr,
4132 AtomicOrdering Ord) const {
4133 BasicBlock *BB = Builder.GetInsertBlock();
4134 Module *M = BB->getParent()->getParent();
4135 Type *Ty = Val->getType();
4136 unsigned SZ = Ty->getPrimitiveSizeInBits();
4137
4138 Type *CastTy = Builder.getIntNTy(SZ);
4139 assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic stores supported");
4140 Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_S2_storew_locked
4141 : Intrinsic::hexagon_S4_stored_locked;
4142
4143 Val = Builder.CreateBitCast(Val, CastTy);
4144
4145 Value *Call = Builder.CreateIntrinsic(IntID, {Addr, Val},
4146 /*FMFSource=*/nullptr, "stcx");
4147 Value *Cmp = Builder.CreateICmpEQ(Call, Builder.getInt32(0), "");
4148 Value *Ext = Builder.CreateZExt(Cmp, Type::getInt32Ty(M->getContext()));
4149 return Ext;
4150}
4151
4154 // Do not expand loads and stores that don't exceed 64 bits.
4155 return LI->getType()->getPrimitiveSizeInBits() > 64
4158}
4159
4162 // Do not expand loads and stores that don't exceed 64 bits.
4163 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() > 64
4166}
4167
4173
4175 MachineInstr &MI, MachineBasicBlock *BB) const {
4176 switch (MI.getOpcode()) {
4177 case TargetOpcode::PATCHABLE_EVENT_CALL:
4178 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
4179 // These are lowered in the AsmPrinter.
4180 return BB;
4181 default:
4182 llvm_unreachable("Unexpected instruction with custom inserter");
4183 }
4184}
4185
4189 const TargetInstrInfo *TII) const {
4190 assert(MBBI->isCall() && MBBI->getCFIType() &&
4191 "Invalid call instruction for a KCFI check");
4192
4193 switch (MBBI->getOpcode()) {
4194 case Hexagon::J2_callr:
4195 case Hexagon::PS_callr_nr:
4196 break;
4197 default:
4198 llvm_unreachable("Unexpected CFI call opcode");
4199 }
4200
4201 MachineOperand &Target = MBBI->getOperand(0);
4202 assert(Target.isReg() && "Invalid target operand for an indirect call");
4203 Target.setIsRenamable(false);
4204
4205 return BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(Hexagon::KCFI_CHECK))
4206 .addReg(Target.getReg())
4207 .addImm(MBBI->getCFIType())
4208 .getInstr();
4209}
4210
4212 const Instruction &AndI) const {
4213 // Only sink 'and' mask to cmp use block if it is masking a single bit since
4214 // this will fold the and/cmp/br into a single tstbit instruction.
4216 if (!Mask)
4217 return false;
4218 return Mask->getValue().isPowerOf2();
4219}
4220
4221// Check if the result of the node is only used as a return value, as
4222// otherwise we can't perform a tail-call.
4224 SDValue &Chain) const {
4225 if (N->getNumValues() != 1)
4226 return false;
4227 if (!N->hasNUsesOfValue(1, 0))
4228 return false;
4229
4230 SDNode *Copy = *N->user_begin();
4231
4232 if (Copy->getOpcode() == ISD::BITCAST) {
4233 return isUsedByReturnOnly(Copy, Chain);
4234 }
4235
4236 if (Copy->getOpcode() != ISD::CopyToReg) {
4237 return false;
4238 }
4239
4240 // If the ISD::CopyToReg has a glue operand, we conservatively assume it
4241 // isn't safe to perform a tail call.
4242 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == MVT::Glue)
4243 return false;
4244
4245 // The copy must be used by a HexagonISD::RET_GLUE, and nothing else.
4246 bool HasRet = false;
4247 for (SDNode *Node : Copy->users()) {
4248 if (Node->getOpcode() != HexagonISD::RET_GLUE)
4249 return false;
4250 HasRet = true;
4251 }
4252 if (!HasRet)
4253 return false;
4254
4255 Chain = Copy->getOperand(0);
4256 return true;
4257}
4258
4260 const MachineFunction &MF) const {
4261 if (MF.getFunction().hasFnAttribute("probe-stack"))
4262 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
4263 "inline-asm";
4264 return false;
4265}
4266
4268 Align StackAlign) const {
4269 const Function &Fn = MF.getFunction();
4270 unsigned StackProbeSize =
4271 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
4272 // Round down to the stack alignment.
4273 StackProbeSize = alignDown(StackProbeSize, StackAlign.value());
4274 return StackProbeSize ? StackProbeSize : StackAlign.value();
4275}
return SDValue()
const AArch64Subtarget & Subtarget
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo & TII
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")
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 bool isBrevLdIntrinsic(const Value *Inst)
static Value * getUnderLyingObjectForBrevLdIntr(Value *V, int &Offset, bool &HasOffset)
static Value * getBrevLdObject(Value *V)
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 unsigned assignVTCMStackOffsets(SmallVectorImpl< CCValAssign > &ArgLocs)
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)
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#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)
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:1508
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:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
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:63
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
AtomicExpansionKind shouldExpandAtomicLoadInIR(const LoadInst *LI) const override
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass.
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
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 LowerBoolVectorSelect(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.
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
AtomicExpansionKind shouldExpandAtomicStoreInIR(const StoreInst *SI) const override
Returns how the given (atomic) store should be expanded by the IR-level AtomicExpand pass into.
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 a boolean value from i1 to a wider type.
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.
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
@ Off
Use window algorithm after SMS algorithm fails.
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