1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
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
7 //===----------------------------------------------------------------------===//
9 // This implements the SelectionDAG class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/CodeGen/ISDOpcodes.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/RuntimeLibcalls.h"
35 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/CodeGen/ValueTypes.h"
42 #include "llvm/IR/Constant.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/DebugInfoMetadata.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/KnownBits.h"
59 #include "llvm/Support/MachineValueType.h"
60 #include "llvm/Support/ManagedStatic.h"
61 #include "llvm/Support/MathExtras.h"
62 #include "llvm/Support/Mutex.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Target/TargetOptions.h"
78 /// makeVTList - Return an instance of the SDVTList struct initialized with the
79 /// specified members.
80 static SDVTList
makeVTList(const EVT
*VTs
, unsigned NumVTs
) {
81 SDVTList Res
= {VTs
, NumVTs
};
85 // Default null implementations of the callbacks.
86 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode
*, SDNode
*) {}
87 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode
*) {}
88 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode
*) {}
90 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
92 #define DEBUG_TYPE "selectiondag"
94 static cl::opt
<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
95 cl::Hidden
, cl::init(true),
96 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
98 static cl::opt
<int> MaxLdStGlue("ldstmemcpy-glue-max",
99 cl::desc("Number limit for gluing ld/st of memcpy."),
100 cl::Hidden
, cl::init(0));
102 static void NewSDValueDbgMsg(SDValue V
, StringRef Msg
, SelectionDAG
*G
) {
103 LLVM_DEBUG(dbgs() << Msg
; V
.getNode()->dump(G
););
106 //===----------------------------------------------------------------------===//
107 // ConstantFPSDNode Class
108 //===----------------------------------------------------------------------===//
110 /// isExactlyValue - We don't rely on operator== working on double values, as
111 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
112 /// As such, this method can be used to do an exact bit-for-bit comparison of
113 /// two floating point values.
114 bool ConstantFPSDNode::isExactlyValue(const APFloat
& V
) const {
115 return getValueAPF().bitwiseIsEqual(V
);
118 bool ConstantFPSDNode::isValueValidForType(EVT VT
,
119 const APFloat
& Val
) {
120 assert(VT
.isFloatingPoint() && "Can only convert between FP types");
122 // convert modifies in place, so make a copy.
123 APFloat Val2
= APFloat(Val
);
125 (void) Val2
.convert(SelectionDAG::EVTToAPFloatSemantics(VT
),
126 APFloat::rmNearestTiesToEven
,
131 //===----------------------------------------------------------------------===//
133 //===----------------------------------------------------------------------===//
135 bool ISD::isConstantSplatVector(const SDNode
*N
, APInt
&SplatVal
) {
136 auto *BV
= dyn_cast
<BuildVectorSDNode
>(N
);
141 unsigned SplatBitSize
;
143 unsigned EltSize
= N
->getValueType(0).getVectorElementType().getSizeInBits();
144 return BV
->isConstantSplat(SplatVal
, SplatUndef
, SplatBitSize
, HasUndefs
,
146 EltSize
== SplatBitSize
;
149 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
150 // specializations of the more general isConstantSplatVector()?
152 bool ISD::isBuildVectorAllOnes(const SDNode
*N
) {
153 // Look through a bit convert.
154 while (N
->getOpcode() == ISD::BITCAST
)
155 N
= N
->getOperand(0).getNode();
157 if (N
->getOpcode() != ISD::BUILD_VECTOR
) return false;
159 unsigned i
= 0, e
= N
->getNumOperands();
161 // Skip over all of the undef values.
162 while (i
!= e
&& N
->getOperand(i
).isUndef())
165 // Do not accept an all-undef vector.
166 if (i
== e
) return false;
168 // Do not accept build_vectors that aren't all constants or which have non-~0
169 // elements. We have to be a bit careful here, as the type of the constant
170 // may not be the same as the type of the vector elements due to type
171 // legalization (the elements are promoted to a legal type for the target and
172 // a vector of a type may be legal when the base element type is not).
173 // We only want to check enough bits to cover the vector elements, because
174 // we care if the resultant vector is all ones, not whether the individual
176 SDValue NotZero
= N
->getOperand(i
);
177 unsigned EltSize
= N
->getValueType(0).getScalarSizeInBits();
178 if (ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(NotZero
)) {
179 if (CN
->getAPIntValue().countTrailingOnes() < EltSize
)
181 } else if (ConstantFPSDNode
*CFPN
= dyn_cast
<ConstantFPSDNode
>(NotZero
)) {
182 if (CFPN
->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize
)
187 // Okay, we have at least one ~0 value, check to see if the rest match or are
188 // undefs. Even with the above element type twiddling, this should be OK, as
189 // the same type legalization should have applied to all the elements.
190 for (++i
; i
!= e
; ++i
)
191 if (N
->getOperand(i
) != NotZero
&& !N
->getOperand(i
).isUndef())
196 bool ISD::isBuildVectorAllZeros(const SDNode
*N
) {
197 // Look through a bit convert.
198 while (N
->getOpcode() == ISD::BITCAST
)
199 N
= N
->getOperand(0).getNode();
201 if (N
->getOpcode() != ISD::BUILD_VECTOR
) return false;
203 bool IsAllUndef
= true;
204 for (const SDValue
&Op
: N
->op_values()) {
208 // Do not accept build_vectors that aren't all constants or which have non-0
209 // elements. We have to be a bit careful here, as the type of the constant
210 // may not be the same as the type of the vector elements due to type
211 // legalization (the elements are promoted to a legal type for the target
212 // and a vector of a type may be legal when the base element type is not).
213 // We only want to check enough bits to cover the vector elements, because
214 // we care if the resultant vector is all zeros, not whether the individual
216 unsigned EltSize
= N
->getValueType(0).getScalarSizeInBits();
217 if (ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(Op
)) {
218 if (CN
->getAPIntValue().countTrailingZeros() < EltSize
)
220 } else if (ConstantFPSDNode
*CFPN
= dyn_cast
<ConstantFPSDNode
>(Op
)) {
221 if (CFPN
->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize
)
227 // Do not accept an all-undef vector.
233 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode
*N
) {
234 if (N
->getOpcode() != ISD::BUILD_VECTOR
)
237 for (const SDValue
&Op
: N
->op_values()) {
240 if (!isa
<ConstantSDNode
>(Op
))
246 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode
*N
) {
247 if (N
->getOpcode() != ISD::BUILD_VECTOR
)
250 for (const SDValue
&Op
: N
->op_values()) {
253 if (!isa
<ConstantFPSDNode
>(Op
))
259 bool ISD::allOperandsUndef(const SDNode
*N
) {
260 // Return false if the node has no operands.
261 // This is "logically inconsistent" with the definition of "all" but
262 // is probably the desired behavior.
263 if (N
->getNumOperands() == 0)
265 return all_of(N
->op_values(), [](SDValue Op
) { return Op
.isUndef(); });
268 bool ISD::matchUnaryPredicate(SDValue Op
,
269 std::function
<bool(ConstantSDNode
*)> Match
,
271 // FIXME: Add support for scalar UNDEF cases?
272 if (auto *Cst
= dyn_cast
<ConstantSDNode
>(Op
))
275 // FIXME: Add support for vector UNDEF cases?
276 if (ISD::BUILD_VECTOR
!= Op
.getOpcode())
279 EVT SVT
= Op
.getValueType().getScalarType();
280 for (unsigned i
= 0, e
= Op
.getNumOperands(); i
!= e
; ++i
) {
281 if (AllowUndefs
&& Op
.getOperand(i
).isUndef()) {
287 auto *Cst
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(i
));
288 if (!Cst
|| Cst
->getValueType(0) != SVT
|| !Match(Cst
))
294 bool ISD::matchBinaryPredicate(
295 SDValue LHS
, SDValue RHS
,
296 std::function
<bool(ConstantSDNode
*, ConstantSDNode
*)> Match
,
298 if (LHS
.getValueType() != RHS
.getValueType())
301 // TODO: Add support for scalar UNDEF cases?
302 if (auto *LHSCst
= dyn_cast
<ConstantSDNode
>(LHS
))
303 if (auto *RHSCst
= dyn_cast
<ConstantSDNode
>(RHS
))
304 return Match(LHSCst
, RHSCst
);
306 // TODO: Add support for vector UNDEF cases?
307 if (ISD::BUILD_VECTOR
!= LHS
.getOpcode() ||
308 ISD::BUILD_VECTOR
!= RHS
.getOpcode())
311 EVT SVT
= LHS
.getValueType().getScalarType();
312 for (unsigned i
= 0, e
= LHS
.getNumOperands(); i
!= e
; ++i
) {
313 SDValue LHSOp
= LHS
.getOperand(i
);
314 SDValue RHSOp
= RHS
.getOperand(i
);
315 bool LHSUndef
= AllowUndefs
&& LHSOp
.isUndef();
316 bool RHSUndef
= AllowUndefs
&& RHSOp
.isUndef();
317 auto *LHSCst
= dyn_cast
<ConstantSDNode
>(LHSOp
);
318 auto *RHSCst
= dyn_cast
<ConstantSDNode
>(RHSOp
);
319 if ((!LHSCst
&& !LHSUndef
) || (!RHSCst
&& !RHSUndef
))
321 if (LHSOp
.getValueType() != SVT
||
322 LHSOp
.getValueType() != RHSOp
.getValueType())
324 if (!Match(LHSCst
, RHSCst
))
330 ISD::NodeType
ISD::getExtForLoadExtType(bool IsFP
, ISD::LoadExtType ExtType
) {
333 return IsFP
? ISD::FP_EXTEND
: ISD::ANY_EXTEND
;
335 return ISD::SIGN_EXTEND
;
337 return ISD::ZERO_EXTEND
;
342 llvm_unreachable("Invalid LoadExtType");
345 ISD::CondCode
ISD::getSetCCSwappedOperands(ISD::CondCode Operation
) {
346 // To perform this operation, we just need to swap the L and G bits of the
348 unsigned OldL
= (Operation
>> 2) & 1;
349 unsigned OldG
= (Operation
>> 1) & 1;
350 return ISD::CondCode((Operation
& ~6) | // Keep the N, U, E bits
351 (OldL
<< 1) | // New G bit
352 (OldG
<< 2)); // New L bit.
355 ISD::CondCode
ISD::getSetCCInverse(ISD::CondCode Op
, bool isInteger
) {
356 unsigned Operation
= Op
;
358 Operation
^= 7; // Flip L, G, E bits, but not U.
360 Operation
^= 15; // Flip all of the condition bits.
362 if (Operation
> ISD::SETTRUE2
)
363 Operation
&= ~8; // Don't let N and U bits get set.
365 return ISD::CondCode(Operation
);
368 /// For an integer comparison, return 1 if the comparison is a signed operation
369 /// and 2 if the result is an unsigned comparison. Return zero if the operation
370 /// does not depend on the sign of the input (setne and seteq).
371 static int isSignedOp(ISD::CondCode Opcode
) {
373 default: llvm_unreachable("Illegal integer setcc operation!");
375 case ISD::SETNE
: return 0;
379 case ISD::SETGE
: return 1;
383 case ISD::SETUGE
: return 2;
387 ISD::CondCode
ISD::getSetCCOrOperation(ISD::CondCode Op1
, ISD::CondCode Op2
,
389 if (IsInteger
&& (isSignedOp(Op1
) | isSignedOp(Op2
)) == 3)
390 // Cannot fold a signed integer setcc with an unsigned integer setcc.
391 return ISD::SETCC_INVALID
;
393 unsigned Op
= Op1
| Op2
; // Combine all of the condition bits.
395 // If the N and U bits get set, then the resultant comparison DOES suddenly
396 // care about orderedness, and it is true when ordered.
397 if (Op
> ISD::SETTRUE2
)
398 Op
&= ~16; // Clear the U bit if the N bit is set.
400 // Canonicalize illegal integer setcc's.
401 if (IsInteger
&& Op
== ISD::SETUNE
) // e.g. SETUGT | SETULT
404 return ISD::CondCode(Op
);
407 ISD::CondCode
ISD::getSetCCAndOperation(ISD::CondCode Op1
, ISD::CondCode Op2
,
409 if (IsInteger
&& (isSignedOp(Op1
) | isSignedOp(Op2
)) == 3)
410 // Cannot fold a signed setcc with an unsigned setcc.
411 return ISD::SETCC_INVALID
;
413 // Combine all of the condition bits.
414 ISD::CondCode Result
= ISD::CondCode(Op1
& Op2
);
416 // Canonicalize illegal integer setcc's.
420 case ISD::SETUO
: Result
= ISD::SETFALSE
; break; // SETUGT & SETULT
421 case ISD::SETOEQ
: // SETEQ & SETU[LG]E
422 case ISD::SETUEQ
: Result
= ISD::SETEQ
; break; // SETUGE & SETULE
423 case ISD::SETOLT
: Result
= ISD::SETULT
; break; // SETULT & SETNE
424 case ISD::SETOGT
: Result
= ISD::SETUGT
; break; // SETUGT & SETNE
431 //===----------------------------------------------------------------------===//
432 // SDNode Profile Support
433 //===----------------------------------------------------------------------===//
435 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
436 static void AddNodeIDOpcode(FoldingSetNodeID
&ID
, unsigned OpC
) {
440 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
441 /// solely with their pointer.
442 static void AddNodeIDValueTypes(FoldingSetNodeID
&ID
, SDVTList VTList
) {
443 ID
.AddPointer(VTList
.VTs
);
446 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
447 static void AddNodeIDOperands(FoldingSetNodeID
&ID
,
448 ArrayRef
<SDValue
> Ops
) {
449 for (auto& Op
: Ops
) {
450 ID
.AddPointer(Op
.getNode());
451 ID
.AddInteger(Op
.getResNo());
455 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
456 static void AddNodeIDOperands(FoldingSetNodeID
&ID
,
457 ArrayRef
<SDUse
> Ops
) {
458 for (auto& Op
: Ops
) {
459 ID
.AddPointer(Op
.getNode());
460 ID
.AddInteger(Op
.getResNo());
464 static void AddNodeIDNode(FoldingSetNodeID
&ID
, unsigned short OpC
,
465 SDVTList VTList
, ArrayRef
<SDValue
> OpList
) {
466 AddNodeIDOpcode(ID
, OpC
);
467 AddNodeIDValueTypes(ID
, VTList
);
468 AddNodeIDOperands(ID
, OpList
);
471 /// If this is an SDNode with special info, add this info to the NodeID data.
472 static void AddNodeIDCustom(FoldingSetNodeID
&ID
, const SDNode
*N
) {
473 switch (N
->getOpcode()) {
474 case ISD::TargetExternalSymbol
:
475 case ISD::ExternalSymbol
:
477 llvm_unreachable("Should only be used on nodes with operands");
478 default: break; // Normal nodes don't need extra info.
479 case ISD::TargetConstant
:
480 case ISD::Constant
: {
481 const ConstantSDNode
*C
= cast
<ConstantSDNode
>(N
);
482 ID
.AddPointer(C
->getConstantIntValue());
483 ID
.AddBoolean(C
->isOpaque());
486 case ISD::TargetConstantFP
:
487 case ISD::ConstantFP
:
488 ID
.AddPointer(cast
<ConstantFPSDNode
>(N
)->getConstantFPValue());
490 case ISD::TargetGlobalAddress
:
491 case ISD::GlobalAddress
:
492 case ISD::TargetGlobalTLSAddress
:
493 case ISD::GlobalTLSAddress
: {
494 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(N
);
495 ID
.AddPointer(GA
->getGlobal());
496 ID
.AddInteger(GA
->getOffset());
497 ID
.AddInteger(GA
->getTargetFlags());
500 case ISD::BasicBlock
:
501 ID
.AddPointer(cast
<BasicBlockSDNode
>(N
)->getBasicBlock());
504 ID
.AddInteger(cast
<RegisterSDNode
>(N
)->getReg());
506 case ISD::RegisterMask
:
507 ID
.AddPointer(cast
<RegisterMaskSDNode
>(N
)->getRegMask());
510 ID
.AddPointer(cast
<SrcValueSDNode
>(N
)->getValue());
512 case ISD::FrameIndex
:
513 case ISD::TargetFrameIndex
:
514 ID
.AddInteger(cast
<FrameIndexSDNode
>(N
)->getIndex());
516 case ISD::LIFETIME_START
:
517 case ISD::LIFETIME_END
:
518 if (cast
<LifetimeSDNode
>(N
)->hasOffset()) {
519 ID
.AddInteger(cast
<LifetimeSDNode
>(N
)->getSize());
520 ID
.AddInteger(cast
<LifetimeSDNode
>(N
)->getOffset());
524 case ISD::TargetJumpTable
:
525 ID
.AddInteger(cast
<JumpTableSDNode
>(N
)->getIndex());
526 ID
.AddInteger(cast
<JumpTableSDNode
>(N
)->getTargetFlags());
528 case ISD::ConstantPool
:
529 case ISD::TargetConstantPool
: {
530 const ConstantPoolSDNode
*CP
= cast
<ConstantPoolSDNode
>(N
);
531 ID
.AddInteger(CP
->getAlignment());
532 ID
.AddInteger(CP
->getOffset());
533 if (CP
->isMachineConstantPoolEntry())
534 CP
->getMachineCPVal()->addSelectionDAGCSEId(ID
);
536 ID
.AddPointer(CP
->getConstVal());
537 ID
.AddInteger(CP
->getTargetFlags());
540 case ISD::TargetIndex
: {
541 const TargetIndexSDNode
*TI
= cast
<TargetIndexSDNode
>(N
);
542 ID
.AddInteger(TI
->getIndex());
543 ID
.AddInteger(TI
->getOffset());
544 ID
.AddInteger(TI
->getTargetFlags());
548 const LoadSDNode
*LD
= cast
<LoadSDNode
>(N
);
549 ID
.AddInteger(LD
->getMemoryVT().getRawBits());
550 ID
.AddInteger(LD
->getRawSubclassData());
551 ID
.AddInteger(LD
->getPointerInfo().getAddrSpace());
555 const StoreSDNode
*ST
= cast
<StoreSDNode
>(N
);
556 ID
.AddInteger(ST
->getMemoryVT().getRawBits());
557 ID
.AddInteger(ST
->getRawSubclassData());
558 ID
.AddInteger(ST
->getPointerInfo().getAddrSpace());
562 const MaskedLoadSDNode
*MLD
= cast
<MaskedLoadSDNode
>(N
);
563 ID
.AddInteger(MLD
->getMemoryVT().getRawBits());
564 ID
.AddInteger(MLD
->getRawSubclassData());
565 ID
.AddInteger(MLD
->getPointerInfo().getAddrSpace());
569 const MaskedStoreSDNode
*MST
= cast
<MaskedStoreSDNode
>(N
);
570 ID
.AddInteger(MST
->getMemoryVT().getRawBits());
571 ID
.AddInteger(MST
->getRawSubclassData());
572 ID
.AddInteger(MST
->getPointerInfo().getAddrSpace());
576 const MaskedGatherSDNode
*MG
= cast
<MaskedGatherSDNode
>(N
);
577 ID
.AddInteger(MG
->getMemoryVT().getRawBits());
578 ID
.AddInteger(MG
->getRawSubclassData());
579 ID
.AddInteger(MG
->getPointerInfo().getAddrSpace());
582 case ISD::MSCATTER
: {
583 const MaskedScatterSDNode
*MS
= cast
<MaskedScatterSDNode
>(N
);
584 ID
.AddInteger(MS
->getMemoryVT().getRawBits());
585 ID
.AddInteger(MS
->getRawSubclassData());
586 ID
.AddInteger(MS
->getPointerInfo().getAddrSpace());
589 case ISD::ATOMIC_CMP_SWAP
:
590 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS
:
591 case ISD::ATOMIC_SWAP
:
592 case ISD::ATOMIC_LOAD_ADD
:
593 case ISD::ATOMIC_LOAD_SUB
:
594 case ISD::ATOMIC_LOAD_AND
:
595 case ISD::ATOMIC_LOAD_CLR
:
596 case ISD::ATOMIC_LOAD_OR
:
597 case ISD::ATOMIC_LOAD_XOR
:
598 case ISD::ATOMIC_LOAD_NAND
:
599 case ISD::ATOMIC_LOAD_MIN
:
600 case ISD::ATOMIC_LOAD_MAX
:
601 case ISD::ATOMIC_LOAD_UMIN
:
602 case ISD::ATOMIC_LOAD_UMAX
:
603 case ISD::ATOMIC_LOAD
:
604 case ISD::ATOMIC_STORE
: {
605 const AtomicSDNode
*AT
= cast
<AtomicSDNode
>(N
);
606 ID
.AddInteger(AT
->getMemoryVT().getRawBits());
607 ID
.AddInteger(AT
->getRawSubclassData());
608 ID
.AddInteger(AT
->getPointerInfo().getAddrSpace());
611 case ISD::PREFETCH
: {
612 const MemSDNode
*PF
= cast
<MemSDNode
>(N
);
613 ID
.AddInteger(PF
->getPointerInfo().getAddrSpace());
616 case ISD::VECTOR_SHUFFLE
: {
617 const ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(N
);
618 for (unsigned i
= 0, e
= N
->getValueType(0).getVectorNumElements();
620 ID
.AddInteger(SVN
->getMaskElt(i
));
623 case ISD::TargetBlockAddress
:
624 case ISD::BlockAddress
: {
625 const BlockAddressSDNode
*BA
= cast
<BlockAddressSDNode
>(N
);
626 ID
.AddPointer(BA
->getBlockAddress());
627 ID
.AddInteger(BA
->getOffset());
628 ID
.AddInteger(BA
->getTargetFlags());
631 } // end switch (N->getOpcode())
633 // Target specific memory nodes could also have address spaces to check.
634 if (N
->isTargetMemoryOpcode())
635 ID
.AddInteger(cast
<MemSDNode
>(N
)->getPointerInfo().getAddrSpace());
638 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
640 static void AddNodeIDNode(FoldingSetNodeID
&ID
, const SDNode
*N
) {
641 AddNodeIDOpcode(ID
, N
->getOpcode());
642 // Add the return value info.
643 AddNodeIDValueTypes(ID
, N
->getVTList());
644 // Add the operand info.
645 AddNodeIDOperands(ID
, N
->ops());
647 // Handle SDNode leafs with special info.
648 AddNodeIDCustom(ID
, N
);
651 //===----------------------------------------------------------------------===//
652 // SelectionDAG Class
653 //===----------------------------------------------------------------------===//
655 /// doNotCSE - Return true if CSE should not be performed for this node.
656 static bool doNotCSE(SDNode
*N
) {
657 if (N
->getValueType(0) == MVT::Glue
)
658 return true; // Never CSE anything that produces a flag.
660 switch (N
->getOpcode()) {
662 case ISD::HANDLENODE
:
664 return true; // Never CSE these nodes.
667 // Check that remaining values produced are not flags.
668 for (unsigned i
= 1, e
= N
->getNumValues(); i
!= e
; ++i
)
669 if (N
->getValueType(i
) == MVT::Glue
)
670 return true; // Never CSE anything that produces a flag.
675 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
677 void SelectionDAG::RemoveDeadNodes() {
678 // Create a dummy node (which is not added to allnodes), that adds a reference
679 // to the root node, preventing it from being deleted.
680 HandleSDNode
Dummy(getRoot());
682 SmallVector
<SDNode
*, 128> DeadNodes
;
684 // Add all obviously-dead nodes to the DeadNodes worklist.
685 for (SDNode
&Node
: allnodes())
686 if (Node
.use_empty())
687 DeadNodes
.push_back(&Node
);
689 RemoveDeadNodes(DeadNodes
);
691 // If the root changed (e.g. it was a dead load, update the root).
692 setRoot(Dummy
.getValue());
695 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
696 /// given list, and any nodes that become unreachable as a result.
697 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl
<SDNode
*> &DeadNodes
) {
699 // Process the worklist, deleting the nodes and adding their uses to the
701 while (!DeadNodes
.empty()) {
702 SDNode
*N
= DeadNodes
.pop_back_val();
703 // Skip to next node if we've already managed to delete the node. This could
704 // happen if replacing a node causes a node previously added to the node to
706 if (N
->getOpcode() == ISD::DELETED_NODE
)
709 for (DAGUpdateListener
*DUL
= UpdateListeners
; DUL
; DUL
= DUL
->Next
)
710 DUL
->NodeDeleted(N
, nullptr);
712 // Take the node out of the appropriate CSE map.
713 RemoveNodeFromCSEMaps(N
);
715 // Next, brutally remove the operand list. This is safe to do, as there are
716 // no cycles in the graph.
717 for (SDNode::op_iterator I
= N
->op_begin(), E
= N
->op_end(); I
!= E
; ) {
719 SDNode
*Operand
= Use
.getNode();
722 // Now that we removed this operand, see if there are no uses of it left.
723 if (Operand
->use_empty())
724 DeadNodes
.push_back(Operand
);
731 void SelectionDAG::RemoveDeadNode(SDNode
*N
){
732 SmallVector
<SDNode
*, 16> DeadNodes(1, N
);
734 // Create a dummy node that adds a reference to the root node, preventing
735 // it from being deleted. (This matters if the root is an operand of the
737 HandleSDNode
Dummy(getRoot());
739 RemoveDeadNodes(DeadNodes
);
742 void SelectionDAG::DeleteNode(SDNode
*N
) {
743 // First take this out of the appropriate CSE map.
744 RemoveNodeFromCSEMaps(N
);
746 // Finally, remove uses due to operands of this node, remove from the
747 // AllNodes list, and delete the node.
748 DeleteNodeNotInCSEMaps(N
);
751 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode
*N
) {
752 assert(N
->getIterator() != AllNodes
.begin() &&
753 "Cannot delete the entry node!");
754 assert(N
->use_empty() && "Cannot delete a node that is not dead!");
756 // Drop all of the operands and decrement used node's use counts.
762 void SDDbgInfo::erase(const SDNode
*Node
) {
763 DbgValMapType::iterator I
= DbgValMap
.find(Node
);
764 if (I
== DbgValMap
.end())
766 for (auto &Val
: I
->second
)
767 Val
->setIsInvalidated();
771 void SelectionDAG::DeallocateNode(SDNode
*N
) {
772 // If we have operands, deallocate them.
775 NodeAllocator
.Deallocate(AllNodes
.remove(N
));
777 // Set the opcode to DELETED_NODE to help catch bugs when node
778 // memory is reallocated.
779 // FIXME: There are places in SDag that have grown a dependency on the opcode
780 // value in the released node.
781 __asan_unpoison_memory_region(&N
->NodeType
, sizeof(N
->NodeType
));
782 N
->NodeType
= ISD::DELETED_NODE
;
784 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
785 // them and forget about that node.
790 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
791 static void VerifySDNode(SDNode
*N
) {
792 switch (N
->getOpcode()) {
795 case ISD::BUILD_PAIR
: {
796 EVT VT
= N
->getValueType(0);
797 assert(N
->getNumValues() == 1 && "Too many results!");
798 assert(!VT
.isVector() && (VT
.isInteger() || VT
.isFloatingPoint()) &&
799 "Wrong return type!");
800 assert(N
->getNumOperands() == 2 && "Wrong number of operands!");
801 assert(N
->getOperand(0).getValueType() == N
->getOperand(1).getValueType() &&
802 "Mismatched operand types!");
803 assert(N
->getOperand(0).getValueType().isInteger() == VT
.isInteger() &&
804 "Wrong operand type!");
805 assert(VT
.getSizeInBits() == 2 * N
->getOperand(0).getValueSizeInBits() &&
806 "Wrong return type size");
809 case ISD::BUILD_VECTOR
: {
810 assert(N
->getNumValues() == 1 && "Too many results!");
811 assert(N
->getValueType(0).isVector() && "Wrong return type!");
812 assert(N
->getNumOperands() == N
->getValueType(0).getVectorNumElements() &&
813 "Wrong number of operands!");
814 EVT EltVT
= N
->getValueType(0).getVectorElementType();
815 for (SDNode::op_iterator I
= N
->op_begin(), E
= N
->op_end(); I
!= E
; ++I
) {
816 assert((I
->getValueType() == EltVT
||
817 (EltVT
.isInteger() && I
->getValueType().isInteger() &&
818 EltVT
.bitsLE(I
->getValueType()))) &&
819 "Wrong operand type!");
820 assert(I
->getValueType() == N
->getOperand(0).getValueType() &&
821 "Operands must all have the same type");
829 /// Insert a newly allocated node into the DAG.
831 /// Handles insertion into the all nodes list and CSE map, as well as
832 /// verification and other common operations when a new node is allocated.
833 void SelectionDAG::InsertNode(SDNode
*N
) {
834 AllNodes
.push_back(N
);
836 N
->PersistentId
= NextPersistentId
++;
839 for (DAGUpdateListener
*DUL
= UpdateListeners
; DUL
; DUL
= DUL
->Next
)
840 DUL
->NodeInserted(N
);
843 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
844 /// correspond to it. This is useful when we're about to delete or repurpose
845 /// the node. We don't want future request for structurally identical nodes
846 /// to return N anymore.
847 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode
*N
) {
849 switch (N
->getOpcode()) {
850 case ISD::HANDLENODE
: return false; // noop.
852 assert(CondCodeNodes
[cast
<CondCodeSDNode
>(N
)->get()] &&
853 "Cond code doesn't exist!");
854 Erased
= CondCodeNodes
[cast
<CondCodeSDNode
>(N
)->get()] != nullptr;
855 CondCodeNodes
[cast
<CondCodeSDNode
>(N
)->get()] = nullptr;
857 case ISD::ExternalSymbol
:
858 Erased
= ExternalSymbols
.erase(cast
<ExternalSymbolSDNode
>(N
)->getSymbol());
860 case ISD::TargetExternalSymbol
: {
861 ExternalSymbolSDNode
*ESN
= cast
<ExternalSymbolSDNode
>(N
);
862 Erased
= TargetExternalSymbols
.erase(
863 std::pair
<std::string
,unsigned char>(ESN
->getSymbol(),
864 ESN
->getTargetFlags()));
867 case ISD::MCSymbol
: {
868 auto *MCSN
= cast
<MCSymbolSDNode
>(N
);
869 Erased
= MCSymbols
.erase(MCSN
->getMCSymbol());
872 case ISD::VALUETYPE
: {
873 EVT VT
= cast
<VTSDNode
>(N
)->getVT();
874 if (VT
.isExtended()) {
875 Erased
= ExtendedValueTypeNodes
.erase(VT
);
877 Erased
= ValueTypeNodes
[VT
.getSimpleVT().SimpleTy
] != nullptr;
878 ValueTypeNodes
[VT
.getSimpleVT().SimpleTy
] = nullptr;
883 // Remove it from the CSE Map.
884 assert(N
->getOpcode() != ISD::DELETED_NODE
&& "DELETED_NODE in CSEMap!");
885 assert(N
->getOpcode() != ISD::EntryToken
&& "EntryToken in CSEMap!");
886 Erased
= CSEMap
.RemoveNode(N
);
890 // Verify that the node was actually in one of the CSE maps, unless it has a
891 // flag result (which cannot be CSE'd) or is one of the special cases that are
892 // not subject to CSE.
893 if (!Erased
&& N
->getValueType(N
->getNumValues()-1) != MVT::Glue
&&
894 !N
->isMachineOpcode() && !doNotCSE(N
)) {
897 llvm_unreachable("Node is not in map!");
903 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
904 /// maps and modified in place. Add it back to the CSE maps, unless an identical
905 /// node already exists, in which case transfer all its users to the existing
906 /// node. This transfer can potentially trigger recursive merging.
908 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode
*N
) {
909 // For node types that aren't CSE'd, just act as if no identical node
912 SDNode
*Existing
= CSEMap
.GetOrInsertNode(N
);
914 // If there was already an existing matching node, use ReplaceAllUsesWith
915 // to replace the dead one with the existing one. This can cause
916 // recursive merging of other unrelated nodes down the line.
917 ReplaceAllUsesWith(N
, Existing
);
919 // N is now dead. Inform the listeners and delete it.
920 for (DAGUpdateListener
*DUL
= UpdateListeners
; DUL
; DUL
= DUL
->Next
)
921 DUL
->NodeDeleted(N
, Existing
);
922 DeleteNodeNotInCSEMaps(N
);
927 // If the node doesn't already exist, we updated it. Inform listeners.
928 for (DAGUpdateListener
*DUL
= UpdateListeners
; DUL
; DUL
= DUL
->Next
)
932 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
933 /// were replaced with those specified. If this node is never memoized,
934 /// return null, otherwise return a pointer to the slot it would take. If a
935 /// node already exists with these operands, the slot will be non-null.
936 SDNode
*SelectionDAG::FindModifiedNodeSlot(SDNode
*N
, SDValue Op
,
941 SDValue Ops
[] = { Op
};
943 AddNodeIDNode(ID
, N
->getOpcode(), N
->getVTList(), Ops
);
944 AddNodeIDCustom(ID
, N
);
945 SDNode
*Node
= FindNodeOrInsertPos(ID
, SDLoc(N
), InsertPos
);
947 Node
->intersectFlagsWith(N
->getFlags());
951 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
952 /// were replaced with those specified. If this node is never memoized,
953 /// return null, otherwise return a pointer to the slot it would take. If a
954 /// node already exists with these operands, the slot will be non-null.
955 SDNode
*SelectionDAG::FindModifiedNodeSlot(SDNode
*N
,
956 SDValue Op1
, SDValue Op2
,
961 SDValue Ops
[] = { Op1
, Op2
};
963 AddNodeIDNode(ID
, N
->getOpcode(), N
->getVTList(), Ops
);
964 AddNodeIDCustom(ID
, N
);
965 SDNode
*Node
= FindNodeOrInsertPos(ID
, SDLoc(N
), InsertPos
);
967 Node
->intersectFlagsWith(N
->getFlags());
971 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
972 /// were replaced with those specified. If this node is never memoized,
973 /// return null, otherwise return a pointer to the slot it would take. If a
974 /// node already exists with these operands, the slot will be non-null.
975 SDNode
*SelectionDAG::FindModifiedNodeSlot(SDNode
*N
, ArrayRef
<SDValue
> Ops
,
981 AddNodeIDNode(ID
, N
->getOpcode(), N
->getVTList(), Ops
);
982 AddNodeIDCustom(ID
, N
);
983 SDNode
*Node
= FindNodeOrInsertPos(ID
, SDLoc(N
), InsertPos
);
985 Node
->intersectFlagsWith(N
->getFlags());
989 unsigned SelectionDAG::getEVTAlignment(EVT VT
) const {
990 Type
*Ty
= VT
== MVT::iPTR
?
991 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
992 VT
.getTypeForEVT(*getContext());
994 return getDataLayout().getABITypeAlignment(Ty
);
997 // EntryNode could meaningfully have debug info if we can find it...
998 SelectionDAG::SelectionDAG(const TargetMachine
&tm
, CodeGenOpt::Level OL
)
999 : TM(tm
), OptLevel(OL
),
1000 EntryNode(ISD::EntryToken
, 0, DebugLoc(), getVTList(MVT::Other
)),
1001 Root(getEntryNode()) {
1002 InsertNode(&EntryNode
);
1003 DbgInfo
= new SDDbgInfo();
1006 void SelectionDAG::init(MachineFunction
&NewMF
,
1007 OptimizationRemarkEmitter
&NewORE
,
1008 Pass
*PassPtr
, const TargetLibraryInfo
*LibraryInfo
,
1009 LegacyDivergenceAnalysis
* Divergence
) {
1011 SDAGISelPass
= PassPtr
;
1013 TLI
= getSubtarget().getTargetLowering();
1014 TSI
= getSubtarget().getSelectionDAGInfo();
1015 LibInfo
= LibraryInfo
;
1016 Context
= &MF
->getFunction().getContext();
1020 SelectionDAG::~SelectionDAG() {
1021 assert(!UpdateListeners
&& "Dangling registered DAGUpdateListeners");
1023 OperandRecycler
.clear(OperandAllocator
);
1027 void SelectionDAG::allnodes_clear() {
1028 assert(&*AllNodes
.begin() == &EntryNode
);
1029 AllNodes
.remove(AllNodes
.begin());
1030 while (!AllNodes
.empty())
1031 DeallocateNode(&AllNodes
.front());
1033 NextPersistentId
= 0;
1037 SDNode
*SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID
&ID
,
1039 SDNode
*N
= CSEMap
.FindNodeOrInsertPos(ID
, InsertPos
);
1041 switch (N
->getOpcode()) {
1044 case ISD::ConstantFP
:
1045 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1046 "debug location. Use another overload.");
1052 SDNode
*SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID
&ID
,
1053 const SDLoc
&DL
, void *&InsertPos
) {
1054 SDNode
*N
= CSEMap
.FindNodeOrInsertPos(ID
, InsertPos
);
1056 switch (N
->getOpcode()) {
1058 case ISD::ConstantFP
:
1059 // Erase debug location from the node if the node is used at several
1060 // different places. Do not propagate one location to all uses as it
1061 // will cause a worse single stepping debugging experience.
1062 if (N
->getDebugLoc() != DL
.getDebugLoc())
1063 N
->setDebugLoc(DebugLoc());
1066 // When the node's point of use is located earlier in the instruction
1067 // sequence than its prior point of use, update its debug info to the
1068 // earlier location.
1069 if (DL
.getIROrder() && DL
.getIROrder() < N
->getIROrder())
1070 N
->setDebugLoc(DL
.getDebugLoc());
1077 void SelectionDAG::clear() {
1079 OperandRecycler
.clear(OperandAllocator
);
1080 OperandAllocator
.Reset();
1083 ExtendedValueTypeNodes
.clear();
1084 ExternalSymbols
.clear();
1085 TargetExternalSymbols
.clear();
1087 std::fill(CondCodeNodes
.begin(), CondCodeNodes
.end(),
1088 static_cast<CondCodeSDNode
*>(nullptr));
1089 std::fill(ValueTypeNodes
.begin(), ValueTypeNodes
.end(),
1090 static_cast<SDNode
*>(nullptr));
1092 EntryNode
.UseList
= nullptr;
1093 InsertNode(&EntryNode
);
1094 Root
= getEntryNode();
1098 SDValue
SelectionDAG::getFPExtendOrRound(SDValue Op
, const SDLoc
&DL
, EVT VT
) {
1099 return VT
.bitsGT(Op
.getValueType())
1100 ? getNode(ISD::FP_EXTEND
, DL
, VT
, Op
)
1101 : getNode(ISD::FP_ROUND
, DL
, VT
, Op
, getIntPtrConstant(0, DL
));
1104 SDValue
SelectionDAG::getAnyExtOrTrunc(SDValue Op
, const SDLoc
&DL
, EVT VT
) {
1105 return VT
.bitsGT(Op
.getValueType()) ?
1106 getNode(ISD::ANY_EXTEND
, DL
, VT
, Op
) :
1107 getNode(ISD::TRUNCATE
, DL
, VT
, Op
);
1110 SDValue
SelectionDAG::getSExtOrTrunc(SDValue Op
, const SDLoc
&DL
, EVT VT
) {
1111 return VT
.bitsGT(Op
.getValueType()) ?
1112 getNode(ISD::SIGN_EXTEND
, DL
, VT
, Op
) :
1113 getNode(ISD::TRUNCATE
, DL
, VT
, Op
);
1116 SDValue
SelectionDAG::getZExtOrTrunc(SDValue Op
, const SDLoc
&DL
, EVT VT
) {
1117 return VT
.bitsGT(Op
.getValueType()) ?
1118 getNode(ISD::ZERO_EXTEND
, DL
, VT
, Op
) :
1119 getNode(ISD::TRUNCATE
, DL
, VT
, Op
);
1122 SDValue
SelectionDAG::getBoolExtOrTrunc(SDValue Op
, const SDLoc
&SL
, EVT VT
,
1124 if (VT
.bitsLE(Op
.getValueType()))
1125 return getNode(ISD::TRUNCATE
, SL
, VT
, Op
);
1127 TargetLowering::BooleanContent BType
= TLI
->getBooleanContents(OpVT
);
1128 return getNode(TLI
->getExtendForContent(BType
), SL
, VT
, Op
);
1131 SDValue
SelectionDAG::getZeroExtendInReg(SDValue Op
, const SDLoc
&DL
, EVT VT
) {
1132 assert(!VT
.isVector() &&
1133 "getZeroExtendInReg should use the vector element type instead of "
1134 "the vector type!");
1135 if (Op
.getValueType().getScalarType() == VT
) return Op
;
1136 unsigned BitWidth
= Op
.getScalarValueSizeInBits();
1137 APInt Imm
= APInt::getLowBitsSet(BitWidth
,
1138 VT
.getSizeInBits());
1139 return getNode(ISD::AND
, DL
, Op
.getValueType(), Op
,
1140 getConstant(Imm
, DL
, Op
.getValueType()));
1143 SDValue
SelectionDAG::getPtrExtOrTrunc(SDValue Op
, const SDLoc
&DL
, EVT VT
) {
1144 // Only unsigned pointer semantics are supported right now. In the future this
1145 // might delegate to TLI to check pointer signedness.
1146 return getZExtOrTrunc(Op
, DL
, VT
);
1149 SDValue
SelectionDAG::getPtrExtendInReg(SDValue Op
, const SDLoc
&DL
, EVT VT
) {
1150 // Only unsigned pointer semantics are supported right now. In the future this
1151 // might delegate to TLI to check pointer signedness.
1152 return getZeroExtendInReg(Op
, DL
, VT
);
1155 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1156 SDValue
SelectionDAG::getNOT(const SDLoc
&DL
, SDValue Val
, EVT VT
) {
1157 EVT EltVT
= VT
.getScalarType();
1159 getConstant(APInt::getAllOnesValue(EltVT
.getSizeInBits()), DL
, VT
);
1160 return getNode(ISD::XOR
, DL
, VT
, Val
, NegOne
);
1163 SDValue
SelectionDAG::getLogicalNOT(const SDLoc
&DL
, SDValue Val
, EVT VT
) {
1164 SDValue TrueValue
= getBoolConstant(true, DL
, VT
, VT
);
1165 return getNode(ISD::XOR
, DL
, VT
, Val
, TrueValue
);
1168 SDValue
SelectionDAG::getBoolConstant(bool V
, const SDLoc
&DL
, EVT VT
,
1171 return getConstant(0, DL
, VT
);
1173 switch (TLI
->getBooleanContents(OpVT
)) {
1174 case TargetLowering::ZeroOrOneBooleanContent
:
1175 case TargetLowering::UndefinedBooleanContent
:
1176 return getConstant(1, DL
, VT
);
1177 case TargetLowering::ZeroOrNegativeOneBooleanContent
:
1178 return getAllOnesConstant(DL
, VT
);
1180 llvm_unreachable("Unexpected boolean content enum!");
1183 SDValue
SelectionDAG::getConstant(uint64_t Val
, const SDLoc
&DL
, EVT VT
,
1184 bool isT
, bool isO
) {
1185 EVT EltVT
= VT
.getScalarType();
1186 assert((EltVT
.getSizeInBits() >= 64 ||
1187 (uint64_t)((int64_t)Val
>> EltVT
.getSizeInBits()) + 1 < 2) &&
1188 "getConstant with a uint64_t value that doesn't fit in the type!");
1189 return getConstant(APInt(EltVT
.getSizeInBits(), Val
), DL
, VT
, isT
, isO
);
1192 SDValue
SelectionDAG::getConstant(const APInt
&Val
, const SDLoc
&DL
, EVT VT
,
1193 bool isT
, bool isO
) {
1194 return getConstant(*ConstantInt::get(*Context
, Val
), DL
, VT
, isT
, isO
);
1197 SDValue
SelectionDAG::getConstant(const ConstantInt
&Val
, const SDLoc
&DL
,
1198 EVT VT
, bool isT
, bool isO
) {
1199 assert(VT
.isInteger() && "Cannot create FP integer constant!");
1201 EVT EltVT
= VT
.getScalarType();
1202 const ConstantInt
*Elt
= &Val
;
1204 // In some cases the vector type is legal but the element type is illegal and
1205 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1206 // inserted value (the type does not need to match the vector element type).
1207 // Any extra bits introduced will be truncated away.
1208 if (VT
.isVector() && TLI
->getTypeAction(*getContext(), EltVT
) ==
1209 TargetLowering::TypePromoteInteger
) {
1210 EltVT
= TLI
->getTypeToTransformTo(*getContext(), EltVT
);
1211 APInt NewVal
= Elt
->getValue().zextOrTrunc(EltVT
.getSizeInBits());
1212 Elt
= ConstantInt::get(*getContext(), NewVal
);
1214 // In other cases the element type is illegal and needs to be expanded, for
1215 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1216 // the value into n parts and use a vector type with n-times the elements.
1217 // Then bitcast to the type requested.
1218 // Legalizing constants too early makes the DAGCombiner's job harder so we
1219 // only legalize if the DAG tells us we must produce legal types.
1220 else if (NewNodesMustHaveLegalTypes
&& VT
.isVector() &&
1221 TLI
->getTypeAction(*getContext(), EltVT
) ==
1222 TargetLowering::TypeExpandInteger
) {
1223 const APInt
&NewVal
= Elt
->getValue();
1224 EVT ViaEltVT
= TLI
->getTypeToTransformTo(*getContext(), EltVT
);
1225 unsigned ViaEltSizeInBits
= ViaEltVT
.getSizeInBits();
1226 unsigned ViaVecNumElts
= VT
.getSizeInBits() / ViaEltSizeInBits
;
1227 EVT ViaVecVT
= EVT::getVectorVT(*getContext(), ViaEltVT
, ViaVecNumElts
);
1229 // Check the temporary vector is the correct size. If this fails then
1230 // getTypeToTransformTo() probably returned a type whose size (in bits)
1231 // isn't a power-of-2 factor of the requested type size.
1232 assert(ViaVecVT
.getSizeInBits() == VT
.getSizeInBits());
1234 SmallVector
<SDValue
, 2> EltParts
;
1235 for (unsigned i
= 0; i
< ViaVecNumElts
/ VT
.getVectorNumElements(); ++i
) {
1236 EltParts
.push_back(getConstant(NewVal
.lshr(i
* ViaEltSizeInBits
)
1237 .zextOrTrunc(ViaEltSizeInBits
), DL
,
1238 ViaEltVT
, isT
, isO
));
1241 // EltParts is currently in little endian order. If we actually want
1242 // big-endian order then reverse it now.
1243 if (getDataLayout().isBigEndian())
1244 std::reverse(EltParts
.begin(), EltParts
.end());
1246 // The elements must be reversed when the element order is different
1247 // to the endianness of the elements (because the BITCAST is itself a
1248 // vector shuffle in this situation). However, we do not need any code to
1249 // perform this reversal because getConstant() is producing a vector
1251 // This situation occurs in MIPS MSA.
1253 SmallVector
<SDValue
, 8> Ops
;
1254 for (unsigned i
= 0, e
= VT
.getVectorNumElements(); i
!= e
; ++i
)
1255 Ops
.insert(Ops
.end(), EltParts
.begin(), EltParts
.end());
1257 SDValue V
= getNode(ISD::BITCAST
, DL
, VT
, getBuildVector(ViaVecVT
, DL
, Ops
));
1261 assert(Elt
->getBitWidth() == EltVT
.getSizeInBits() &&
1262 "APInt size does not match type size!");
1263 unsigned Opc
= isT
? ISD::TargetConstant
: ISD::Constant
;
1264 FoldingSetNodeID ID
;
1265 AddNodeIDNode(ID
, Opc
, getVTList(EltVT
), None
);
1269 SDNode
*N
= nullptr;
1270 if ((N
= FindNodeOrInsertPos(ID
, DL
, IP
)))
1272 return SDValue(N
, 0);
1275 N
= newSDNode
<ConstantSDNode
>(isT
, isO
, Elt
, EltVT
);
1276 CSEMap
.InsertNode(N
, IP
);
1278 NewSDValueDbgMsg(SDValue(N
, 0), "Creating constant: ", this);
1281 SDValue
Result(N
, 0);
1283 Result
= getSplatBuildVector(VT
, DL
, Result
);
1288 SDValue
SelectionDAG::getIntPtrConstant(uint64_t Val
, const SDLoc
&DL
,
1290 return getConstant(Val
, DL
, TLI
->getPointerTy(getDataLayout()), isTarget
);
1293 SDValue
SelectionDAG::getShiftAmountConstant(uint64_t Val
, EVT VT
,
1294 const SDLoc
&DL
, bool LegalTypes
) {
1295 EVT ShiftVT
= TLI
->getShiftAmountTy(VT
, getDataLayout(), LegalTypes
);
1296 return getConstant(Val
, DL
, ShiftVT
);
1299 SDValue
SelectionDAG::getConstantFP(const APFloat
&V
, const SDLoc
&DL
, EVT VT
,
1301 return getConstantFP(*ConstantFP::get(*getContext(), V
), DL
, VT
, isTarget
);
1304 SDValue
SelectionDAG::getConstantFP(const ConstantFP
&V
, const SDLoc
&DL
,
1305 EVT VT
, bool isTarget
) {
1306 assert(VT
.isFloatingPoint() && "Cannot create integer FP constant!");
1308 EVT EltVT
= VT
.getScalarType();
1310 // Do the map lookup using the actual bit pattern for the floating point
1311 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1312 // we don't have issues with SNANs.
1313 unsigned Opc
= isTarget
? ISD::TargetConstantFP
: ISD::ConstantFP
;
1314 FoldingSetNodeID ID
;
1315 AddNodeIDNode(ID
, Opc
, getVTList(EltVT
), None
);
1318 SDNode
*N
= nullptr;
1319 if ((N
= FindNodeOrInsertPos(ID
, DL
, IP
)))
1321 return SDValue(N
, 0);
1324 N
= newSDNode
<ConstantFPSDNode
>(isTarget
, &V
, EltVT
);
1325 CSEMap
.InsertNode(N
, IP
);
1329 SDValue
Result(N
, 0);
1331 Result
= getSplatBuildVector(VT
, DL
, Result
);
1332 NewSDValueDbgMsg(Result
, "Creating fp constant: ", this);
1336 SDValue
SelectionDAG::getConstantFP(double Val
, const SDLoc
&DL
, EVT VT
,
1338 EVT EltVT
= VT
.getScalarType();
1339 if (EltVT
== MVT::f32
)
1340 return getConstantFP(APFloat((float)Val
), DL
, VT
, isTarget
);
1341 else if (EltVT
== MVT::f64
)
1342 return getConstantFP(APFloat(Val
), DL
, VT
, isTarget
);
1343 else if (EltVT
== MVT::f80
|| EltVT
== MVT::f128
|| EltVT
== MVT::ppcf128
||
1344 EltVT
== MVT::f16
) {
1346 APFloat APF
= APFloat(Val
);
1347 APF
.convert(EVTToAPFloatSemantics(EltVT
), APFloat::rmNearestTiesToEven
,
1349 return getConstantFP(APF
, DL
, VT
, isTarget
);
1351 llvm_unreachable("Unsupported type in getConstantFP");
1354 SDValue
SelectionDAG::getGlobalAddress(const GlobalValue
*GV
, const SDLoc
&DL
,
1355 EVT VT
, int64_t Offset
, bool isTargetGA
,
1356 unsigned char TargetFlags
) {
1357 assert((TargetFlags
== 0 || isTargetGA
) &&
1358 "Cannot set target flags on target-independent globals");
1360 // Truncate (with sign-extension) the offset value to the pointer size.
1361 unsigned BitWidth
= getDataLayout().getPointerTypeSizeInBits(GV
->getType());
1363 Offset
= SignExtend64(Offset
, BitWidth
);
1366 if (GV
->isThreadLocal())
1367 Opc
= isTargetGA
? ISD::TargetGlobalTLSAddress
: ISD::GlobalTLSAddress
;
1369 Opc
= isTargetGA
? ISD::TargetGlobalAddress
: ISD::GlobalAddress
;
1371 FoldingSetNodeID ID
;
1372 AddNodeIDNode(ID
, Opc
, getVTList(VT
), None
);
1374 ID
.AddInteger(Offset
);
1375 ID
.AddInteger(TargetFlags
);
1377 if (SDNode
*E
= FindNodeOrInsertPos(ID
, DL
, IP
))
1378 return SDValue(E
, 0);
1380 auto *N
= newSDNode
<GlobalAddressSDNode
>(
1381 Opc
, DL
.getIROrder(), DL
.getDebugLoc(), GV
, VT
, Offset
, TargetFlags
);
1382 CSEMap
.InsertNode(N
, IP
);
1384 return SDValue(N
, 0);
1387 SDValue
SelectionDAG::getFrameIndex(int FI
, EVT VT
, bool isTarget
) {
1388 unsigned Opc
= isTarget
? ISD::TargetFrameIndex
: ISD::FrameIndex
;
1389 FoldingSetNodeID ID
;
1390 AddNodeIDNode(ID
, Opc
, getVTList(VT
), None
);
1393 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1394 return SDValue(E
, 0);
1396 auto *N
= newSDNode
<FrameIndexSDNode
>(FI
, VT
, isTarget
);
1397 CSEMap
.InsertNode(N
, IP
);
1399 return SDValue(N
, 0);
1402 SDValue
SelectionDAG::getJumpTable(int JTI
, EVT VT
, bool isTarget
,
1403 unsigned char TargetFlags
) {
1404 assert((TargetFlags
== 0 || isTarget
) &&
1405 "Cannot set target flags on target-independent jump tables");
1406 unsigned Opc
= isTarget
? ISD::TargetJumpTable
: ISD::JumpTable
;
1407 FoldingSetNodeID ID
;
1408 AddNodeIDNode(ID
, Opc
, getVTList(VT
), None
);
1410 ID
.AddInteger(TargetFlags
);
1412 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1413 return SDValue(E
, 0);
1415 auto *N
= newSDNode
<JumpTableSDNode
>(JTI
, VT
, isTarget
, TargetFlags
);
1416 CSEMap
.InsertNode(N
, IP
);
1418 return SDValue(N
, 0);
1421 SDValue
SelectionDAG::getConstantPool(const Constant
*C
, EVT VT
,
1422 unsigned Alignment
, int Offset
,
1424 unsigned char TargetFlags
) {
1425 assert((TargetFlags
== 0 || isTarget
) &&
1426 "Cannot set target flags on target-independent globals");
1428 Alignment
= MF
->getFunction().hasOptSize()
1429 ? getDataLayout().getABITypeAlignment(C
->getType())
1430 : getDataLayout().getPrefTypeAlignment(C
->getType());
1431 unsigned Opc
= isTarget
? ISD::TargetConstantPool
: ISD::ConstantPool
;
1432 FoldingSetNodeID ID
;
1433 AddNodeIDNode(ID
, Opc
, getVTList(VT
), None
);
1434 ID
.AddInteger(Alignment
);
1435 ID
.AddInteger(Offset
);
1437 ID
.AddInteger(TargetFlags
);
1439 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1440 return SDValue(E
, 0);
1442 auto *N
= newSDNode
<ConstantPoolSDNode
>(isTarget
, C
, VT
, Offset
, Alignment
,
1444 CSEMap
.InsertNode(N
, IP
);
1446 return SDValue(N
, 0);
1449 SDValue
SelectionDAG::getConstantPool(MachineConstantPoolValue
*C
, EVT VT
,
1450 unsigned Alignment
, int Offset
,
1452 unsigned char TargetFlags
) {
1453 assert((TargetFlags
== 0 || isTarget
) &&
1454 "Cannot set target flags on target-independent globals");
1456 Alignment
= getDataLayout().getPrefTypeAlignment(C
->getType());
1457 unsigned Opc
= isTarget
? ISD::TargetConstantPool
: ISD::ConstantPool
;
1458 FoldingSetNodeID ID
;
1459 AddNodeIDNode(ID
, Opc
, getVTList(VT
), None
);
1460 ID
.AddInteger(Alignment
);
1461 ID
.AddInteger(Offset
);
1462 C
->addSelectionDAGCSEId(ID
);
1463 ID
.AddInteger(TargetFlags
);
1465 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1466 return SDValue(E
, 0);
1468 auto *N
= newSDNode
<ConstantPoolSDNode
>(isTarget
, C
, VT
, Offset
, Alignment
,
1470 CSEMap
.InsertNode(N
, IP
);
1472 return SDValue(N
, 0);
1475 SDValue
SelectionDAG::getTargetIndex(int Index
, EVT VT
, int64_t Offset
,
1476 unsigned char TargetFlags
) {
1477 FoldingSetNodeID ID
;
1478 AddNodeIDNode(ID
, ISD::TargetIndex
, getVTList(VT
), None
);
1479 ID
.AddInteger(Index
);
1480 ID
.AddInteger(Offset
);
1481 ID
.AddInteger(TargetFlags
);
1483 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1484 return SDValue(E
, 0);
1486 auto *N
= newSDNode
<TargetIndexSDNode
>(Index
, VT
, Offset
, TargetFlags
);
1487 CSEMap
.InsertNode(N
, IP
);
1489 return SDValue(N
, 0);
1492 SDValue
SelectionDAG::getBasicBlock(MachineBasicBlock
*MBB
) {
1493 FoldingSetNodeID ID
;
1494 AddNodeIDNode(ID
, ISD::BasicBlock
, getVTList(MVT::Other
), None
);
1497 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1498 return SDValue(E
, 0);
1500 auto *N
= newSDNode
<BasicBlockSDNode
>(MBB
);
1501 CSEMap
.InsertNode(N
, IP
);
1503 return SDValue(N
, 0);
1506 SDValue
SelectionDAG::getValueType(EVT VT
) {
1507 if (VT
.isSimple() && (unsigned)VT
.getSimpleVT().SimpleTy
>=
1508 ValueTypeNodes
.size())
1509 ValueTypeNodes
.resize(VT
.getSimpleVT().SimpleTy
+1);
1511 SDNode
*&N
= VT
.isExtended() ?
1512 ExtendedValueTypeNodes
[VT
] : ValueTypeNodes
[VT
.getSimpleVT().SimpleTy
];
1514 if (N
) return SDValue(N
, 0);
1515 N
= newSDNode
<VTSDNode
>(VT
);
1517 return SDValue(N
, 0);
1520 SDValue
SelectionDAG::getExternalSymbol(const char *Sym
, EVT VT
) {
1521 SDNode
*&N
= ExternalSymbols
[Sym
];
1522 if (N
) return SDValue(N
, 0);
1523 N
= newSDNode
<ExternalSymbolSDNode
>(false, Sym
, 0, VT
);
1525 return SDValue(N
, 0);
1528 SDValue
SelectionDAG::getMCSymbol(MCSymbol
*Sym
, EVT VT
) {
1529 SDNode
*&N
= MCSymbols
[Sym
];
1531 return SDValue(N
, 0);
1532 N
= newSDNode
<MCSymbolSDNode
>(Sym
, VT
);
1534 return SDValue(N
, 0);
1537 SDValue
SelectionDAG::getTargetExternalSymbol(const char *Sym
, EVT VT
,
1538 unsigned char TargetFlags
) {
1540 TargetExternalSymbols
[std::pair
<std::string
,unsigned char>(Sym
,
1542 if (N
) return SDValue(N
, 0);
1543 N
= newSDNode
<ExternalSymbolSDNode
>(true, Sym
, TargetFlags
, VT
);
1545 return SDValue(N
, 0);
1548 SDValue
SelectionDAG::getCondCode(ISD::CondCode Cond
) {
1549 if ((unsigned)Cond
>= CondCodeNodes
.size())
1550 CondCodeNodes
.resize(Cond
+1);
1552 if (!CondCodeNodes
[Cond
]) {
1553 auto *N
= newSDNode
<CondCodeSDNode
>(Cond
);
1554 CondCodeNodes
[Cond
] = N
;
1558 return SDValue(CondCodeNodes
[Cond
], 0);
1561 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1562 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1563 static void commuteShuffle(SDValue
&N1
, SDValue
&N2
, MutableArrayRef
<int> M
) {
1565 ShuffleVectorSDNode::commuteMask(M
);
1568 SDValue
SelectionDAG::getVectorShuffle(EVT VT
, const SDLoc
&dl
, SDValue N1
,
1569 SDValue N2
, ArrayRef
<int> Mask
) {
1570 assert(VT
.getVectorNumElements() == Mask
.size() &&
1571 "Must have the same number of vector elements as mask elements!");
1572 assert(VT
== N1
.getValueType() && VT
== N2
.getValueType() &&
1573 "Invalid VECTOR_SHUFFLE");
1575 // Canonicalize shuffle undef, undef -> undef
1576 if (N1
.isUndef() && N2
.isUndef())
1577 return getUNDEF(VT
);
1579 // Validate that all indices in Mask are within the range of the elements
1580 // input to the shuffle.
1581 int NElts
= Mask
.size();
1582 assert(llvm::all_of(Mask
,
1583 [&](int M
) { return M
< (NElts
* 2) && M
>= -1; }) &&
1584 "Index out of range");
1586 // Copy the mask so we can do any needed cleanup.
1587 SmallVector
<int, 8> MaskVec(Mask
.begin(), Mask
.end());
1589 // Canonicalize shuffle v, v -> v, undef
1592 for (int i
= 0; i
!= NElts
; ++i
)
1593 if (MaskVec
[i
] >= NElts
) MaskVec
[i
] -= NElts
;
1596 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1598 commuteShuffle(N1
, N2
, MaskVec
);
1600 if (TLI
->hasVectorBlend()) {
1601 // If shuffling a splat, try to blend the splat instead. We do this here so
1602 // that even when this arises during lowering we don't have to re-handle it.
1603 auto BlendSplat
= [&](BuildVectorSDNode
*BV
, int Offset
) {
1604 BitVector UndefElements
;
1605 SDValue Splat
= BV
->getSplatValue(&UndefElements
);
1609 for (int i
= 0; i
< NElts
; ++i
) {
1610 if (MaskVec
[i
] < Offset
|| MaskVec
[i
] >= (Offset
+ NElts
))
1613 // If this input comes from undef, mark it as such.
1614 if (UndefElements
[MaskVec
[i
] - Offset
]) {
1619 // If we can blend a non-undef lane, use that instead.
1620 if (!UndefElements
[i
])
1621 MaskVec
[i
] = i
+ Offset
;
1624 if (auto *N1BV
= dyn_cast
<BuildVectorSDNode
>(N1
))
1625 BlendSplat(N1BV
, 0);
1626 if (auto *N2BV
= dyn_cast
<BuildVectorSDNode
>(N2
))
1627 BlendSplat(N2BV
, NElts
);
1630 // Canonicalize all index into lhs, -> shuffle lhs, undef
1631 // Canonicalize all index into rhs, -> shuffle rhs, undef
1632 bool AllLHS
= true, AllRHS
= true;
1633 bool N2Undef
= N2
.isUndef();
1634 for (int i
= 0; i
!= NElts
; ++i
) {
1635 if (MaskVec
[i
] >= NElts
) {
1640 } else if (MaskVec
[i
] >= 0) {
1644 if (AllLHS
&& AllRHS
)
1645 return getUNDEF(VT
);
1646 if (AllLHS
&& !N2Undef
)
1650 commuteShuffle(N1
, N2
, MaskVec
);
1652 // Reset our undef status after accounting for the mask.
1653 N2Undef
= N2
.isUndef();
1654 // Re-check whether both sides ended up undef.
1655 if (N1
.isUndef() && N2Undef
)
1656 return getUNDEF(VT
);
1658 // If Identity shuffle return that node.
1659 bool Identity
= true, AllSame
= true;
1660 for (int i
= 0; i
!= NElts
; ++i
) {
1661 if (MaskVec
[i
] >= 0 && MaskVec
[i
] != i
) Identity
= false;
1662 if (MaskVec
[i
] != MaskVec
[0]) AllSame
= false;
1664 if (Identity
&& NElts
)
1667 // Shuffling a constant splat doesn't change the result.
1671 // Look through any bitcasts. We check that these don't change the number
1672 // (and size) of elements and just changes their types.
1673 while (V
.getOpcode() == ISD::BITCAST
)
1674 V
= V
->getOperand(0);
1676 // A splat should always show up as a build vector node.
1677 if (auto *BV
= dyn_cast
<BuildVectorSDNode
>(V
)) {
1678 BitVector UndefElements
;
1679 SDValue Splat
= BV
->getSplatValue(&UndefElements
);
1680 // If this is a splat of an undef, shuffling it is also undef.
1681 if (Splat
&& Splat
.isUndef())
1682 return getUNDEF(VT
);
1685 V
.getValueType().getVectorNumElements() == VT
.getVectorNumElements();
1687 // We only have a splat which can skip shuffles if there is a splatted
1688 // value and no undef lanes rearranged by the shuffle.
1689 if (Splat
&& UndefElements
.none()) {
1690 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1691 // number of elements match or the value splatted is a zero constant.
1694 if (auto *C
= dyn_cast
<ConstantSDNode
>(Splat
))
1695 if (C
->isNullValue())
1699 // If the shuffle itself creates a splat, build the vector directly.
1700 if (AllSame
&& SameNumElts
) {
1701 EVT BuildVT
= BV
->getValueType(0);
1702 const SDValue
&Splatted
= BV
->getOperand(MaskVec
[0]);
1703 SDValue NewBV
= getSplatBuildVector(BuildVT
, dl
, Splatted
);
1705 // We may have jumped through bitcasts, so the type of the
1706 // BUILD_VECTOR may not match the type of the shuffle.
1708 NewBV
= getNode(ISD::BITCAST
, dl
, VT
, NewBV
);
1714 FoldingSetNodeID ID
;
1715 SDValue Ops
[2] = { N1
, N2
};
1716 AddNodeIDNode(ID
, ISD::VECTOR_SHUFFLE
, getVTList(VT
), Ops
);
1717 for (int i
= 0; i
!= NElts
; ++i
)
1718 ID
.AddInteger(MaskVec
[i
]);
1721 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
))
1722 return SDValue(E
, 0);
1724 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1725 // SDNode doesn't have access to it. This memory will be "leaked" when
1726 // the node is deallocated, but recovered when the NodeAllocator is released.
1727 int *MaskAlloc
= OperandAllocator
.Allocate
<int>(NElts
);
1728 llvm::copy(MaskVec
, MaskAlloc
);
1730 auto *N
= newSDNode
<ShuffleVectorSDNode
>(VT
, dl
.getIROrder(),
1731 dl
.getDebugLoc(), MaskAlloc
);
1732 createOperands(N
, Ops
);
1734 CSEMap
.InsertNode(N
, IP
);
1736 SDValue V
= SDValue(N
, 0);
1737 NewSDValueDbgMsg(V
, "Creating new node: ", this);
1741 SDValue
SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode
&SV
) {
1742 EVT VT
= SV
.getValueType(0);
1743 SmallVector
<int, 8> MaskVec(SV
.getMask().begin(), SV
.getMask().end());
1744 ShuffleVectorSDNode::commuteMask(MaskVec
);
1746 SDValue Op0
= SV
.getOperand(0);
1747 SDValue Op1
= SV
.getOperand(1);
1748 return getVectorShuffle(VT
, SDLoc(&SV
), Op1
, Op0
, MaskVec
);
1751 SDValue
SelectionDAG::getRegister(unsigned RegNo
, EVT VT
) {
1752 FoldingSetNodeID ID
;
1753 AddNodeIDNode(ID
, ISD::Register
, getVTList(VT
), None
);
1754 ID
.AddInteger(RegNo
);
1756 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1757 return SDValue(E
, 0);
1759 auto *N
= newSDNode
<RegisterSDNode
>(RegNo
, VT
);
1760 N
->SDNodeBits
.IsDivergent
= TLI
->isSDNodeSourceOfDivergence(N
, FLI
, DA
);
1761 CSEMap
.InsertNode(N
, IP
);
1763 return SDValue(N
, 0);
1766 SDValue
SelectionDAG::getRegisterMask(const uint32_t *RegMask
) {
1767 FoldingSetNodeID ID
;
1768 AddNodeIDNode(ID
, ISD::RegisterMask
, getVTList(MVT::Untyped
), None
);
1769 ID
.AddPointer(RegMask
);
1771 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1772 return SDValue(E
, 0);
1774 auto *N
= newSDNode
<RegisterMaskSDNode
>(RegMask
);
1775 CSEMap
.InsertNode(N
, IP
);
1777 return SDValue(N
, 0);
1780 SDValue
SelectionDAG::getEHLabel(const SDLoc
&dl
, SDValue Root
,
1782 return getLabelNode(ISD::EH_LABEL
, dl
, Root
, Label
);
1785 SDValue
SelectionDAG::getLabelNode(unsigned Opcode
, const SDLoc
&dl
,
1786 SDValue Root
, MCSymbol
*Label
) {
1787 FoldingSetNodeID ID
;
1788 SDValue Ops
[] = { Root
};
1789 AddNodeIDNode(ID
, Opcode
, getVTList(MVT::Other
), Ops
);
1790 ID
.AddPointer(Label
);
1792 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1793 return SDValue(E
, 0);
1795 auto *N
= newSDNode
<LabelSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(), Label
);
1796 createOperands(N
, Ops
);
1798 CSEMap
.InsertNode(N
, IP
);
1800 return SDValue(N
, 0);
1803 SDValue
SelectionDAG::getBlockAddress(const BlockAddress
*BA
, EVT VT
,
1806 unsigned char TargetFlags
) {
1807 unsigned Opc
= isTarget
? ISD::TargetBlockAddress
: ISD::BlockAddress
;
1809 FoldingSetNodeID ID
;
1810 AddNodeIDNode(ID
, Opc
, getVTList(VT
), None
);
1812 ID
.AddInteger(Offset
);
1813 ID
.AddInteger(TargetFlags
);
1815 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1816 return SDValue(E
, 0);
1818 auto *N
= newSDNode
<BlockAddressSDNode
>(Opc
, VT
, BA
, Offset
, TargetFlags
);
1819 CSEMap
.InsertNode(N
, IP
);
1821 return SDValue(N
, 0);
1824 SDValue
SelectionDAG::getSrcValue(const Value
*V
) {
1825 assert((!V
|| V
->getType()->isPointerTy()) &&
1826 "SrcValue is not a pointer?");
1828 FoldingSetNodeID ID
;
1829 AddNodeIDNode(ID
, ISD::SRCVALUE
, getVTList(MVT::Other
), None
);
1833 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1834 return SDValue(E
, 0);
1836 auto *N
= newSDNode
<SrcValueSDNode
>(V
);
1837 CSEMap
.InsertNode(N
, IP
);
1839 return SDValue(N
, 0);
1842 SDValue
SelectionDAG::getMDNode(const MDNode
*MD
) {
1843 FoldingSetNodeID ID
;
1844 AddNodeIDNode(ID
, ISD::MDNODE_SDNODE
, getVTList(MVT::Other
), None
);
1848 if (SDNode
*E
= FindNodeOrInsertPos(ID
, IP
))
1849 return SDValue(E
, 0);
1851 auto *N
= newSDNode
<MDNodeSDNode
>(MD
);
1852 CSEMap
.InsertNode(N
, IP
);
1854 return SDValue(N
, 0);
1857 SDValue
SelectionDAG::getBitcast(EVT VT
, SDValue V
) {
1858 if (VT
== V
.getValueType())
1861 return getNode(ISD::BITCAST
, SDLoc(V
), VT
, V
);
1864 SDValue
SelectionDAG::getAddrSpaceCast(const SDLoc
&dl
, EVT VT
, SDValue Ptr
,
1865 unsigned SrcAS
, unsigned DestAS
) {
1866 SDValue Ops
[] = {Ptr
};
1867 FoldingSetNodeID ID
;
1868 AddNodeIDNode(ID
, ISD::ADDRSPACECAST
, getVTList(VT
), Ops
);
1869 ID
.AddInteger(SrcAS
);
1870 ID
.AddInteger(DestAS
);
1873 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
))
1874 return SDValue(E
, 0);
1876 auto *N
= newSDNode
<AddrSpaceCastSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(),
1878 createOperands(N
, Ops
);
1880 CSEMap
.InsertNode(N
, IP
);
1882 return SDValue(N
, 0);
1885 /// getShiftAmountOperand - Return the specified value casted to
1886 /// the target's desired shift amount type.
1887 SDValue
SelectionDAG::getShiftAmountOperand(EVT LHSTy
, SDValue Op
) {
1888 EVT OpTy
= Op
.getValueType();
1889 EVT ShTy
= TLI
->getShiftAmountTy(LHSTy
, getDataLayout());
1890 if (OpTy
== ShTy
|| OpTy
.isVector()) return Op
;
1892 return getZExtOrTrunc(Op
, SDLoc(Op
), ShTy
);
1895 SDValue
SelectionDAG::expandVAArg(SDNode
*Node
) {
1897 const TargetLowering
&TLI
= getTargetLoweringInfo();
1898 const Value
*V
= cast
<SrcValueSDNode
>(Node
->getOperand(2))->getValue();
1899 EVT VT
= Node
->getValueType(0);
1900 SDValue Tmp1
= Node
->getOperand(0);
1901 SDValue Tmp2
= Node
->getOperand(1);
1902 unsigned Align
= Node
->getConstantOperandVal(3);
1904 SDValue VAListLoad
= getLoad(TLI
.getPointerTy(getDataLayout()), dl
, Tmp1
,
1905 Tmp2
, MachinePointerInfo(V
));
1906 SDValue VAList
= VAListLoad
;
1908 if (Align
> TLI
.getMinStackArgumentAlignment()) {
1909 assert(((Align
& (Align
-1)) == 0) && "Expected Align to be a power of 2");
1911 VAList
= getNode(ISD::ADD
, dl
, VAList
.getValueType(), VAList
,
1912 getConstant(Align
- 1, dl
, VAList
.getValueType()));
1914 VAList
= getNode(ISD::AND
, dl
, VAList
.getValueType(), VAList
,
1915 getConstant(-(int64_t)Align
, dl
, VAList
.getValueType()));
1918 // Increment the pointer, VAList, to the next vaarg
1919 Tmp1
= getNode(ISD::ADD
, dl
, VAList
.getValueType(), VAList
,
1920 getConstant(getDataLayout().getTypeAllocSize(
1921 VT
.getTypeForEVT(*getContext())),
1922 dl
, VAList
.getValueType()));
1923 // Store the incremented VAList to the legalized pointer
1925 getStore(VAListLoad
.getValue(1), dl
, Tmp1
, Tmp2
, MachinePointerInfo(V
));
1926 // Load the actual argument out of the pointer VAList
1927 return getLoad(VT
, dl
, Tmp1
, VAList
, MachinePointerInfo());
1930 SDValue
SelectionDAG::expandVACopy(SDNode
*Node
) {
1932 const TargetLowering
&TLI
= getTargetLoweringInfo();
1933 // This defaults to loading a pointer from the input and storing it to the
1934 // output, returning the chain.
1935 const Value
*VD
= cast
<SrcValueSDNode
>(Node
->getOperand(3))->getValue();
1936 const Value
*VS
= cast
<SrcValueSDNode
>(Node
->getOperand(4))->getValue();
1938 getLoad(TLI
.getPointerTy(getDataLayout()), dl
, Node
->getOperand(0),
1939 Node
->getOperand(2), MachinePointerInfo(VS
));
1940 return getStore(Tmp1
.getValue(1), dl
, Tmp1
, Node
->getOperand(1),
1941 MachinePointerInfo(VD
));
1944 SDValue
SelectionDAG::CreateStackTemporary(EVT VT
, unsigned minAlign
) {
1945 MachineFrameInfo
&MFI
= getMachineFunction().getFrameInfo();
1946 unsigned ByteSize
= VT
.getStoreSize();
1947 Type
*Ty
= VT
.getTypeForEVT(*getContext());
1948 unsigned StackAlign
=
1949 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty
), minAlign
);
1951 int FrameIdx
= MFI
.CreateStackObject(ByteSize
, StackAlign
, false);
1952 return getFrameIndex(FrameIdx
, TLI
->getFrameIndexTy(getDataLayout()));
1955 SDValue
SelectionDAG::CreateStackTemporary(EVT VT1
, EVT VT2
) {
1956 unsigned Bytes
= std::max(VT1
.getStoreSize(), VT2
.getStoreSize());
1957 Type
*Ty1
= VT1
.getTypeForEVT(*getContext());
1958 Type
*Ty2
= VT2
.getTypeForEVT(*getContext());
1959 const DataLayout
&DL
= getDataLayout();
1961 std::max(DL
.getPrefTypeAlignment(Ty1
), DL
.getPrefTypeAlignment(Ty2
));
1963 MachineFrameInfo
&MFI
= getMachineFunction().getFrameInfo();
1964 int FrameIdx
= MFI
.CreateStackObject(Bytes
, Align
, false);
1965 return getFrameIndex(FrameIdx
, TLI
->getFrameIndexTy(getDataLayout()));
1968 SDValue
SelectionDAG::FoldSetCC(EVT VT
, SDValue N1
, SDValue N2
,
1969 ISD::CondCode Cond
, const SDLoc
&dl
) {
1970 EVT OpVT
= N1
.getValueType();
1972 // These setcc operations always fold.
1976 case ISD::SETFALSE2
: return getBoolConstant(false, dl
, VT
, OpVT
);
1978 case ISD::SETTRUE2
: return getBoolConstant(true, dl
, VT
, OpVT
);
1990 assert(!OpVT
.isInteger() && "Illegal setcc for integer!");
1994 if (OpVT
.isInteger()) {
1995 // For EQ and NE, we can always pick a value for the undef to make the
1996 // predicate pass or fail, so we can return undef.
1997 // Matches behavior in llvm::ConstantFoldCompareInstruction.
1998 // icmp eq/ne X, undef -> undef.
1999 if ((N1
.isUndef() || N2
.isUndef()) &&
2000 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
))
2001 return getUNDEF(VT
);
2003 // If both operands are undef, we can return undef for int comparison.
2004 // icmp undef, undef -> undef.
2005 if (N1
.isUndef() && N2
.isUndef())
2006 return getUNDEF(VT
);
2008 // icmp X, X -> true/false
2009 // icmp X, undef -> true/false because undef could be X.
2011 return getBoolConstant(ISD::isTrueWhenEqual(Cond
), dl
, VT
, OpVT
);
2014 if (ConstantSDNode
*N2C
= dyn_cast
<ConstantSDNode
>(N2
)) {
2015 const APInt
&C2
= N2C
->getAPIntValue();
2016 if (ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
)) {
2017 const APInt
&C1
= N1C
->getAPIntValue();
2020 default: llvm_unreachable("Unknown integer setcc!");
2021 case ISD::SETEQ
: return getBoolConstant(C1
== C2
, dl
, VT
, OpVT
);
2022 case ISD::SETNE
: return getBoolConstant(C1
!= C2
, dl
, VT
, OpVT
);
2023 case ISD::SETULT
: return getBoolConstant(C1
.ult(C2
), dl
, VT
, OpVT
);
2024 case ISD::SETUGT
: return getBoolConstant(C1
.ugt(C2
), dl
, VT
, OpVT
);
2025 case ISD::SETULE
: return getBoolConstant(C1
.ule(C2
), dl
, VT
, OpVT
);
2026 case ISD::SETUGE
: return getBoolConstant(C1
.uge(C2
), dl
, VT
, OpVT
);
2027 case ISD::SETLT
: return getBoolConstant(C1
.slt(C2
), dl
, VT
, OpVT
);
2028 case ISD::SETGT
: return getBoolConstant(C1
.sgt(C2
), dl
, VT
, OpVT
);
2029 case ISD::SETLE
: return getBoolConstant(C1
.sle(C2
), dl
, VT
, OpVT
);
2030 case ISD::SETGE
: return getBoolConstant(C1
.sge(C2
), dl
, VT
, OpVT
);
2035 auto *N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
2036 auto *N2CFP
= dyn_cast
<ConstantFPSDNode
>(N2
);
2038 if (N1CFP
&& N2CFP
) {
2039 APFloat::cmpResult R
= N1CFP
->getValueAPF().compare(N2CFP
->getValueAPF());
2042 case ISD::SETEQ
: if (R
==APFloat::cmpUnordered
)
2043 return getUNDEF(VT
);
2045 case ISD::SETOEQ
: return getBoolConstant(R
==APFloat::cmpEqual
, dl
, VT
,
2047 case ISD::SETNE
: if (R
==APFloat::cmpUnordered
)
2048 return getUNDEF(VT
);
2050 case ISD::SETONE
: return getBoolConstant(R
==APFloat::cmpGreaterThan
||
2051 R
==APFloat::cmpLessThan
, dl
, VT
,
2053 case ISD::SETLT
: if (R
==APFloat::cmpUnordered
)
2054 return getUNDEF(VT
);
2056 case ISD::SETOLT
: return getBoolConstant(R
==APFloat::cmpLessThan
, dl
, VT
,
2058 case ISD::SETGT
: if (R
==APFloat::cmpUnordered
)
2059 return getUNDEF(VT
);
2061 case ISD::SETOGT
: return getBoolConstant(R
==APFloat::cmpGreaterThan
, dl
,
2063 case ISD::SETLE
: if (R
==APFloat::cmpUnordered
)
2064 return getUNDEF(VT
);
2066 case ISD::SETOLE
: return getBoolConstant(R
==APFloat::cmpLessThan
||
2067 R
==APFloat::cmpEqual
, dl
, VT
,
2069 case ISD::SETGE
: if (R
==APFloat::cmpUnordered
)
2070 return getUNDEF(VT
);
2072 case ISD::SETOGE
: return getBoolConstant(R
==APFloat::cmpGreaterThan
||
2073 R
==APFloat::cmpEqual
, dl
, VT
, OpVT
);
2074 case ISD::SETO
: return getBoolConstant(R
!=APFloat::cmpUnordered
, dl
, VT
,
2076 case ISD::SETUO
: return getBoolConstant(R
==APFloat::cmpUnordered
, dl
, VT
,
2078 case ISD::SETUEQ
: return getBoolConstant(R
==APFloat::cmpUnordered
||
2079 R
==APFloat::cmpEqual
, dl
, VT
,
2081 case ISD::SETUNE
: return getBoolConstant(R
!=APFloat::cmpEqual
, dl
, VT
,
2083 case ISD::SETULT
: return getBoolConstant(R
==APFloat::cmpUnordered
||
2084 R
==APFloat::cmpLessThan
, dl
, VT
,
2086 case ISD::SETUGT
: return getBoolConstant(R
==APFloat::cmpGreaterThan
||
2087 R
==APFloat::cmpUnordered
, dl
, VT
,
2089 case ISD::SETULE
: return getBoolConstant(R
!=APFloat::cmpGreaterThan
, dl
,
2091 case ISD::SETUGE
: return getBoolConstant(R
!=APFloat::cmpLessThan
, dl
, VT
,
2094 } else if (N1CFP
&& OpVT
.isSimple() && !N2
.isUndef()) {
2095 // Ensure that the constant occurs on the RHS.
2096 ISD::CondCode SwappedCond
= ISD::getSetCCSwappedOperands(Cond
);
2097 if (!TLI
->isCondCodeLegal(SwappedCond
, OpVT
.getSimpleVT()))
2099 return getSetCC(dl
, VT
, N2
, N1
, SwappedCond
);
2100 } else if ((N2CFP
&& N2CFP
->getValueAPF().isNaN()) ||
2101 (OpVT
.isFloatingPoint() && (N1
.isUndef() || N2
.isUndef()))) {
2102 // If an operand is known to be a nan (or undef that could be a nan), we can
2104 // Choosing NaN for the undef will always make unordered comparison succeed
2105 // and ordered comparison fails.
2106 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2107 switch (ISD::getUnorderedFlavor(Cond
)) {
2109 llvm_unreachable("Unknown flavor!");
2110 case 0: // Known false.
2111 return getBoolConstant(false, dl
, VT
, OpVT
);
2112 case 1: // Known true.
2113 return getBoolConstant(true, dl
, VT
, OpVT
);
2114 case 2: // Undefined.
2115 return getUNDEF(VT
);
2119 // Could not fold it.
2123 /// See if the specified operand can be simplified with the knowledge that only
2124 /// the bits specified by Mask are used.
2125 SDValue
SelectionDAG::GetDemandedBits(SDValue V
, const APInt
&Mask
) {
2126 switch (V
.getOpcode()) {
2129 case ISD::Constant
: {
2130 const ConstantSDNode
*CV
= cast
<ConstantSDNode
>(V
.getNode());
2131 assert(CV
&& "Const value should be ConstSDNode.");
2132 const APInt
&CVal
= CV
->getAPIntValue();
2133 APInt NewVal
= CVal
& Mask
;
2135 return getConstant(NewVal
, SDLoc(V
), V
.getValueType());
2140 // If the LHS or RHS don't contribute bits to the or, drop them.
2141 if (MaskedValueIsZero(V
.getOperand(0), Mask
))
2142 return V
.getOperand(1);
2143 if (MaskedValueIsZero(V
.getOperand(1), Mask
))
2144 return V
.getOperand(0);
2147 // Only look at single-use SRLs.
2148 if (!V
.getNode()->hasOneUse())
2150 if (ConstantSDNode
*RHSC
= dyn_cast
<ConstantSDNode
>(V
.getOperand(1))) {
2151 // See if we can recursively simplify the LHS.
2152 unsigned Amt
= RHSC
->getZExtValue();
2154 // Watch out for shift count overflow though.
2155 if (Amt
>= Mask
.getBitWidth())
2157 APInt NewMask
= Mask
<< Amt
;
2158 if (SDValue SimplifyLHS
= GetDemandedBits(V
.getOperand(0), NewMask
))
2159 return getNode(ISD::SRL
, SDLoc(V
), V
.getValueType(), SimplifyLHS
,
2164 // X & -1 -> X (ignoring bits which aren't demanded).
2165 // Also handle the case where masked out bits in X are known to be zero.
2166 if (ConstantSDNode
*RHSC
= isConstOrConstSplat(V
.getOperand(1))) {
2167 const APInt
&AndVal
= RHSC
->getAPIntValue();
2168 if (Mask
.isSubsetOf(AndVal
) ||
2169 Mask
.isSubsetOf(computeKnownBits(V
.getOperand(0)).Zero
| AndVal
))
2170 return V
.getOperand(0);
2174 case ISD::ANY_EXTEND
: {
2175 SDValue Src
= V
.getOperand(0);
2176 unsigned SrcBitWidth
= Src
.getScalarValueSizeInBits();
2177 // Being conservative here - only peek through if we only demand bits in the
2178 // non-extended source (even though the extended bits are technically undef).
2179 if (Mask
.getActiveBits() > SrcBitWidth
)
2181 APInt SrcMask
= Mask
.trunc(SrcBitWidth
);
2182 if (SDValue DemandedSrc
= GetDemandedBits(Src
, SrcMask
))
2183 return getNode(ISD::ANY_EXTEND
, SDLoc(V
), V
.getValueType(), DemandedSrc
);
2186 case ISD::SIGN_EXTEND_INREG
:
2187 EVT ExVT
= cast
<VTSDNode
>(V
.getOperand(1))->getVT();
2188 unsigned ExVTBits
= ExVT
.getScalarSizeInBits();
2190 // If none of the extended bits are demanded, eliminate the sextinreg.
2191 if (Mask
.getActiveBits() <= ExVTBits
)
2192 return V
.getOperand(0);
2199 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2200 /// use this predicate to simplify operations downstream.
2201 bool SelectionDAG::SignBitIsZero(SDValue Op
, unsigned Depth
) const {
2202 unsigned BitWidth
= Op
.getScalarValueSizeInBits();
2203 return MaskedValueIsZero(Op
, APInt::getSignMask(BitWidth
), Depth
);
2206 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2207 /// this predicate to simplify operations downstream. Mask is known to be zero
2208 /// for bits that V cannot have.
2209 bool SelectionDAG::MaskedValueIsZero(SDValue Op
, const APInt
&Mask
,
2210 unsigned Depth
) const {
2211 return Mask
.isSubsetOf(computeKnownBits(Op
, Depth
).Zero
);
2214 /// isSplatValue - Return true if the vector V has the same value
2215 /// across all DemandedElts.
2216 bool SelectionDAG::isSplatValue(SDValue V
, const APInt
&DemandedElts
,
2219 return false; // No demanded elts, better to assume we don't know anything.
2221 EVT VT
= V
.getValueType();
2222 assert(VT
.isVector() && "Vector type expected");
2224 unsigned NumElts
= VT
.getVectorNumElements();
2225 assert(NumElts
== DemandedElts
.getBitWidth() && "Vector size mismatch");
2226 UndefElts
= APInt::getNullValue(NumElts
);
2228 switch (V
.getOpcode()) {
2229 case ISD::BUILD_VECTOR
: {
2231 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2232 SDValue Op
= V
.getOperand(i
);
2234 UndefElts
.setBit(i
);
2237 if (!DemandedElts
[i
])
2239 if (Scl
&& Scl
!= Op
)
2245 case ISD::VECTOR_SHUFFLE
: {
2246 // Check if this is a shuffle node doing a splat.
2247 // TODO: Do we need to handle shuffle(splat, undef, mask)?
2248 int SplatIndex
= -1;
2249 ArrayRef
<int> Mask
= cast
<ShuffleVectorSDNode
>(V
)->getMask();
2250 for (int i
= 0; i
!= (int)NumElts
; ++i
) {
2253 UndefElts
.setBit(i
);
2256 if (!DemandedElts
[i
])
2258 if (0 <= SplatIndex
&& SplatIndex
!= M
)
2264 case ISD::EXTRACT_SUBVECTOR
: {
2265 SDValue Src
= V
.getOperand(0);
2266 ConstantSDNode
*SubIdx
= dyn_cast
<ConstantSDNode
>(V
.getOperand(1));
2267 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
2268 if (SubIdx
&& SubIdx
->getAPIntValue().ule(NumSrcElts
- NumElts
)) {
2269 // Offset the demanded elts by the subvector index.
2270 uint64_t Idx
= SubIdx
->getZExtValue();
2272 APInt DemandedSrc
= DemandedElts
.zextOrSelf(NumSrcElts
).shl(Idx
);
2273 if (isSplatValue(Src
, DemandedSrc
, UndefSrcElts
)) {
2274 UndefElts
= UndefSrcElts
.extractBits(NumElts
, Idx
);
2283 APInt UndefLHS
, UndefRHS
;
2284 SDValue LHS
= V
.getOperand(0);
2285 SDValue RHS
= V
.getOperand(1);
2286 if (isSplatValue(LHS
, DemandedElts
, UndefLHS
) &&
2287 isSplatValue(RHS
, DemandedElts
, UndefRHS
)) {
2288 UndefElts
= UndefLHS
| UndefRHS
;
2298 /// Helper wrapper to main isSplatValue function.
2299 bool SelectionDAG::isSplatValue(SDValue V
, bool AllowUndefs
) {
2300 EVT VT
= V
.getValueType();
2301 assert(VT
.isVector() && "Vector type expected");
2302 unsigned NumElts
= VT
.getVectorNumElements();
2305 APInt DemandedElts
= APInt::getAllOnesValue(NumElts
);
2306 return isSplatValue(V
, DemandedElts
, UndefElts
) &&
2307 (AllowUndefs
|| !UndefElts
);
2310 SDValue
SelectionDAG::getSplatSourceVector(SDValue V
, int &SplatIdx
) {
2311 V
= peekThroughExtractSubvectors(V
);
2313 EVT VT
= V
.getValueType();
2314 unsigned Opcode
= V
.getOpcode();
2318 APInt DemandedElts
= APInt::getAllOnesValue(VT
.getVectorNumElements());
2319 if (isSplatValue(V
, DemandedElts
, UndefElts
)) {
2320 // Handle case where all demanded elements are UNDEF.
2321 if (DemandedElts
.isSubsetOf(UndefElts
)) {
2323 return getUNDEF(VT
);
2325 SplatIdx
= (UndefElts
& DemandedElts
).countTrailingOnes();
2330 case ISD::VECTOR_SHUFFLE
: {
2331 // Check if this is a shuffle node doing a splat.
2332 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2333 // getTargetVShiftNode currently struggles without the splat source.
2334 auto *SVN
= cast
<ShuffleVectorSDNode
>(V
);
2335 if (!SVN
->isSplat())
2337 int Idx
= SVN
->getSplatIndex();
2338 int NumElts
= V
.getValueType().getVectorNumElements();
2339 SplatIdx
= Idx
% NumElts
;
2340 return V
.getOperand(Idx
/ NumElts
);
2347 SDValue
SelectionDAG::getSplatValue(SDValue V
) {
2349 if (SDValue SrcVector
= getSplatSourceVector(V
, SplatIdx
))
2350 return getNode(ISD::EXTRACT_VECTOR_ELT
, SDLoc(V
),
2351 SrcVector
.getValueType().getScalarType(), SrcVector
,
2352 getIntPtrConstant(SplatIdx
, SDLoc(V
)));
2356 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2357 /// is less than the element bit-width of the shift node, return it.
2358 static const APInt
*getValidShiftAmountConstant(SDValue V
) {
2359 if (ConstantSDNode
*SA
= isConstOrConstSplat(V
.getOperand(1))) {
2360 // Shifting more than the bitwidth is not valid.
2361 const APInt
&ShAmt
= SA
->getAPIntValue();
2362 if (ShAmt
.ult(V
.getScalarValueSizeInBits()))
2368 /// Determine which bits of Op are known to be either zero or one and return
2369 /// them in Known. For vectors, the known bits are those that are shared by
2370 /// every vector element.
2371 KnownBits
SelectionDAG::computeKnownBits(SDValue Op
, unsigned Depth
) const {
2372 EVT VT
= Op
.getValueType();
2373 APInt DemandedElts
= VT
.isVector()
2374 ? APInt::getAllOnesValue(VT
.getVectorNumElements())
2376 return computeKnownBits(Op
, DemandedElts
, Depth
);
2379 /// Determine which bits of Op are known to be either zero or one and return
2380 /// them in Known. The DemandedElts argument allows us to only collect the known
2381 /// bits that are shared by the requested vector elements.
2382 KnownBits
SelectionDAG::computeKnownBits(SDValue Op
, const APInt
&DemandedElts
,
2383 unsigned Depth
) const {
2384 unsigned BitWidth
= Op
.getScalarValueSizeInBits();
2386 KnownBits
Known(BitWidth
); // Don't know anything.
2388 if (auto *C
= dyn_cast
<ConstantSDNode
>(Op
)) {
2389 // We know all of the bits for a constant!
2390 Known
.One
= C
->getAPIntValue();
2391 Known
.Zero
= ~Known
.One
;
2394 if (auto *C
= dyn_cast
<ConstantFPSDNode
>(Op
)) {
2395 // We know all of the bits for a constant fp!
2396 Known
.One
= C
->getValueAPF().bitcastToAPInt();
2397 Known
.Zero
= ~Known
.One
;
2402 return Known
; // Limit search depth.
2405 unsigned NumElts
= DemandedElts
.getBitWidth();
2406 assert((!Op
.getValueType().isVector() ||
2407 NumElts
== Op
.getValueType().getVectorNumElements()) &&
2408 "Unexpected vector size");
2411 return Known
; // No demanded elts, better to assume we don't know anything.
2413 unsigned Opcode
= Op
.getOpcode();
2415 case ISD::BUILD_VECTOR
:
2416 // Collect the known bits that are shared by every demanded vector element.
2417 Known
.Zero
.setAllBits(); Known
.One
.setAllBits();
2418 for (unsigned i
= 0, e
= Op
.getNumOperands(); i
!= e
; ++i
) {
2419 if (!DemandedElts
[i
])
2422 SDValue SrcOp
= Op
.getOperand(i
);
2423 Known2
= computeKnownBits(SrcOp
, Depth
+ 1);
2425 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2426 if (SrcOp
.getValueSizeInBits() != BitWidth
) {
2427 assert(SrcOp
.getValueSizeInBits() > BitWidth
&&
2428 "Expected BUILD_VECTOR implicit truncation");
2429 Known2
= Known2
.trunc(BitWidth
);
2432 // Known bits are the values that are shared by every demanded element.
2433 Known
.One
&= Known2
.One
;
2434 Known
.Zero
&= Known2
.Zero
;
2436 // If we don't know any bits, early out.
2437 if (Known
.isUnknown())
2441 case ISD::VECTOR_SHUFFLE
: {
2442 // Collect the known bits that are shared by every vector element referenced
2444 APInt
DemandedLHS(NumElts
, 0), DemandedRHS(NumElts
, 0);
2445 Known
.Zero
.setAllBits(); Known
.One
.setAllBits();
2446 const ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(Op
);
2447 assert(NumElts
== SVN
->getMask().size() && "Unexpected vector size");
2448 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2449 if (!DemandedElts
[i
])
2452 int M
= SVN
->getMaskElt(i
);
2454 // For UNDEF elements, we don't know anything about the common state of
2455 // the shuffle result.
2457 DemandedLHS
.clearAllBits();
2458 DemandedRHS
.clearAllBits();
2462 if ((unsigned)M
< NumElts
)
2463 DemandedLHS
.setBit((unsigned)M
% NumElts
);
2465 DemandedRHS
.setBit((unsigned)M
% NumElts
);
2467 // Known bits are the values that are shared by every demanded element.
2468 if (!!DemandedLHS
) {
2469 SDValue LHS
= Op
.getOperand(0);
2470 Known2
= computeKnownBits(LHS
, DemandedLHS
, Depth
+ 1);
2471 Known
.One
&= Known2
.One
;
2472 Known
.Zero
&= Known2
.Zero
;
2474 // If we don't know any bits, early out.
2475 if (Known
.isUnknown())
2477 if (!!DemandedRHS
) {
2478 SDValue RHS
= Op
.getOperand(1);
2479 Known2
= computeKnownBits(RHS
, DemandedRHS
, Depth
+ 1);
2480 Known
.One
&= Known2
.One
;
2481 Known
.Zero
&= Known2
.Zero
;
2485 case ISD::CONCAT_VECTORS
: {
2486 // Split DemandedElts and test each of the demanded subvectors.
2487 Known
.Zero
.setAllBits(); Known
.One
.setAllBits();
2488 EVT SubVectorVT
= Op
.getOperand(0).getValueType();
2489 unsigned NumSubVectorElts
= SubVectorVT
.getVectorNumElements();
2490 unsigned NumSubVectors
= Op
.getNumOperands();
2491 for (unsigned i
= 0; i
!= NumSubVectors
; ++i
) {
2492 APInt DemandedSub
= DemandedElts
.lshr(i
* NumSubVectorElts
);
2493 DemandedSub
= DemandedSub
.trunc(NumSubVectorElts
);
2494 if (!!DemandedSub
) {
2495 SDValue Sub
= Op
.getOperand(i
);
2496 Known2
= computeKnownBits(Sub
, DemandedSub
, Depth
+ 1);
2497 Known
.One
&= Known2
.One
;
2498 Known
.Zero
&= Known2
.Zero
;
2500 // If we don't know any bits, early out.
2501 if (Known
.isUnknown())
2506 case ISD::INSERT_SUBVECTOR
: {
2507 // If we know the element index, demand any elements from the subvector and
2508 // the remainder from the src its inserted into, otherwise demand them all.
2509 SDValue Src
= Op
.getOperand(0);
2510 SDValue Sub
= Op
.getOperand(1);
2511 ConstantSDNode
*SubIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
2512 unsigned NumSubElts
= Sub
.getValueType().getVectorNumElements();
2513 if (SubIdx
&& SubIdx
->getAPIntValue().ule(NumElts
- NumSubElts
)) {
2514 Known
.One
.setAllBits();
2515 Known
.Zero
.setAllBits();
2516 uint64_t Idx
= SubIdx
->getZExtValue();
2517 APInt DemandedSubElts
= DemandedElts
.extractBits(NumSubElts
, Idx
);
2518 if (!!DemandedSubElts
) {
2519 Known
= computeKnownBits(Sub
, DemandedSubElts
, Depth
+ 1);
2520 if (Known
.isUnknown())
2521 break; // early-out.
2523 APInt SubMask
= APInt::getBitsSet(NumElts
, Idx
, Idx
+ NumSubElts
);
2524 APInt DemandedSrcElts
= DemandedElts
& ~SubMask
;
2525 if (!!DemandedSrcElts
) {
2526 Known2
= computeKnownBits(Src
, DemandedSrcElts
, Depth
+ 1);
2527 Known
.One
&= Known2
.One
;
2528 Known
.Zero
&= Known2
.Zero
;
2531 Known
= computeKnownBits(Sub
, Depth
+ 1);
2532 if (Known
.isUnknown())
2533 break; // early-out.
2534 Known2
= computeKnownBits(Src
, Depth
+ 1);
2535 Known
.One
&= Known2
.One
;
2536 Known
.Zero
&= Known2
.Zero
;
2540 case ISD::EXTRACT_SUBVECTOR
: {
2541 // If we know the element index, just demand that subvector elements,
2542 // otherwise demand them all.
2543 SDValue Src
= Op
.getOperand(0);
2544 ConstantSDNode
*SubIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
2545 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
2546 if (SubIdx
&& SubIdx
->getAPIntValue().ule(NumSrcElts
- NumElts
)) {
2547 // Offset the demanded elts by the subvector index.
2548 uint64_t Idx
= SubIdx
->getZExtValue();
2549 APInt DemandedSrc
= DemandedElts
.zextOrSelf(NumSrcElts
).shl(Idx
);
2550 Known
= computeKnownBits(Src
, DemandedSrc
, Depth
+ 1);
2552 Known
= computeKnownBits(Src
, Depth
+ 1);
2556 case ISD::SCALAR_TO_VECTOR
: {
2557 // We know about scalar_to_vector as much as we know about it source,
2558 // which becomes the first element of otherwise unknown vector.
2559 if (DemandedElts
!= 1)
2562 SDValue N0
= Op
.getOperand(0);
2563 Known
= computeKnownBits(N0
, Depth
+ 1);
2564 if (N0
.getValueSizeInBits() != BitWidth
)
2565 Known
= Known
.trunc(BitWidth
);
2569 case ISD::BITCAST
: {
2570 SDValue N0
= Op
.getOperand(0);
2571 EVT SubVT
= N0
.getValueType();
2572 unsigned SubBitWidth
= SubVT
.getScalarSizeInBits();
2574 // Ignore bitcasts from unsupported types.
2575 if (!(SubVT
.isInteger() || SubVT
.isFloatingPoint()))
2578 // Fast handling of 'identity' bitcasts.
2579 if (BitWidth
== SubBitWidth
) {
2580 Known
= computeKnownBits(N0
, DemandedElts
, Depth
+ 1);
2584 bool IsLE
= getDataLayout().isLittleEndian();
2586 // Bitcast 'small element' vector to 'large element' scalar/vector.
2587 if ((BitWidth
% SubBitWidth
) == 0) {
2588 assert(N0
.getValueType().isVector() && "Expected bitcast from vector");
2590 // Collect known bits for the (larger) output by collecting the known
2591 // bits from each set of sub elements and shift these into place.
2592 // We need to separately call computeKnownBits for each set of
2593 // sub elements as the knownbits for each is likely to be different.
2594 unsigned SubScale
= BitWidth
/ SubBitWidth
;
2595 APInt
SubDemandedElts(NumElts
* SubScale
, 0);
2596 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2597 if (DemandedElts
[i
])
2598 SubDemandedElts
.setBit(i
* SubScale
);
2600 for (unsigned i
= 0; i
!= SubScale
; ++i
) {
2601 Known2
= computeKnownBits(N0
, SubDemandedElts
.shl(i
),
2603 unsigned Shifts
= IsLE
? i
: SubScale
- 1 - i
;
2604 Known
.One
|= Known2
.One
.zext(BitWidth
).shl(SubBitWidth
* Shifts
);
2605 Known
.Zero
|= Known2
.Zero
.zext(BitWidth
).shl(SubBitWidth
* Shifts
);
2609 // Bitcast 'large element' scalar/vector to 'small element' vector.
2610 if ((SubBitWidth
% BitWidth
) == 0) {
2611 assert(Op
.getValueType().isVector() && "Expected bitcast to vector");
2613 // Collect known bits for the (smaller) output by collecting the known
2614 // bits from the overlapping larger input elements and extracting the
2615 // sub sections we actually care about.
2616 unsigned SubScale
= SubBitWidth
/ BitWidth
;
2617 APInt
SubDemandedElts(NumElts
/ SubScale
, 0);
2618 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2619 if (DemandedElts
[i
])
2620 SubDemandedElts
.setBit(i
/ SubScale
);
2622 Known2
= computeKnownBits(N0
, SubDemandedElts
, Depth
+ 1);
2624 Known
.Zero
.setAllBits(); Known
.One
.setAllBits();
2625 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2626 if (DemandedElts
[i
]) {
2627 unsigned Shifts
= IsLE
? i
: NumElts
- 1 - i
;
2628 unsigned Offset
= (Shifts
% SubScale
) * BitWidth
;
2629 Known
.One
&= Known2
.One
.lshr(Offset
).trunc(BitWidth
);
2630 Known
.Zero
&= Known2
.Zero
.lshr(Offset
).trunc(BitWidth
);
2631 // If we don't know any bits, early out.
2632 if (Known
.isUnknown())
2639 // If either the LHS or the RHS are Zero, the result is zero.
2640 Known
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
2641 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2643 // Output known-1 bits are only known if set in both the LHS & RHS.
2644 Known
.One
&= Known2
.One
;
2645 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2646 Known
.Zero
|= Known2
.Zero
;
2649 Known
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
2650 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2652 // Output known-0 bits are only known if clear in both the LHS & RHS.
2653 Known
.Zero
&= Known2
.Zero
;
2654 // Output known-1 are known to be set if set in either the LHS | RHS.
2655 Known
.One
|= Known2
.One
;
2658 Known
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
2659 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2661 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2662 APInt KnownZeroOut
= (Known
.Zero
& Known2
.Zero
) | (Known
.One
& Known2
.One
);
2663 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2664 Known
.One
= (Known
.Zero
& Known2
.One
) | (Known
.One
& Known2
.Zero
);
2665 Known
.Zero
= KnownZeroOut
;
2669 Known
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
2670 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2672 // If low bits are zero in either operand, output low known-0 bits.
2673 // Also compute a conservative estimate for high known-0 bits.
2674 // More trickiness is possible, but this is sufficient for the
2675 // interesting case of alignment computation.
2676 unsigned TrailZ
= Known
.countMinTrailingZeros() +
2677 Known2
.countMinTrailingZeros();
2678 unsigned LeadZ
= std::max(Known
.countMinLeadingZeros() +
2679 Known2
.countMinLeadingZeros(),
2680 BitWidth
) - BitWidth
;
2683 Known
.Zero
.setLowBits(std::min(TrailZ
, BitWidth
));
2684 Known
.Zero
.setHighBits(std::min(LeadZ
, BitWidth
));
2688 // For the purposes of computing leading zeros we can conservatively
2689 // treat a udiv as a logical right shift by the power of 2 known to
2690 // be less than the denominator.
2691 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2692 unsigned LeadZ
= Known2
.countMinLeadingZeros();
2694 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
2695 unsigned RHSMaxLeadingZeros
= Known2
.countMaxLeadingZeros();
2696 if (RHSMaxLeadingZeros
!= BitWidth
)
2697 LeadZ
= std::min(BitWidth
, LeadZ
+ BitWidth
- RHSMaxLeadingZeros
- 1);
2699 Known
.Zero
.setHighBits(LeadZ
);
2704 Known
= computeKnownBits(Op
.getOperand(2), DemandedElts
, Depth
+1);
2705 // If we don't know any bits, early out.
2706 if (Known
.isUnknown())
2708 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+1);
2710 // Only known if known in both the LHS and RHS.
2711 Known
.One
&= Known2
.One
;
2712 Known
.Zero
&= Known2
.Zero
;
2714 case ISD::SELECT_CC
:
2715 Known
= computeKnownBits(Op
.getOperand(3), DemandedElts
, Depth
+1);
2716 // If we don't know any bits, early out.
2717 if (Known
.isUnknown())
2719 Known2
= computeKnownBits(Op
.getOperand(2), DemandedElts
, Depth
+1);
2721 // Only known if known in both the LHS and RHS.
2722 Known
.One
&= Known2
.One
;
2723 Known
.Zero
&= Known2
.Zero
;
2727 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS
:
2728 if (Op
.getResNo() != 1)
2730 // The boolean result conforms to getBooleanContents.
2731 // If we know the result of a setcc has the top bits zero, use this info.
2732 // We know that we have an integer-based boolean since these operations
2733 // are only available for integer.
2734 if (TLI
->getBooleanContents(Op
.getValueType().isVector(), false) ==
2735 TargetLowering::ZeroOrOneBooleanContent
&&
2737 Known
.Zero
.setBitsFrom(1);
2740 // If we know the result of a setcc has the top bits zero, use this info.
2741 if (TLI
->getBooleanContents(Op
.getOperand(0).getValueType()) ==
2742 TargetLowering::ZeroOrOneBooleanContent
&&
2744 Known
.Zero
.setBitsFrom(1);
2747 if (const APInt
*ShAmt
= getValidShiftAmountConstant(Op
)) {
2748 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2749 unsigned Shift
= ShAmt
->getZExtValue();
2750 Known
.Zero
<<= Shift
;
2751 Known
.One
<<= Shift
;
2752 // Low bits are known zero.
2753 Known
.Zero
.setLowBits(Shift
);
2757 if (const APInt
*ShAmt
= getValidShiftAmountConstant(Op
)) {
2758 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2759 unsigned Shift
= ShAmt
->getZExtValue();
2760 Known
.Zero
.lshrInPlace(Shift
);
2761 Known
.One
.lshrInPlace(Shift
);
2762 // High bits are known zero.
2763 Known
.Zero
.setHighBits(Shift
);
2764 } else if (auto *BV
= dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(1))) {
2765 // If the shift amount is a vector of constants see if we can bound
2766 // the number of upper zero bits.
2767 unsigned ShiftAmountMin
= BitWidth
;
2768 for (unsigned i
= 0; i
!= BV
->getNumOperands(); ++i
) {
2769 if (auto *C
= dyn_cast
<ConstantSDNode
>(BV
->getOperand(i
))) {
2770 const APInt
&ShAmt
= C
->getAPIntValue();
2771 if (ShAmt
.ult(BitWidth
)) {
2772 ShiftAmountMin
= std::min
<unsigned>(ShiftAmountMin
,
2773 ShAmt
.getZExtValue());
2777 // Don't know anything.
2782 Known
.Zero
.setHighBits(ShiftAmountMin
);
2786 if (const APInt
*ShAmt
= getValidShiftAmountConstant(Op
)) {
2787 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2788 unsigned Shift
= ShAmt
->getZExtValue();
2789 // Sign extend known zero/one bit (else is unknown).
2790 Known
.Zero
.ashrInPlace(Shift
);
2791 Known
.One
.ashrInPlace(Shift
);
2796 if (ConstantSDNode
*C
= isConstOrConstSplat(Op
.getOperand(2), DemandedElts
)) {
2797 unsigned Amt
= C
->getAPIntValue().urem(BitWidth
);
2799 // For fshl, 0-shift returns the 1st arg.
2800 // For fshr, 0-shift returns the 2nd arg.
2802 Known
= computeKnownBits(Op
.getOperand(Opcode
== ISD::FSHL
? 0 : 1),
2803 DemandedElts
, Depth
+ 1);
2807 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2808 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2809 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2810 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
2811 if (Opcode
== ISD::FSHL
) {
2814 Known2
.One
.lshrInPlace(BitWidth
- Amt
);
2815 Known2
.Zero
.lshrInPlace(BitWidth
- Amt
);
2817 Known
.One
<<= BitWidth
- Amt
;
2818 Known
.Zero
<<= BitWidth
- Amt
;
2819 Known2
.One
.lshrInPlace(Amt
);
2820 Known2
.Zero
.lshrInPlace(Amt
);
2822 Known
.One
|= Known2
.One
;
2823 Known
.Zero
|= Known2
.Zero
;
2826 case ISD::SIGN_EXTEND_INREG
: {
2827 EVT EVT
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT();
2828 unsigned EBits
= EVT
.getScalarSizeInBits();
2830 // Sign extension. Compute the demanded bits in the result that are not
2831 // present in the input.
2832 APInt NewBits
= APInt::getHighBitsSet(BitWidth
, BitWidth
- EBits
);
2834 APInt InSignMask
= APInt::getSignMask(EBits
);
2835 APInt InputDemandedBits
= APInt::getLowBitsSet(BitWidth
, EBits
);
2837 // If the sign extended bits are demanded, we know that the sign
2839 InSignMask
= InSignMask
.zext(BitWidth
);
2840 if (NewBits
.getBoolValue())
2841 InputDemandedBits
|= InSignMask
;
2843 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2844 Known
.One
&= InputDemandedBits
;
2845 Known
.Zero
&= InputDemandedBits
;
2847 // If the sign bit of the input is known set or clear, then we know the
2848 // top bits of the result.
2849 if (Known
.Zero
.intersects(InSignMask
)) { // Input sign bit known clear
2850 Known
.Zero
|= NewBits
;
2851 Known
.One
&= ~NewBits
;
2852 } else if (Known
.One
.intersects(InSignMask
)) { // Input sign bit known set
2853 Known
.One
|= NewBits
;
2854 Known
.Zero
&= ~NewBits
;
2855 } else { // Input sign bit unknown
2856 Known
.Zero
&= ~NewBits
;
2857 Known
.One
&= ~NewBits
;
2862 case ISD::CTTZ_ZERO_UNDEF
: {
2863 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2864 // If we have a known 1, its position is our upper bound.
2865 unsigned PossibleTZ
= Known2
.countMaxTrailingZeros();
2866 unsigned LowBits
= Log2_32(PossibleTZ
) + 1;
2867 Known
.Zero
.setBitsFrom(LowBits
);
2871 case ISD::CTLZ_ZERO_UNDEF
: {
2872 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2873 // If we have a known 1, its position is our upper bound.
2874 unsigned PossibleLZ
= Known2
.countMaxLeadingZeros();
2875 unsigned LowBits
= Log2_32(PossibleLZ
) + 1;
2876 Known
.Zero
.setBitsFrom(LowBits
);
2880 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2881 // If we know some of the bits are zero, they can't be one.
2882 unsigned PossibleOnes
= Known2
.countMaxPopulation();
2883 Known
.Zero
.setBitsFrom(Log2_32(PossibleOnes
) + 1);
2887 LoadSDNode
*LD
= cast
<LoadSDNode
>(Op
);
2888 // If this is a ZEXTLoad and we are looking at the loaded value.
2889 if (ISD::isZEXTLoad(Op
.getNode()) && Op
.getResNo() == 0) {
2890 EVT VT
= LD
->getMemoryVT();
2891 unsigned MemBits
= VT
.getScalarSizeInBits();
2892 Known
.Zero
.setBitsFrom(MemBits
);
2893 } else if (const MDNode
*Ranges
= LD
->getRanges()) {
2894 if (LD
->getExtensionType() == ISD::NON_EXTLOAD
)
2895 computeKnownBitsFromRangeMetadata(*Ranges
, Known
);
2899 case ISD::ZERO_EXTEND_VECTOR_INREG
: {
2900 EVT InVT
= Op
.getOperand(0).getValueType();
2901 APInt InDemandedElts
= DemandedElts
.zextOrSelf(InVT
.getVectorNumElements());
2902 Known
= computeKnownBits(Op
.getOperand(0), InDemandedElts
, Depth
+ 1);
2903 Known
= Known
.zext(BitWidth
, true /* ExtendedBitsAreKnownZero */);
2906 case ISD::ZERO_EXTEND
: {
2907 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2908 Known
= Known
.zext(BitWidth
, true /* ExtendedBitsAreKnownZero */);
2911 case ISD::SIGN_EXTEND_VECTOR_INREG
: {
2912 EVT InVT
= Op
.getOperand(0).getValueType();
2913 APInt InDemandedElts
= DemandedElts
.zextOrSelf(InVT
.getVectorNumElements());
2914 Known
= computeKnownBits(Op
.getOperand(0), InDemandedElts
, Depth
+ 1);
2915 // If the sign bit is known to be zero or one, then sext will extend
2916 // it to the top bits, else it will just zext.
2917 Known
= Known
.sext(BitWidth
);
2920 case ISD::SIGN_EXTEND
: {
2921 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2922 // If the sign bit is known to be zero or one, then sext will extend
2923 // it to the top bits, else it will just zext.
2924 Known
= Known
.sext(BitWidth
);
2927 case ISD::ANY_EXTEND
: {
2928 Known
= computeKnownBits(Op
.getOperand(0), Depth
+1);
2929 Known
= Known
.zext(BitWidth
, false /* ExtendedBitsAreKnownZero */);
2932 case ISD::TRUNCATE
: {
2933 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2934 Known
= Known
.trunc(BitWidth
);
2937 case ISD::AssertZext
: {
2938 EVT VT
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT();
2939 APInt InMask
= APInt::getLowBitsSet(BitWidth
, VT
.getSizeInBits());
2940 Known
= computeKnownBits(Op
.getOperand(0), Depth
+1);
2941 Known
.Zero
|= (~InMask
);
2942 Known
.One
&= (~Known
.Zero
);
2946 // All bits are zero except the low bit.
2947 Known
.Zero
.setBitsFrom(1);
2951 if (Op
.getResNo() == 1) {
2952 // If we know the result of a setcc has the top bits zero, use this info.
2953 if (TLI
->getBooleanContents(Op
.getOperand(0).getValueType()) ==
2954 TargetLowering::ZeroOrOneBooleanContent
&&
2956 Known
.Zero
.setBitsFrom(1);
2962 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
2963 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
2964 Known
= KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
2971 if (Op
.getResNo() == 1) {
2972 // If we know the result of a setcc has the top bits zero, use this info.
2973 if (TLI
->getBooleanContents(Op
.getOperand(0).getValueType()) ==
2974 TargetLowering::ZeroOrOneBooleanContent
&&
2976 Known
.Zero
.setBitsFrom(1);
2983 assert(Op
.getResNo() == 0 && "We only compute knownbits for the sum here.");
2985 // With ADDE and ADDCARRY, a carry bit may be added in.
2987 if (Opcode
== ISD::ADDE
)
2988 // Can't track carry from glue, set carry to unknown.
2990 else if (Opcode
== ISD::ADDCARRY
)
2991 // TODO: Compute known bits for the carry operand. Not sure if it is worth
2992 // the trouble (how often will we find a known carry bit). And I haven't
2993 // tested this very much yet, but something like this might work:
2994 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
2995 // Carry = Carry.zextOrTrunc(1, false);
3000 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3001 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
3002 Known
= KnownBits::computeForAddCarry(Known
, Known2
, Carry
);
3006 if (ConstantSDNode
*Rem
= isConstOrConstSplat(Op
.getOperand(1))) {
3007 const APInt
&RA
= Rem
->getAPIntValue().abs();
3008 if (RA
.isPowerOf2()) {
3009 APInt LowBits
= RA
- 1;
3010 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3012 // The low bits of the first operand are unchanged by the srem.
3013 Known
.Zero
= Known2
.Zero
& LowBits
;
3014 Known
.One
= Known2
.One
& LowBits
;
3016 // If the first operand is non-negative or has all low bits zero, then
3017 // the upper bits are all zero.
3018 if (Known2
.Zero
[BitWidth
-1] || ((Known2
.Zero
& LowBits
) == LowBits
))
3019 Known
.Zero
|= ~LowBits
;
3021 // If the first operand is negative and not all low bits are zero, then
3022 // the upper bits are all one.
3023 if (Known2
.One
[BitWidth
-1] && ((Known2
.One
& LowBits
) != 0))
3024 Known
.One
|= ~LowBits
;
3025 assert((Known
.Zero
& Known
.One
) == 0&&"Bits known to be one AND zero?");
3030 if (ConstantSDNode
*Rem
= isConstOrConstSplat(Op
.getOperand(1))) {
3031 const APInt
&RA
= Rem
->getAPIntValue();
3032 if (RA
.isPowerOf2()) {
3033 APInt LowBits
= (RA
- 1);
3034 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3036 // The upper bits are all zero, the lower ones are unchanged.
3037 Known
.Zero
= Known2
.Zero
| ~LowBits
;
3038 Known
.One
= Known2
.One
& LowBits
;
3043 // Since the result is less than or equal to either operand, any leading
3044 // zero bits in either operand must also exist in the result.
3045 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3046 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
3049 std::max(Known
.countMinLeadingZeros(), Known2
.countMinLeadingZeros());
3051 Known
.Zero
.setHighBits(Leaders
);
3054 case ISD::EXTRACT_ELEMENT
: {
3055 Known
= computeKnownBits(Op
.getOperand(0), Depth
+1);
3056 const unsigned Index
= Op
.getConstantOperandVal(1);
3057 const unsigned EltBitWidth
= Op
.getValueSizeInBits();
3059 // Remove low part of known bits mask
3060 Known
.Zero
= Known
.Zero
.getHiBits(Known
.getBitWidth() - Index
* EltBitWidth
);
3061 Known
.One
= Known
.One
.getHiBits(Known
.getBitWidth() - Index
* EltBitWidth
);
3063 // Remove high part of known bit mask
3064 Known
= Known
.trunc(EltBitWidth
);
3067 case ISD::EXTRACT_VECTOR_ELT
: {
3068 SDValue InVec
= Op
.getOperand(0);
3069 SDValue EltNo
= Op
.getOperand(1);
3070 EVT VecVT
= InVec
.getValueType();
3071 const unsigned EltBitWidth
= VecVT
.getScalarSizeInBits();
3072 const unsigned NumSrcElts
= VecVT
.getVectorNumElements();
3073 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3074 // anything about the extended bits.
3075 if (BitWidth
> EltBitWidth
)
3076 Known
= Known
.trunc(EltBitWidth
);
3077 ConstantSDNode
*ConstEltNo
= dyn_cast
<ConstantSDNode
>(EltNo
);
3078 if (ConstEltNo
&& ConstEltNo
->getAPIntValue().ult(NumSrcElts
)) {
3079 // If we know the element index, just demand that vector element.
3080 unsigned Idx
= ConstEltNo
->getZExtValue();
3081 APInt DemandedElt
= APInt::getOneBitSet(NumSrcElts
, Idx
);
3082 Known
= computeKnownBits(InVec
, DemandedElt
, Depth
+ 1);
3084 // Unknown element index, so ignore DemandedElts and demand them all.
3085 Known
= computeKnownBits(InVec
, Depth
+ 1);
3087 if (BitWidth
> EltBitWidth
)
3088 Known
= Known
.zext(BitWidth
, false /* => any extend */);
3091 case ISD::INSERT_VECTOR_ELT
: {
3092 SDValue InVec
= Op
.getOperand(0);
3093 SDValue InVal
= Op
.getOperand(1);
3094 SDValue EltNo
= Op
.getOperand(2);
3096 ConstantSDNode
*CEltNo
= dyn_cast
<ConstantSDNode
>(EltNo
);
3097 if (CEltNo
&& CEltNo
->getAPIntValue().ult(NumElts
)) {
3098 // If we know the element index, split the demand between the
3099 // source vector and the inserted element.
3100 Known
.Zero
= Known
.One
= APInt::getAllOnesValue(BitWidth
);
3101 unsigned EltIdx
= CEltNo
->getZExtValue();
3103 // If we demand the inserted element then add its common known bits.
3104 if (DemandedElts
[EltIdx
]) {
3105 Known2
= computeKnownBits(InVal
, Depth
+ 1);
3106 Known
.One
&= Known2
.One
.zextOrTrunc(Known
.One
.getBitWidth());
3107 Known
.Zero
&= Known2
.Zero
.zextOrTrunc(Known
.Zero
.getBitWidth());
3110 // If we demand the source vector then add its common known bits, ensuring
3111 // that we don't demand the inserted element.
3112 APInt VectorElts
= DemandedElts
& ~(APInt::getOneBitSet(NumElts
, EltIdx
));
3114 Known2
= computeKnownBits(InVec
, VectorElts
, Depth
+ 1);
3115 Known
.One
&= Known2
.One
;
3116 Known
.Zero
&= Known2
.Zero
;
3119 // Unknown element index, so ignore DemandedElts and demand them all.
3120 Known
= computeKnownBits(InVec
, Depth
+ 1);
3121 Known2
= computeKnownBits(InVal
, Depth
+ 1);
3122 Known
.One
&= Known2
.One
.zextOrTrunc(Known
.One
.getBitWidth());
3123 Known
.Zero
&= Known2
.Zero
.zextOrTrunc(Known
.Zero
.getBitWidth());
3127 case ISD::BITREVERSE
: {
3128 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3129 Known
.Zero
= Known2
.Zero
.reverseBits();
3130 Known
.One
= Known2
.One
.reverseBits();
3134 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3135 Known
.Zero
= Known2
.Zero
.byteSwap();
3136 Known
.One
= Known2
.One
.byteSwap();
3140 Known2
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3142 // If the source's MSB is zero then we know the rest of the bits already.
3143 if (Known2
.isNonNegative()) {
3144 Known
.Zero
= Known2
.Zero
;
3145 Known
.One
= Known2
.One
;
3149 // We only know that the absolute values's MSB will be zero iff there is
3150 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3151 Known2
.One
.clearSignBit();
3152 if (Known2
.One
.getBoolValue()) {
3153 Known
.Zero
= APInt::getSignMask(BitWidth
);
3159 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3160 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
3162 // UMIN - we know that the result will have the maximum of the
3163 // known zero leading bits of the inputs.
3164 unsigned LeadZero
= Known
.countMinLeadingZeros();
3165 LeadZero
= std::max(LeadZero
, Known2
.countMinLeadingZeros());
3167 Known
.Zero
&= Known2
.Zero
;
3168 Known
.One
&= Known2
.One
;
3169 Known
.Zero
.setHighBits(LeadZero
);
3173 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3174 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
3176 // UMAX - we know that the result will have the maximum of the
3177 // known one leading bits of the inputs.
3178 unsigned LeadOne
= Known
.countMinLeadingOnes();
3179 LeadOne
= std::max(LeadOne
, Known2
.countMinLeadingOnes());
3181 Known
.Zero
&= Known2
.Zero
;
3182 Known
.One
&= Known2
.One
;
3183 Known
.One
.setHighBits(LeadOne
);
3188 // If we have a clamp pattern, we know that the number of sign bits will be
3189 // the minimum of the clamp min/max range.
3190 bool IsMax
= (Opcode
== ISD::SMAX
);
3191 ConstantSDNode
*CstLow
= nullptr, *CstHigh
= nullptr;
3192 if ((CstLow
= isConstOrConstSplat(Op
.getOperand(1), DemandedElts
)))
3193 if (Op
.getOperand(0).getOpcode() == (IsMax
? ISD::SMIN
: ISD::SMAX
))
3195 isConstOrConstSplat(Op
.getOperand(0).getOperand(1), DemandedElts
);
3196 if (CstLow
&& CstHigh
) {
3198 std::swap(CstLow
, CstHigh
);
3200 const APInt
&ValueLow
= CstLow
->getAPIntValue();
3201 const APInt
&ValueHigh
= CstHigh
->getAPIntValue();
3202 if (ValueLow
.sle(ValueHigh
)) {
3203 unsigned LowSignBits
= ValueLow
.getNumSignBits();
3204 unsigned HighSignBits
= ValueHigh
.getNumSignBits();
3205 unsigned MinSignBits
= std::min(LowSignBits
, HighSignBits
);
3206 if (ValueLow
.isNegative() && ValueHigh
.isNegative()) {
3207 Known
.One
.setHighBits(MinSignBits
);
3210 if (ValueLow
.isNonNegative() && ValueHigh
.isNonNegative()) {
3211 Known
.Zero
.setHighBits(MinSignBits
);
3217 // Fallback - just get the shared known bits of the operands.
3218 Known
= computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
3219 if (Known
.isUnknown()) break; // Early-out
3220 Known2
= computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
3221 Known
.Zero
&= Known2
.Zero
;
3222 Known
.One
&= Known2
.One
;
3225 case ISD::FrameIndex
:
3226 case ISD::TargetFrameIndex
:
3227 TLI
->computeKnownBitsForFrameIndex(Op
, Known
, DemandedElts
, *this, Depth
);
3231 if (Opcode
< ISD::BUILTIN_OP_END
)
3234 case ISD::INTRINSIC_WO_CHAIN
:
3235 case ISD::INTRINSIC_W_CHAIN
:
3236 case ISD::INTRINSIC_VOID
:
3237 // Allow the target to implement this method for its nodes.
3238 TLI
->computeKnownBitsForTargetNode(Op
, Known
, DemandedElts
, *this, Depth
);
3242 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
3246 SelectionDAG::OverflowKind
SelectionDAG::computeOverflowKind(SDValue N0
,
3248 // X + 0 never overflow
3249 if (isNullConstant(N1
))
3252 KnownBits N1Known
= computeKnownBits(N1
);
3253 if (N1Known
.Zero
.getBoolValue()) {
3254 KnownBits N0Known
= computeKnownBits(N0
);
3257 (void)(~N0Known
.Zero
).uadd_ov(~N1Known
.Zero
, overflow
);
3262 // mulhi + 1 never overflow
3263 if (N0
.getOpcode() == ISD::UMUL_LOHI
&& N0
.getResNo() == 1 &&
3264 (~N1Known
.Zero
& 0x01) == ~N1Known
.Zero
)
3267 if (N1
.getOpcode() == ISD::UMUL_LOHI
&& N1
.getResNo() == 1) {
3268 KnownBits N0Known
= computeKnownBits(N0
);
3270 if ((~N0Known
.Zero
& 0x01) == ~N0Known
.Zero
)
3274 return OFK_Sometime
;
3277 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val
) const {
3278 EVT OpVT
= Val
.getValueType();
3279 unsigned BitWidth
= OpVT
.getScalarSizeInBits();
3281 // Is the constant a known power of 2?
3282 if (ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(Val
))
3283 return Const
->getAPIntValue().zextOrTrunc(BitWidth
).isPowerOf2();
3285 // A left-shift of a constant one will have exactly one bit set because
3286 // shifting the bit off the end is undefined.
3287 if (Val
.getOpcode() == ISD::SHL
) {
3288 auto *C
= isConstOrConstSplat(Val
.getOperand(0));
3289 if (C
&& C
->getAPIntValue() == 1)
3293 // Similarly, a logical right-shift of a constant sign-bit will have exactly
3295 if (Val
.getOpcode() == ISD::SRL
) {
3296 auto *C
= isConstOrConstSplat(Val
.getOperand(0));
3297 if (C
&& C
->getAPIntValue().isSignMask())
3301 // Are all operands of a build vector constant powers of two?
3302 if (Val
.getOpcode() == ISD::BUILD_VECTOR
)
3303 if (llvm::all_of(Val
->ops(), [BitWidth
](SDValue E
) {
3304 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(E
))
3305 return C
->getAPIntValue().zextOrTrunc(BitWidth
).isPowerOf2();
3310 // More could be done here, though the above checks are enough
3311 // to handle some common cases.
3313 // Fall back to computeKnownBits to catch other known cases.
3314 KnownBits Known
= computeKnownBits(Val
);
3315 return (Known
.countMaxPopulation() == 1) && (Known
.countMinPopulation() == 1);
3318 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op
, unsigned Depth
) const {
3319 EVT VT
= Op
.getValueType();
3320 APInt DemandedElts
= VT
.isVector()
3321 ? APInt::getAllOnesValue(VT
.getVectorNumElements())
3323 return ComputeNumSignBits(Op
, DemandedElts
, Depth
);
3326 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op
, const APInt
&DemandedElts
,
3327 unsigned Depth
) const {
3328 EVT VT
= Op
.getValueType();
3329 assert((VT
.isInteger() || VT
.isFloatingPoint()) && "Invalid VT!");
3330 unsigned VTBits
= VT
.getScalarSizeInBits();
3331 unsigned NumElts
= DemandedElts
.getBitWidth();
3333 unsigned FirstAnswer
= 1;
3335 if (auto *C
= dyn_cast
<ConstantSDNode
>(Op
)) {
3336 const APInt
&Val
= C
->getAPIntValue();
3337 return Val
.getNumSignBits();
3341 return 1; // Limit search depth.
3344 return 1; // No demanded elts, better to assume we don't know anything.
3346 unsigned Opcode
= Op
.getOpcode();
3349 case ISD::AssertSext
:
3350 Tmp
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT().getSizeInBits();
3351 return VTBits
-Tmp
+1;
3352 case ISD::AssertZext
:
3353 Tmp
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT().getSizeInBits();
3356 case ISD::BUILD_VECTOR
:
3358 for (unsigned i
= 0, e
= Op
.getNumOperands(); (i
< e
) && (Tmp
> 1); ++i
) {
3359 if (!DemandedElts
[i
])
3362 SDValue SrcOp
= Op
.getOperand(i
);
3363 Tmp2
= ComputeNumSignBits(Op
.getOperand(i
), Depth
+ 1);
3365 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3366 if (SrcOp
.getValueSizeInBits() != VTBits
) {
3367 assert(SrcOp
.getValueSizeInBits() > VTBits
&&
3368 "Expected BUILD_VECTOR implicit truncation");
3369 unsigned ExtraBits
= SrcOp
.getValueSizeInBits() - VTBits
;
3370 Tmp2
= (Tmp2
> ExtraBits
? Tmp2
- ExtraBits
: 1);
3372 Tmp
= std::min(Tmp
, Tmp2
);
3376 case ISD::VECTOR_SHUFFLE
: {
3377 // Collect the minimum number of sign bits that are shared by every vector
3378 // element referenced by the shuffle.
3379 APInt
DemandedLHS(NumElts
, 0), DemandedRHS(NumElts
, 0);
3380 const ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(Op
);
3381 assert(NumElts
== SVN
->getMask().size() && "Unexpected vector size");
3382 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
3383 int M
= SVN
->getMaskElt(i
);
3384 if (!DemandedElts
[i
])
3386 // For UNDEF elements, we don't know anything about the common state of
3387 // the shuffle result.
3390 if ((unsigned)M
< NumElts
)
3391 DemandedLHS
.setBit((unsigned)M
% NumElts
);
3393 DemandedRHS
.setBit((unsigned)M
% NumElts
);
3395 Tmp
= std::numeric_limits
<unsigned>::max();
3397 Tmp
= ComputeNumSignBits(Op
.getOperand(0), DemandedLHS
, Depth
+ 1);
3398 if (!!DemandedRHS
) {
3399 Tmp2
= ComputeNumSignBits(Op
.getOperand(1), DemandedRHS
, Depth
+ 1);
3400 Tmp
= std::min(Tmp
, Tmp2
);
3402 // If we don't know anything, early out and try computeKnownBits fall-back.
3405 assert(Tmp
<= VTBits
&& "Failed to determine minimum sign bits");
3409 case ISD::BITCAST
: {
3410 SDValue N0
= Op
.getOperand(0);
3411 EVT SrcVT
= N0
.getValueType();
3412 unsigned SrcBits
= SrcVT
.getScalarSizeInBits();
3414 // Ignore bitcasts from unsupported types..
3415 if (!(SrcVT
.isInteger() || SrcVT
.isFloatingPoint()))
3418 // Fast handling of 'identity' bitcasts.
3419 if (VTBits
== SrcBits
)
3420 return ComputeNumSignBits(N0
, DemandedElts
, Depth
+ 1);
3422 bool IsLE
= getDataLayout().isLittleEndian();
3424 // Bitcast 'large element' scalar/vector to 'small element' vector.
3425 if ((SrcBits
% VTBits
) == 0) {
3426 assert(VT
.isVector() && "Expected bitcast to vector");
3428 unsigned Scale
= SrcBits
/ VTBits
;
3429 APInt
SrcDemandedElts(NumElts
/ Scale
, 0);
3430 for (unsigned i
= 0; i
!= NumElts
; ++i
)
3431 if (DemandedElts
[i
])
3432 SrcDemandedElts
.setBit(i
/ Scale
);
3434 // Fast case - sign splat can be simply split across the small elements.
3435 Tmp
= ComputeNumSignBits(N0
, SrcDemandedElts
, Depth
+ 1);
3439 // Slow case - determine how far the sign extends into each sub-element.
3441 for (unsigned i
= 0; i
!= NumElts
; ++i
)
3442 if (DemandedElts
[i
]) {
3443 unsigned SubOffset
= i
% Scale
;
3444 SubOffset
= (IsLE
? ((Scale
- 1) - SubOffset
) : SubOffset
);
3445 SubOffset
= SubOffset
* VTBits
;
3446 if (Tmp
<= SubOffset
)
3448 Tmp2
= std::min(Tmp2
, Tmp
- SubOffset
);
3455 case ISD::SIGN_EXTEND
:
3456 Tmp
= VTBits
- Op
.getOperand(0).getScalarValueSizeInBits();
3457 return ComputeNumSignBits(Op
.getOperand(0), DemandedElts
, Depth
+1) + Tmp
;
3458 case ISD::SIGN_EXTEND_INREG
:
3459 // Max of the input and what this extends.
3460 Tmp
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT().getScalarSizeInBits();
3462 Tmp2
= ComputeNumSignBits(Op
.getOperand(0), DemandedElts
, Depth
+1);
3463 return std::max(Tmp
, Tmp2
);
3464 case ISD::SIGN_EXTEND_VECTOR_INREG
: {
3465 SDValue Src
= Op
.getOperand(0);
3466 EVT SrcVT
= Src
.getValueType();
3467 APInt DemandedSrcElts
= DemandedElts
.zextOrSelf(SrcVT
.getVectorNumElements());
3468 Tmp
= VTBits
- SrcVT
.getScalarSizeInBits();
3469 return ComputeNumSignBits(Src
, DemandedSrcElts
, Depth
+1) + Tmp
;
3473 Tmp
= ComputeNumSignBits(Op
.getOperand(0), DemandedElts
, Depth
+1);
3474 // SRA X, C -> adds C sign bits.
3475 if (ConstantSDNode
*C
=
3476 isConstOrConstSplat(Op
.getOperand(1), DemandedElts
)) {
3477 APInt ShiftVal
= C
->getAPIntValue();
3479 Tmp
= ShiftVal
.uge(VTBits
) ? VTBits
: ShiftVal
.getZExtValue();
3483 if (ConstantSDNode
*C
=
3484 isConstOrConstSplat(Op
.getOperand(1), DemandedElts
)) {
3485 // shl destroys sign bits.
3486 Tmp
= ComputeNumSignBits(Op
.getOperand(0), DemandedElts
, Depth
+1);
3487 if (C
->getAPIntValue().uge(VTBits
) || // Bad shift.
3488 C
->getAPIntValue().uge(Tmp
)) break; // Shifted all sign bits out.
3489 return Tmp
- C
->getZExtValue();
3494 case ISD::XOR
: // NOT is handled here.
3495 // Logical binary ops preserve the number of sign bits at the worst.
3496 Tmp
= ComputeNumSignBits(Op
.getOperand(0), DemandedElts
, Depth
+1);
3498 Tmp2
= ComputeNumSignBits(Op
.getOperand(1), DemandedElts
, Depth
+1);
3499 FirstAnswer
= std::min(Tmp
, Tmp2
);
3500 // We computed what we know about the sign bits as our first
3501 // answer. Now proceed to the generic code that uses
3502 // computeKnownBits, and pick whichever answer is better.
3508 Tmp
= ComputeNumSignBits(Op
.getOperand(1), DemandedElts
, Depth
+1);
3509 if (Tmp
== 1) return 1; // Early out.
3510 Tmp2
= ComputeNumSignBits(Op
.getOperand(2), DemandedElts
, Depth
+1);
3511 return std::min(Tmp
, Tmp2
);
3512 case ISD::SELECT_CC
:
3513 Tmp
= ComputeNumSignBits(Op
.getOperand(2), DemandedElts
, Depth
+1);
3514 if (Tmp
== 1) return 1; // Early out.
3515 Tmp2
= ComputeNumSignBits(Op
.getOperand(3), DemandedElts
, Depth
+1);
3516 return std::min(Tmp
, Tmp2
);
3520 // If we have a clamp pattern, we know that the number of sign bits will be
3521 // the minimum of the clamp min/max range.
3522 bool IsMax
= (Opcode
== ISD::SMAX
);
3523 ConstantSDNode
*CstLow
= nullptr, *CstHigh
= nullptr;
3524 if ((CstLow
= isConstOrConstSplat(Op
.getOperand(1), DemandedElts
)))
3525 if (Op
.getOperand(0).getOpcode() == (IsMax
? ISD::SMIN
: ISD::SMAX
))
3527 isConstOrConstSplat(Op
.getOperand(0).getOperand(1), DemandedElts
);
3528 if (CstLow
&& CstHigh
) {
3530 std::swap(CstLow
, CstHigh
);
3531 if (CstLow
->getAPIntValue().sle(CstHigh
->getAPIntValue())) {
3532 Tmp
= CstLow
->getAPIntValue().getNumSignBits();
3533 Tmp2
= CstHigh
->getAPIntValue().getNumSignBits();
3534 return std::min(Tmp
, Tmp2
);
3538 // Fallback - just get the minimum number of sign bits of the operands.
3539 Tmp
= ComputeNumSignBits(Op
.getOperand(0), Depth
+ 1);
3541 return 1; // Early out.
3542 Tmp2
= ComputeNumSignBits(Op
.getOperand(1), Depth
+ 1);
3543 return std::min(Tmp
, Tmp2
);
3547 Tmp
= ComputeNumSignBits(Op
.getOperand(0), Depth
+ 1);
3549 return 1; // Early out.
3550 Tmp2
= ComputeNumSignBits(Op
.getOperand(1), Depth
+ 1);
3551 return std::min(Tmp
, Tmp2
);
3558 if (Op
.getResNo() != 1)
3560 // The boolean result conforms to getBooleanContents. Fall through.
3561 // If setcc returns 0/-1, all bits are sign bits.
3562 // We know that we have an integer-based boolean since these operations
3563 // are only available for integer.
3564 if (TLI
->getBooleanContents(VT
.isVector(), false) ==
3565 TargetLowering::ZeroOrNegativeOneBooleanContent
)
3569 // If setcc returns 0/-1, all bits are sign bits.
3570 if (TLI
->getBooleanContents(Op
.getOperand(0).getValueType()) ==
3571 TargetLowering::ZeroOrNegativeOneBooleanContent
)
3576 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1))) {
3577 unsigned RotAmt
= C
->getAPIntValue().urem(VTBits
);
3579 // Handle rotate right by N like a rotate left by 32-N.
3580 if (Opcode
== ISD::ROTR
)
3581 RotAmt
= (VTBits
- RotAmt
) % VTBits
;
3583 // If we aren't rotating out all of the known-in sign bits, return the
3584 // number that are left. This handles rotl(sext(x), 1) for example.
3585 Tmp
= ComputeNumSignBits(Op
.getOperand(0), Depth
+1);
3586 if (Tmp
> (RotAmt
+ 1)) return (Tmp
- RotAmt
);
3591 // Add can have at most one carry bit. Thus we know that the output
3592 // is, at worst, one more bit than the inputs.
3593 Tmp
= ComputeNumSignBits(Op
.getOperand(0), Depth
+1);
3594 if (Tmp
== 1) return 1; // Early out.
3596 // Special case decrementing a value (ADD X, -1):
3597 if (ConstantSDNode
*CRHS
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1)))
3598 if (CRHS
->isAllOnesValue()) {
3599 KnownBits Known
= computeKnownBits(Op
.getOperand(0), Depth
+1);
3601 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3603 if ((Known
.Zero
| 1).isAllOnesValue())
3606 // If we are subtracting one from a positive number, there is no carry
3607 // out of the result.
3608 if (Known
.isNonNegative())
3612 Tmp2
= ComputeNumSignBits(Op
.getOperand(1), Depth
+1);
3613 if (Tmp2
== 1) return 1;
3614 return std::min(Tmp
, Tmp2
)-1;
3617 Tmp2
= ComputeNumSignBits(Op
.getOperand(1), Depth
+1);
3618 if (Tmp2
== 1) return 1;
3621 if (ConstantSDNode
*CLHS
= isConstOrConstSplat(Op
.getOperand(0)))
3622 if (CLHS
->isNullValue()) {
3623 KnownBits Known
= computeKnownBits(Op
.getOperand(1), Depth
+1);
3624 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3626 if ((Known
.Zero
| 1).isAllOnesValue())
3629 // If the input is known to be positive (the sign bit is known clear),
3630 // the output of the NEG has the same number of sign bits as the input.
3631 if (Known
.isNonNegative())
3634 // Otherwise, we treat this like a SUB.
3637 // Sub can have at most one carry bit. Thus we know that the output
3638 // is, at worst, one more bit than the inputs.
3639 Tmp
= ComputeNumSignBits(Op
.getOperand(0), Depth
+1);
3640 if (Tmp
== 1) return 1; // Early out.
3641 return std::min(Tmp
, Tmp2
)-1;
3642 case ISD::TRUNCATE
: {
3643 // Check if the sign bits of source go down as far as the truncated value.
3644 unsigned NumSrcBits
= Op
.getOperand(0).getScalarValueSizeInBits();
3645 unsigned NumSrcSignBits
= ComputeNumSignBits(Op
.getOperand(0), Depth
+ 1);
3646 if (NumSrcSignBits
> (NumSrcBits
- VTBits
))
3647 return NumSrcSignBits
- (NumSrcBits
- VTBits
);
3650 case ISD::EXTRACT_ELEMENT
: {
3651 const int KnownSign
= ComputeNumSignBits(Op
.getOperand(0), Depth
+1);
3652 const int BitWidth
= Op
.getValueSizeInBits();
3653 const int Items
= Op
.getOperand(0).getValueSizeInBits() / BitWidth
;
3655 // Get reverse index (starting from 1), Op1 value indexes elements from
3656 // little end. Sign starts at big end.
3657 const int rIndex
= Items
- 1 - Op
.getConstantOperandVal(1);
3659 // If the sign portion ends in our element the subtraction gives correct
3660 // result. Otherwise it gives either negative or > bitwidth result
3661 return std::max(std::min(KnownSign
- rIndex
* BitWidth
, BitWidth
), 0);
3663 case ISD::INSERT_VECTOR_ELT
: {
3664 SDValue InVec
= Op
.getOperand(0);
3665 SDValue InVal
= Op
.getOperand(1);
3666 SDValue EltNo
= Op
.getOperand(2);
3668 ConstantSDNode
*CEltNo
= dyn_cast
<ConstantSDNode
>(EltNo
);
3669 if (CEltNo
&& CEltNo
->getAPIntValue().ult(NumElts
)) {
3670 // If we know the element index, split the demand between the
3671 // source vector and the inserted element.
3672 unsigned EltIdx
= CEltNo
->getZExtValue();
3674 // If we demand the inserted element then get its sign bits.
3675 Tmp
= std::numeric_limits
<unsigned>::max();
3676 if (DemandedElts
[EltIdx
]) {
3677 // TODO - handle implicit truncation of inserted elements.
3678 if (InVal
.getScalarValueSizeInBits() != VTBits
)
3680 Tmp
= ComputeNumSignBits(InVal
, Depth
+ 1);
3683 // If we demand the source vector then get its sign bits, and determine
3685 APInt VectorElts
= DemandedElts
;
3686 VectorElts
.clearBit(EltIdx
);
3688 Tmp2
= ComputeNumSignBits(InVec
, VectorElts
, Depth
+ 1);
3689 Tmp
= std::min(Tmp
, Tmp2
);
3692 // Unknown element index, so ignore DemandedElts and demand them all.
3693 Tmp
= ComputeNumSignBits(InVec
, Depth
+ 1);
3694 Tmp2
= ComputeNumSignBits(InVal
, Depth
+ 1);
3695 Tmp
= std::min(Tmp
, Tmp2
);
3697 assert(Tmp
<= VTBits
&& "Failed to determine minimum sign bits");
3700 case ISD::EXTRACT_VECTOR_ELT
: {
3701 SDValue InVec
= Op
.getOperand(0);
3702 SDValue EltNo
= Op
.getOperand(1);
3703 EVT VecVT
= InVec
.getValueType();
3704 const unsigned BitWidth
= Op
.getValueSizeInBits();
3705 const unsigned EltBitWidth
= Op
.getOperand(0).getScalarValueSizeInBits();
3706 const unsigned NumSrcElts
= VecVT
.getVectorNumElements();
3708 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3709 // anything about sign bits. But if the sizes match we can derive knowledge
3710 // about sign bits from the vector operand.
3711 if (BitWidth
!= EltBitWidth
)
3714 // If we know the element index, just demand that vector element, else for
3715 // an unknown element index, ignore DemandedElts and demand them all.
3716 APInt DemandedSrcElts
= APInt::getAllOnesValue(NumSrcElts
);
3717 ConstantSDNode
*ConstEltNo
= dyn_cast
<ConstantSDNode
>(EltNo
);
3718 if (ConstEltNo
&& ConstEltNo
->getAPIntValue().ult(NumSrcElts
))
3720 APInt::getOneBitSet(NumSrcElts
, ConstEltNo
->getZExtValue());
3722 return ComputeNumSignBits(InVec
, DemandedSrcElts
, Depth
+ 1);
3724 case ISD::EXTRACT_SUBVECTOR
: {
3725 // If we know the element index, just demand that subvector elements,
3726 // otherwise demand them all.
3727 SDValue Src
= Op
.getOperand(0);
3728 ConstantSDNode
*SubIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
3729 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
3730 if (SubIdx
&& SubIdx
->getAPIntValue().ule(NumSrcElts
- NumElts
)) {
3731 // Offset the demanded elts by the subvector index.
3732 uint64_t Idx
= SubIdx
->getZExtValue();
3733 APInt DemandedSrc
= DemandedElts
.zextOrSelf(NumSrcElts
).shl(Idx
);
3734 return ComputeNumSignBits(Src
, DemandedSrc
, Depth
+ 1);
3736 return ComputeNumSignBits(Src
, Depth
+ 1);
3738 case ISD::CONCAT_VECTORS
: {
3739 // Determine the minimum number of sign bits across all demanded
3740 // elts of the input vectors. Early out if the result is already 1.
3741 Tmp
= std::numeric_limits
<unsigned>::max();
3742 EVT SubVectorVT
= Op
.getOperand(0).getValueType();
3743 unsigned NumSubVectorElts
= SubVectorVT
.getVectorNumElements();
3744 unsigned NumSubVectors
= Op
.getNumOperands();
3745 for (unsigned i
= 0; (i
< NumSubVectors
) && (Tmp
> 1); ++i
) {
3746 APInt DemandedSub
= DemandedElts
.lshr(i
* NumSubVectorElts
);
3747 DemandedSub
= DemandedSub
.trunc(NumSubVectorElts
);
3750 Tmp2
= ComputeNumSignBits(Op
.getOperand(i
), DemandedSub
, Depth
+ 1);
3751 Tmp
= std::min(Tmp
, Tmp2
);
3753 assert(Tmp
<= VTBits
&& "Failed to determine minimum sign bits");
3756 case ISD::INSERT_SUBVECTOR
: {
3757 // If we know the element index, demand any elements from the subvector and
3758 // the remainder from the src its inserted into, otherwise demand them all.
3759 SDValue Src
= Op
.getOperand(0);
3760 SDValue Sub
= Op
.getOperand(1);
3761 auto *SubIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
3762 unsigned NumSubElts
= Sub
.getValueType().getVectorNumElements();
3763 if (SubIdx
&& SubIdx
->getAPIntValue().ule(NumElts
- NumSubElts
)) {
3764 Tmp
= std::numeric_limits
<unsigned>::max();
3765 uint64_t Idx
= SubIdx
->getZExtValue();
3766 APInt DemandedSubElts
= DemandedElts
.extractBits(NumSubElts
, Idx
);
3767 if (!!DemandedSubElts
) {
3768 Tmp
= ComputeNumSignBits(Sub
, DemandedSubElts
, Depth
+ 1);
3769 if (Tmp
== 1) return 1; // early-out
3771 APInt SubMask
= APInt::getBitsSet(NumElts
, Idx
, Idx
+ NumSubElts
);
3772 APInt DemandedSrcElts
= DemandedElts
& ~SubMask
;
3773 if (!!DemandedSrcElts
) {
3774 Tmp2
= ComputeNumSignBits(Src
, DemandedSrcElts
, Depth
+ 1);
3775 Tmp
= std::min(Tmp
, Tmp2
);
3777 assert(Tmp
<= VTBits
&& "Failed to determine minimum sign bits");
3781 // Not able to determine the index so just assume worst case.
3782 Tmp
= ComputeNumSignBits(Sub
, Depth
+ 1);
3783 if (Tmp
== 1) return 1; // early-out
3784 Tmp2
= ComputeNumSignBits(Src
, Depth
+ 1);
3785 Tmp
= std::min(Tmp
, Tmp2
);
3786 assert(Tmp
<= VTBits
&& "Failed to determine minimum sign bits");
3791 // If we are looking at the loaded value of the SDNode.
3792 if (Op
.getResNo() == 0) {
3793 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3794 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(Op
)) {
3795 unsigned ExtType
= LD
->getExtensionType();
3798 case ISD::SEXTLOAD
: // '17' bits known
3799 Tmp
= LD
->getMemoryVT().getScalarSizeInBits();
3800 return VTBits
-Tmp
+1;
3801 case ISD::ZEXTLOAD
: // '16' bits known
3802 Tmp
= LD
->getMemoryVT().getScalarSizeInBits();
3808 // Allow the target to implement this method for its nodes.
3809 if (Opcode
>= ISD::BUILTIN_OP_END
||
3810 Opcode
== ISD::INTRINSIC_WO_CHAIN
||
3811 Opcode
== ISD::INTRINSIC_W_CHAIN
||
3812 Opcode
== ISD::INTRINSIC_VOID
) {
3814 TLI
->ComputeNumSignBitsForTargetNode(Op
, DemandedElts
, *this, Depth
);
3816 FirstAnswer
= std::max(FirstAnswer
, NumBits
);
3819 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3820 // use this information.
3821 KnownBits Known
= computeKnownBits(Op
, DemandedElts
, Depth
);
3824 if (Known
.isNonNegative()) { // sign bit is 0
3826 } else if (Known
.isNegative()) { // sign bit is 1;
3833 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3834 // the number of identical bits in the top of the input value.
3836 Mask
<<= Mask
.getBitWidth()-VTBits
;
3837 // Return # leading zeros. We use 'min' here in case Val was zero before
3838 // shifting. We don't want to return '64' as for an i32 "0".
3839 return std::max(FirstAnswer
, std::min(VTBits
, Mask
.countLeadingZeros()));
3842 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op
) const {
3843 if ((Op
.getOpcode() != ISD::ADD
&& Op
.getOpcode() != ISD::OR
) ||
3844 !isa
<ConstantSDNode
>(Op
.getOperand(1)))
3847 if (Op
.getOpcode() == ISD::OR
&&
3848 !MaskedValueIsZero(Op
.getOperand(0), Op
.getConstantOperandAPInt(1)))
3854 bool SelectionDAG::isKnownNeverNaN(SDValue Op
, bool SNaN
, unsigned Depth
) const {
3855 // If we're told that NaNs won't happen, assume they won't.
3856 if (getTarget().Options
.NoNaNsFPMath
|| Op
->getFlags().hasNoNaNs())
3860 return false; // Limit search depth.
3862 // TODO: Handle vectors.
3863 // If the value is a constant, we can obviously see if it is a NaN or not.
3864 if (const ConstantFPSDNode
*C
= dyn_cast
<ConstantFPSDNode
>(Op
)) {
3865 return !C
->getValueAPF().isNaN() ||
3866 (SNaN
&& !C
->getValueAPF().isSignaling());
3869 unsigned Opcode
= Op
.getOpcode();
3880 // TODO: Need isKnownNeverInfinity
3883 case ISD::FCANONICALIZE
:
3891 case ISD::FNEARBYINT
: {
3894 return isKnownNeverNaN(Op
.getOperand(0), SNaN
, Depth
+ 1);
3898 case ISD::FCOPYSIGN
: {
3899 return isKnownNeverNaN(Op
.getOperand(0), SNaN
, Depth
+ 1);
3902 return isKnownNeverNaN(Op
.getOperand(1), SNaN
, Depth
+ 1) &&
3903 isKnownNeverNaN(Op
.getOperand(2), SNaN
, Depth
+ 1);
3904 case ISD::FP_EXTEND
:
3905 case ISD::FP_ROUND
: {
3908 return isKnownNeverNaN(Op
.getOperand(0), SNaN
, Depth
+ 1);
3910 case ISD::SINT_TO_FP
:
3911 case ISD::UINT_TO_FP
:
3917 return isKnownNeverNaN(Op
.getOperand(0), SNaN
, Depth
+ 1) &&
3918 isKnownNeverNaN(Op
.getOperand(1), SNaN
, Depth
+ 1) &&
3919 isKnownNeverNaN(Op
.getOperand(2), SNaN
, Depth
+ 1);
3921 case ISD::FSQRT
: // Need is known positive
3929 // TODO: Refine on operand
3933 case ISD::FMAXNUM
: {
3934 // Only one needs to be known not-nan, since it will be returned if the
3935 // other ends up being one.
3936 return isKnownNeverNaN(Op
.getOperand(0), SNaN
, Depth
+ 1) ||
3937 isKnownNeverNaN(Op
.getOperand(1), SNaN
, Depth
+ 1);
3939 case ISD::FMINNUM_IEEE
:
3940 case ISD::FMAXNUM_IEEE
: {
3943 // This can return a NaN if either operand is an sNaN, or if both operands
3945 return (isKnownNeverNaN(Op
.getOperand(0), false, Depth
+ 1) &&
3946 isKnownNeverSNaN(Op
.getOperand(1), Depth
+ 1)) ||
3947 (isKnownNeverNaN(Op
.getOperand(1), false, Depth
+ 1) &&
3948 isKnownNeverSNaN(Op
.getOperand(0), Depth
+ 1));
3951 case ISD::FMAXIMUM
: {
3952 // TODO: Does this quiet or return the origina NaN as-is?
3953 return isKnownNeverNaN(Op
.getOperand(0), SNaN
, Depth
+ 1) &&
3954 isKnownNeverNaN(Op
.getOperand(1), SNaN
, Depth
+ 1);
3956 case ISD::EXTRACT_VECTOR_ELT
: {
3957 return isKnownNeverNaN(Op
.getOperand(0), SNaN
, Depth
+ 1);
3960 if (Opcode
>= ISD::BUILTIN_OP_END
||
3961 Opcode
== ISD::INTRINSIC_WO_CHAIN
||
3962 Opcode
== ISD::INTRINSIC_W_CHAIN
||
3963 Opcode
== ISD::INTRINSIC_VOID
) {
3964 return TLI
->isKnownNeverNaNForTargetNode(Op
, *this, SNaN
, Depth
);
3971 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op
) const {
3972 assert(Op
.getValueType().isFloatingPoint() &&
3973 "Floating point type expected");
3975 // If the value is a constant, we can obviously see if it is a zero or not.
3976 // TODO: Add BuildVector support.
3977 if (const ConstantFPSDNode
*C
= dyn_cast
<ConstantFPSDNode
>(Op
))
3978 return !C
->isZero();
3982 bool SelectionDAG::isKnownNeverZero(SDValue Op
) const {
3983 assert(!Op
.getValueType().isFloatingPoint() &&
3984 "Floating point types unsupported - use isKnownNeverZeroFloat");
3986 // If the value is a constant, we can obviously see if it is a zero or not.
3987 if (ISD::matchUnaryPredicate(
3988 Op
, [](ConstantSDNode
*C
) { return !C
->isNullValue(); }))
3991 // TODO: Recognize more cases here.
3992 switch (Op
.getOpcode()) {
3995 if (isKnownNeverZero(Op
.getOperand(1)) ||
3996 isKnownNeverZero(Op
.getOperand(0)))
4004 bool SelectionDAG::isEqualTo(SDValue A
, SDValue B
) const {
4005 // Check the obvious case.
4006 if (A
== B
) return true;
4008 // For for negative and positive zero.
4009 if (const ConstantFPSDNode
*CA
= dyn_cast
<ConstantFPSDNode
>(A
))
4010 if (const ConstantFPSDNode
*CB
= dyn_cast
<ConstantFPSDNode
>(B
))
4011 if (CA
->isZero() && CB
->isZero()) return true;
4013 // Otherwise they may not be equal.
4017 // FIXME: unify with llvm::haveNoCommonBitsSet.
4018 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4019 bool SelectionDAG::haveNoCommonBitsSet(SDValue A
, SDValue B
) const {
4020 assert(A
.getValueType() == B
.getValueType() &&
4021 "Values must have the same type");
4022 return (computeKnownBits(A
).Zero
| computeKnownBits(B
).Zero
).isAllOnesValue();
4025 static SDValue
FoldBUILD_VECTOR(const SDLoc
&DL
, EVT VT
,
4026 ArrayRef
<SDValue
> Ops
,
4027 SelectionDAG
&DAG
) {
4028 int NumOps
= Ops
.size();
4029 assert(NumOps
!= 0 && "Can't build an empty vector!");
4030 assert(VT
.getVectorNumElements() == (unsigned)NumOps
&&
4031 "Incorrect element count in BUILD_VECTOR!");
4033 // BUILD_VECTOR of UNDEFs is UNDEF.
4034 if (llvm::all_of(Ops
, [](SDValue Op
) { return Op
.isUndef(); }))
4035 return DAG
.getUNDEF(VT
);
4037 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4038 SDValue IdentitySrc
;
4039 bool IsIdentity
= true;
4040 for (int i
= 0; i
!= NumOps
; ++i
) {
4041 if (Ops
[i
].getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
4042 Ops
[i
].getOperand(0).getValueType() != VT
||
4043 (IdentitySrc
&& Ops
[i
].getOperand(0) != IdentitySrc
) ||
4044 !isa
<ConstantSDNode
>(Ops
[i
].getOperand(1)) ||
4045 cast
<ConstantSDNode
>(Ops
[i
].getOperand(1))->getAPIntValue() != i
) {
4049 IdentitySrc
= Ops
[i
].getOperand(0);
4057 static SDValue
FoldCONCAT_VECTORS(const SDLoc
&DL
, EVT VT
,
4058 ArrayRef
<SDValue
> Ops
,
4059 SelectionDAG
&DAG
) {
4060 assert(!Ops
.empty() && "Can't concatenate an empty list of vectors!");
4061 assert(llvm::all_of(Ops
,
4063 return Ops
[0].getValueType() == Op
.getValueType();
4065 "Concatenation of vectors with inconsistent value types!");
4066 assert((Ops
.size() * Ops
[0].getValueType().getVectorNumElements()) ==
4067 VT
.getVectorNumElements() &&
4068 "Incorrect element count in vector concatenation!");
4070 if (Ops
.size() == 1)
4073 // Concat of UNDEFs is UNDEF.
4074 if (llvm::all_of(Ops
, [](SDValue Op
) { return Op
.isUndef(); }))
4075 return DAG
.getUNDEF(VT
);
4077 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4078 // simplified to one big BUILD_VECTOR.
4079 // FIXME: Add support for SCALAR_TO_VECTOR as well.
4080 EVT SVT
= VT
.getScalarType();
4081 SmallVector
<SDValue
, 16> Elts
;
4082 for (SDValue Op
: Ops
) {
4083 EVT OpVT
= Op
.getValueType();
4085 Elts
.append(OpVT
.getVectorNumElements(), DAG
.getUNDEF(SVT
));
4086 else if (Op
.getOpcode() == ISD::BUILD_VECTOR
)
4087 Elts
.append(Op
->op_begin(), Op
->op_end());
4092 // BUILD_VECTOR requires all inputs to be of the same type, find the
4093 // maximum type and extend them all.
4094 for (SDValue Op
: Elts
)
4095 SVT
= (SVT
.bitsLT(Op
.getValueType()) ? Op
.getValueType() : SVT
);
4097 if (SVT
.bitsGT(VT
.getScalarType()))
4098 for (SDValue
&Op
: Elts
)
4099 Op
= DAG
.getTargetLoweringInfo().isZExtFree(Op
.getValueType(), SVT
)
4100 ? DAG
.getZExtOrTrunc(Op
, DL
, SVT
)
4101 : DAG
.getSExtOrTrunc(Op
, DL
, SVT
);
4103 SDValue V
= DAG
.getBuildVector(VT
, DL
, Elts
);
4104 NewSDValueDbgMsg(V
, "New node fold concat vectors: ", &DAG
);
4108 /// Gets or creates the specified node.
4109 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, EVT VT
) {
4110 FoldingSetNodeID ID
;
4111 AddNodeIDNode(ID
, Opcode
, getVTList(VT
), None
);
4113 if (SDNode
*E
= FindNodeOrInsertPos(ID
, DL
, IP
))
4114 return SDValue(E
, 0);
4116 auto *N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(),
4118 CSEMap
.InsertNode(N
, IP
);
4121 SDValue V
= SDValue(N
, 0);
4122 NewSDValueDbgMsg(V
, "Creating new node: ", this);
4126 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, EVT VT
,
4127 SDValue Operand
, const SDNodeFlags Flags
) {
4128 // Constant fold unary operations with an integer constant operand. Even
4129 // opaque constant will be folded, because the folding of unary operations
4130 // doesn't create new constants with different values. Nevertheless, the
4131 // opaque flag is preserved during folding to prevent future folding with
4133 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Operand
)) {
4134 const APInt
&Val
= C
->getAPIntValue();
4137 case ISD::SIGN_EXTEND
:
4138 return getConstant(Val
.sextOrTrunc(VT
.getSizeInBits()), DL
, VT
,
4139 C
->isTargetOpcode(), C
->isOpaque());
4144 case ISD::ANY_EXTEND
:
4145 case ISD::ZERO_EXTEND
:
4146 return getConstant(Val
.zextOrTrunc(VT
.getSizeInBits()), DL
, VT
,
4147 C
->isTargetOpcode(), C
->isOpaque());
4148 case ISD::UINT_TO_FP
:
4149 case ISD::SINT_TO_FP
: {
4150 APFloat
apf(EVTToAPFloatSemantics(VT
),
4151 APInt::getNullValue(VT
.getSizeInBits()));
4152 (void)apf
.convertFromAPInt(Val
,
4153 Opcode
==ISD::SINT_TO_FP
,
4154 APFloat::rmNearestTiesToEven
);
4155 return getConstantFP(apf
, DL
, VT
);
4158 if (VT
== MVT::f16
&& C
->getValueType(0) == MVT::i16
)
4159 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val
), DL
, VT
);
4160 if (VT
== MVT::f32
&& C
->getValueType(0) == MVT::i32
)
4161 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val
), DL
, VT
);
4162 if (VT
== MVT::f64
&& C
->getValueType(0) == MVT::i64
)
4163 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val
), DL
, VT
);
4164 if (VT
== MVT::f128
&& C
->getValueType(0) == MVT::i128
)
4165 return getConstantFP(APFloat(APFloat::IEEEquad(), Val
), DL
, VT
);
4168 return getConstant(Val
.abs(), DL
, VT
, C
->isTargetOpcode(),
4170 case ISD::BITREVERSE
:
4171 return getConstant(Val
.reverseBits(), DL
, VT
, C
->isTargetOpcode(),
4174 return getConstant(Val
.byteSwap(), DL
, VT
, C
->isTargetOpcode(),
4177 return getConstant(Val
.countPopulation(), DL
, VT
, C
->isTargetOpcode(),
4180 case ISD::CTLZ_ZERO_UNDEF
:
4181 return getConstant(Val
.countLeadingZeros(), DL
, VT
, C
->isTargetOpcode(),
4184 case ISD::CTTZ_ZERO_UNDEF
:
4185 return getConstant(Val
.countTrailingZeros(), DL
, VT
, C
->isTargetOpcode(),
4187 case ISD::FP16_TO_FP
: {
4189 APFloat
FPV(APFloat::IEEEhalf(),
4190 (Val
.getBitWidth() == 16) ? Val
: Val
.trunc(16));
4192 // This can return overflow, underflow, or inexact; we don't care.
4193 // FIXME need to be more flexible about rounding mode.
4194 (void)FPV
.convert(EVTToAPFloatSemantics(VT
),
4195 APFloat::rmNearestTiesToEven
, &Ignored
);
4196 return getConstantFP(FPV
, DL
, VT
);
4201 // Constant fold unary operations with a floating point constant operand.
4202 if (ConstantFPSDNode
*C
= dyn_cast
<ConstantFPSDNode
>(Operand
)) {
4203 APFloat V
= C
->getValueAPF(); // make copy
4207 return getConstantFP(V
, DL
, VT
);
4210 return getConstantFP(V
, DL
, VT
);
4212 APFloat::opStatus fs
= V
.roundToIntegral(APFloat::rmTowardPositive
);
4213 if (fs
== APFloat::opOK
|| fs
== APFloat::opInexact
)
4214 return getConstantFP(V
, DL
, VT
);
4218 APFloat::opStatus fs
= V
.roundToIntegral(APFloat::rmTowardZero
);
4219 if (fs
== APFloat::opOK
|| fs
== APFloat::opInexact
)
4220 return getConstantFP(V
, DL
, VT
);
4224 APFloat::opStatus fs
= V
.roundToIntegral(APFloat::rmTowardNegative
);
4225 if (fs
== APFloat::opOK
|| fs
== APFloat::opInexact
)
4226 return getConstantFP(V
, DL
, VT
);
4229 case ISD::FP_EXTEND
: {
4231 // This can return overflow, underflow, or inexact; we don't care.
4232 // FIXME need to be more flexible about rounding mode.
4233 (void)V
.convert(EVTToAPFloatSemantics(VT
),
4234 APFloat::rmNearestTiesToEven
, &ignored
);
4235 return getConstantFP(V
, DL
, VT
);
4237 case ISD::FP_TO_SINT
:
4238 case ISD::FP_TO_UINT
: {
4240 APSInt
IntVal(VT
.getSizeInBits(), Opcode
== ISD::FP_TO_UINT
);
4241 // FIXME need to be more flexible about rounding mode.
4242 APFloat::opStatus s
=
4243 V
.convertToInteger(IntVal
, APFloat::rmTowardZero
, &ignored
);
4244 if (s
== APFloat::opInvalidOp
) // inexact is OK, in fact usual
4246 return getConstant(IntVal
, DL
, VT
);
4249 if (VT
== MVT::i16
&& C
->getValueType(0) == MVT::f16
)
4250 return getConstant((uint16_t)V
.bitcastToAPInt().getZExtValue(), DL
, VT
);
4251 else if (VT
== MVT::i32
&& C
->getValueType(0) == MVT::f32
)
4252 return getConstant((uint32_t)V
.bitcastToAPInt().getZExtValue(), DL
, VT
);
4253 else if (VT
== MVT::i64
&& C
->getValueType(0) == MVT::f64
)
4254 return getConstant(V
.bitcastToAPInt().getZExtValue(), DL
, VT
);
4256 case ISD::FP_TO_FP16
: {
4258 // This can return overflow, underflow, or inexact; we don't care.
4259 // FIXME need to be more flexible about rounding mode.
4260 (void)V
.convert(APFloat::IEEEhalf(),
4261 APFloat::rmNearestTiesToEven
, &Ignored
);
4262 return getConstant(V
.bitcastToAPInt(), DL
, VT
);
4267 // Constant fold unary operations with a vector integer or float operand.
4268 if (BuildVectorSDNode
*BV
= dyn_cast
<BuildVectorSDNode
>(Operand
)) {
4269 if (BV
->isConstant()) {
4272 // FIXME: Entirely reasonable to perform folding of other unary
4273 // operations here as the need arises.
4280 case ISD::FP_EXTEND
:
4281 case ISD::FP_TO_SINT
:
4282 case ISD::FP_TO_UINT
:
4284 case ISD::ANY_EXTEND
:
4285 case ISD::ZERO_EXTEND
:
4286 case ISD::SIGN_EXTEND
:
4287 case ISD::UINT_TO_FP
:
4288 case ISD::SINT_TO_FP
:
4290 case ISD::BITREVERSE
:
4293 case ISD::CTLZ_ZERO_UNDEF
:
4295 case ISD::CTTZ_ZERO_UNDEF
:
4297 SDValue Ops
= { Operand
};
4298 if (SDValue Fold
= FoldConstantVectorArithmetic(Opcode
, DL
, VT
, Ops
))
4305 unsigned OpOpcode
= Operand
.getNode()->getOpcode();
4307 case ISD::TokenFactor
:
4308 case ISD::MERGE_VALUES
:
4309 case ISD::CONCAT_VECTORS
:
4310 return Operand
; // Factor, merge or concat of one node? No need.
4311 case ISD::BUILD_VECTOR
: {
4312 // Attempt to simplify BUILD_VECTOR.
4313 SDValue Ops
[] = {Operand
};
4314 if (SDValue V
= FoldBUILD_VECTOR(DL
, VT
, Ops
, *this))
4318 case ISD::FP_ROUND
: llvm_unreachable("Invalid method to make FP_ROUND node");
4319 case ISD::FP_EXTEND
:
4320 assert(VT
.isFloatingPoint() &&
4321 Operand
.getValueType().isFloatingPoint() && "Invalid FP cast!");
4322 if (Operand
.getValueType() == VT
) return Operand
; // noop conversion.
4323 assert((!VT
.isVector() ||
4324 VT
.getVectorNumElements() ==
4325 Operand
.getValueType().getVectorNumElements()) &&
4326 "Vector element count mismatch!");
4327 assert(Operand
.getValueType().bitsLT(VT
) &&
4328 "Invalid fpext node, dst < src!");
4329 if (Operand
.isUndef())
4330 return getUNDEF(VT
);
4332 case ISD::SIGN_EXTEND
:
4333 assert(VT
.isInteger() && Operand
.getValueType().isInteger() &&
4334 "Invalid SIGN_EXTEND!");
4335 assert(VT
.isVector() == Operand
.getValueType().isVector() &&
4336 "SIGN_EXTEND result type type should be vector iff the operand "
4338 if (Operand
.getValueType() == VT
) return Operand
; // noop extension
4339 assert((!VT
.isVector() ||
4340 VT
.getVectorNumElements() ==
4341 Operand
.getValueType().getVectorNumElements()) &&
4342 "Vector element count mismatch!");
4343 assert(Operand
.getValueType().bitsLT(VT
) &&
4344 "Invalid sext node, dst < src!");
4345 if (OpOpcode
== ISD::SIGN_EXTEND
|| OpOpcode
== ISD::ZERO_EXTEND
)
4346 return getNode(OpOpcode
, DL
, VT
, Operand
.getOperand(0));
4347 else if (OpOpcode
== ISD::UNDEF
)
4348 // sext(undef) = 0, because the top bits will all be the same.
4349 return getConstant(0, DL
, VT
);
4351 case ISD::ZERO_EXTEND
:
4352 assert(VT
.isInteger() && Operand
.getValueType().isInteger() &&
4353 "Invalid ZERO_EXTEND!");
4354 assert(VT
.isVector() == Operand
.getValueType().isVector() &&
4355 "ZERO_EXTEND result type type should be vector iff the operand "
4357 if (Operand
.getValueType() == VT
) return Operand
; // noop extension
4358 assert((!VT
.isVector() ||
4359 VT
.getVectorNumElements() ==
4360 Operand
.getValueType().getVectorNumElements()) &&
4361 "Vector element count mismatch!");
4362 assert(Operand
.getValueType().bitsLT(VT
) &&
4363 "Invalid zext node, dst < src!");
4364 if (OpOpcode
== ISD::ZERO_EXTEND
) // (zext (zext x)) -> (zext x)
4365 return getNode(ISD::ZERO_EXTEND
, DL
, VT
, Operand
.getOperand(0));
4366 else if (OpOpcode
== ISD::UNDEF
)
4367 // zext(undef) = 0, because the top bits will be zero.
4368 return getConstant(0, DL
, VT
);
4370 case ISD::ANY_EXTEND
:
4371 assert(VT
.isInteger() && Operand
.getValueType().isInteger() &&
4372 "Invalid ANY_EXTEND!");
4373 assert(VT
.isVector() == Operand
.getValueType().isVector() &&
4374 "ANY_EXTEND result type type should be vector iff the operand "
4376 if (Operand
.getValueType() == VT
) return Operand
; // noop extension
4377 assert((!VT
.isVector() ||
4378 VT
.getVectorNumElements() ==
4379 Operand
.getValueType().getVectorNumElements()) &&
4380 "Vector element count mismatch!");
4381 assert(Operand
.getValueType().bitsLT(VT
) &&
4382 "Invalid anyext node, dst < src!");
4384 if (OpOpcode
== ISD::ZERO_EXTEND
|| OpOpcode
== ISD::SIGN_EXTEND
||
4385 OpOpcode
== ISD::ANY_EXTEND
)
4386 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
4387 return getNode(OpOpcode
, DL
, VT
, Operand
.getOperand(0));
4388 else if (OpOpcode
== ISD::UNDEF
)
4389 return getUNDEF(VT
);
4391 // (ext (trunc x)) -> x
4392 if (OpOpcode
== ISD::TRUNCATE
) {
4393 SDValue OpOp
= Operand
.getOperand(0);
4394 if (OpOp
.getValueType() == VT
) {
4395 transferDbgValues(Operand
, OpOp
);
4401 assert(VT
.isInteger() && Operand
.getValueType().isInteger() &&
4402 "Invalid TRUNCATE!");
4403 assert(VT
.isVector() == Operand
.getValueType().isVector() &&
4404 "TRUNCATE result type type should be vector iff the operand "
4406 if (Operand
.getValueType() == VT
) return Operand
; // noop truncate
4407 assert((!VT
.isVector() ||
4408 VT
.getVectorNumElements() ==
4409 Operand
.getValueType().getVectorNumElements()) &&
4410 "Vector element count mismatch!");
4411 assert(Operand
.getValueType().bitsGT(VT
) &&
4412 "Invalid truncate node, src < dst!");
4413 if (OpOpcode
== ISD::TRUNCATE
)
4414 return getNode(ISD::TRUNCATE
, DL
, VT
, Operand
.getOperand(0));
4415 if (OpOpcode
== ISD::ZERO_EXTEND
|| OpOpcode
== ISD::SIGN_EXTEND
||
4416 OpOpcode
== ISD::ANY_EXTEND
) {
4417 // If the source is smaller than the dest, we still need an extend.
4418 if (Operand
.getOperand(0).getValueType().getScalarType()
4419 .bitsLT(VT
.getScalarType()))
4420 return getNode(OpOpcode
, DL
, VT
, Operand
.getOperand(0));
4421 if (Operand
.getOperand(0).getValueType().bitsGT(VT
))
4422 return getNode(ISD::TRUNCATE
, DL
, VT
, Operand
.getOperand(0));
4423 return Operand
.getOperand(0);
4425 if (OpOpcode
== ISD::UNDEF
)
4426 return getUNDEF(VT
);
4428 case ISD::ANY_EXTEND_VECTOR_INREG
:
4429 case ISD::ZERO_EXTEND_VECTOR_INREG
:
4430 case ISD::SIGN_EXTEND_VECTOR_INREG
:
4431 assert(VT
.isVector() && "This DAG node is restricted to vector types.");
4432 assert(Operand
.getValueType().bitsLE(VT
) &&
4433 "The input must be the same size or smaller than the result.");
4434 assert(VT
.getVectorNumElements() <
4435 Operand
.getValueType().getVectorNumElements() &&
4436 "The destination vector type must have fewer lanes than the input.");
4439 assert(VT
.isInteger() && VT
== Operand
.getValueType() &&
4441 if (OpOpcode
== ISD::UNDEF
)
4442 return getUNDEF(VT
);
4445 assert(VT
.isInteger() && VT
== Operand
.getValueType() &&
4447 assert((VT
.getScalarSizeInBits() % 16 == 0) &&
4448 "BSWAP types must be a multiple of 16 bits!");
4449 if (OpOpcode
== ISD::UNDEF
)
4450 return getUNDEF(VT
);
4452 case ISD::BITREVERSE
:
4453 assert(VT
.isInteger() && VT
== Operand
.getValueType() &&
4454 "Invalid BITREVERSE!");
4455 if (OpOpcode
== ISD::UNDEF
)
4456 return getUNDEF(VT
);
4459 // Basic sanity checking.
4460 assert(VT
.getSizeInBits() == Operand
.getValueSizeInBits() &&
4461 "Cannot BITCAST between types of different sizes!");
4462 if (VT
== Operand
.getValueType()) return Operand
; // noop conversion.
4463 if (OpOpcode
== ISD::BITCAST
) // bitconv(bitconv(x)) -> bitconv(x)
4464 return getNode(ISD::BITCAST
, DL
, VT
, Operand
.getOperand(0));
4465 if (OpOpcode
== ISD::UNDEF
)
4466 return getUNDEF(VT
);
4468 case ISD::SCALAR_TO_VECTOR
:
4469 assert(VT
.isVector() && !Operand
.getValueType().isVector() &&
4470 (VT
.getVectorElementType() == Operand
.getValueType() ||
4471 (VT
.getVectorElementType().isInteger() &&
4472 Operand
.getValueType().isInteger() &&
4473 VT
.getVectorElementType().bitsLE(Operand
.getValueType()))) &&
4474 "Illegal SCALAR_TO_VECTOR node!");
4475 if (OpOpcode
== ISD::UNDEF
)
4476 return getUNDEF(VT
);
4477 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4478 if (OpOpcode
== ISD::EXTRACT_VECTOR_ELT
&&
4479 isa
<ConstantSDNode
>(Operand
.getOperand(1)) &&
4480 Operand
.getConstantOperandVal(1) == 0 &&
4481 Operand
.getOperand(0).getValueType() == VT
)
4482 return Operand
.getOperand(0);
4485 // Negation of an unknown bag of bits is still completely undefined.
4486 if (OpOpcode
== ISD::UNDEF
)
4487 return getUNDEF(VT
);
4489 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4490 if ((getTarget().Options
.UnsafeFPMath
|| Flags
.hasNoSignedZeros()) &&
4491 OpOpcode
== ISD::FSUB
)
4492 return getNode(ISD::FSUB
, DL
, VT
, Operand
.getOperand(1),
4493 Operand
.getOperand(0), Flags
);
4494 if (OpOpcode
== ISD::FNEG
) // --X -> X
4495 return Operand
.getOperand(0);
4498 if (OpOpcode
== ISD::FNEG
) // abs(-X) -> abs(X)
4499 return getNode(ISD::FABS
, DL
, VT
, Operand
.getOperand(0));
4504 SDVTList VTs
= getVTList(VT
);
4505 SDValue Ops
[] = {Operand
};
4506 if (VT
!= MVT::Glue
) { // Don't CSE flag producing nodes
4507 FoldingSetNodeID ID
;
4508 AddNodeIDNode(ID
, Opcode
, VTs
, Ops
);
4510 if (SDNode
*E
= FindNodeOrInsertPos(ID
, DL
, IP
)) {
4511 E
->intersectFlagsWith(Flags
);
4512 return SDValue(E
, 0);
4515 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
4517 createOperands(N
, Ops
);
4518 CSEMap
.InsertNode(N
, IP
);
4520 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
4521 createOperands(N
, Ops
);
4525 SDValue V
= SDValue(N
, 0);
4526 NewSDValueDbgMsg(V
, "Creating new node: ", this);
4530 static std::pair
<APInt
, bool> FoldValue(unsigned Opcode
, const APInt
&C1
,
4533 case ISD::ADD
: return std::make_pair(C1
+ C2
, true);
4534 case ISD::SUB
: return std::make_pair(C1
- C2
, true);
4535 case ISD::MUL
: return std::make_pair(C1
* C2
, true);
4536 case ISD::AND
: return std::make_pair(C1
& C2
, true);
4537 case ISD::OR
: return std::make_pair(C1
| C2
, true);
4538 case ISD::XOR
: return std::make_pair(C1
^ C2
, true);
4539 case ISD::SHL
: return std::make_pair(C1
<< C2
, true);
4540 case ISD::SRL
: return std::make_pair(C1
.lshr(C2
), true);
4541 case ISD::SRA
: return std::make_pair(C1
.ashr(C2
), true);
4542 case ISD::ROTL
: return std::make_pair(C1
.rotl(C2
), true);
4543 case ISD::ROTR
: return std::make_pair(C1
.rotr(C2
), true);
4544 case ISD::SMIN
: return std::make_pair(C1
.sle(C2
) ? C1
: C2
, true);
4545 case ISD::SMAX
: return std::make_pair(C1
.sge(C2
) ? C1
: C2
, true);
4546 case ISD::UMIN
: return std::make_pair(C1
.ule(C2
) ? C1
: C2
, true);
4547 case ISD::UMAX
: return std::make_pair(C1
.uge(C2
) ? C1
: C2
, true);
4548 case ISD::SADDSAT
: return std::make_pair(C1
.sadd_sat(C2
), true);
4549 case ISD::UADDSAT
: return std::make_pair(C1
.uadd_sat(C2
), true);
4550 case ISD::SSUBSAT
: return std::make_pair(C1
.ssub_sat(C2
), true);
4551 case ISD::USUBSAT
: return std::make_pair(C1
.usub_sat(C2
), true);
4553 if (!C2
.getBoolValue())
4555 return std::make_pair(C1
.udiv(C2
), true);
4557 if (!C2
.getBoolValue())
4559 return std::make_pair(C1
.urem(C2
), true);
4561 if (!C2
.getBoolValue())
4563 return std::make_pair(C1
.sdiv(C2
), true);
4565 if (!C2
.getBoolValue())
4567 return std::make_pair(C1
.srem(C2
), true);
4569 return std::make_pair(APInt(1, 0), false);
4572 SDValue
SelectionDAG::FoldConstantArithmetic(unsigned Opcode
, const SDLoc
&DL
,
4573 EVT VT
, const ConstantSDNode
*C1
,
4574 const ConstantSDNode
*C2
) {
4575 if (C1
->isOpaque() || C2
->isOpaque())
4578 std::pair
<APInt
, bool> Folded
= FoldValue(Opcode
, C1
->getAPIntValue(),
4579 C2
->getAPIntValue());
4582 return getConstant(Folded
.first
, DL
, VT
);
4585 SDValue
SelectionDAG::FoldSymbolOffset(unsigned Opcode
, EVT VT
,
4586 const GlobalAddressSDNode
*GA
,
4588 if (GA
->getOpcode() != ISD::GlobalAddress
)
4590 if (!TLI
->isOffsetFoldingLegal(GA
))
4592 auto *C2
= dyn_cast
<ConstantSDNode
>(N2
);
4595 int64_t Offset
= C2
->getSExtValue();
4597 case ISD::ADD
: break;
4598 case ISD::SUB
: Offset
= -uint64_t(Offset
); break;
4599 default: return SDValue();
4601 return getGlobalAddress(GA
->getGlobal(), SDLoc(C2
), VT
,
4602 GA
->getOffset() + uint64_t(Offset
));
4605 bool SelectionDAG::isUndef(unsigned Opcode
, ArrayRef
<SDValue
> Ops
) {
4611 // If a divisor is zero/undef or any element of a divisor vector is
4612 // zero/undef, the whole op is undef.
4613 assert(Ops
.size() == 2 && "Div/rem should have 2 operands");
4614 SDValue Divisor
= Ops
[1];
4615 if (Divisor
.isUndef() || isNullConstant(Divisor
))
4618 return ISD::isBuildVectorOfConstantSDNodes(Divisor
.getNode()) &&
4619 llvm::any_of(Divisor
->op_values(),
4620 [](SDValue V
) { return V
.isUndef() ||
4621 isNullConstant(V
); });
4622 // TODO: Handle signed overflow.
4624 // TODO: Handle oversized shifts.
4630 SDValue
SelectionDAG::FoldConstantArithmetic(unsigned Opcode
, const SDLoc
&DL
,
4631 EVT VT
, SDNode
*N1
, SDNode
*N2
) {
4632 // If the opcode is a target-specific ISD node, there's nothing we can
4633 // do here and the operand rules may not line up with the below, so
4635 if (Opcode
>= ISD::BUILTIN_OP_END
)
4638 if (isUndef(Opcode
, {SDValue(N1
, 0), SDValue(N2
, 0)}))
4639 return getUNDEF(VT
);
4641 // Handle the case of two scalars.
4642 if (auto *C1
= dyn_cast
<ConstantSDNode
>(N1
)) {
4643 if (auto *C2
= dyn_cast
<ConstantSDNode
>(N2
)) {
4644 SDValue Folded
= FoldConstantArithmetic(Opcode
, DL
, VT
, C1
, C2
);
4645 assert((!Folded
|| !VT
.isVector()) &&
4646 "Can't fold vectors ops with scalar operands");
4651 // fold (add Sym, c) -> Sym+c
4652 if (GlobalAddressSDNode
*GA
= dyn_cast
<GlobalAddressSDNode
>(N1
))
4653 return FoldSymbolOffset(Opcode
, VT
, GA
, N2
);
4654 if (TLI
->isCommutativeBinOp(Opcode
))
4655 if (GlobalAddressSDNode
*GA
= dyn_cast
<GlobalAddressSDNode
>(N2
))
4656 return FoldSymbolOffset(Opcode
, VT
, GA
, N1
);
4658 // For vectors, extract each constant element and fold them individually.
4659 // Either input may be an undef value.
4660 auto *BV1
= dyn_cast
<BuildVectorSDNode
>(N1
);
4661 if (!BV1
&& !N1
->isUndef())
4663 auto *BV2
= dyn_cast
<BuildVectorSDNode
>(N2
);
4664 if (!BV2
&& !N2
->isUndef())
4666 // If both operands are undef, that's handled the same way as scalars.
4670 assert((!BV1
|| !BV2
|| BV1
->getNumOperands() == BV2
->getNumOperands()) &&
4671 "Vector binop with different number of elements in operands?");
4673 EVT SVT
= VT
.getScalarType();
4675 if (NewNodesMustHaveLegalTypes
&& LegalSVT
.isInteger()) {
4676 LegalSVT
= TLI
->getTypeToTransformTo(*getContext(), LegalSVT
);
4677 if (LegalSVT
.bitsLT(SVT
))
4680 SmallVector
<SDValue
, 4> Outputs
;
4681 unsigned NumOps
= BV1
? BV1
->getNumOperands() : BV2
->getNumOperands();
4682 for (unsigned I
= 0; I
!= NumOps
; ++I
) {
4683 SDValue V1
= BV1
? BV1
->getOperand(I
) : getUNDEF(SVT
);
4684 SDValue V2
= BV2
? BV2
->getOperand(I
) : getUNDEF(SVT
);
4685 if (SVT
.isInteger()) {
4686 if (V1
->getValueType(0).bitsGT(SVT
))
4687 V1
= getNode(ISD::TRUNCATE
, DL
, SVT
, V1
);
4688 if (V2
->getValueType(0).bitsGT(SVT
))
4689 V2
= getNode(ISD::TRUNCATE
, DL
, SVT
, V2
);
4692 if (V1
->getValueType(0) != SVT
|| V2
->getValueType(0) != SVT
)
4695 // Fold one vector element.
4696 SDValue ScalarResult
= getNode(Opcode
, DL
, SVT
, V1
, V2
);
4697 if (LegalSVT
!= SVT
)
4698 ScalarResult
= getNode(ISD::SIGN_EXTEND
, DL
, LegalSVT
, ScalarResult
);
4700 // Scalar folding only succeeded if the result is a constant or UNDEF.
4701 if (!ScalarResult
.isUndef() && ScalarResult
.getOpcode() != ISD::Constant
&&
4702 ScalarResult
.getOpcode() != ISD::ConstantFP
)
4704 Outputs
.push_back(ScalarResult
);
4707 assert(VT
.getVectorNumElements() == Outputs
.size() &&
4708 "Vector size mismatch!");
4710 // We may have a vector type but a scalar result. Create a splat.
4711 Outputs
.resize(VT
.getVectorNumElements(), Outputs
.back());
4713 // Build a big vector out of the scalar elements we generated.
4714 return getBuildVector(VT
, SDLoc(), Outputs
);
4717 // TODO: Merge with FoldConstantArithmetic
4718 SDValue
SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode
,
4719 const SDLoc
&DL
, EVT VT
,
4720 ArrayRef
<SDValue
> Ops
,
4721 const SDNodeFlags Flags
) {
4722 // If the opcode is a target-specific ISD node, there's nothing we can
4723 // do here and the operand rules may not line up with the below, so
4725 if (Opcode
>= ISD::BUILTIN_OP_END
)
4728 if (isUndef(Opcode
, Ops
))
4729 return getUNDEF(VT
);
4731 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4735 unsigned NumElts
= VT
.getVectorNumElements();
4737 auto IsScalarOrSameVectorSize
= [&](const SDValue
&Op
) {
4738 return !Op
.getValueType().isVector() ||
4739 Op
.getValueType().getVectorNumElements() == NumElts
;
4742 auto IsConstantBuildVectorOrUndef
= [&](const SDValue
&Op
) {
4743 BuildVectorSDNode
*BV
= dyn_cast
<BuildVectorSDNode
>(Op
);
4744 return (Op
.isUndef()) || (Op
.getOpcode() == ISD::CONDCODE
) ||
4745 (BV
&& BV
->isConstant());
4748 // All operands must be vector types with the same number of elements as
4749 // the result type and must be either UNDEF or a build vector of constant
4750 // or UNDEF scalars.
4751 if (!llvm::all_of(Ops
, IsConstantBuildVectorOrUndef
) ||
4752 !llvm::all_of(Ops
, IsScalarOrSameVectorSize
))
4755 // If we are comparing vectors, then the result needs to be a i1 boolean
4756 // that is then sign-extended back to the legal result type.
4757 EVT SVT
= (Opcode
== ISD::SETCC
? MVT::i1
: VT
.getScalarType());
4759 // Find legal integer scalar type for constant promotion and
4760 // ensure that its scalar size is at least as large as source.
4761 EVT LegalSVT
= VT
.getScalarType();
4762 if (NewNodesMustHaveLegalTypes
&& LegalSVT
.isInteger()) {
4763 LegalSVT
= TLI
->getTypeToTransformTo(*getContext(), LegalSVT
);
4764 if (LegalSVT
.bitsLT(VT
.getScalarType()))
4768 // Constant fold each scalar lane separately.
4769 SmallVector
<SDValue
, 4> ScalarResults
;
4770 for (unsigned i
= 0; i
!= NumElts
; i
++) {
4771 SmallVector
<SDValue
, 4> ScalarOps
;
4772 for (SDValue Op
: Ops
) {
4773 EVT InSVT
= Op
.getValueType().getScalarType();
4774 BuildVectorSDNode
*InBV
= dyn_cast
<BuildVectorSDNode
>(Op
);
4776 // We've checked that this is UNDEF or a constant of some kind.
4778 ScalarOps
.push_back(getUNDEF(InSVT
));
4780 ScalarOps
.push_back(Op
);
4784 SDValue ScalarOp
= InBV
->getOperand(i
);
4785 EVT ScalarVT
= ScalarOp
.getValueType();
4787 // Build vector (integer) scalar operands may need implicit
4788 // truncation - do this before constant folding.
4789 if (ScalarVT
.isInteger() && ScalarVT
.bitsGT(InSVT
))
4790 ScalarOp
= getNode(ISD::TRUNCATE
, DL
, InSVT
, ScalarOp
);
4792 ScalarOps
.push_back(ScalarOp
);
4795 // Constant fold the scalar operands.
4796 SDValue ScalarResult
= getNode(Opcode
, DL
, SVT
, ScalarOps
, Flags
);
4798 // Legalize the (integer) scalar constant if necessary.
4799 if (LegalSVT
!= SVT
)
4800 ScalarResult
= getNode(ISD::SIGN_EXTEND
, DL
, LegalSVT
, ScalarResult
);
4802 // Scalar folding only succeeded if the result is a constant or UNDEF.
4803 if (!ScalarResult
.isUndef() && ScalarResult
.getOpcode() != ISD::Constant
&&
4804 ScalarResult
.getOpcode() != ISD::ConstantFP
)
4806 ScalarResults
.push_back(ScalarResult
);
4809 SDValue V
= getBuildVector(VT
, DL
, ScalarResults
);
4810 NewSDValueDbgMsg(V
, "New node fold constant vector: ", this);
4814 SDValue
SelectionDAG::foldConstantFPMath(unsigned Opcode
, const SDLoc
&DL
,
4815 EVT VT
, SDValue N1
, SDValue N2
) {
4816 // TODO: We don't do any constant folding for strict FP opcodes here, but we
4817 // should. That will require dealing with a potentially non-default
4818 // rounding mode, checking the "opStatus" return value from the APFloat
4819 // math calculations, and possibly other variations.
4820 auto *N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
.getNode());
4821 auto *N2CFP
= dyn_cast
<ConstantFPSDNode
>(N2
.getNode());
4822 if (N1CFP
&& N2CFP
) {
4823 APFloat C1
= N1CFP
->getValueAPF(), C2
= N2CFP
->getValueAPF();
4826 C1
.add(C2
, APFloat::rmNearestTiesToEven
);
4827 return getConstantFP(C1
, DL
, VT
);
4829 C1
.subtract(C2
, APFloat::rmNearestTiesToEven
);
4830 return getConstantFP(C1
, DL
, VT
);
4832 C1
.multiply(C2
, APFloat::rmNearestTiesToEven
);
4833 return getConstantFP(C1
, DL
, VT
);
4835 C1
.divide(C2
, APFloat::rmNearestTiesToEven
);
4836 return getConstantFP(C1
, DL
, VT
);
4839 return getConstantFP(C1
, DL
, VT
);
4840 case ISD::FCOPYSIGN
:
4842 return getConstantFP(C1
, DL
, VT
);
4846 if (N1CFP
&& Opcode
== ISD::FP_ROUND
) {
4847 APFloat C1
= N1CFP
->getValueAPF(); // make copy
4849 // This can return overflow, underflow, or inexact; we don't care.
4850 // FIXME need to be more flexible about rounding mode.
4851 (void) C1
.convert(EVTToAPFloatSemantics(VT
), APFloat::rmNearestTiesToEven
,
4853 return getConstantFP(C1
, DL
, VT
);
4862 // If both operands are undef, the result is undef. If 1 operand is undef,
4863 // the result is NaN. This should match the behavior of the IR optimizer.
4864 if (N1
.isUndef() && N2
.isUndef())
4865 return getUNDEF(VT
);
4866 if (N1
.isUndef() || N2
.isUndef())
4867 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT
)), DL
, VT
);
4872 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, EVT VT
,
4873 SDValue N1
, SDValue N2
, const SDNodeFlags Flags
) {
4874 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
4875 ConstantSDNode
*N2C
= dyn_cast
<ConstantSDNode
>(N2
);
4876 ConstantFPSDNode
*N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
4877 ConstantFPSDNode
*N2CFP
= dyn_cast
<ConstantFPSDNode
>(N2
);
4879 // Canonicalize constant to RHS if commutative.
4880 if (TLI
->isCommutativeBinOp(Opcode
)) {
4882 std::swap(N1C
, N2C
);
4884 } else if (N1CFP
&& !N2CFP
) {
4885 std::swap(N1CFP
, N2CFP
);
4892 case ISD::TokenFactor
:
4893 assert(VT
== MVT::Other
&& N1
.getValueType() == MVT::Other
&&
4894 N2
.getValueType() == MVT::Other
&& "Invalid token factor!");
4895 // Fold trivial token factors.
4896 if (N1
.getOpcode() == ISD::EntryToken
) return N2
;
4897 if (N2
.getOpcode() == ISD::EntryToken
) return N1
;
4898 if (N1
== N2
) return N1
;
4900 case ISD::BUILD_VECTOR
: {
4901 // Attempt to simplify BUILD_VECTOR.
4902 SDValue Ops
[] = {N1
, N2
};
4903 if (SDValue V
= FoldBUILD_VECTOR(DL
, VT
, Ops
, *this))
4907 case ISD::CONCAT_VECTORS
: {
4908 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4909 SDValue Ops
[] = {N1
, N2
};
4910 if (SDValue V
= FoldCONCAT_VECTORS(DL
, VT
, Ops
, *this))
4915 assert(VT
.isInteger() && "This operator does not apply to FP types!");
4916 assert(N1
.getValueType() == N2
.getValueType() &&
4917 N1
.getValueType() == VT
&& "Binary operator types must match!");
4918 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4919 // worth handling here.
4920 if (N2C
&& N2C
->isNullValue())
4922 if (N2C
&& N2C
->isAllOnesValue()) // X & -1 -> X
4929 assert(VT
.isInteger() && "This operator does not apply to FP types!");
4930 assert(N1
.getValueType() == N2
.getValueType() &&
4931 N1
.getValueType() == VT
&& "Binary operator types must match!");
4932 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4933 // it's worth handling here.
4934 if (N2C
&& N2C
->isNullValue())
4952 assert(VT
.isInteger() && "This operator does not apply to FP types!");
4953 assert(N1
.getValueType() == N2
.getValueType() &&
4954 N1
.getValueType() == VT
&& "Binary operator types must match!");
4961 assert(VT
.isFloatingPoint() && "This operator only applies to FP types!");
4962 assert(N1
.getValueType() == N2
.getValueType() &&
4963 N1
.getValueType() == VT
&& "Binary operator types must match!");
4964 if (SDValue V
= simplifyFPBinop(Opcode
, N1
, N2
))
4967 case ISD::FCOPYSIGN
: // N1 and result must match. N1/N2 need not match.
4968 assert(N1
.getValueType() == VT
&&
4969 N1
.getValueType().isFloatingPoint() &&
4970 N2
.getValueType().isFloatingPoint() &&
4971 "Invalid FCOPYSIGN!");
4976 if (SDValue V
= simplifyShift(N1
, N2
))
4981 assert(VT
== N1
.getValueType() &&
4982 "Shift operators return type must be the same as their first arg");
4983 assert(VT
.isInteger() && N2
.getValueType().isInteger() &&
4984 "Shifts only work on integers");
4985 assert((!VT
.isVector() || VT
== N2
.getValueType()) &&
4986 "Vector shift amounts must be in the same as their first arg");
4987 // Verify that the shift amount VT is big enough to hold valid shift
4988 // amounts. This catches things like trying to shift an i1024 value by an
4989 // i8, which is easy to fall into in generic code that uses
4990 // TLI.getShiftAmount().
4991 assert(N2
.getValueSizeInBits() >= Log2_32_Ceil(N1
.getValueSizeInBits()) &&
4992 "Invalid use of small shift amount with oversized value!");
4994 // Always fold shifts of i1 values so the code generator doesn't need to
4995 // handle them. Since we know the size of the shift has to be less than the
4996 // size of the value, the shift/rotate count is guaranteed to be zero.
4999 if (N2C
&& N2C
->isNullValue())
5002 case ISD::FP_ROUND_INREG
: {
5003 EVT EVT
= cast
<VTSDNode
>(N2
)->getVT();
5004 assert(VT
== N1
.getValueType() && "Not an inreg round!");
5005 assert(VT
.isFloatingPoint() && EVT
.isFloatingPoint() &&
5006 "Cannot FP_ROUND_INREG integer types");
5007 assert(EVT
.isVector() == VT
.isVector() &&
5008 "FP_ROUND_INREG type should be vector iff the operand "
5010 assert((!EVT
.isVector() ||
5011 EVT
.getVectorNumElements() == VT
.getVectorNumElements()) &&
5012 "Vector element counts must match in FP_ROUND_INREG");
5013 assert(EVT
.bitsLE(VT
) && "Not rounding down!");
5015 if (cast
<VTSDNode
>(N2
)->getVT() == VT
) return N1
; // Not actually rounding.
5019 assert(VT
.isFloatingPoint() &&
5020 N1
.getValueType().isFloatingPoint() &&
5021 VT
.bitsLE(N1
.getValueType()) &&
5022 N2C
&& (N2C
->getZExtValue() == 0 || N2C
->getZExtValue() == 1) &&
5023 "Invalid FP_ROUND!");
5024 if (N1
.getValueType() == VT
) return N1
; // noop conversion.
5026 case ISD::AssertSext
:
5027 case ISD::AssertZext
: {
5028 EVT EVT
= cast
<VTSDNode
>(N2
)->getVT();
5029 assert(VT
== N1
.getValueType() && "Not an inreg extend!");
5030 assert(VT
.isInteger() && EVT
.isInteger() &&
5031 "Cannot *_EXTEND_INREG FP types");
5032 assert(!EVT
.isVector() &&
5033 "AssertSExt/AssertZExt type should be the vector element type "
5034 "rather than the vector type!");
5035 assert(EVT
.bitsLE(VT
.getScalarType()) && "Not extending!");
5036 if (VT
.getScalarType() == EVT
) return N1
; // noop assertion.
5039 case ISD::SIGN_EXTEND_INREG
: {
5040 EVT EVT
= cast
<VTSDNode
>(N2
)->getVT();
5041 assert(VT
== N1
.getValueType() && "Not an inreg extend!");
5042 assert(VT
.isInteger() && EVT
.isInteger() &&
5043 "Cannot *_EXTEND_INREG FP types");
5044 assert(EVT
.isVector() == VT
.isVector() &&
5045 "SIGN_EXTEND_INREG type should be vector iff the operand "
5047 assert((!EVT
.isVector() ||
5048 EVT
.getVectorNumElements() == VT
.getVectorNumElements()) &&
5049 "Vector element counts must match in SIGN_EXTEND_INREG");
5050 assert(EVT
.bitsLE(VT
) && "Not extending!");
5051 if (EVT
== VT
) return N1
; // Not actually extending
5053 auto SignExtendInReg
= [&](APInt Val
, llvm::EVT ConstantVT
) {
5054 unsigned FromBits
= EVT
.getScalarSizeInBits();
5055 Val
<<= Val
.getBitWidth() - FromBits
;
5056 Val
.ashrInPlace(Val
.getBitWidth() - FromBits
);
5057 return getConstant(Val
, DL
, ConstantVT
);
5061 const APInt
&Val
= N1C
->getAPIntValue();
5062 return SignExtendInReg(Val
, VT
);
5064 if (ISD::isBuildVectorOfConstantSDNodes(N1
.getNode())) {
5065 SmallVector
<SDValue
, 8> Ops
;
5066 llvm::EVT OpVT
= N1
.getOperand(0).getValueType();
5067 for (int i
= 0, e
= VT
.getVectorNumElements(); i
!= e
; ++i
) {
5068 SDValue Op
= N1
.getOperand(i
);
5070 Ops
.push_back(getUNDEF(OpVT
));
5073 ConstantSDNode
*C
= cast
<ConstantSDNode
>(Op
);
5074 APInt Val
= C
->getAPIntValue();
5075 Ops
.push_back(SignExtendInReg(Val
, OpVT
));
5077 return getBuildVector(VT
, DL
, Ops
);
5081 case ISD::EXTRACT_VECTOR_ELT
:
5082 assert(VT
.getSizeInBits() >= N1
.getValueType().getScalarSizeInBits() &&
5083 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5084 element type of the vector.");
5086 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
5088 return getUNDEF(VT
);
5090 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
5091 if (N2C
&& N2C
->getAPIntValue().uge(N1
.getValueType().getVectorNumElements()))
5092 return getUNDEF(VT
);
5094 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5095 // expanding copies of large vectors from registers.
5097 N1
.getOpcode() == ISD::CONCAT_VECTORS
&&
5098 N1
.getNumOperands() > 0) {
5100 N1
.getOperand(0).getValueType().getVectorNumElements();
5101 return getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, VT
,
5102 N1
.getOperand(N2C
->getZExtValue() / Factor
),
5103 getConstant(N2C
->getZExtValue() % Factor
, DL
,
5104 N2
.getValueType()));
5107 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
5108 // expanding large vector constants.
5109 if (N2C
&& N1
.getOpcode() == ISD::BUILD_VECTOR
) {
5110 SDValue Elt
= N1
.getOperand(N2C
->getZExtValue());
5112 if (VT
!= Elt
.getValueType())
5113 // If the vector element type is not legal, the BUILD_VECTOR operands
5114 // are promoted and implicitly truncated, and the result implicitly
5115 // extended. Make that explicit here.
5116 Elt
= getAnyExtOrTrunc(Elt
, DL
, VT
);
5121 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5122 // operations are lowered to scalars.
5123 if (N1
.getOpcode() == ISD::INSERT_VECTOR_ELT
) {
5124 // If the indices are the same, return the inserted element else
5125 // if the indices are known different, extract the element from
5126 // the original vector.
5127 SDValue N1Op2
= N1
.getOperand(2);
5128 ConstantSDNode
*N1Op2C
= dyn_cast
<ConstantSDNode
>(N1Op2
);
5130 if (N1Op2C
&& N2C
) {
5131 if (N1Op2C
->getZExtValue() == N2C
->getZExtValue()) {
5132 if (VT
== N1
.getOperand(1).getValueType())
5133 return N1
.getOperand(1);
5135 return getSExtOrTrunc(N1
.getOperand(1), DL
, VT
);
5138 return getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, VT
, N1
.getOperand(0), N2
);
5142 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5143 // when vector types are scalarized and v1iX is legal.
5144 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
5145 if (N1
.getOpcode() == ISD::EXTRACT_SUBVECTOR
&&
5146 N1
.getValueType().getVectorNumElements() == 1) {
5147 return getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, VT
, N1
.getOperand(0),
5151 case ISD::EXTRACT_ELEMENT
:
5152 assert(N2C
&& (unsigned)N2C
->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5153 assert(!N1
.getValueType().isVector() && !VT
.isVector() &&
5154 (N1
.getValueType().isInteger() == VT
.isInteger()) &&
5155 N1
.getValueType() != VT
&&
5156 "Wrong types for EXTRACT_ELEMENT!");
5158 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5159 // 64-bit integers into 32-bit parts. Instead of building the extract of
5160 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5161 if (N1
.getOpcode() == ISD::BUILD_PAIR
)
5162 return N1
.getOperand(N2C
->getZExtValue());
5164 // EXTRACT_ELEMENT of a constant int is also very common.
5166 unsigned ElementSize
= VT
.getSizeInBits();
5167 unsigned Shift
= ElementSize
* N2C
->getZExtValue();
5168 APInt ShiftedVal
= N1C
->getAPIntValue().lshr(Shift
);
5169 return getConstant(ShiftedVal
.trunc(ElementSize
), DL
, VT
);
5172 case ISD::EXTRACT_SUBVECTOR
:
5173 if (VT
.isSimple() && N1
.getValueType().isSimple()) {
5174 assert(VT
.isVector() && N1
.getValueType().isVector() &&
5175 "Extract subvector VTs must be a vectors!");
5176 assert(VT
.getVectorElementType() ==
5177 N1
.getValueType().getVectorElementType() &&
5178 "Extract subvector VTs must have the same element type!");
5179 assert(VT
.getSimpleVT() <= N1
.getSimpleValueType() &&
5180 "Extract subvector must be from larger vector to smaller vector!");
5183 assert((VT
.getVectorNumElements() + N2C
->getZExtValue()
5184 <= N1
.getValueType().getVectorNumElements())
5185 && "Extract subvector overflow!");
5188 // Trivial extraction.
5189 if (VT
.getSimpleVT() == N1
.getSimpleValueType())
5192 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5194 return getUNDEF(VT
);
5196 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5197 // the concat have the same type as the extract.
5198 if (N2C
&& N1
.getOpcode() == ISD::CONCAT_VECTORS
&&
5199 N1
.getNumOperands() > 0 &&
5200 VT
== N1
.getOperand(0).getValueType()) {
5201 unsigned Factor
= VT
.getVectorNumElements();
5202 return N1
.getOperand(N2C
->getZExtValue() / Factor
);
5205 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5206 // during shuffle legalization.
5207 if (N1
.getOpcode() == ISD::INSERT_SUBVECTOR
&& N2
== N1
.getOperand(2) &&
5208 VT
== N1
.getOperand(1).getValueType())
5209 return N1
.getOperand(1);
5214 // Perform trivial constant folding.
5216 FoldConstantArithmetic(Opcode
, DL
, VT
, N1
.getNode(), N2
.getNode()))
5219 if (SDValue V
= foldConstantFPMath(Opcode
, DL
, VT
, N1
, N2
))
5222 // Canonicalize an UNDEF to the RHS, even over a constant.
5224 if (TLI
->isCommutativeBinOp(Opcode
)) {
5228 case ISD::FP_ROUND_INREG
:
5229 case ISD::SIGN_EXTEND_INREG
:
5231 return getUNDEF(VT
); // fold op(undef, arg2) -> undef
5238 return getConstant(0, DL
, VT
); // fold op(undef, arg2) -> 0
5243 // Fold a bunch of operators when the RHS is undef.
5248 // Handle undef ^ undef -> 0 special case. This is a common
5250 return getConstant(0, DL
, VT
);
5258 return getUNDEF(VT
); // fold op(arg1, undef) -> undef
5263 return getConstant(0, DL
, VT
); // fold op(arg1, undef) -> 0
5267 return getAllOnesConstant(DL
, VT
);
5271 // Memoize this node if possible.
5273 SDVTList VTs
= getVTList(VT
);
5274 SDValue Ops
[] = {N1
, N2
};
5275 if (VT
!= MVT::Glue
) {
5276 FoldingSetNodeID ID
;
5277 AddNodeIDNode(ID
, Opcode
, VTs
, Ops
);
5279 if (SDNode
*E
= FindNodeOrInsertPos(ID
, DL
, IP
)) {
5280 E
->intersectFlagsWith(Flags
);
5281 return SDValue(E
, 0);
5284 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
5286 createOperands(N
, Ops
);
5287 CSEMap
.InsertNode(N
, IP
);
5289 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
5290 createOperands(N
, Ops
);
5294 SDValue V
= SDValue(N
, 0);
5295 NewSDValueDbgMsg(V
, "Creating new node: ", this);
5299 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, EVT VT
,
5300 SDValue N1
, SDValue N2
, SDValue N3
,
5301 const SDNodeFlags Flags
) {
5302 // Perform various simplifications.
5305 assert(VT
.isFloatingPoint() && "This operator only applies to FP types!");
5306 assert(N1
.getValueType() == VT
&& N2
.getValueType() == VT
&&
5307 N3
.getValueType() == VT
&& "FMA types must match!");
5308 ConstantFPSDNode
*N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
5309 ConstantFPSDNode
*N2CFP
= dyn_cast
<ConstantFPSDNode
>(N2
);
5310 ConstantFPSDNode
*N3CFP
= dyn_cast
<ConstantFPSDNode
>(N3
);
5311 if (N1CFP
&& N2CFP
&& N3CFP
) {
5312 APFloat V1
= N1CFP
->getValueAPF();
5313 const APFloat
&V2
= N2CFP
->getValueAPF();
5314 const APFloat
&V3
= N3CFP
->getValueAPF();
5315 V1
.fusedMultiplyAdd(V2
, V3
, APFloat::rmNearestTiesToEven
);
5316 return getConstantFP(V1
, DL
, VT
);
5320 case ISD::BUILD_VECTOR
: {
5321 // Attempt to simplify BUILD_VECTOR.
5322 SDValue Ops
[] = {N1
, N2
, N3
};
5323 if (SDValue V
= FoldBUILD_VECTOR(DL
, VT
, Ops
, *this))
5327 case ISD::CONCAT_VECTORS
: {
5328 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
5329 SDValue Ops
[] = {N1
, N2
, N3
};
5330 if (SDValue V
= FoldCONCAT_VECTORS(DL
, VT
, Ops
, *this))
5335 assert(VT
.isInteger() && "SETCC result type must be an integer!");
5336 assert(N1
.getValueType() == N2
.getValueType() &&
5337 "SETCC operands must have the same type!");
5338 assert(VT
.isVector() == N1
.getValueType().isVector() &&
5339 "SETCC type should be vector iff the operand type is vector!");
5340 assert((!VT
.isVector() ||
5341 VT
.getVectorNumElements() == N1
.getValueType().getVectorNumElements()) &&
5342 "SETCC vector element counts must match!");
5343 // Use FoldSetCC to simplify SETCC's.
5344 if (SDValue V
= FoldSetCC(VT
, N1
, N2
, cast
<CondCodeSDNode
>(N3
)->get(), DL
))
5346 // Vector constant folding.
5347 SDValue Ops
[] = {N1
, N2
, N3
};
5348 if (SDValue V
= FoldConstantVectorArithmetic(Opcode
, DL
, VT
, Ops
)) {
5349 NewSDValueDbgMsg(V
, "New node vector constant folding: ", this);
5356 if (SDValue V
= simplifySelect(N1
, N2
, N3
))
5359 case ISD::VECTOR_SHUFFLE
:
5360 llvm_unreachable("should use getVectorShuffle constructor!");
5361 case ISD::INSERT_VECTOR_ELT
: {
5362 ConstantSDNode
*N3C
= dyn_cast
<ConstantSDNode
>(N3
);
5363 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
5364 if (N3C
&& N3C
->getZExtValue() >= N1
.getValueType().getVectorNumElements())
5365 return getUNDEF(VT
);
5368 case ISD::INSERT_SUBVECTOR
: {
5370 if (VT
.isSimple() && N1
.getValueType().isSimple()
5371 && N2
.getValueType().isSimple()) {
5372 assert(VT
.isVector() && N1
.getValueType().isVector() &&
5373 N2
.getValueType().isVector() &&
5374 "Insert subvector VTs must be a vectors");
5375 assert(VT
== N1
.getValueType() &&
5376 "Dest and insert subvector source types must match!");
5377 assert(N2
.getSimpleValueType() <= N1
.getSimpleValueType() &&
5378 "Insert subvector must be from smaller vector to larger vector!");
5379 if (isa
<ConstantSDNode
>(Index
)) {
5380 assert((N2
.getValueType().getVectorNumElements() +
5381 cast
<ConstantSDNode
>(Index
)->getZExtValue()
5382 <= VT
.getVectorNumElements())
5383 && "Insert subvector overflow!");
5386 // Trivial insertion.
5387 if (VT
.getSimpleVT() == N2
.getSimpleValueType())
5393 // Fold bit_convert nodes from a type to themselves.
5394 if (N1
.getValueType() == VT
)
5399 // Memoize node if it doesn't produce a flag.
5401 SDVTList VTs
= getVTList(VT
);
5402 SDValue Ops
[] = {N1
, N2
, N3
};
5403 if (VT
!= MVT::Glue
) {
5404 FoldingSetNodeID ID
;
5405 AddNodeIDNode(ID
, Opcode
, VTs
, Ops
);
5407 if (SDNode
*E
= FindNodeOrInsertPos(ID
, DL
, IP
)) {
5408 E
->intersectFlagsWith(Flags
);
5409 return SDValue(E
, 0);
5412 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
5414 createOperands(N
, Ops
);
5415 CSEMap
.InsertNode(N
, IP
);
5417 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
5418 createOperands(N
, Ops
);
5422 SDValue V
= SDValue(N
, 0);
5423 NewSDValueDbgMsg(V
, "Creating new node: ", this);
5427 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, EVT VT
,
5428 SDValue N1
, SDValue N2
, SDValue N3
, SDValue N4
) {
5429 SDValue Ops
[] = { N1
, N2
, N3
, N4
};
5430 return getNode(Opcode
, DL
, VT
, Ops
);
5433 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, EVT VT
,
5434 SDValue N1
, SDValue N2
, SDValue N3
, SDValue N4
,
5436 SDValue Ops
[] = { N1
, N2
, N3
, N4
, N5
};
5437 return getNode(Opcode
, DL
, VT
, Ops
);
5440 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5441 /// the incoming stack arguments to be loaded from the stack.
5442 SDValue
SelectionDAG::getStackArgumentTokenFactor(SDValue Chain
) {
5443 SmallVector
<SDValue
, 8> ArgChains
;
5445 // Include the original chain at the beginning of the list. When this is
5446 // used by target LowerCall hooks, this helps legalize find the
5447 // CALLSEQ_BEGIN node.
5448 ArgChains
.push_back(Chain
);
5450 // Add a chain value for each stack argument.
5451 for (SDNode::use_iterator U
= getEntryNode().getNode()->use_begin(),
5452 UE
= getEntryNode().getNode()->use_end(); U
!= UE
; ++U
)
5453 if (LoadSDNode
*L
= dyn_cast
<LoadSDNode
>(*U
))
5454 if (FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(L
->getBasePtr()))
5455 if (FI
->getIndex() < 0)
5456 ArgChains
.push_back(SDValue(L
, 1));
5458 // Build a tokenfactor for all the chains.
5459 return getNode(ISD::TokenFactor
, SDLoc(Chain
), MVT::Other
, ArgChains
);
5462 /// getMemsetValue - Vectorized representation of the memset value
5464 static SDValue
getMemsetValue(SDValue Value
, EVT VT
, SelectionDAG
&DAG
,
5466 assert(!Value
.isUndef());
5468 unsigned NumBits
= VT
.getScalarSizeInBits();
5469 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Value
)) {
5470 assert(C
->getAPIntValue().getBitWidth() == 8);
5471 APInt Val
= APInt::getSplat(NumBits
, C
->getAPIntValue());
5472 if (VT
.isInteger()) {
5473 bool IsOpaque
= VT
.getSizeInBits() > 64 ||
5474 !DAG
.getTargetLoweringInfo().isLegalStoreImmediate(C
->getSExtValue());
5475 return DAG
.getConstant(Val
, dl
, VT
, false, IsOpaque
);
5477 return DAG
.getConstantFP(APFloat(DAG
.EVTToAPFloatSemantics(VT
), Val
), dl
,
5481 assert(Value
.getValueType() == MVT::i8
&& "memset with non-byte fill value?");
5482 EVT IntVT
= VT
.getScalarType();
5483 if (!IntVT
.isInteger())
5484 IntVT
= EVT::getIntegerVT(*DAG
.getContext(), IntVT
.getSizeInBits());
5486 Value
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, IntVT
, Value
);
5488 // Use a multiplication with 0x010101... to extend the input to the
5490 APInt Magic
= APInt::getSplat(NumBits
, APInt(8, 0x01));
5491 Value
= DAG
.getNode(ISD::MUL
, dl
, IntVT
, Value
,
5492 DAG
.getConstant(Magic
, dl
, IntVT
));
5495 if (VT
!= Value
.getValueType() && !VT
.isInteger())
5496 Value
= DAG
.getBitcast(VT
.getScalarType(), Value
);
5497 if (VT
!= Value
.getValueType())
5498 Value
= DAG
.getSplatBuildVector(VT
, dl
, Value
);
5503 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5504 /// used when a memcpy is turned into a memset when the source is a constant
5506 static SDValue
getMemsetStringVal(EVT VT
, const SDLoc
&dl
, SelectionDAG
&DAG
,
5507 const TargetLowering
&TLI
,
5508 const ConstantDataArraySlice
&Slice
) {
5509 // Handle vector with all elements zero.
5510 if (Slice
.Array
== nullptr) {
5512 return DAG
.getConstant(0, dl
, VT
);
5513 else if (VT
== MVT::f32
|| VT
== MVT::f64
|| VT
== MVT::f128
)
5514 return DAG
.getConstantFP(0.0, dl
, VT
);
5515 else if (VT
.isVector()) {
5516 unsigned NumElts
= VT
.getVectorNumElements();
5517 MVT EltVT
= (VT
.getVectorElementType() == MVT::f32
) ? MVT::i32
: MVT::i64
;
5518 return DAG
.getNode(ISD::BITCAST
, dl
, VT
,
5519 DAG
.getConstant(0, dl
,
5520 EVT::getVectorVT(*DAG
.getContext(),
5523 llvm_unreachable("Expected type!");
5526 assert(!VT
.isVector() && "Can't handle vector type here!");
5527 unsigned NumVTBits
= VT
.getSizeInBits();
5528 unsigned NumVTBytes
= NumVTBits
/ 8;
5529 unsigned NumBytes
= std::min(NumVTBytes
, unsigned(Slice
.Length
));
5531 APInt
Val(NumVTBits
, 0);
5532 if (DAG
.getDataLayout().isLittleEndian()) {
5533 for (unsigned i
= 0; i
!= NumBytes
; ++i
)
5534 Val
|= (uint64_t)(unsigned char)Slice
[i
] << i
*8;
5536 for (unsigned i
= 0; i
!= NumBytes
; ++i
)
5537 Val
|= (uint64_t)(unsigned char)Slice
[i
] << (NumVTBytes
-i
-1)*8;
5540 // If the "cost" of materializing the integer immediate is less than the cost
5541 // of a load, then it is cost effective to turn the load into the immediate.
5542 Type
*Ty
= VT
.getTypeForEVT(*DAG
.getContext());
5543 if (TLI
.shouldConvertConstantLoadToIntImm(Val
, Ty
))
5544 return DAG
.getConstant(Val
, dl
, VT
);
5545 return SDValue(nullptr, 0);
5548 SDValue
SelectionDAG::getMemBasePlusOffset(SDValue Base
, unsigned Offset
,
5550 EVT VT
= Base
.getValueType();
5551 return getNode(ISD::ADD
, DL
, VT
, Base
, getConstant(Offset
, DL
, VT
));
5554 /// Returns true if memcpy source is constant data.
5555 static bool isMemSrcFromConstant(SDValue Src
, ConstantDataArraySlice
&Slice
) {
5556 uint64_t SrcDelta
= 0;
5557 GlobalAddressSDNode
*G
= nullptr;
5558 if (Src
.getOpcode() == ISD::GlobalAddress
)
5559 G
= cast
<GlobalAddressSDNode
>(Src
);
5560 else if (Src
.getOpcode() == ISD::ADD
&&
5561 Src
.getOperand(0).getOpcode() == ISD::GlobalAddress
&&
5562 Src
.getOperand(1).getOpcode() == ISD::Constant
) {
5563 G
= cast
<GlobalAddressSDNode
>(Src
.getOperand(0));
5564 SrcDelta
= cast
<ConstantSDNode
>(Src
.getOperand(1))->getZExtValue();
5569 return getConstantDataArrayInfo(G
->getGlobal(), Slice
, 8,
5570 SrcDelta
+ G
->getOffset());
5573 static bool shouldLowerMemFuncForSize(const MachineFunction
&MF
) {
5574 // On Darwin, -Os means optimize for size without hurting performance, so
5575 // only really optimize for size when -Oz (MinSize) is used.
5576 if (MF
.getTarget().getTargetTriple().isOSDarwin())
5577 return MF
.getFunction().hasMinSize();
5578 return MF
.getFunction().hasOptSize();
5581 static void chainLoadsAndStoresForMemcpy(SelectionDAG
&DAG
, const SDLoc
&dl
,
5582 SmallVector
<SDValue
, 32> &OutChains
, unsigned From
,
5583 unsigned To
, SmallVector
<SDValue
, 16> &OutLoadChains
,
5584 SmallVector
<SDValue
, 16> &OutStoreChains
) {
5585 assert(OutLoadChains
.size() && "Missing loads in memcpy inlining");
5586 assert(OutStoreChains
.size() && "Missing stores in memcpy inlining");
5587 SmallVector
<SDValue
, 16> GluedLoadChains
;
5588 for (unsigned i
= From
; i
< To
; ++i
) {
5589 OutChains
.push_back(OutLoadChains
[i
]);
5590 GluedLoadChains
.push_back(OutLoadChains
[i
]);
5593 // Chain for all loads.
5594 SDValue LoadToken
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
,
5597 for (unsigned i
= From
; i
< To
; ++i
) {
5598 StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(OutStoreChains
[i
]);
5599 SDValue NewStore
= DAG
.getTruncStore(LoadToken
, dl
, ST
->getValue(),
5600 ST
->getBasePtr(), ST
->getMemoryVT(),
5601 ST
->getMemOperand());
5602 OutChains
.push_back(NewStore
);
5606 static SDValue
getMemcpyLoadsAndStores(SelectionDAG
&DAG
, const SDLoc
&dl
,
5607 SDValue Chain
, SDValue Dst
, SDValue Src
,
5608 uint64_t Size
, unsigned Align
,
5609 bool isVol
, bool AlwaysInline
,
5610 MachinePointerInfo DstPtrInfo
,
5611 MachinePointerInfo SrcPtrInfo
) {
5612 // Turn a memcpy of undef to nop.
5616 // Expand memcpy to a series of load and store ops if the size operand falls
5617 // below a certain threshold.
5618 // TODO: In the AlwaysInline case, if the size is big then generate a loop
5619 // rather than maybe a humongous number of loads and stores.
5620 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
5621 const DataLayout
&DL
= DAG
.getDataLayout();
5622 LLVMContext
&C
= *DAG
.getContext();
5623 std::vector
<EVT
> MemOps
;
5624 bool DstAlignCanChange
= false;
5625 MachineFunction
&MF
= DAG
.getMachineFunction();
5626 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
5627 bool OptSize
= shouldLowerMemFuncForSize(MF
);
5628 FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(Dst
);
5629 if (FI
&& !MFI
.isFixedObjectIndex(FI
->getIndex()))
5630 DstAlignCanChange
= true;
5631 unsigned SrcAlign
= DAG
.InferPtrAlignment(Src
);
5632 if (Align
> SrcAlign
)
5634 ConstantDataArraySlice Slice
;
5635 bool CopyFromConstant
= isMemSrcFromConstant(Src
, Slice
);
5636 bool isZeroConstant
= CopyFromConstant
&& Slice
.Array
== nullptr;
5637 unsigned Limit
= AlwaysInline
? ~0U : TLI
.getMaxStoresPerMemcpy(OptSize
);
5639 if (!TLI
.findOptimalMemOpLowering(MemOps
, Limit
, Size
,
5640 (DstAlignCanChange
? 0 : Align
),
5641 (isZeroConstant
? 0 : SrcAlign
),
5642 false, false, CopyFromConstant
, true,
5643 DstPtrInfo
.getAddrSpace(),
5644 SrcPtrInfo
.getAddrSpace(),
5645 MF
.getFunction().getAttributes()))
5648 if (DstAlignCanChange
) {
5649 Type
*Ty
= MemOps
[0].getTypeForEVT(C
);
5650 unsigned NewAlign
= (unsigned)DL
.getABITypeAlignment(Ty
);
5652 // Don't promote to an alignment that would require dynamic stack
5654 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
5655 if (!TRI
->needsStackRealignment(MF
))
5656 while (NewAlign
> Align
&&
5657 DL
.exceedsNaturalStackAlignment(NewAlign
))
5660 if (NewAlign
> Align
) {
5661 // Give the stack frame object a larger alignment if needed.
5662 if (MFI
.getObjectAlignment(FI
->getIndex()) < NewAlign
)
5663 MFI
.setObjectAlignment(FI
->getIndex(), NewAlign
);
5668 MachineMemOperand::Flags MMOFlags
=
5669 isVol
? MachineMemOperand::MOVolatile
: MachineMemOperand::MONone
;
5670 SmallVector
<SDValue
, 16> OutLoadChains
;
5671 SmallVector
<SDValue
, 16> OutStoreChains
;
5672 SmallVector
<SDValue
, 32> OutChains
;
5673 unsigned NumMemOps
= MemOps
.size();
5674 uint64_t SrcOff
= 0, DstOff
= 0;
5675 for (unsigned i
= 0; i
!= NumMemOps
; ++i
) {
5677 unsigned VTSize
= VT
.getSizeInBits() / 8;
5678 SDValue Value
, Store
;
5680 if (VTSize
> Size
) {
5681 // Issuing an unaligned load / store pair that overlaps with the previous
5682 // pair. Adjust the offset accordingly.
5683 assert(i
== NumMemOps
-1 && i
!= 0);
5684 SrcOff
-= VTSize
- Size
;
5685 DstOff
-= VTSize
- Size
;
5688 if (CopyFromConstant
&&
5689 (isZeroConstant
|| (VT
.isInteger() && !VT
.isVector()))) {
5690 // It's unlikely a store of a vector immediate can be done in a single
5691 // instruction. It would require a load from a constantpool first.
5692 // We only handle zero vectors here.
5693 // FIXME: Handle other cases where store of vector immediate is done in
5694 // a single instruction.
5695 ConstantDataArraySlice SubSlice
;
5696 if (SrcOff
< Slice
.Length
) {
5698 SubSlice
.move(SrcOff
);
5700 // This is an out-of-bounds access and hence UB. Pretend we read zero.
5701 SubSlice
.Array
= nullptr;
5702 SubSlice
.Offset
= 0;
5703 SubSlice
.Length
= VTSize
;
5705 Value
= getMemsetStringVal(VT
, dl
, DAG
, TLI
, SubSlice
);
5706 if (Value
.getNode()) {
5707 Store
= DAG
.getStore(Chain
, dl
, Value
,
5708 DAG
.getMemBasePlusOffset(Dst
, DstOff
, dl
),
5709 DstPtrInfo
.getWithOffset(DstOff
), Align
,
5711 OutChains
.push_back(Store
);
5715 if (!Store
.getNode()) {
5716 // The type might not be legal for the target. This should only happen
5717 // if the type is smaller than a legal type, as on PPC, so the right
5718 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
5719 // to Load/Store if NVT==VT.
5720 // FIXME does the case above also need this?
5721 EVT NVT
= TLI
.getTypeToTransformTo(C
, VT
);
5722 assert(NVT
.bitsGE(VT
));
5724 bool isDereferenceable
=
5725 SrcPtrInfo
.getWithOffset(SrcOff
).isDereferenceable(VTSize
, C
, DL
);
5726 MachineMemOperand::Flags SrcMMOFlags
= MMOFlags
;
5727 if (isDereferenceable
)
5728 SrcMMOFlags
|= MachineMemOperand::MODereferenceable
;
5730 Value
= DAG
.getExtLoad(ISD::EXTLOAD
, dl
, NVT
, Chain
,
5731 DAG
.getMemBasePlusOffset(Src
, SrcOff
, dl
),
5732 SrcPtrInfo
.getWithOffset(SrcOff
), VT
,
5733 MinAlign(SrcAlign
, SrcOff
), SrcMMOFlags
);
5734 OutLoadChains
.push_back(Value
.getValue(1));
5736 Store
= DAG
.getTruncStore(
5737 Chain
, dl
, Value
, DAG
.getMemBasePlusOffset(Dst
, DstOff
, dl
),
5738 DstPtrInfo
.getWithOffset(DstOff
), VT
, Align
, MMOFlags
);
5739 OutStoreChains
.push_back(Store
);
5746 unsigned GluedLdStLimit
= MaxLdStGlue
== 0 ?
5747 TLI
.getMaxGluedStoresPerMemcpy() : MaxLdStGlue
;
5748 unsigned NumLdStInMemcpy
= OutStoreChains
.size();
5750 if (NumLdStInMemcpy
) {
5751 // It may be that memcpy might be converted to memset if it's memcpy
5752 // of constants. In such a case, we won't have loads and stores, but
5753 // just stores. In the absence of loads, there is nothing to gang up.
5754 if ((GluedLdStLimit
<= 1) || !EnableMemCpyDAGOpt
) {
5755 // If target does not care, just leave as it.
5756 for (unsigned i
= 0; i
< NumLdStInMemcpy
; ++i
) {
5757 OutChains
.push_back(OutLoadChains
[i
]);
5758 OutChains
.push_back(OutStoreChains
[i
]);
5761 // Ld/St less than/equal limit set by target.
5762 if (NumLdStInMemcpy
<= GluedLdStLimit
) {
5763 chainLoadsAndStoresForMemcpy(DAG
, dl
, OutChains
, 0,
5764 NumLdStInMemcpy
, OutLoadChains
,
5767 unsigned NumberLdChain
= NumLdStInMemcpy
/ GluedLdStLimit
;
5768 unsigned RemainingLdStInMemcpy
= NumLdStInMemcpy
% GluedLdStLimit
;
5769 unsigned GlueIter
= 0;
5771 for (unsigned cnt
= 0; cnt
< NumberLdChain
; ++cnt
) {
5772 unsigned IndexFrom
= NumLdStInMemcpy
- GlueIter
- GluedLdStLimit
;
5773 unsigned IndexTo
= NumLdStInMemcpy
- GlueIter
;
5775 chainLoadsAndStoresForMemcpy(DAG
, dl
, OutChains
, IndexFrom
, IndexTo
,
5776 OutLoadChains
, OutStoreChains
);
5777 GlueIter
+= GluedLdStLimit
;
5781 if (RemainingLdStInMemcpy
) {
5782 chainLoadsAndStoresForMemcpy(DAG
, dl
, OutChains
, 0,
5783 RemainingLdStInMemcpy
, OutLoadChains
,
5789 return DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, OutChains
);
5792 static SDValue
getMemmoveLoadsAndStores(SelectionDAG
&DAG
, const SDLoc
&dl
,
5793 SDValue Chain
, SDValue Dst
, SDValue Src
,
5794 uint64_t Size
, unsigned Align
,
5795 bool isVol
, bool AlwaysInline
,
5796 MachinePointerInfo DstPtrInfo
,
5797 MachinePointerInfo SrcPtrInfo
) {
5798 // Turn a memmove of undef to nop.
5802 // Expand memmove to a series of load and store ops if the size operand falls
5803 // below a certain threshold.
5804 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
5805 const DataLayout
&DL
= DAG
.getDataLayout();
5806 LLVMContext
&C
= *DAG
.getContext();
5807 std::vector
<EVT
> MemOps
;
5808 bool DstAlignCanChange
= false;
5809 MachineFunction
&MF
= DAG
.getMachineFunction();
5810 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
5811 bool OptSize
= shouldLowerMemFuncForSize(MF
);
5812 FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(Dst
);
5813 if (FI
&& !MFI
.isFixedObjectIndex(FI
->getIndex()))
5814 DstAlignCanChange
= true;
5815 unsigned SrcAlign
= DAG
.InferPtrAlignment(Src
);
5816 if (Align
> SrcAlign
)
5818 unsigned Limit
= AlwaysInline
? ~0U : TLI
.getMaxStoresPerMemmove(OptSize
);
5820 if (!TLI
.findOptimalMemOpLowering(MemOps
, Limit
, Size
,
5821 (DstAlignCanChange
? 0 : Align
), SrcAlign
,
5822 false, false, false, false,
5823 DstPtrInfo
.getAddrSpace(),
5824 SrcPtrInfo
.getAddrSpace(),
5825 MF
.getFunction().getAttributes()))
5828 if (DstAlignCanChange
) {
5829 Type
*Ty
= MemOps
[0].getTypeForEVT(C
);
5830 unsigned NewAlign
= (unsigned)DL
.getABITypeAlignment(Ty
);
5831 if (NewAlign
> Align
) {
5832 // Give the stack frame object a larger alignment if needed.
5833 if (MFI
.getObjectAlignment(FI
->getIndex()) < NewAlign
)
5834 MFI
.setObjectAlignment(FI
->getIndex(), NewAlign
);
5839 MachineMemOperand::Flags MMOFlags
=
5840 isVol
? MachineMemOperand::MOVolatile
: MachineMemOperand::MONone
;
5841 uint64_t SrcOff
= 0, DstOff
= 0;
5842 SmallVector
<SDValue
, 8> LoadValues
;
5843 SmallVector
<SDValue
, 8> LoadChains
;
5844 SmallVector
<SDValue
, 8> OutChains
;
5845 unsigned NumMemOps
= MemOps
.size();
5846 for (unsigned i
= 0; i
< NumMemOps
; i
++) {
5848 unsigned VTSize
= VT
.getSizeInBits() / 8;
5851 bool isDereferenceable
=
5852 SrcPtrInfo
.getWithOffset(SrcOff
).isDereferenceable(VTSize
, C
, DL
);
5853 MachineMemOperand::Flags SrcMMOFlags
= MMOFlags
;
5854 if (isDereferenceable
)
5855 SrcMMOFlags
|= MachineMemOperand::MODereferenceable
;
5858 DAG
.getLoad(VT
, dl
, Chain
, DAG
.getMemBasePlusOffset(Src
, SrcOff
, dl
),
5859 SrcPtrInfo
.getWithOffset(SrcOff
), SrcAlign
, SrcMMOFlags
);
5860 LoadValues
.push_back(Value
);
5861 LoadChains
.push_back(Value
.getValue(1));
5864 Chain
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, LoadChains
);
5866 for (unsigned i
= 0; i
< NumMemOps
; i
++) {
5868 unsigned VTSize
= VT
.getSizeInBits() / 8;
5871 Store
= DAG
.getStore(Chain
, dl
, LoadValues
[i
],
5872 DAG
.getMemBasePlusOffset(Dst
, DstOff
, dl
),
5873 DstPtrInfo
.getWithOffset(DstOff
), Align
, MMOFlags
);
5874 OutChains
.push_back(Store
);
5878 return DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, OutChains
);
5881 /// Lower the call to 'memset' intrinsic function into a series of store
5884 /// \param DAG Selection DAG where lowered code is placed.
5885 /// \param dl Link to corresponding IR location.
5886 /// \param Chain Control flow dependency.
5887 /// \param Dst Pointer to destination memory location.
5888 /// \param Src Value of byte to write into the memory.
5889 /// \param Size Number of bytes to write.
5890 /// \param Align Alignment of the destination in bytes.
5891 /// \param isVol True if destination is volatile.
5892 /// \param DstPtrInfo IR information on the memory pointer.
5893 /// \returns New head in the control flow, if lowering was successful, empty
5894 /// SDValue otherwise.
5896 /// The function tries to replace 'llvm.memset' intrinsic with several store
5897 /// operations and value calculation code. This is usually profitable for small
5899 static SDValue
getMemsetStores(SelectionDAG
&DAG
, const SDLoc
&dl
,
5900 SDValue Chain
, SDValue Dst
, SDValue Src
,
5901 uint64_t Size
, unsigned Align
, bool isVol
,
5902 MachinePointerInfo DstPtrInfo
) {
5903 // Turn a memset of undef to nop.
5907 // Expand memset to a series of load/store ops if the size operand
5908 // falls below a certain threshold.
5909 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
5910 std::vector
<EVT
> MemOps
;
5911 bool DstAlignCanChange
= false;
5912 MachineFunction
&MF
= DAG
.getMachineFunction();
5913 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
5914 bool OptSize
= shouldLowerMemFuncForSize(MF
);
5915 FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(Dst
);
5916 if (FI
&& !MFI
.isFixedObjectIndex(FI
->getIndex()))
5917 DstAlignCanChange
= true;
5919 isa
<ConstantSDNode
>(Src
) && cast
<ConstantSDNode
>(Src
)->isNullValue();
5920 if (!TLI
.findOptimalMemOpLowering(MemOps
, TLI
.getMaxStoresPerMemset(OptSize
),
5921 Size
, (DstAlignCanChange
? 0 : Align
), 0,
5922 true, IsZeroVal
, false, true,
5923 DstPtrInfo
.getAddrSpace(), ~0u,
5924 MF
.getFunction().getAttributes()))
5927 if (DstAlignCanChange
) {
5928 Type
*Ty
= MemOps
[0].getTypeForEVT(*DAG
.getContext());
5929 unsigned NewAlign
= (unsigned)DAG
.getDataLayout().getABITypeAlignment(Ty
);
5930 if (NewAlign
> Align
) {
5931 // Give the stack frame object a larger alignment if needed.
5932 if (MFI
.getObjectAlignment(FI
->getIndex()) < NewAlign
)
5933 MFI
.setObjectAlignment(FI
->getIndex(), NewAlign
);
5938 SmallVector
<SDValue
, 8> OutChains
;
5939 uint64_t DstOff
= 0;
5940 unsigned NumMemOps
= MemOps
.size();
5942 // Find the largest store and generate the bit pattern for it.
5943 EVT LargestVT
= MemOps
[0];
5944 for (unsigned i
= 1; i
< NumMemOps
; i
++)
5945 if (MemOps
[i
].bitsGT(LargestVT
))
5946 LargestVT
= MemOps
[i
];
5947 SDValue MemSetValue
= getMemsetValue(Src
, LargestVT
, DAG
, dl
);
5949 for (unsigned i
= 0; i
< NumMemOps
; i
++) {
5951 unsigned VTSize
= VT
.getSizeInBits() / 8;
5952 if (VTSize
> Size
) {
5953 // Issuing an unaligned load / store pair that overlaps with the previous
5954 // pair. Adjust the offset accordingly.
5955 assert(i
== NumMemOps
-1 && i
!= 0);
5956 DstOff
-= VTSize
- Size
;
5959 // If this store is smaller than the largest store see whether we can get
5960 // the smaller value for free with a truncate.
5961 SDValue Value
= MemSetValue
;
5962 if (VT
.bitsLT(LargestVT
)) {
5963 if (!LargestVT
.isVector() && !VT
.isVector() &&
5964 TLI
.isTruncateFree(LargestVT
, VT
))
5965 Value
= DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, MemSetValue
);
5967 Value
= getMemsetValue(Src
, VT
, DAG
, dl
);
5969 assert(Value
.getValueType() == VT
&& "Value with wrong type.");
5970 SDValue Store
= DAG
.getStore(
5971 Chain
, dl
, Value
, DAG
.getMemBasePlusOffset(Dst
, DstOff
, dl
),
5972 DstPtrInfo
.getWithOffset(DstOff
), Align
,
5973 isVol
? MachineMemOperand::MOVolatile
: MachineMemOperand::MONone
);
5974 OutChains
.push_back(Store
);
5975 DstOff
+= VT
.getSizeInBits() / 8;
5979 return DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, OutChains
);
5982 static void checkAddrSpaceIsValidForLibcall(const TargetLowering
*TLI
,
5984 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5985 // pointer operands can be losslessly bitcasted to pointers of address space 0
5986 if (AS
!= 0 && !TLI
->isNoopAddrSpaceCast(AS
, 0)) {
5987 report_fatal_error("cannot lower memory intrinsic in address space " +
5992 SDValue
SelectionDAG::getMemcpy(SDValue Chain
, const SDLoc
&dl
, SDValue Dst
,
5993 SDValue Src
, SDValue Size
, unsigned Align
,
5994 bool isVol
, bool AlwaysInline
, bool isTailCall
,
5995 MachinePointerInfo DstPtrInfo
,
5996 MachinePointerInfo SrcPtrInfo
) {
5997 assert(Align
&& "The SDAG layer expects explicit alignment and reserves 0");
5999 // Check to see if we should lower the memcpy to loads and stores first.
6000 // For cases within the target-specified limits, this is the best choice.
6001 ConstantSDNode
*ConstantSize
= dyn_cast
<ConstantSDNode
>(Size
);
6003 // Memcpy with size zero? Just return the original chain.
6004 if (ConstantSize
->isNullValue())
6007 SDValue Result
= getMemcpyLoadsAndStores(*this, dl
, Chain
, Dst
, Src
,
6008 ConstantSize
->getZExtValue(),Align
,
6009 isVol
, false, DstPtrInfo
, SrcPtrInfo
);
6010 if (Result
.getNode())
6014 // Then check to see if we should lower the memcpy with target-specific
6015 // code. If the target chooses to do this, this is the next best.
6017 SDValue Result
= TSI
->EmitTargetCodeForMemcpy(
6018 *this, dl
, Chain
, Dst
, Src
, Size
, Align
, isVol
, AlwaysInline
,
6019 DstPtrInfo
, SrcPtrInfo
);
6020 if (Result
.getNode())
6024 // If we really need inline code and the target declined to provide it,
6025 // use a (potentially long) sequence of loads and stores.
6027 assert(ConstantSize
&& "AlwaysInline requires a constant size!");
6028 return getMemcpyLoadsAndStores(*this, dl
, Chain
, Dst
, Src
,
6029 ConstantSize
->getZExtValue(), Align
, isVol
,
6030 true, DstPtrInfo
, SrcPtrInfo
);
6033 checkAddrSpaceIsValidForLibcall(TLI
, DstPtrInfo
.getAddrSpace());
6034 checkAddrSpaceIsValidForLibcall(TLI
, SrcPtrInfo
.getAddrSpace());
6036 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6037 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6038 // respect volatile, so they may do things like read or write memory
6039 // beyond the given memory regions. But fixing this isn't easy, and most
6040 // people don't care.
6042 // Emit a library call.
6043 TargetLowering::ArgListTy Args
;
6044 TargetLowering::ArgListEntry Entry
;
6045 Entry
.Ty
= Type::getInt8PtrTy(*getContext());
6046 Entry
.Node
= Dst
; Args
.push_back(Entry
);
6047 Entry
.Node
= Src
; Args
.push_back(Entry
);
6049 Entry
.Ty
= getDataLayout().getIntPtrType(*getContext());
6050 Entry
.Node
= Size
; Args
.push_back(Entry
);
6051 // FIXME: pass in SDLoc
6052 TargetLowering::CallLoweringInfo
CLI(*this);
6055 .setLibCallee(TLI
->getLibcallCallingConv(RTLIB::MEMCPY
),
6056 Dst
.getValueType().getTypeForEVT(*getContext()),
6057 getExternalSymbol(TLI
->getLibcallName(RTLIB::MEMCPY
),
6058 TLI
->getPointerTy(getDataLayout())),
6061 .setTailCall(isTailCall
);
6063 std::pair
<SDValue
,SDValue
> CallResult
= TLI
->LowerCallTo(CLI
);
6064 return CallResult
.second
;
6067 SDValue
SelectionDAG::getAtomicMemcpy(SDValue Chain
, const SDLoc
&dl
,
6068 SDValue Dst
, unsigned DstAlign
,
6069 SDValue Src
, unsigned SrcAlign
,
6070 SDValue Size
, Type
*SizeTy
,
6071 unsigned ElemSz
, bool isTailCall
,
6072 MachinePointerInfo DstPtrInfo
,
6073 MachinePointerInfo SrcPtrInfo
) {
6074 // Emit a library call.
6075 TargetLowering::ArgListTy Args
;
6076 TargetLowering::ArgListEntry Entry
;
6077 Entry
.Ty
= getDataLayout().getIntPtrType(*getContext());
6079 Args
.push_back(Entry
);
6082 Args
.push_back(Entry
);
6086 Args
.push_back(Entry
);
6088 RTLIB::Libcall LibraryCall
=
6089 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz
);
6090 if (LibraryCall
== RTLIB::UNKNOWN_LIBCALL
)
6091 report_fatal_error("Unsupported element size");
6093 TargetLowering::CallLoweringInfo
CLI(*this);
6096 .setLibCallee(TLI
->getLibcallCallingConv(LibraryCall
),
6097 Type::getVoidTy(*getContext()),
6098 getExternalSymbol(TLI
->getLibcallName(LibraryCall
),
6099 TLI
->getPointerTy(getDataLayout())),
6102 .setTailCall(isTailCall
);
6104 std::pair
<SDValue
, SDValue
> CallResult
= TLI
->LowerCallTo(CLI
);
6105 return CallResult
.second
;
6108 SDValue
SelectionDAG::getMemmove(SDValue Chain
, const SDLoc
&dl
, SDValue Dst
,
6109 SDValue Src
, SDValue Size
, unsigned Align
,
6110 bool isVol
, bool isTailCall
,
6111 MachinePointerInfo DstPtrInfo
,
6112 MachinePointerInfo SrcPtrInfo
) {
6113 assert(Align
&& "The SDAG layer expects explicit alignment and reserves 0");
6115 // Check to see if we should lower the memmove to loads and stores first.
6116 // For cases within the target-specified limits, this is the best choice.
6117 ConstantSDNode
*ConstantSize
= dyn_cast
<ConstantSDNode
>(Size
);
6119 // Memmove with size zero? Just return the original chain.
6120 if (ConstantSize
->isNullValue())
6124 getMemmoveLoadsAndStores(*this, dl
, Chain
, Dst
, Src
,
6125 ConstantSize
->getZExtValue(), Align
, isVol
,
6126 false, DstPtrInfo
, SrcPtrInfo
);
6127 if (Result
.getNode())
6131 // Then check to see if we should lower the memmove with target-specific
6132 // code. If the target chooses to do this, this is the next best.
6134 SDValue Result
= TSI
->EmitTargetCodeForMemmove(
6135 *this, dl
, Chain
, Dst
, Src
, Size
, Align
, isVol
, DstPtrInfo
, SrcPtrInfo
);
6136 if (Result
.getNode())
6140 checkAddrSpaceIsValidForLibcall(TLI
, DstPtrInfo
.getAddrSpace());
6141 checkAddrSpaceIsValidForLibcall(TLI
, SrcPtrInfo
.getAddrSpace());
6143 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6144 // not be safe. See memcpy above for more details.
6146 // Emit a library call.
6147 TargetLowering::ArgListTy Args
;
6148 TargetLowering::ArgListEntry Entry
;
6149 Entry
.Ty
= Type::getInt8PtrTy(*getContext());
6150 Entry
.Node
= Dst
; Args
.push_back(Entry
);
6151 Entry
.Node
= Src
; Args
.push_back(Entry
);
6153 Entry
.Ty
= getDataLayout().getIntPtrType(*getContext());
6154 Entry
.Node
= Size
; Args
.push_back(Entry
);
6155 // FIXME: pass in SDLoc
6156 TargetLowering::CallLoweringInfo
CLI(*this);
6159 .setLibCallee(TLI
->getLibcallCallingConv(RTLIB::MEMMOVE
),
6160 Dst
.getValueType().getTypeForEVT(*getContext()),
6161 getExternalSymbol(TLI
->getLibcallName(RTLIB::MEMMOVE
),
6162 TLI
->getPointerTy(getDataLayout())),
6165 .setTailCall(isTailCall
);
6167 std::pair
<SDValue
,SDValue
> CallResult
= TLI
->LowerCallTo(CLI
);
6168 return CallResult
.second
;
6171 SDValue
SelectionDAG::getAtomicMemmove(SDValue Chain
, const SDLoc
&dl
,
6172 SDValue Dst
, unsigned DstAlign
,
6173 SDValue Src
, unsigned SrcAlign
,
6174 SDValue Size
, Type
*SizeTy
,
6175 unsigned ElemSz
, bool isTailCall
,
6176 MachinePointerInfo DstPtrInfo
,
6177 MachinePointerInfo SrcPtrInfo
) {
6178 // Emit a library call.
6179 TargetLowering::ArgListTy Args
;
6180 TargetLowering::ArgListEntry Entry
;
6181 Entry
.Ty
= getDataLayout().getIntPtrType(*getContext());
6183 Args
.push_back(Entry
);
6186 Args
.push_back(Entry
);
6190 Args
.push_back(Entry
);
6192 RTLIB::Libcall LibraryCall
=
6193 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz
);
6194 if (LibraryCall
== RTLIB::UNKNOWN_LIBCALL
)
6195 report_fatal_error("Unsupported element size");
6197 TargetLowering::CallLoweringInfo
CLI(*this);
6200 .setLibCallee(TLI
->getLibcallCallingConv(LibraryCall
),
6201 Type::getVoidTy(*getContext()),
6202 getExternalSymbol(TLI
->getLibcallName(LibraryCall
),
6203 TLI
->getPointerTy(getDataLayout())),
6206 .setTailCall(isTailCall
);
6208 std::pair
<SDValue
, SDValue
> CallResult
= TLI
->LowerCallTo(CLI
);
6209 return CallResult
.second
;
6212 SDValue
SelectionDAG::getMemset(SDValue Chain
, const SDLoc
&dl
, SDValue Dst
,
6213 SDValue Src
, SDValue Size
, unsigned Align
,
6214 bool isVol
, bool isTailCall
,
6215 MachinePointerInfo DstPtrInfo
) {
6216 assert(Align
&& "The SDAG layer expects explicit alignment and reserves 0");
6218 // Check to see if we should lower the memset to stores first.
6219 // For cases within the target-specified limits, this is the best choice.
6220 ConstantSDNode
*ConstantSize
= dyn_cast
<ConstantSDNode
>(Size
);
6222 // Memset with size zero? Just return the original chain.
6223 if (ConstantSize
->isNullValue())
6227 getMemsetStores(*this, dl
, Chain
, Dst
, Src
, ConstantSize
->getZExtValue(),
6228 Align
, isVol
, DstPtrInfo
);
6230 if (Result
.getNode())
6234 // Then check to see if we should lower the memset with target-specific
6235 // code. If the target chooses to do this, this is the next best.
6237 SDValue Result
= TSI
->EmitTargetCodeForMemset(
6238 *this, dl
, Chain
, Dst
, Src
, Size
, Align
, isVol
, DstPtrInfo
);
6239 if (Result
.getNode())
6243 checkAddrSpaceIsValidForLibcall(TLI
, DstPtrInfo
.getAddrSpace());
6245 // Emit a library call.
6246 TargetLowering::ArgListTy Args
;
6247 TargetLowering::ArgListEntry Entry
;
6248 Entry
.Node
= Dst
; Entry
.Ty
= Type::getInt8PtrTy(*getContext());
6249 Args
.push_back(Entry
);
6251 Entry
.Ty
= Src
.getValueType().getTypeForEVT(*getContext());
6252 Args
.push_back(Entry
);
6254 Entry
.Ty
= getDataLayout().getIntPtrType(*getContext());
6255 Args
.push_back(Entry
);
6257 // FIXME: pass in SDLoc
6258 TargetLowering::CallLoweringInfo
CLI(*this);
6261 .setLibCallee(TLI
->getLibcallCallingConv(RTLIB::MEMSET
),
6262 Dst
.getValueType().getTypeForEVT(*getContext()),
6263 getExternalSymbol(TLI
->getLibcallName(RTLIB::MEMSET
),
6264 TLI
->getPointerTy(getDataLayout())),
6267 .setTailCall(isTailCall
);
6269 std::pair
<SDValue
,SDValue
> CallResult
= TLI
->LowerCallTo(CLI
);
6270 return CallResult
.second
;
6273 SDValue
SelectionDAG::getAtomicMemset(SDValue Chain
, const SDLoc
&dl
,
6274 SDValue Dst
, unsigned DstAlign
,
6275 SDValue Value
, SDValue Size
, Type
*SizeTy
,
6276 unsigned ElemSz
, bool isTailCall
,
6277 MachinePointerInfo DstPtrInfo
) {
6278 // Emit a library call.
6279 TargetLowering::ArgListTy Args
;
6280 TargetLowering::ArgListEntry Entry
;
6281 Entry
.Ty
= getDataLayout().getIntPtrType(*getContext());
6283 Args
.push_back(Entry
);
6285 Entry
.Ty
= Type::getInt8Ty(*getContext());
6287 Args
.push_back(Entry
);
6291 Args
.push_back(Entry
);
6293 RTLIB::Libcall LibraryCall
=
6294 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz
);
6295 if (LibraryCall
== RTLIB::UNKNOWN_LIBCALL
)
6296 report_fatal_error("Unsupported element size");
6298 TargetLowering::CallLoweringInfo
CLI(*this);
6301 .setLibCallee(TLI
->getLibcallCallingConv(LibraryCall
),
6302 Type::getVoidTy(*getContext()),
6303 getExternalSymbol(TLI
->getLibcallName(LibraryCall
),
6304 TLI
->getPointerTy(getDataLayout())),
6307 .setTailCall(isTailCall
);
6309 std::pair
<SDValue
, SDValue
> CallResult
= TLI
->LowerCallTo(CLI
);
6310 return CallResult
.second
;
6313 SDValue
SelectionDAG::getAtomic(unsigned Opcode
, const SDLoc
&dl
, EVT MemVT
,
6314 SDVTList VTList
, ArrayRef
<SDValue
> Ops
,
6315 MachineMemOperand
*MMO
) {
6316 FoldingSetNodeID ID
;
6317 ID
.AddInteger(MemVT
.getRawBits());
6318 AddNodeIDNode(ID
, Opcode
, VTList
, Ops
);
6319 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6321 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6322 cast
<AtomicSDNode
>(E
)->refineAlignment(MMO
);
6323 return SDValue(E
, 0);
6326 auto *N
= newSDNode
<AtomicSDNode
>(Opcode
, dl
.getIROrder(), dl
.getDebugLoc(),
6327 VTList
, MemVT
, MMO
);
6328 createOperands(N
, Ops
);
6330 CSEMap
.InsertNode(N
, IP
);
6332 return SDValue(N
, 0);
6335 SDValue
SelectionDAG::getAtomicCmpSwap(unsigned Opcode
, const SDLoc
&dl
,
6336 EVT MemVT
, SDVTList VTs
, SDValue Chain
,
6337 SDValue Ptr
, SDValue Cmp
, SDValue Swp
,
6338 MachineMemOperand
*MMO
) {
6339 assert(Opcode
== ISD::ATOMIC_CMP_SWAP
||
6340 Opcode
== ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS
);
6341 assert(Cmp
.getValueType() == Swp
.getValueType() && "Invalid Atomic Op Types");
6343 SDValue Ops
[] = {Chain
, Ptr
, Cmp
, Swp
};
6344 return getAtomic(Opcode
, dl
, MemVT
, VTs
, Ops
, MMO
);
6347 SDValue
SelectionDAG::getAtomic(unsigned Opcode
, const SDLoc
&dl
, EVT MemVT
,
6348 SDValue Chain
, SDValue Ptr
, SDValue Val
,
6349 MachineMemOperand
*MMO
) {
6350 assert((Opcode
== ISD::ATOMIC_LOAD_ADD
||
6351 Opcode
== ISD::ATOMIC_LOAD_SUB
||
6352 Opcode
== ISD::ATOMIC_LOAD_AND
||
6353 Opcode
== ISD::ATOMIC_LOAD_CLR
||
6354 Opcode
== ISD::ATOMIC_LOAD_OR
||
6355 Opcode
== ISD::ATOMIC_LOAD_XOR
||
6356 Opcode
== ISD::ATOMIC_LOAD_NAND
||
6357 Opcode
== ISD::ATOMIC_LOAD_MIN
||
6358 Opcode
== ISD::ATOMIC_LOAD_MAX
||
6359 Opcode
== ISD::ATOMIC_LOAD_UMIN
||
6360 Opcode
== ISD::ATOMIC_LOAD_UMAX
||
6361 Opcode
== ISD::ATOMIC_LOAD_FADD
||
6362 Opcode
== ISD::ATOMIC_LOAD_FSUB
||
6363 Opcode
== ISD::ATOMIC_SWAP
||
6364 Opcode
== ISD::ATOMIC_STORE
) &&
6365 "Invalid Atomic Op");
6367 EVT VT
= Val
.getValueType();
6369 SDVTList VTs
= Opcode
== ISD::ATOMIC_STORE
? getVTList(MVT::Other
) :
6370 getVTList(VT
, MVT::Other
);
6371 SDValue Ops
[] = {Chain
, Ptr
, Val
};
6372 return getAtomic(Opcode
, dl
, MemVT
, VTs
, Ops
, MMO
);
6375 SDValue
SelectionDAG::getAtomic(unsigned Opcode
, const SDLoc
&dl
, EVT MemVT
,
6376 EVT VT
, SDValue Chain
, SDValue Ptr
,
6377 MachineMemOperand
*MMO
) {
6378 assert(Opcode
== ISD::ATOMIC_LOAD
&& "Invalid Atomic Op");
6380 SDVTList VTs
= getVTList(VT
, MVT::Other
);
6381 SDValue Ops
[] = {Chain
, Ptr
};
6382 return getAtomic(Opcode
, dl
, MemVT
, VTs
, Ops
, MMO
);
6385 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6386 SDValue
SelectionDAG::getMergeValues(ArrayRef
<SDValue
> Ops
, const SDLoc
&dl
) {
6387 if (Ops
.size() == 1)
6390 SmallVector
<EVT
, 4> VTs
;
6391 VTs
.reserve(Ops
.size());
6392 for (unsigned i
= 0; i
< Ops
.size(); ++i
)
6393 VTs
.push_back(Ops
[i
].getValueType());
6394 return getNode(ISD::MERGE_VALUES
, dl
, getVTList(VTs
), Ops
);
6397 SDValue
SelectionDAG::getMemIntrinsicNode(
6398 unsigned Opcode
, const SDLoc
&dl
, SDVTList VTList
, ArrayRef
<SDValue
> Ops
,
6399 EVT MemVT
, MachinePointerInfo PtrInfo
, unsigned Align
,
6400 MachineMemOperand::Flags Flags
, unsigned Size
) {
6401 if (Align
== 0) // Ensure that codegen never sees alignment 0
6402 Align
= getEVTAlignment(MemVT
);
6405 Size
= MemVT
.getStoreSize();
6407 MachineFunction
&MF
= getMachineFunction();
6408 MachineMemOperand
*MMO
=
6409 MF
.getMachineMemOperand(PtrInfo
, Flags
, Size
, Align
);
6411 return getMemIntrinsicNode(Opcode
, dl
, VTList
, Ops
, MemVT
, MMO
);
6414 SDValue
SelectionDAG::getMemIntrinsicNode(unsigned Opcode
, const SDLoc
&dl
,
6416 ArrayRef
<SDValue
> Ops
, EVT MemVT
,
6417 MachineMemOperand
*MMO
) {
6418 assert((Opcode
== ISD::INTRINSIC_VOID
||
6419 Opcode
== ISD::INTRINSIC_W_CHAIN
||
6420 Opcode
== ISD::PREFETCH
||
6421 Opcode
== ISD::LIFETIME_START
||
6422 Opcode
== ISD::LIFETIME_END
||
6423 ((int)Opcode
<= std::numeric_limits
<int>::max() &&
6424 (int)Opcode
>= ISD::FIRST_TARGET_MEMORY_OPCODE
)) &&
6425 "Opcode is not a memory-accessing opcode!");
6427 // Memoize the node unless it returns a flag.
6428 MemIntrinsicSDNode
*N
;
6429 if (VTList
.VTs
[VTList
.NumVTs
-1] != MVT::Glue
) {
6430 FoldingSetNodeID ID
;
6431 AddNodeIDNode(ID
, Opcode
, VTList
, Ops
);
6432 ID
.AddInteger(getSyntheticNodeSubclassData
<MemIntrinsicSDNode
>(
6433 Opcode
, dl
.getIROrder(), VTList
, MemVT
, MMO
));
6434 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6436 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6437 cast
<MemIntrinsicSDNode
>(E
)->refineAlignment(MMO
);
6438 return SDValue(E
, 0);
6441 N
= newSDNode
<MemIntrinsicSDNode
>(Opcode
, dl
.getIROrder(), dl
.getDebugLoc(),
6442 VTList
, MemVT
, MMO
);
6443 createOperands(N
, Ops
);
6445 CSEMap
.InsertNode(N
, IP
);
6447 N
= newSDNode
<MemIntrinsicSDNode
>(Opcode
, dl
.getIROrder(), dl
.getDebugLoc(),
6448 VTList
, MemVT
, MMO
);
6449 createOperands(N
, Ops
);
6452 return SDValue(N
, 0);
6455 SDValue
SelectionDAG::getLifetimeNode(bool IsStart
, const SDLoc
&dl
,
6456 SDValue Chain
, int FrameIndex
,
6457 int64_t Size
, int64_t Offset
) {
6458 const unsigned Opcode
= IsStart
? ISD::LIFETIME_START
: ISD::LIFETIME_END
;
6459 const auto VTs
= getVTList(MVT::Other
);
6462 getFrameIndex(FrameIndex
,
6463 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
6466 FoldingSetNodeID ID
;
6467 AddNodeIDNode(ID
, Opcode
, VTs
, Ops
);
6468 ID
.AddInteger(FrameIndex
);
6469 ID
.AddInteger(Size
);
6470 ID
.AddInteger(Offset
);
6472 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
))
6473 return SDValue(E
, 0);
6475 LifetimeSDNode
*N
= newSDNode
<LifetimeSDNode
>(
6476 Opcode
, dl
.getIROrder(), dl
.getDebugLoc(), VTs
, Size
, Offset
);
6477 createOperands(N
, Ops
);
6478 CSEMap
.InsertNode(N
, IP
);
6481 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6485 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6486 /// MachinePointerInfo record from it. This is particularly useful because the
6487 /// code generator has many cases where it doesn't bother passing in a
6488 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6489 static MachinePointerInfo
InferPointerInfo(const MachinePointerInfo
&Info
,
6490 SelectionDAG
&DAG
, SDValue Ptr
,
6491 int64_t Offset
= 0) {
6492 // If this is FI+Offset, we can model it.
6493 if (const FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(Ptr
))
6494 return MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(),
6495 FI
->getIndex(), Offset
);
6497 // If this is (FI+Offset1)+Offset2, we can model it.
6498 if (Ptr
.getOpcode() != ISD::ADD
||
6499 !isa
<ConstantSDNode
>(Ptr
.getOperand(1)) ||
6500 !isa
<FrameIndexSDNode
>(Ptr
.getOperand(0)))
6503 int FI
= cast
<FrameIndexSDNode
>(Ptr
.getOperand(0))->getIndex();
6504 return MachinePointerInfo::getFixedStack(
6505 DAG
.getMachineFunction(), FI
,
6506 Offset
+ cast
<ConstantSDNode
>(Ptr
.getOperand(1))->getSExtValue());
6509 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6510 /// MachinePointerInfo record from it. This is particularly useful because the
6511 /// code generator has many cases where it doesn't bother passing in a
6512 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6513 static MachinePointerInfo
InferPointerInfo(const MachinePointerInfo
&Info
,
6514 SelectionDAG
&DAG
, SDValue Ptr
,
6516 // If the 'Offset' value isn't a constant, we can't handle this.
6517 if (ConstantSDNode
*OffsetNode
= dyn_cast
<ConstantSDNode
>(OffsetOp
))
6518 return InferPointerInfo(Info
, DAG
, Ptr
, OffsetNode
->getSExtValue());
6519 if (OffsetOp
.isUndef())
6520 return InferPointerInfo(Info
, DAG
, Ptr
);
6524 SDValue
SelectionDAG::getLoad(ISD::MemIndexedMode AM
, ISD::LoadExtType ExtType
,
6525 EVT VT
, const SDLoc
&dl
, SDValue Chain
,
6526 SDValue Ptr
, SDValue Offset
,
6527 MachinePointerInfo PtrInfo
, EVT MemVT
,
6529 MachineMemOperand::Flags MMOFlags
,
6530 const AAMDNodes
&AAInfo
, const MDNode
*Ranges
) {
6531 assert(Chain
.getValueType() == MVT::Other
&&
6532 "Invalid chain type");
6533 if (Alignment
== 0) // Ensure that codegen never sees alignment 0
6534 Alignment
= getEVTAlignment(MemVT
);
6536 MMOFlags
|= MachineMemOperand::MOLoad
;
6537 assert((MMOFlags
& MachineMemOperand::MOStore
) == 0);
6538 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
6540 if (PtrInfo
.V
.isNull())
6541 PtrInfo
= InferPointerInfo(PtrInfo
, *this, Ptr
, Offset
);
6543 MachineFunction
&MF
= getMachineFunction();
6544 MachineMemOperand
*MMO
= MF
.getMachineMemOperand(
6545 PtrInfo
, MMOFlags
, MemVT
.getStoreSize(), Alignment
, AAInfo
, Ranges
);
6546 return getLoad(AM
, ExtType
, VT
, dl
, Chain
, Ptr
, Offset
, MemVT
, MMO
);
6549 SDValue
SelectionDAG::getLoad(ISD::MemIndexedMode AM
, ISD::LoadExtType ExtType
,
6550 EVT VT
, const SDLoc
&dl
, SDValue Chain
,
6551 SDValue Ptr
, SDValue Offset
, EVT MemVT
,
6552 MachineMemOperand
*MMO
) {
6554 ExtType
= ISD::NON_EXTLOAD
;
6555 } else if (ExtType
== ISD::NON_EXTLOAD
) {
6556 assert(VT
== MemVT
&& "Non-extending load from different memory type!");
6559 assert(MemVT
.getScalarType().bitsLT(VT
.getScalarType()) &&
6560 "Should only be an extending load, not truncating!");
6561 assert(VT
.isInteger() == MemVT
.isInteger() &&
6562 "Cannot convert from FP to Int or Int -> FP!");
6563 assert(VT
.isVector() == MemVT
.isVector() &&
6564 "Cannot use an ext load to convert to or from a vector!");
6565 assert((!VT
.isVector() ||
6566 VT
.getVectorNumElements() == MemVT
.getVectorNumElements()) &&
6567 "Cannot use an ext load to change the number of vector elements!");
6570 bool Indexed
= AM
!= ISD::UNINDEXED
;
6571 assert((Indexed
|| Offset
.isUndef()) && "Unindexed load with an offset!");
6573 SDVTList VTs
= Indexed
?
6574 getVTList(VT
, Ptr
.getValueType(), MVT::Other
) : getVTList(VT
, MVT::Other
);
6575 SDValue Ops
[] = { Chain
, Ptr
, Offset
};
6576 FoldingSetNodeID ID
;
6577 AddNodeIDNode(ID
, ISD::LOAD
, VTs
, Ops
);
6578 ID
.AddInteger(MemVT
.getRawBits());
6579 ID
.AddInteger(getSyntheticNodeSubclassData
<LoadSDNode
>(
6580 dl
.getIROrder(), VTs
, AM
, ExtType
, MemVT
, MMO
));
6581 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6583 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6584 cast
<LoadSDNode
>(E
)->refineAlignment(MMO
);
6585 return SDValue(E
, 0);
6587 auto *N
= newSDNode
<LoadSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(), VTs
, AM
,
6588 ExtType
, MemVT
, MMO
);
6589 createOperands(N
, Ops
);
6591 CSEMap
.InsertNode(N
, IP
);
6594 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6598 SDValue
SelectionDAG::getLoad(EVT VT
, const SDLoc
&dl
, SDValue Chain
,
6599 SDValue Ptr
, MachinePointerInfo PtrInfo
,
6601 MachineMemOperand::Flags MMOFlags
,
6602 const AAMDNodes
&AAInfo
, const MDNode
*Ranges
) {
6603 SDValue Undef
= getUNDEF(Ptr
.getValueType());
6604 return getLoad(ISD::UNINDEXED
, ISD::NON_EXTLOAD
, VT
, dl
, Chain
, Ptr
, Undef
,
6605 PtrInfo
, VT
, Alignment
, MMOFlags
, AAInfo
, Ranges
);
6608 SDValue
SelectionDAG::getLoad(EVT VT
, const SDLoc
&dl
, SDValue Chain
,
6609 SDValue Ptr
, MachineMemOperand
*MMO
) {
6610 SDValue Undef
= getUNDEF(Ptr
.getValueType());
6611 return getLoad(ISD::UNINDEXED
, ISD::NON_EXTLOAD
, VT
, dl
, Chain
, Ptr
, Undef
,
6615 SDValue
SelectionDAG::getExtLoad(ISD::LoadExtType ExtType
, const SDLoc
&dl
,
6616 EVT VT
, SDValue Chain
, SDValue Ptr
,
6617 MachinePointerInfo PtrInfo
, EVT MemVT
,
6619 MachineMemOperand::Flags MMOFlags
,
6620 const AAMDNodes
&AAInfo
) {
6621 SDValue Undef
= getUNDEF(Ptr
.getValueType());
6622 return getLoad(ISD::UNINDEXED
, ExtType
, VT
, dl
, Chain
, Ptr
, Undef
, PtrInfo
,
6623 MemVT
, Alignment
, MMOFlags
, AAInfo
);
6626 SDValue
SelectionDAG::getExtLoad(ISD::LoadExtType ExtType
, const SDLoc
&dl
,
6627 EVT VT
, SDValue Chain
, SDValue Ptr
, EVT MemVT
,
6628 MachineMemOperand
*MMO
) {
6629 SDValue Undef
= getUNDEF(Ptr
.getValueType());
6630 return getLoad(ISD::UNINDEXED
, ExtType
, VT
, dl
, Chain
, Ptr
, Undef
,
6634 SDValue
SelectionDAG::getIndexedLoad(SDValue OrigLoad
, const SDLoc
&dl
,
6635 SDValue Base
, SDValue Offset
,
6636 ISD::MemIndexedMode AM
) {
6637 LoadSDNode
*LD
= cast
<LoadSDNode
>(OrigLoad
);
6638 assert(LD
->getOffset().isUndef() && "Load is already a indexed load!");
6639 // Don't propagate the invariant or dereferenceable flags.
6641 LD
->getMemOperand()->getFlags() &
6642 ~(MachineMemOperand::MOInvariant
| MachineMemOperand::MODereferenceable
);
6643 return getLoad(AM
, LD
->getExtensionType(), OrigLoad
.getValueType(), dl
,
6644 LD
->getChain(), Base
, Offset
, LD
->getPointerInfo(),
6645 LD
->getMemoryVT(), LD
->getAlignment(), MMOFlags
,
6649 SDValue
SelectionDAG::getStore(SDValue Chain
, const SDLoc
&dl
, SDValue Val
,
6650 SDValue Ptr
, MachinePointerInfo PtrInfo
,
6652 MachineMemOperand::Flags MMOFlags
,
6653 const AAMDNodes
&AAInfo
) {
6654 assert(Chain
.getValueType() == MVT::Other
&& "Invalid chain type");
6655 if (Alignment
== 0) // Ensure that codegen never sees alignment 0
6656 Alignment
= getEVTAlignment(Val
.getValueType());
6658 MMOFlags
|= MachineMemOperand::MOStore
;
6659 assert((MMOFlags
& MachineMemOperand::MOLoad
) == 0);
6661 if (PtrInfo
.V
.isNull())
6662 PtrInfo
= InferPointerInfo(PtrInfo
, *this, Ptr
);
6664 MachineFunction
&MF
= getMachineFunction();
6665 MachineMemOperand
*MMO
= MF
.getMachineMemOperand(
6666 PtrInfo
, MMOFlags
, Val
.getValueType().getStoreSize(), Alignment
, AAInfo
);
6667 return getStore(Chain
, dl
, Val
, Ptr
, MMO
);
6670 SDValue
SelectionDAG::getStore(SDValue Chain
, const SDLoc
&dl
, SDValue Val
,
6671 SDValue Ptr
, MachineMemOperand
*MMO
) {
6672 assert(Chain
.getValueType() == MVT::Other
&&
6673 "Invalid chain type");
6674 EVT VT
= Val
.getValueType();
6675 SDVTList VTs
= getVTList(MVT::Other
);
6676 SDValue Undef
= getUNDEF(Ptr
.getValueType());
6677 SDValue Ops
[] = { Chain
, Val
, Ptr
, Undef
};
6678 FoldingSetNodeID ID
;
6679 AddNodeIDNode(ID
, ISD::STORE
, VTs
, Ops
);
6680 ID
.AddInteger(VT
.getRawBits());
6681 ID
.AddInteger(getSyntheticNodeSubclassData
<StoreSDNode
>(
6682 dl
.getIROrder(), VTs
, ISD::UNINDEXED
, false, VT
, MMO
));
6683 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6685 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6686 cast
<StoreSDNode
>(E
)->refineAlignment(MMO
);
6687 return SDValue(E
, 0);
6689 auto *N
= newSDNode
<StoreSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(), VTs
,
6690 ISD::UNINDEXED
, false, VT
, MMO
);
6691 createOperands(N
, Ops
);
6693 CSEMap
.InsertNode(N
, IP
);
6696 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6700 SDValue
SelectionDAG::getTruncStore(SDValue Chain
, const SDLoc
&dl
, SDValue Val
,
6701 SDValue Ptr
, MachinePointerInfo PtrInfo
,
6702 EVT SVT
, unsigned Alignment
,
6703 MachineMemOperand::Flags MMOFlags
,
6704 const AAMDNodes
&AAInfo
) {
6705 assert(Chain
.getValueType() == MVT::Other
&&
6706 "Invalid chain type");
6707 if (Alignment
== 0) // Ensure that codegen never sees alignment 0
6708 Alignment
= getEVTAlignment(SVT
);
6710 MMOFlags
|= MachineMemOperand::MOStore
;
6711 assert((MMOFlags
& MachineMemOperand::MOLoad
) == 0);
6713 if (PtrInfo
.V
.isNull())
6714 PtrInfo
= InferPointerInfo(PtrInfo
, *this, Ptr
);
6716 MachineFunction
&MF
= getMachineFunction();
6717 MachineMemOperand
*MMO
= MF
.getMachineMemOperand(
6718 PtrInfo
, MMOFlags
, SVT
.getStoreSize(), Alignment
, AAInfo
);
6719 return getTruncStore(Chain
, dl
, Val
, Ptr
, SVT
, MMO
);
6722 SDValue
SelectionDAG::getTruncStore(SDValue Chain
, const SDLoc
&dl
, SDValue Val
,
6723 SDValue Ptr
, EVT SVT
,
6724 MachineMemOperand
*MMO
) {
6725 EVT VT
= Val
.getValueType();
6727 assert(Chain
.getValueType() == MVT::Other
&&
6728 "Invalid chain type");
6730 return getStore(Chain
, dl
, Val
, Ptr
, MMO
);
6732 assert(SVT
.getScalarType().bitsLT(VT
.getScalarType()) &&
6733 "Should only be a truncating store, not extending!");
6734 assert(VT
.isInteger() == SVT
.isInteger() &&
6735 "Can't do FP-INT conversion!");
6736 assert(VT
.isVector() == SVT
.isVector() &&
6737 "Cannot use trunc store to convert to or from a vector!");
6738 assert((!VT
.isVector() ||
6739 VT
.getVectorNumElements() == SVT
.getVectorNumElements()) &&
6740 "Cannot use trunc store to change the number of vector elements!");
6742 SDVTList VTs
= getVTList(MVT::Other
);
6743 SDValue Undef
= getUNDEF(Ptr
.getValueType());
6744 SDValue Ops
[] = { Chain
, Val
, Ptr
, Undef
};
6745 FoldingSetNodeID ID
;
6746 AddNodeIDNode(ID
, ISD::STORE
, VTs
, Ops
);
6747 ID
.AddInteger(SVT
.getRawBits());
6748 ID
.AddInteger(getSyntheticNodeSubclassData
<StoreSDNode
>(
6749 dl
.getIROrder(), VTs
, ISD::UNINDEXED
, true, SVT
, MMO
));
6750 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6752 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6753 cast
<StoreSDNode
>(E
)->refineAlignment(MMO
);
6754 return SDValue(E
, 0);
6756 auto *N
= newSDNode
<StoreSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(), VTs
,
6757 ISD::UNINDEXED
, true, SVT
, MMO
);
6758 createOperands(N
, Ops
);
6760 CSEMap
.InsertNode(N
, IP
);
6763 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6767 SDValue
SelectionDAG::getIndexedStore(SDValue OrigStore
, const SDLoc
&dl
,
6768 SDValue Base
, SDValue Offset
,
6769 ISD::MemIndexedMode AM
) {
6770 StoreSDNode
*ST
= cast
<StoreSDNode
>(OrigStore
);
6771 assert(ST
->getOffset().isUndef() && "Store is already a indexed store!");
6772 SDVTList VTs
= getVTList(Base
.getValueType(), MVT::Other
);
6773 SDValue Ops
[] = { ST
->getChain(), ST
->getValue(), Base
, Offset
};
6774 FoldingSetNodeID ID
;
6775 AddNodeIDNode(ID
, ISD::STORE
, VTs
, Ops
);
6776 ID
.AddInteger(ST
->getMemoryVT().getRawBits());
6777 ID
.AddInteger(ST
->getRawSubclassData());
6778 ID
.AddInteger(ST
->getPointerInfo().getAddrSpace());
6780 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
))
6781 return SDValue(E
, 0);
6783 auto *N
= newSDNode
<StoreSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(), VTs
, AM
,
6784 ST
->isTruncatingStore(), ST
->getMemoryVT(),
6785 ST
->getMemOperand());
6786 createOperands(N
, Ops
);
6788 CSEMap
.InsertNode(N
, IP
);
6791 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6795 SDValue
SelectionDAG::getMaskedLoad(EVT VT
, const SDLoc
&dl
, SDValue Chain
,
6796 SDValue Ptr
, SDValue Mask
, SDValue PassThru
,
6797 EVT MemVT
, MachineMemOperand
*MMO
,
6798 ISD::LoadExtType ExtTy
, bool isExpanding
) {
6799 SDVTList VTs
= getVTList(VT
, MVT::Other
);
6800 SDValue Ops
[] = { Chain
, Ptr
, Mask
, PassThru
};
6801 FoldingSetNodeID ID
;
6802 AddNodeIDNode(ID
, ISD::MLOAD
, VTs
, Ops
);
6803 ID
.AddInteger(VT
.getRawBits());
6804 ID
.AddInteger(getSyntheticNodeSubclassData
<MaskedLoadSDNode
>(
6805 dl
.getIROrder(), VTs
, ExtTy
, isExpanding
, MemVT
, MMO
));
6806 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6808 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6809 cast
<MaskedLoadSDNode
>(E
)->refineAlignment(MMO
);
6810 return SDValue(E
, 0);
6812 auto *N
= newSDNode
<MaskedLoadSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(), VTs
,
6813 ExtTy
, isExpanding
, MemVT
, MMO
);
6814 createOperands(N
, Ops
);
6816 CSEMap
.InsertNode(N
, IP
);
6819 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6823 SDValue
SelectionDAG::getMaskedStore(SDValue Chain
, const SDLoc
&dl
,
6824 SDValue Val
, SDValue Ptr
, SDValue Mask
,
6825 EVT MemVT
, MachineMemOperand
*MMO
,
6826 bool IsTruncating
, bool IsCompressing
) {
6827 assert(Chain
.getValueType() == MVT::Other
&&
6828 "Invalid chain type");
6829 EVT VT
= Val
.getValueType();
6830 SDVTList VTs
= getVTList(MVT::Other
);
6831 SDValue Ops
[] = { Chain
, Val
, Ptr
, Mask
};
6832 FoldingSetNodeID ID
;
6833 AddNodeIDNode(ID
, ISD::MSTORE
, VTs
, Ops
);
6834 ID
.AddInteger(VT
.getRawBits());
6835 ID
.AddInteger(getSyntheticNodeSubclassData
<MaskedStoreSDNode
>(
6836 dl
.getIROrder(), VTs
, IsTruncating
, IsCompressing
, MemVT
, MMO
));
6837 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6839 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6840 cast
<MaskedStoreSDNode
>(E
)->refineAlignment(MMO
);
6841 return SDValue(E
, 0);
6843 auto *N
= newSDNode
<MaskedStoreSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(), VTs
,
6844 IsTruncating
, IsCompressing
, MemVT
, MMO
);
6845 createOperands(N
, Ops
);
6847 CSEMap
.InsertNode(N
, IP
);
6850 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6854 SDValue
SelectionDAG::getMaskedGather(SDVTList VTs
, EVT VT
, const SDLoc
&dl
,
6855 ArrayRef
<SDValue
> Ops
,
6856 MachineMemOperand
*MMO
) {
6857 assert(Ops
.size() == 6 && "Incompatible number of operands");
6859 FoldingSetNodeID ID
;
6860 AddNodeIDNode(ID
, ISD::MGATHER
, VTs
, Ops
);
6861 ID
.AddInteger(VT
.getRawBits());
6862 ID
.AddInteger(getSyntheticNodeSubclassData
<MaskedGatherSDNode
>(
6863 dl
.getIROrder(), VTs
, VT
, MMO
));
6864 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6866 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6867 cast
<MaskedGatherSDNode
>(E
)->refineAlignment(MMO
);
6868 return SDValue(E
, 0);
6871 auto *N
= newSDNode
<MaskedGatherSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(),
6873 createOperands(N
, Ops
);
6875 assert(N
->getPassThru().getValueType() == N
->getValueType(0) &&
6876 "Incompatible type of the PassThru value in MaskedGatherSDNode");
6877 assert(N
->getMask().getValueType().getVectorNumElements() ==
6878 N
->getValueType(0).getVectorNumElements() &&
6879 "Vector width mismatch between mask and data");
6880 assert(N
->getIndex().getValueType().getVectorNumElements() >=
6881 N
->getValueType(0).getVectorNumElements() &&
6882 "Vector width mismatch between index and data");
6883 assert(isa
<ConstantSDNode
>(N
->getScale()) &&
6884 cast
<ConstantSDNode
>(N
->getScale())->getAPIntValue().isPowerOf2() &&
6885 "Scale should be a constant power of 2");
6887 CSEMap
.InsertNode(N
, IP
);
6890 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6894 SDValue
SelectionDAG::getMaskedScatter(SDVTList VTs
, EVT VT
, const SDLoc
&dl
,
6895 ArrayRef
<SDValue
> Ops
,
6896 MachineMemOperand
*MMO
) {
6897 assert(Ops
.size() == 6 && "Incompatible number of operands");
6899 FoldingSetNodeID ID
;
6900 AddNodeIDNode(ID
, ISD::MSCATTER
, VTs
, Ops
);
6901 ID
.AddInteger(VT
.getRawBits());
6902 ID
.AddInteger(getSyntheticNodeSubclassData
<MaskedScatterSDNode
>(
6903 dl
.getIROrder(), VTs
, VT
, MMO
));
6904 ID
.AddInteger(MMO
->getPointerInfo().getAddrSpace());
6906 if (SDNode
*E
= FindNodeOrInsertPos(ID
, dl
, IP
)) {
6907 cast
<MaskedScatterSDNode
>(E
)->refineAlignment(MMO
);
6908 return SDValue(E
, 0);
6910 auto *N
= newSDNode
<MaskedScatterSDNode
>(dl
.getIROrder(), dl
.getDebugLoc(),
6912 createOperands(N
, Ops
);
6914 assert(N
->getMask().getValueType().getVectorNumElements() ==
6915 N
->getValue().getValueType().getVectorNumElements() &&
6916 "Vector width mismatch between mask and data");
6917 assert(N
->getIndex().getValueType().getVectorNumElements() >=
6918 N
->getValue().getValueType().getVectorNumElements() &&
6919 "Vector width mismatch between index and data");
6920 assert(isa
<ConstantSDNode
>(N
->getScale()) &&
6921 cast
<ConstantSDNode
>(N
->getScale())->getAPIntValue().isPowerOf2() &&
6922 "Scale should be a constant power of 2");
6924 CSEMap
.InsertNode(N
, IP
);
6927 NewSDValueDbgMsg(V
, "Creating new node: ", this);
6931 SDValue
SelectionDAG::simplifySelect(SDValue Cond
, SDValue T
, SDValue F
) {
6932 // select undef, T, F --> T (if T is a constant), otherwise F
6933 // select, ?, undef, F --> F
6934 // select, ?, T, undef --> T
6936 return isConstantValueOfAnyType(T
) ? T
: F
;
6942 // select true, T, F --> T
6943 // select false, T, F --> F
6944 if (auto *CondC
= dyn_cast
<ConstantSDNode
>(Cond
))
6945 return CondC
->isNullValue() ? F
: T
;
6947 // TODO: This should simplify VSELECT with constant condition using something
6948 // like this (but check boolean contents to be complete?):
6949 // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
6951 // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
6954 // select ?, T, T --> T
6961 SDValue
SelectionDAG::simplifyShift(SDValue X
, SDValue Y
) {
6962 // shift undef, Y --> 0 (can always assume that the undef value is 0)
6964 return getConstant(0, SDLoc(X
.getNode()), X
.getValueType());
6965 // shift X, undef --> undef (because it may shift by the bitwidth)
6967 return getUNDEF(X
.getValueType());
6971 if (isNullOrNullSplat(X
) || isNullOrNullSplat(Y
))
6974 // shift X, C >= bitwidth(X) --> undef
6975 // All vector elements must be too big (or undef) to avoid partial undefs.
6976 auto isShiftTooBig
= [X
](ConstantSDNode
*Val
) {
6977 return !Val
|| Val
->getAPIntValue().uge(X
.getScalarValueSizeInBits());
6979 if (ISD::matchUnaryPredicate(Y
, isShiftTooBig
, true))
6980 return getUNDEF(X
.getValueType());
6985 // TODO: Use fast-math-flags to enable more simplifications.
6986 SDValue
SelectionDAG::simplifyFPBinop(unsigned Opcode
, SDValue X
, SDValue Y
) {
6987 ConstantFPSDNode
*YC
= isConstOrConstSplatFP(Y
, /* AllowUndefs */ true);
6992 if (Opcode
== ISD::FADD
)
6993 if (YC
->getValueAPF().isNegZero())
6997 if (Opcode
== ISD::FSUB
)
6998 if (YC
->getValueAPF().isPosZero())
7003 if (Opcode
== ISD::FMUL
|| Opcode
== ISD::FDIV
)
7004 if (YC
->getValueAPF().isExactlyValue(1.0))
7010 SDValue
SelectionDAG::getVAArg(EVT VT
, const SDLoc
&dl
, SDValue Chain
,
7011 SDValue Ptr
, SDValue SV
, unsigned Align
) {
7012 SDValue Ops
[] = { Chain
, Ptr
, SV
, getTargetConstant(Align
, dl
, MVT::i32
) };
7013 return getNode(ISD::VAARG
, dl
, getVTList(VT
, MVT::Other
), Ops
);
7016 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, EVT VT
,
7017 ArrayRef
<SDUse
> Ops
) {
7018 switch (Ops
.size()) {
7019 case 0: return getNode(Opcode
, DL
, VT
);
7020 case 1: return getNode(Opcode
, DL
, VT
, static_cast<const SDValue
>(Ops
[0]));
7021 case 2: return getNode(Opcode
, DL
, VT
, Ops
[0], Ops
[1]);
7022 case 3: return getNode(Opcode
, DL
, VT
, Ops
[0], Ops
[1], Ops
[2]);
7026 // Copy from an SDUse array into an SDValue array for use with
7027 // the regular getNode logic.
7028 SmallVector
<SDValue
, 8> NewOps(Ops
.begin(), Ops
.end());
7029 return getNode(Opcode
, DL
, VT
, NewOps
);
7032 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, EVT VT
,
7033 ArrayRef
<SDValue
> Ops
, const SDNodeFlags Flags
) {
7034 unsigned NumOps
= Ops
.size();
7036 case 0: return getNode(Opcode
, DL
, VT
);
7037 case 1: return getNode(Opcode
, DL
, VT
, Ops
[0], Flags
);
7038 case 2: return getNode(Opcode
, DL
, VT
, Ops
[0], Ops
[1], Flags
);
7039 case 3: return getNode(Opcode
, DL
, VT
, Ops
[0], Ops
[1], Ops
[2], Flags
);
7045 case ISD::BUILD_VECTOR
:
7046 // Attempt to simplify BUILD_VECTOR.
7047 if (SDValue V
= FoldBUILD_VECTOR(DL
, VT
, Ops
, *this))
7050 case ISD::CONCAT_VECTORS
:
7051 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
7052 if (SDValue V
= FoldCONCAT_VECTORS(DL
, VT
, Ops
, *this))
7055 case ISD::SELECT_CC
:
7056 assert(NumOps
== 5 && "SELECT_CC takes 5 operands!");
7057 assert(Ops
[0].getValueType() == Ops
[1].getValueType() &&
7058 "LHS and RHS of condition must have same type!");
7059 assert(Ops
[2].getValueType() == Ops
[3].getValueType() &&
7060 "True and False arms of SelectCC must have same type!");
7061 assert(Ops
[2].getValueType() == VT
&&
7062 "select_cc node must be of same type as true and false value!");
7065 assert(NumOps
== 5 && "BR_CC takes 5 operands!");
7066 assert(Ops
[2].getValueType() == Ops
[3].getValueType() &&
7067 "LHS/RHS of comparison should match types!");
7073 SDVTList VTs
= getVTList(VT
);
7075 if (VT
!= MVT::Glue
) {
7076 FoldingSetNodeID ID
;
7077 AddNodeIDNode(ID
, Opcode
, VTs
, Ops
);
7080 if (SDNode
*E
= FindNodeOrInsertPos(ID
, DL
, IP
))
7081 return SDValue(E
, 0);
7083 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
7084 createOperands(N
, Ops
);
7086 CSEMap
.InsertNode(N
, IP
);
7088 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
7089 createOperands(N
, Ops
);
7094 NewSDValueDbgMsg(V
, "Creating new node: ", this);
7098 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
,
7099 ArrayRef
<EVT
> ResultTys
, ArrayRef
<SDValue
> Ops
) {
7100 return getNode(Opcode
, DL
, getVTList(ResultTys
), Ops
);
7103 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, SDVTList VTList
,
7104 ArrayRef
<SDValue
> Ops
) {
7105 if (VTList
.NumVTs
== 1)
7106 return getNode(Opcode
, DL
, VTList
.VTs
[0], Ops
);
7110 // FIXME: figure out how to safely handle things like
7111 // int foo(int x) { return 1 << (x & 255); }
7112 // int bar() { return foo(256); }
7113 case ISD::SRA_PARTS
:
7114 case ISD::SRL_PARTS
:
7115 case ISD::SHL_PARTS
:
7116 if (N3
.getOpcode() == ISD::SIGN_EXTEND_INREG
&&
7117 cast
<VTSDNode
>(N3
.getOperand(1))->getVT() != MVT::i1
)
7118 return getNode(Opcode
, DL
, VT
, N1
, N2
, N3
.getOperand(0));
7119 else if (N3
.getOpcode() == ISD::AND
)
7120 if (ConstantSDNode
*AndRHS
= dyn_cast
<ConstantSDNode
>(N3
.getOperand(1))) {
7121 // If the and is only masking out bits that cannot effect the shift,
7122 // eliminate the and.
7123 unsigned NumBits
= VT
.getScalarSizeInBits()*2;
7124 if ((AndRHS
->getValue() & (NumBits
-1)) == NumBits
-1)
7125 return getNode(Opcode
, DL
, VT
, N1
, N2
, N3
.getOperand(0));
7131 // Memoize the node unless it returns a flag.
7133 if (VTList
.VTs
[VTList
.NumVTs
-1] != MVT::Glue
) {
7134 FoldingSetNodeID ID
;
7135 AddNodeIDNode(ID
, Opcode
, VTList
, Ops
);
7137 if (SDNode
*E
= FindNodeOrInsertPos(ID
, DL
, IP
))
7138 return SDValue(E
, 0);
7140 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTList
);
7141 createOperands(N
, Ops
);
7142 CSEMap
.InsertNode(N
, IP
);
7144 N
= newSDNode
<SDNode
>(Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTList
);
7145 createOperands(N
, Ops
);
7149 NewSDValueDbgMsg(V
, "Creating new node: ", this);
7153 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
,
7155 return getNode(Opcode
, DL
, VTList
, None
);
7158 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, SDVTList VTList
,
7160 SDValue Ops
[] = { N1
};
7161 return getNode(Opcode
, DL
, VTList
, Ops
);
7164 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, SDVTList VTList
,
7165 SDValue N1
, SDValue N2
) {
7166 SDValue Ops
[] = { N1
, N2
};
7167 return getNode(Opcode
, DL
, VTList
, Ops
);
7170 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, SDVTList VTList
,
7171 SDValue N1
, SDValue N2
, SDValue N3
) {
7172 SDValue Ops
[] = { N1
, N2
, N3
};
7173 return getNode(Opcode
, DL
, VTList
, Ops
);
7176 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, SDVTList VTList
,
7177 SDValue N1
, SDValue N2
, SDValue N3
, SDValue N4
) {
7178 SDValue Ops
[] = { N1
, N2
, N3
, N4
};
7179 return getNode(Opcode
, DL
, VTList
, Ops
);
7182 SDValue
SelectionDAG::getNode(unsigned Opcode
, const SDLoc
&DL
, SDVTList VTList
,
7183 SDValue N1
, SDValue N2
, SDValue N3
, SDValue N4
,
7185 SDValue Ops
[] = { N1
, N2
, N3
, N4
, N5
};
7186 return getNode(Opcode
, DL
, VTList
, Ops
);
7189 SDVTList
SelectionDAG::getVTList(EVT VT
) {
7190 return makeVTList(SDNode::getValueTypeList(VT
), 1);
7193 SDVTList
SelectionDAG::getVTList(EVT VT1
, EVT VT2
) {
7194 FoldingSetNodeID ID
;
7196 ID
.AddInteger(VT1
.getRawBits());
7197 ID
.AddInteger(VT2
.getRawBits());
7200 SDVTListNode
*Result
= VTListMap
.FindNodeOrInsertPos(ID
, IP
);
7202 EVT
*Array
= Allocator
.Allocate
<EVT
>(2);
7205 Result
= new (Allocator
) SDVTListNode(ID
.Intern(Allocator
), Array
, 2);
7206 VTListMap
.InsertNode(Result
, IP
);
7208 return Result
->getSDVTList();
7211 SDVTList
SelectionDAG::getVTList(EVT VT1
, EVT VT2
, EVT VT3
) {
7212 FoldingSetNodeID ID
;
7214 ID
.AddInteger(VT1
.getRawBits());
7215 ID
.AddInteger(VT2
.getRawBits());
7216 ID
.AddInteger(VT3
.getRawBits());
7219 SDVTListNode
*Result
= VTListMap
.FindNodeOrInsertPos(ID
, IP
);
7221 EVT
*Array
= Allocator
.Allocate
<EVT
>(3);
7225 Result
= new (Allocator
) SDVTListNode(ID
.Intern(Allocator
), Array
, 3);
7226 VTListMap
.InsertNode(Result
, IP
);
7228 return Result
->getSDVTList();
7231 SDVTList
SelectionDAG::getVTList(EVT VT1
, EVT VT2
, EVT VT3
, EVT VT4
) {
7232 FoldingSetNodeID ID
;
7234 ID
.AddInteger(VT1
.getRawBits());
7235 ID
.AddInteger(VT2
.getRawBits());
7236 ID
.AddInteger(VT3
.getRawBits());
7237 ID
.AddInteger(VT4
.getRawBits());
7240 SDVTListNode
*Result
= VTListMap
.FindNodeOrInsertPos(ID
, IP
);
7242 EVT
*Array
= Allocator
.Allocate
<EVT
>(4);
7247 Result
= new (Allocator
) SDVTListNode(ID
.Intern(Allocator
), Array
, 4);
7248 VTListMap
.InsertNode(Result
, IP
);
7250 return Result
->getSDVTList();
7253 SDVTList
SelectionDAG::getVTList(ArrayRef
<EVT
> VTs
) {
7254 unsigned NumVTs
= VTs
.size();
7255 FoldingSetNodeID ID
;
7256 ID
.AddInteger(NumVTs
);
7257 for (unsigned index
= 0; index
< NumVTs
; index
++) {
7258 ID
.AddInteger(VTs
[index
].getRawBits());
7262 SDVTListNode
*Result
= VTListMap
.FindNodeOrInsertPos(ID
, IP
);
7264 EVT
*Array
= Allocator
.Allocate
<EVT
>(NumVTs
);
7265 llvm::copy(VTs
, Array
);
7266 Result
= new (Allocator
) SDVTListNode(ID
.Intern(Allocator
), Array
, NumVTs
);
7267 VTListMap
.InsertNode(Result
, IP
);
7269 return Result
->getSDVTList();
7273 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7274 /// specified operands. If the resultant node already exists in the DAG,
7275 /// this does not modify the specified node, instead it returns the node that
7276 /// already exists. If the resultant node does not exist in the DAG, the
7277 /// input node is returned. As a degenerate case, if you specify the same
7278 /// input operands as the node already has, the input node is returned.
7279 SDNode
*SelectionDAG::UpdateNodeOperands(SDNode
*N
, SDValue Op
) {
7280 assert(N
->getNumOperands() == 1 && "Update with wrong number of operands");
7282 // Check to see if there is no change.
7283 if (Op
== N
->getOperand(0)) return N
;
7285 // See if the modified node already exists.
7286 void *InsertPos
= nullptr;
7287 if (SDNode
*Existing
= FindModifiedNodeSlot(N
, Op
, InsertPos
))
7290 // Nope it doesn't. Remove the node from its current place in the maps.
7292 if (!RemoveNodeFromCSEMaps(N
))
7293 InsertPos
= nullptr;
7295 // Now we update the operands.
7296 N
->OperandList
[0].set(Op
);
7298 updateDivergence(N
);
7299 // If this gets put into a CSE map, add it.
7300 if (InsertPos
) CSEMap
.InsertNode(N
, InsertPos
);
7304 SDNode
*SelectionDAG::UpdateNodeOperands(SDNode
*N
, SDValue Op1
, SDValue Op2
) {
7305 assert(N
->getNumOperands() == 2 && "Update with wrong number of operands");
7307 // Check to see if there is no change.
7308 if (Op1
== N
->getOperand(0) && Op2
== N
->getOperand(1))
7309 return N
; // No operands changed, just return the input node.
7311 // See if the modified node already exists.
7312 void *InsertPos
= nullptr;
7313 if (SDNode
*Existing
= FindModifiedNodeSlot(N
, Op1
, Op2
, InsertPos
))
7316 // Nope it doesn't. Remove the node from its current place in the maps.
7318 if (!RemoveNodeFromCSEMaps(N
))
7319 InsertPos
= nullptr;
7321 // Now we update the operands.
7322 if (N
->OperandList
[0] != Op1
)
7323 N
->OperandList
[0].set(Op1
);
7324 if (N
->OperandList
[1] != Op2
)
7325 N
->OperandList
[1].set(Op2
);
7327 updateDivergence(N
);
7328 // If this gets put into a CSE map, add it.
7329 if (InsertPos
) CSEMap
.InsertNode(N
, InsertPos
);
7333 SDNode
*SelectionDAG::
7334 UpdateNodeOperands(SDNode
*N
, SDValue Op1
, SDValue Op2
, SDValue Op3
) {
7335 SDValue Ops
[] = { Op1
, Op2
, Op3
};
7336 return UpdateNodeOperands(N
, Ops
);
7339 SDNode
*SelectionDAG::
7340 UpdateNodeOperands(SDNode
*N
, SDValue Op1
, SDValue Op2
,
7341 SDValue Op3
, SDValue Op4
) {
7342 SDValue Ops
[] = { Op1
, Op2
, Op3
, Op4
};
7343 return UpdateNodeOperands(N
, Ops
);
7346 SDNode
*SelectionDAG::
7347 UpdateNodeOperands(SDNode
*N
, SDValue Op1
, SDValue Op2
,
7348 SDValue Op3
, SDValue Op4
, SDValue Op5
) {
7349 SDValue Ops
[] = { Op1
, Op2
, Op3
, Op4
, Op5
};
7350 return UpdateNodeOperands(N
, Ops
);
7353 SDNode
*SelectionDAG::
7354 UpdateNodeOperands(SDNode
*N
, ArrayRef
<SDValue
> Ops
) {
7355 unsigned NumOps
= Ops
.size();
7356 assert(N
->getNumOperands() == NumOps
&&
7357 "Update with wrong number of operands");
7359 // If no operands changed just return the input node.
7360 if (std::equal(Ops
.begin(), Ops
.end(), N
->op_begin()))
7363 // See if the modified node already exists.
7364 void *InsertPos
= nullptr;
7365 if (SDNode
*Existing
= FindModifiedNodeSlot(N
, Ops
, InsertPos
))
7368 // Nope it doesn't. Remove the node from its current place in the maps.
7370 if (!RemoveNodeFromCSEMaps(N
))
7371 InsertPos
= nullptr;
7373 // Now we update the operands.
7374 for (unsigned i
= 0; i
!= NumOps
; ++i
)
7375 if (N
->OperandList
[i
] != Ops
[i
])
7376 N
->OperandList
[i
].set(Ops
[i
]);
7378 updateDivergence(N
);
7379 // If this gets put into a CSE map, add it.
7380 if (InsertPos
) CSEMap
.InsertNode(N
, InsertPos
);
7384 /// DropOperands - Release the operands and set this node to have
7386 void SDNode::DropOperands() {
7387 // Unlike the code in MorphNodeTo that does this, we don't need to
7388 // watch for dead nodes here.
7389 for (op_iterator I
= op_begin(), E
= op_end(); I
!= E
; ) {
7395 void SelectionDAG::setNodeMemRefs(MachineSDNode
*N
,
7396 ArrayRef
<MachineMemOperand
*> NewMemRefs
) {
7397 if (NewMemRefs
.empty()) {
7402 // Check if we can avoid allocating by storing a single reference directly.
7403 if (NewMemRefs
.size() == 1) {
7404 N
->MemRefs
= NewMemRefs
[0];
7409 MachineMemOperand
**MemRefsBuffer
=
7410 Allocator
.template Allocate
<MachineMemOperand
*>(NewMemRefs
.size());
7411 llvm::copy(NewMemRefs
, MemRefsBuffer
);
7412 N
->MemRefs
= MemRefsBuffer
;
7413 N
->NumMemRefs
= static_cast<int>(NewMemRefs
.size());
7416 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
7419 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7421 SDVTList VTs
= getVTList(VT
);
7422 return SelectNodeTo(N
, MachineOpc
, VTs
, None
);
7425 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7426 EVT VT
, SDValue Op1
) {
7427 SDVTList VTs
= getVTList(VT
);
7428 SDValue Ops
[] = { Op1
};
7429 return SelectNodeTo(N
, MachineOpc
, VTs
, Ops
);
7432 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7433 EVT VT
, SDValue Op1
,
7435 SDVTList VTs
= getVTList(VT
);
7436 SDValue Ops
[] = { Op1
, Op2
};
7437 return SelectNodeTo(N
, MachineOpc
, VTs
, Ops
);
7440 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7441 EVT VT
, SDValue Op1
,
7442 SDValue Op2
, SDValue Op3
) {
7443 SDVTList VTs
= getVTList(VT
);
7444 SDValue Ops
[] = { Op1
, Op2
, Op3
};
7445 return SelectNodeTo(N
, MachineOpc
, VTs
, Ops
);
7448 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7449 EVT VT
, ArrayRef
<SDValue
> Ops
) {
7450 SDVTList VTs
= getVTList(VT
);
7451 return SelectNodeTo(N
, MachineOpc
, VTs
, Ops
);
7454 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7455 EVT VT1
, EVT VT2
, ArrayRef
<SDValue
> Ops
) {
7456 SDVTList VTs
= getVTList(VT1
, VT2
);
7457 return SelectNodeTo(N
, MachineOpc
, VTs
, Ops
);
7460 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7462 SDVTList VTs
= getVTList(VT1
, VT2
);
7463 return SelectNodeTo(N
, MachineOpc
, VTs
, None
);
7466 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7467 EVT VT1
, EVT VT2
, EVT VT3
,
7468 ArrayRef
<SDValue
> Ops
) {
7469 SDVTList VTs
= getVTList(VT1
, VT2
, VT3
);
7470 return SelectNodeTo(N
, MachineOpc
, VTs
, Ops
);
7473 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7475 SDValue Op1
, SDValue Op2
) {
7476 SDVTList VTs
= getVTList(VT1
, VT2
);
7477 SDValue Ops
[] = { Op1
, Op2
};
7478 return SelectNodeTo(N
, MachineOpc
, VTs
, Ops
);
7481 SDNode
*SelectionDAG::SelectNodeTo(SDNode
*N
, unsigned MachineOpc
,
7482 SDVTList VTs
,ArrayRef
<SDValue
> Ops
) {
7483 SDNode
*New
= MorphNodeTo(N
, ~MachineOpc
, VTs
, Ops
);
7484 // Reset the NodeID to -1.
7487 ReplaceAllUsesWith(N
, New
);
7493 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
7494 /// the line number information on the merged node since it is not possible to
7495 /// preserve the information that operation is associated with multiple lines.
7496 /// This will make the debugger working better at -O0, were there is a higher
7497 /// probability having other instructions associated with that line.
7499 /// For IROrder, we keep the smaller of the two
7500 SDNode
*SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode
*N
, const SDLoc
&OLoc
) {
7501 DebugLoc NLoc
= N
->getDebugLoc();
7502 if (NLoc
&& OptLevel
== CodeGenOpt::None
&& OLoc
.getDebugLoc() != NLoc
) {
7503 N
->setDebugLoc(DebugLoc());
7505 unsigned Order
= std::min(N
->getIROrder(), OLoc
.getIROrder());
7506 N
->setIROrder(Order
);
7510 /// MorphNodeTo - This *mutates* the specified node to have the specified
7511 /// return type, opcode, and operands.
7513 /// Note that MorphNodeTo returns the resultant node. If there is already a
7514 /// node of the specified opcode and operands, it returns that node instead of
7515 /// the current one. Note that the SDLoc need not be the same.
7517 /// Using MorphNodeTo is faster than creating a new node and swapping it in
7518 /// with ReplaceAllUsesWith both because it often avoids allocating a new
7519 /// node, and because it doesn't require CSE recalculation for any of
7520 /// the node's users.
7522 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
7523 /// As a consequence it isn't appropriate to use from within the DAG combiner or
7524 /// the legalizer which maintain worklists that would need to be updated when
7525 /// deleting things.
7526 SDNode
*SelectionDAG::MorphNodeTo(SDNode
*N
, unsigned Opc
,
7527 SDVTList VTs
, ArrayRef
<SDValue
> Ops
) {
7528 // If an identical node already exists, use it.
7530 if (VTs
.VTs
[VTs
.NumVTs
-1] != MVT::Glue
) {
7531 FoldingSetNodeID ID
;
7532 AddNodeIDNode(ID
, Opc
, VTs
, Ops
);
7533 if (SDNode
*ON
= FindNodeOrInsertPos(ID
, SDLoc(N
), IP
))
7534 return UpdateSDLocOnMergeSDNode(ON
, SDLoc(N
));
7537 if (!RemoveNodeFromCSEMaps(N
))
7540 // Start the morphing.
7542 N
->ValueList
= VTs
.VTs
;
7543 N
->NumValues
= VTs
.NumVTs
;
7545 // Clear the operands list, updating used nodes to remove this from their
7546 // use list. Keep track of any operands that become dead as a result.
7547 SmallPtrSet
<SDNode
*, 16> DeadNodeSet
;
7548 for (SDNode::op_iterator I
= N
->op_begin(), E
= N
->op_end(); I
!= E
; ) {
7550 SDNode
*Used
= Use
.getNode();
7552 if (Used
->use_empty())
7553 DeadNodeSet
.insert(Used
);
7556 // For MachineNode, initialize the memory references information.
7557 if (MachineSDNode
*MN
= dyn_cast
<MachineSDNode
>(N
))
7560 // Swap for an appropriately sized array from the recycler.
7562 createOperands(N
, Ops
);
7564 // Delete any nodes that are still dead after adding the uses for the
7566 if (!DeadNodeSet
.empty()) {
7567 SmallVector
<SDNode
*, 16> DeadNodes
;
7568 for (SDNode
*N
: DeadNodeSet
)
7570 DeadNodes
.push_back(N
);
7571 RemoveDeadNodes(DeadNodes
);
7575 CSEMap
.InsertNode(N
, IP
); // Memoize the new node.
7579 SDNode
* SelectionDAG::mutateStrictFPToFP(SDNode
*Node
) {
7580 unsigned OrigOpc
= Node
->getOpcode();
7582 bool IsUnary
= false;
7583 bool IsTernary
= false;
7586 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
7587 case ISD::STRICT_FADD
: NewOpc
= ISD::FADD
; break;
7588 case ISD::STRICT_FSUB
: NewOpc
= ISD::FSUB
; break;
7589 case ISD::STRICT_FMUL
: NewOpc
= ISD::FMUL
; break;
7590 case ISD::STRICT_FDIV
: NewOpc
= ISD::FDIV
; break;
7591 case ISD::STRICT_FREM
: NewOpc
= ISD::FREM
; break;
7592 case ISD::STRICT_FMA
: NewOpc
= ISD::FMA
; IsTernary
= true; break;
7593 case ISD::STRICT_FSQRT
: NewOpc
= ISD::FSQRT
; IsUnary
= true; break;
7594 case ISD::STRICT_FPOW
: NewOpc
= ISD::FPOW
; break;
7595 case ISD::STRICT_FPOWI
: NewOpc
= ISD::FPOWI
; break;
7596 case ISD::STRICT_FSIN
: NewOpc
= ISD::FSIN
; IsUnary
= true; break;
7597 case ISD::STRICT_FCOS
: NewOpc
= ISD::FCOS
; IsUnary
= true; break;
7598 case ISD::STRICT_FEXP
: NewOpc
= ISD::FEXP
; IsUnary
= true; break;
7599 case ISD::STRICT_FEXP2
: NewOpc
= ISD::FEXP2
; IsUnary
= true; break;
7600 case ISD::STRICT_FLOG
: NewOpc
= ISD::FLOG
; IsUnary
= true; break;
7601 case ISD::STRICT_FLOG10
: NewOpc
= ISD::FLOG10
; IsUnary
= true; break;
7602 case ISD::STRICT_FLOG2
: NewOpc
= ISD::FLOG2
; IsUnary
= true; break;
7603 case ISD::STRICT_FRINT
: NewOpc
= ISD::FRINT
; IsUnary
= true; break;
7604 case ISD::STRICT_FNEARBYINT
:
7605 NewOpc
= ISD::FNEARBYINT
;
7608 case ISD::STRICT_FMAXNUM
: NewOpc
= ISD::FMAXNUM
; break;
7609 case ISD::STRICT_FMINNUM
: NewOpc
= ISD::FMINNUM
; break;
7610 case ISD::STRICT_FCEIL
: NewOpc
= ISD::FCEIL
; IsUnary
= true; break;
7611 case ISD::STRICT_FFLOOR
: NewOpc
= ISD::FFLOOR
; IsUnary
= true; break;
7612 case ISD::STRICT_FROUND
: NewOpc
= ISD::FROUND
; IsUnary
= true; break;
7613 case ISD::STRICT_FTRUNC
: NewOpc
= ISD::FTRUNC
; IsUnary
= true; break;
7616 // We're taking this node out of the chain, so we need to re-link things.
7617 SDValue InputChain
= Node
->getOperand(0);
7618 SDValue OutputChain
= SDValue(Node
, 1);
7619 ReplaceAllUsesOfValueWith(OutputChain
, InputChain
);
7621 SDVTList VTs
= getVTList(Node
->getOperand(1).getValueType());
7622 SDNode
*Res
= nullptr;
7624 Res
= MorphNodeTo(Node
, NewOpc
, VTs
, { Node
->getOperand(1) });
7626 Res
= MorphNodeTo(Node
, NewOpc
, VTs
, { Node
->getOperand(1),
7627 Node
->getOperand(2),
7628 Node
->getOperand(3)});
7630 Res
= MorphNodeTo(Node
, NewOpc
, VTs
, { Node
->getOperand(1),
7631 Node
->getOperand(2) });
7633 // MorphNodeTo can operate in two ways: if an existing node with the
7634 // specified operands exists, it can just return it. Otherwise, it
7635 // updates the node in place to have the requested operands.
7637 // If we updated the node in place, reset the node ID. To the isel,
7638 // this should be just like a newly allocated machine node.
7641 ReplaceAllUsesWith(Node
, Res
);
7642 RemoveDeadNode(Node
);
7648 /// getMachineNode - These are used for target selectors to create a new node
7649 /// with specified return type(s), MachineInstr opcode, and operands.
7651 /// Note that getMachineNode returns the resultant node. If there is already a
7652 /// node of the specified opcode and operands, it returns that node instead of
7653 /// the current one.
7654 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7656 SDVTList VTs
= getVTList(VT
);
7657 return getMachineNode(Opcode
, dl
, VTs
, None
);
7660 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7661 EVT VT
, SDValue Op1
) {
7662 SDVTList VTs
= getVTList(VT
);
7663 SDValue Ops
[] = { Op1
};
7664 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7667 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7668 EVT VT
, SDValue Op1
, SDValue Op2
) {
7669 SDVTList VTs
= getVTList(VT
);
7670 SDValue Ops
[] = { Op1
, Op2
};
7671 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7674 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7675 EVT VT
, SDValue Op1
, SDValue Op2
,
7677 SDVTList VTs
= getVTList(VT
);
7678 SDValue Ops
[] = { Op1
, Op2
, Op3
};
7679 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7682 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7683 EVT VT
, ArrayRef
<SDValue
> Ops
) {
7684 SDVTList VTs
= getVTList(VT
);
7685 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7688 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7689 EVT VT1
, EVT VT2
, SDValue Op1
,
7691 SDVTList VTs
= getVTList(VT1
, VT2
);
7692 SDValue Ops
[] = { Op1
, Op2
};
7693 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7696 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7697 EVT VT1
, EVT VT2
, SDValue Op1
,
7698 SDValue Op2
, SDValue Op3
) {
7699 SDVTList VTs
= getVTList(VT1
, VT2
);
7700 SDValue Ops
[] = { Op1
, Op2
, Op3
};
7701 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7704 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7706 ArrayRef
<SDValue
> Ops
) {
7707 SDVTList VTs
= getVTList(VT1
, VT2
);
7708 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7711 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7712 EVT VT1
, EVT VT2
, EVT VT3
,
7713 SDValue Op1
, SDValue Op2
) {
7714 SDVTList VTs
= getVTList(VT1
, VT2
, VT3
);
7715 SDValue Ops
[] = { Op1
, Op2
};
7716 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7719 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7720 EVT VT1
, EVT VT2
, EVT VT3
,
7721 SDValue Op1
, SDValue Op2
,
7723 SDVTList VTs
= getVTList(VT1
, VT2
, VT3
);
7724 SDValue Ops
[] = { Op1
, Op2
, Op3
};
7725 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7728 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7729 EVT VT1
, EVT VT2
, EVT VT3
,
7730 ArrayRef
<SDValue
> Ops
) {
7731 SDVTList VTs
= getVTList(VT1
, VT2
, VT3
);
7732 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7735 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&dl
,
7736 ArrayRef
<EVT
> ResultTys
,
7737 ArrayRef
<SDValue
> Ops
) {
7738 SDVTList VTs
= getVTList(ResultTys
);
7739 return getMachineNode(Opcode
, dl
, VTs
, Ops
);
7742 MachineSDNode
*SelectionDAG::getMachineNode(unsigned Opcode
, const SDLoc
&DL
,
7744 ArrayRef
<SDValue
> Ops
) {
7745 bool DoCSE
= VTs
.VTs
[VTs
.NumVTs
-1] != MVT::Glue
;
7750 FoldingSetNodeID ID
;
7751 AddNodeIDNode(ID
, ~Opcode
, VTs
, Ops
);
7753 if (SDNode
*E
= FindNodeOrInsertPos(ID
, DL
, IP
)) {
7754 return cast
<MachineSDNode
>(UpdateSDLocOnMergeSDNode(E
, DL
));
7758 // Allocate a new MachineSDNode.
7759 N
= newSDNode
<MachineSDNode
>(~Opcode
, DL
.getIROrder(), DL
.getDebugLoc(), VTs
);
7760 createOperands(N
, Ops
);
7763 CSEMap
.InsertNode(N
, IP
);
7769 /// getTargetExtractSubreg - A convenience function for creating
7770 /// TargetOpcode::EXTRACT_SUBREG nodes.
7771 SDValue
SelectionDAG::getTargetExtractSubreg(int SRIdx
, const SDLoc
&DL
, EVT VT
,
7773 SDValue SRIdxVal
= getTargetConstant(SRIdx
, DL
, MVT::i32
);
7774 SDNode
*Subreg
= getMachineNode(TargetOpcode::EXTRACT_SUBREG
, DL
,
7775 VT
, Operand
, SRIdxVal
);
7776 return SDValue(Subreg
, 0);
7779 /// getTargetInsertSubreg - A convenience function for creating
7780 /// TargetOpcode::INSERT_SUBREG nodes.
7781 SDValue
SelectionDAG::getTargetInsertSubreg(int SRIdx
, const SDLoc
&DL
, EVT VT
,
7782 SDValue Operand
, SDValue Subreg
) {
7783 SDValue SRIdxVal
= getTargetConstant(SRIdx
, DL
, MVT::i32
);
7784 SDNode
*Result
= getMachineNode(TargetOpcode::INSERT_SUBREG
, DL
,
7785 VT
, Operand
, Subreg
, SRIdxVal
);
7786 return SDValue(Result
, 0);
7789 /// getNodeIfExists - Get the specified node if it's already available, or
7790 /// else return NULL.
7791 SDNode
*SelectionDAG::getNodeIfExists(unsigned Opcode
, SDVTList VTList
,
7792 ArrayRef
<SDValue
> Ops
,
7793 const SDNodeFlags Flags
) {
7794 if (VTList
.VTs
[VTList
.NumVTs
- 1] != MVT::Glue
) {
7795 FoldingSetNodeID ID
;
7796 AddNodeIDNode(ID
, Opcode
, VTList
, Ops
);
7798 if (SDNode
*E
= FindNodeOrInsertPos(ID
, SDLoc(), IP
)) {
7799 E
->intersectFlagsWith(Flags
);
7806 /// getDbgValue - Creates a SDDbgValue node.
7809 SDDbgValue
*SelectionDAG::getDbgValue(DIVariable
*Var
, DIExpression
*Expr
,
7810 SDNode
*N
, unsigned R
, bool IsIndirect
,
7811 const DebugLoc
&DL
, unsigned O
) {
7812 assert(cast
<DILocalVariable
>(Var
)->isValidLocationForIntrinsic(DL
) &&
7813 "Expected inlined-at fields to agree");
7814 return new (DbgInfo
->getAlloc())
7815 SDDbgValue(Var
, Expr
, N
, R
, IsIndirect
, DL
, O
);
7819 SDDbgValue
*SelectionDAG::getConstantDbgValue(DIVariable
*Var
,
7822 const DebugLoc
&DL
, unsigned O
) {
7823 assert(cast
<DILocalVariable
>(Var
)->isValidLocationForIntrinsic(DL
) &&
7824 "Expected inlined-at fields to agree");
7825 return new (DbgInfo
->getAlloc()) SDDbgValue(Var
, Expr
, C
, DL
, O
);
7829 SDDbgValue
*SelectionDAG::getFrameIndexDbgValue(DIVariable
*Var
,
7830 DIExpression
*Expr
, unsigned FI
,
7834 assert(cast
<DILocalVariable
>(Var
)->isValidLocationForIntrinsic(DL
) &&
7835 "Expected inlined-at fields to agree");
7836 return new (DbgInfo
->getAlloc())
7837 SDDbgValue(Var
, Expr
, FI
, IsIndirect
, DL
, O
, SDDbgValue::FRAMEIX
);
7841 SDDbgValue
*SelectionDAG::getVRegDbgValue(DIVariable
*Var
,
7843 unsigned VReg
, bool IsIndirect
,
7844 const DebugLoc
&DL
, unsigned O
) {
7845 assert(cast
<DILocalVariable
>(Var
)->isValidLocationForIntrinsic(DL
) &&
7846 "Expected inlined-at fields to agree");
7847 return new (DbgInfo
->getAlloc())
7848 SDDbgValue(Var
, Expr
, VReg
, IsIndirect
, DL
, O
, SDDbgValue::VREG
);
7851 void SelectionDAG::transferDbgValues(SDValue From
, SDValue To
,
7852 unsigned OffsetInBits
, unsigned SizeInBits
,
7853 bool InvalidateDbg
) {
7854 SDNode
*FromNode
= From
.getNode();
7855 SDNode
*ToNode
= To
.getNode();
7856 assert(FromNode
&& ToNode
&& "Can't modify dbg values");
7859 // TODO: assert(From != To && "Redundant dbg value transfer");
7860 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
7861 if (From
== To
|| FromNode
== ToNode
)
7864 if (!FromNode
->getHasDebugValue())
7867 SmallVector
<SDDbgValue
*, 2> ClonedDVs
;
7868 for (SDDbgValue
*Dbg
: GetDbgValues(FromNode
)) {
7869 if (Dbg
->getKind() != SDDbgValue::SDNODE
|| Dbg
->isInvalidated())
7872 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
7874 // Just transfer the dbg value attached to From.
7875 if (Dbg
->getResNo() != From
.getResNo())
7878 DIVariable
*Var
= Dbg
->getVariable();
7879 auto *Expr
= Dbg
->getExpression();
7880 // If a fragment is requested, update the expression.
7882 // When splitting a larger (e.g., sign-extended) value whose
7883 // lower bits are described with an SDDbgValue, do not attempt
7884 // to transfer the SDDbgValue to the upper bits.
7885 if (auto FI
= Expr
->getFragmentInfo())
7886 if (OffsetInBits
+ SizeInBits
> FI
->SizeInBits
)
7888 auto Fragment
= DIExpression::createFragmentExpression(Expr
, OffsetInBits
,
7894 // Clone the SDDbgValue and move it to To.
7896 getDbgValue(Var
, Expr
, ToNode
, To
.getResNo(), Dbg
->isIndirect(),
7897 Dbg
->getDebugLoc(), Dbg
->getOrder());
7898 ClonedDVs
.push_back(Clone
);
7900 if (InvalidateDbg
) {
7901 // Invalidate value and indicate the SDDbgValue should not be emitted.
7902 Dbg
->setIsInvalidated();
7903 Dbg
->setIsEmitted();
7907 for (SDDbgValue
*Dbg
: ClonedDVs
)
7908 AddDbgValue(Dbg
, ToNode
, false);
7911 void SelectionDAG::salvageDebugInfo(SDNode
&N
) {
7912 if (!N
.getHasDebugValue())
7915 SmallVector
<SDDbgValue
*, 2> ClonedDVs
;
7916 for (auto DV
: GetDbgValues(&N
)) {
7917 if (DV
->isInvalidated())
7919 switch (N
.getOpcode()) {
7923 SDValue N0
= N
.getOperand(0);
7924 SDValue N1
= N
.getOperand(1);
7925 if (!isConstantIntBuildVectorOrConstantInt(N0
) &&
7926 isConstantIntBuildVectorOrConstantInt(N1
)) {
7927 uint64_t Offset
= N
.getConstantOperandVal(1);
7928 // Rewrite an ADD constant node into a DIExpression. Since we are
7929 // performing arithmetic to compute the variable's *value* in the
7930 // DIExpression, we need to mark the expression with a
7931 // DW_OP_stack_value.
7932 auto *DIExpr
= DV
->getExpression();
7933 DIExpr
= DIExpression::prepend(DIExpr
, DIExpression::NoDeref
, Offset
,
7934 DIExpression::NoDeref
,
7935 DIExpression::WithStackValue
);
7937 getDbgValue(DV
->getVariable(), DIExpr
, N0
.getNode(), N0
.getResNo(),
7938 DV
->isIndirect(), DV
->getDebugLoc(), DV
->getOrder());
7939 ClonedDVs
.push_back(Clone
);
7940 DV
->setIsInvalidated();
7942 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
7943 N0
.getNode()->dumprFull(this);
7944 dbgs() << " into " << *DIExpr
<< '\n');
7949 for (SDDbgValue
*Dbg
: ClonedDVs
)
7950 AddDbgValue(Dbg
, Dbg
->getSDNode(), false);
7953 /// Creates a SDDbgLabel node.
7954 SDDbgLabel
*SelectionDAG::getDbgLabel(DILabel
*Label
,
7955 const DebugLoc
&DL
, unsigned O
) {
7956 assert(cast
<DILabel
>(Label
)->isValidLocationForIntrinsic(DL
) &&
7957 "Expected inlined-at fields to agree");
7958 return new (DbgInfo
->getAlloc()) SDDbgLabel(Label
, DL
, O
);
7963 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
7964 /// pointed to by a use iterator is deleted, increment the use iterator
7965 /// so that it doesn't dangle.
7967 class RAUWUpdateListener
: public SelectionDAG::DAGUpdateListener
{
7968 SDNode::use_iterator
&UI
;
7969 SDNode::use_iterator
&UE
;
7971 void NodeDeleted(SDNode
*N
, SDNode
*E
) override
{
7972 // Increment the iterator as needed.
7973 while (UI
!= UE
&& N
== *UI
)
7978 RAUWUpdateListener(SelectionDAG
&d
,
7979 SDNode::use_iterator
&ui
,
7980 SDNode::use_iterator
&ue
)
7981 : SelectionDAG::DAGUpdateListener(d
), UI(ui
), UE(ue
) {}
7984 } // end anonymous namespace
7986 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
7987 /// This can cause recursive merging of nodes in the DAG.
7989 /// This version assumes From has a single result value.
7991 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN
, SDValue To
) {
7992 SDNode
*From
= FromN
.getNode();
7993 assert(From
->getNumValues() == 1 && FromN
.getResNo() == 0 &&
7994 "Cannot replace with this method!");
7995 assert(From
!= To
.getNode() && "Cannot replace uses of with self");
7997 // Preserve Debug Values
7998 transferDbgValues(FromN
, To
);
8000 // Iterate over all the existing uses of From. New uses will be added
8001 // to the beginning of the use list, which we avoid visiting.
8002 // This specifically avoids visiting uses of From that arise while the
8003 // replacement is happening, because any such uses would be the result
8004 // of CSE: If an existing node looks like From after one of its operands
8005 // is replaced by To, we don't want to replace of all its users with To
8006 // too. See PR3018 for more info.
8007 SDNode::use_iterator UI
= From
->use_begin(), UE
= From
->use_end();
8008 RAUWUpdateListener
Listener(*this, UI
, UE
);
8012 // This node is about to morph, remove its old self from the CSE maps.
8013 RemoveNodeFromCSEMaps(User
);
8015 // A user can appear in a use list multiple times, and when this
8016 // happens the uses are usually next to each other in the list.
8017 // To help reduce the number of CSE recomputations, process all
8018 // the uses of this user that we can find this way.
8020 SDUse
&Use
= UI
.getUse();
8023 if (To
->isDivergent() != From
->isDivergent())
8024 updateDivergence(User
);
8025 } while (UI
!= UE
&& *UI
== User
);
8026 // Now that we have modified User, add it back to the CSE maps. If it
8027 // already exists there, recursively merge the results together.
8028 AddModifiedNodeToCSEMaps(User
);
8031 // If we just RAUW'd the root, take note.
8032 if (FromN
== getRoot())
8036 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8037 /// This can cause recursive merging of nodes in the DAG.
8039 /// This version assumes that for each value of From, there is a
8040 /// corresponding value in To in the same position with the same type.
8042 void SelectionDAG::ReplaceAllUsesWith(SDNode
*From
, SDNode
*To
) {
8044 for (unsigned i
= 0, e
= From
->getNumValues(); i
!= e
; ++i
)
8045 assert((!From
->hasAnyUseOfValue(i
) ||
8046 From
->getValueType(i
) == To
->getValueType(i
)) &&
8047 "Cannot use this version of ReplaceAllUsesWith!");
8050 // Handle the trivial case.
8054 // Preserve Debug Info. Only do this if there's a use.
8055 for (unsigned i
= 0, e
= From
->getNumValues(); i
!= e
; ++i
)
8056 if (From
->hasAnyUseOfValue(i
)) {
8057 assert((i
< To
->getNumValues()) && "Invalid To location");
8058 transferDbgValues(SDValue(From
, i
), SDValue(To
, i
));
8061 // Iterate over just the existing users of From. See the comments in
8062 // the ReplaceAllUsesWith above.
8063 SDNode::use_iterator UI
= From
->use_begin(), UE
= From
->use_end();
8064 RAUWUpdateListener
Listener(*this, UI
, UE
);
8068 // This node is about to morph, remove its old self from the CSE maps.
8069 RemoveNodeFromCSEMaps(User
);
8071 // A user can appear in a use list multiple times, and when this
8072 // happens the uses are usually next to each other in the list.
8073 // To help reduce the number of CSE recomputations, process all
8074 // the uses of this user that we can find this way.
8076 SDUse
&Use
= UI
.getUse();
8079 if (To
->isDivergent() != From
->isDivergent())
8080 updateDivergence(User
);
8081 } while (UI
!= UE
&& *UI
== User
);
8083 // Now that we have modified User, add it back to the CSE maps. If it
8084 // already exists there, recursively merge the results together.
8085 AddModifiedNodeToCSEMaps(User
);
8088 // If we just RAUW'd the root, take note.
8089 if (From
== getRoot().getNode())
8090 setRoot(SDValue(To
, getRoot().getResNo()));
8093 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8094 /// This can cause recursive merging of nodes in the DAG.
8096 /// This version can replace From with any result values. To must match the
8097 /// number and types of values returned by From.
8098 void SelectionDAG::ReplaceAllUsesWith(SDNode
*From
, const SDValue
*To
) {
8099 if (From
->getNumValues() == 1) // Handle the simple case efficiently.
8100 return ReplaceAllUsesWith(SDValue(From
, 0), To
[0]);
8102 // Preserve Debug Info.
8103 for (unsigned i
= 0, e
= From
->getNumValues(); i
!= e
; ++i
)
8104 transferDbgValues(SDValue(From
, i
), To
[i
]);
8106 // Iterate over just the existing users of From. See the comments in
8107 // the ReplaceAllUsesWith above.
8108 SDNode::use_iterator UI
= From
->use_begin(), UE
= From
->use_end();
8109 RAUWUpdateListener
Listener(*this, UI
, UE
);
8113 // This node is about to morph, remove its old self from the CSE maps.
8114 RemoveNodeFromCSEMaps(User
);
8116 // A user can appear in a use list multiple times, and when this happens the
8117 // uses are usually next to each other in the list. To help reduce the
8118 // number of CSE and divergence recomputations, process all the uses of this
8119 // user that we can find this way.
8120 bool To_IsDivergent
= false;
8122 SDUse
&Use
= UI
.getUse();
8123 const SDValue
&ToOp
= To
[Use
.getResNo()];
8126 To_IsDivergent
|= ToOp
->isDivergent();
8127 } while (UI
!= UE
&& *UI
== User
);
8129 if (To_IsDivergent
!= From
->isDivergent())
8130 updateDivergence(User
);
8132 // Now that we have modified User, add it back to the CSE maps. If it
8133 // already exists there, recursively merge the results together.
8134 AddModifiedNodeToCSEMaps(User
);
8137 // If we just RAUW'd the root, take note.
8138 if (From
== getRoot().getNode())
8139 setRoot(SDValue(To
[getRoot().getResNo()]));
8142 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8143 /// uses of other values produced by From.getNode() alone. The Deleted
8144 /// vector is handled the same way as for ReplaceAllUsesWith.
8145 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From
, SDValue To
){
8146 // Handle the really simple, really trivial case efficiently.
8147 if (From
== To
) return;
8149 // Handle the simple, trivial, case efficiently.
8150 if (From
.getNode()->getNumValues() == 1) {
8151 ReplaceAllUsesWith(From
, To
);
8155 // Preserve Debug Info.
8156 transferDbgValues(From
, To
);
8158 // Iterate over just the existing users of From. See the comments in
8159 // the ReplaceAllUsesWith above.
8160 SDNode::use_iterator UI
= From
.getNode()->use_begin(),
8161 UE
= From
.getNode()->use_end();
8162 RAUWUpdateListener
Listener(*this, UI
, UE
);
8165 bool UserRemovedFromCSEMaps
= false;
8167 // A user can appear in a use list multiple times, and when this
8168 // happens the uses are usually next to each other in the list.
8169 // To help reduce the number of CSE recomputations, process all
8170 // the uses of this user that we can find this way.
8172 SDUse
&Use
= UI
.getUse();
8174 // Skip uses of different values from the same node.
8175 if (Use
.getResNo() != From
.getResNo()) {
8180 // If this node hasn't been modified yet, it's still in the CSE maps,
8181 // so remove its old self from the CSE maps.
8182 if (!UserRemovedFromCSEMaps
) {
8183 RemoveNodeFromCSEMaps(User
);
8184 UserRemovedFromCSEMaps
= true;
8189 if (To
->isDivergent() != From
->isDivergent())
8190 updateDivergence(User
);
8191 } while (UI
!= UE
&& *UI
== User
);
8192 // We are iterating over all uses of the From node, so if a use
8193 // doesn't use the specific value, no changes are made.
8194 if (!UserRemovedFromCSEMaps
)
8197 // Now that we have modified User, add it back to the CSE maps. If it
8198 // already exists there, recursively merge the results together.
8199 AddModifiedNodeToCSEMaps(User
);
8202 // If we just RAUW'd the root, take note.
8203 if (From
== getRoot())
8209 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8210 /// to record information about a use.
8217 /// operator< - Sort Memos by User.
8218 bool operator<(const UseMemo
&L
, const UseMemo
&R
) {
8219 return (intptr_t)L
.User
< (intptr_t)R
.User
;
8222 } // end anonymous namespace
8224 void SelectionDAG::updateDivergence(SDNode
* N
)
8226 if (TLI
->isSDNodeAlwaysUniform(N
))
8228 bool IsDivergent
= TLI
->isSDNodeSourceOfDivergence(N
, FLI
, DA
);
8229 for (auto &Op
: N
->ops()) {
8230 if (Op
.Val
.getValueType() != MVT::Other
)
8231 IsDivergent
|= Op
.getNode()->isDivergent();
8233 if (N
->SDNodeBits
.IsDivergent
!= IsDivergent
) {
8234 N
->SDNodeBits
.IsDivergent
= IsDivergent
;
8235 for (auto U
: N
->uses()) {
8236 updateDivergence(U
);
8241 void SelectionDAG::CreateTopologicalOrder(std::vector
<SDNode
*> &Order
) {
8242 DenseMap
<SDNode
*, unsigned> Degree
;
8243 Order
.reserve(AllNodes
.size());
8244 for (auto &N
: allnodes()) {
8245 unsigned NOps
= N
.getNumOperands();
8248 Order
.push_back(&N
);
8250 for (size_t I
= 0; I
!= Order
.size(); ++I
) {
8251 SDNode
*N
= Order
[I
];
8252 for (auto U
: N
->uses()) {
8253 unsigned &UnsortedOps
= Degree
[U
];
8254 if (0 == --UnsortedOps
)
8261 void SelectionDAG::VerifyDAGDiverence() {
8262 std::vector
<SDNode
*> TopoOrder
;
8263 CreateTopologicalOrder(TopoOrder
);
8264 const TargetLowering
&TLI
= getTargetLoweringInfo();
8265 DenseMap
<const SDNode
*, bool> DivergenceMap
;
8266 for (auto &N
: allnodes()) {
8267 DivergenceMap
[&N
] = false;
8269 for (auto N
: TopoOrder
) {
8270 bool IsDivergent
= DivergenceMap
[N
];
8271 bool IsSDNodeDivergent
= TLI
.isSDNodeSourceOfDivergence(N
, FLI
, DA
);
8272 for (auto &Op
: N
->ops()) {
8273 if (Op
.Val
.getValueType() != MVT::Other
)
8274 IsSDNodeDivergent
|= DivergenceMap
[Op
.getNode()];
8276 if (!IsDivergent
&& IsSDNodeDivergent
&& !TLI
.isSDNodeAlwaysUniform(N
)) {
8277 DivergenceMap
[N
] = true;
8280 for (auto &N
: allnodes()) {
8282 assert(DivergenceMap
[&N
] == N
.isDivergent() &&
8283 "Divergence bit inconsistency detected\n");
8288 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
8289 /// uses of other values produced by From.getNode() alone. The same value
8290 /// may appear in both the From and To list. The Deleted vector is
8291 /// handled the same way as for ReplaceAllUsesWith.
8292 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue
*From
,
8295 // Handle the simple, trivial case efficiently.
8297 return ReplaceAllUsesOfValueWith(*From
, *To
);
8299 transferDbgValues(*From
, *To
);
8301 // Read up all the uses and make records of them. This helps
8302 // processing new uses that are introduced during the
8303 // replacement process.
8304 SmallVector
<UseMemo
, 4> Uses
;
8305 for (unsigned i
= 0; i
!= Num
; ++i
) {
8306 unsigned FromResNo
= From
[i
].getResNo();
8307 SDNode
*FromNode
= From
[i
].getNode();
8308 for (SDNode::use_iterator UI
= FromNode
->use_begin(),
8309 E
= FromNode
->use_end(); UI
!= E
; ++UI
) {
8310 SDUse
&Use
= UI
.getUse();
8311 if (Use
.getResNo() == FromResNo
) {
8312 UseMemo Memo
= { *UI
, i
, &Use
};
8313 Uses
.push_back(Memo
);
8318 // Sort the uses, so that all the uses from a given User are together.
8321 for (unsigned UseIndex
= 0, UseIndexEnd
= Uses
.size();
8322 UseIndex
!= UseIndexEnd
; ) {
8323 // We know that this user uses some value of From. If it is the right
8324 // value, update it.
8325 SDNode
*User
= Uses
[UseIndex
].User
;
8327 // This node is about to morph, remove its old self from the CSE maps.
8328 RemoveNodeFromCSEMaps(User
);
8330 // The Uses array is sorted, so all the uses for a given User
8331 // are next to each other in the list.
8332 // To help reduce the number of CSE recomputations, process all
8333 // the uses of this user that we can find this way.
8335 unsigned i
= Uses
[UseIndex
].Index
;
8336 SDUse
&Use
= *Uses
[UseIndex
].Use
;
8340 } while (UseIndex
!= UseIndexEnd
&& Uses
[UseIndex
].User
== User
);
8342 // Now that we have modified User, add it back to the CSE maps. If it
8343 // already exists there, recursively merge the results together.
8344 AddModifiedNodeToCSEMaps(User
);
8348 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
8349 /// based on their topological order. It returns the maximum id and a vector
8350 /// of the SDNodes* in assigned order by reference.
8351 unsigned SelectionDAG::AssignTopologicalOrder() {
8352 unsigned DAGSize
= 0;
8354 // SortedPos tracks the progress of the algorithm. Nodes before it are
8355 // sorted, nodes after it are unsorted. When the algorithm completes
8356 // it is at the end of the list.
8357 allnodes_iterator SortedPos
= allnodes_begin();
8359 // Visit all the nodes. Move nodes with no operands to the front of
8360 // the list immediately. Annotate nodes that do have operands with their
8361 // operand count. Before we do this, the Node Id fields of the nodes
8362 // may contain arbitrary values. After, the Node Id fields for nodes
8363 // before SortedPos will contain the topological sort index, and the
8364 // Node Id fields for nodes At SortedPos and after will contain the
8365 // count of outstanding operands.
8366 for (allnodes_iterator I
= allnodes_begin(),E
= allnodes_end(); I
!= E
; ) {
8368 checkForCycles(N
, this);
8369 unsigned Degree
= N
->getNumOperands();
8371 // A node with no uses, add it to the result array immediately.
8372 N
->setNodeId(DAGSize
++);
8373 allnodes_iterator
Q(N
);
8375 SortedPos
= AllNodes
.insert(SortedPos
, AllNodes
.remove(Q
));
8376 assert(SortedPos
!= AllNodes
.end() && "Overran node list");
8379 // Temporarily use the Node Id as scratch space for the degree count.
8380 N
->setNodeId(Degree
);
8384 // Visit all the nodes. As we iterate, move nodes into sorted order,
8385 // such that by the time the end is reached all nodes will be sorted.
8386 for (SDNode
&Node
: allnodes()) {
8388 checkForCycles(N
, this);
8389 // N is in sorted position, so all its uses have one less operand
8390 // that needs to be sorted.
8391 for (SDNode::use_iterator UI
= N
->use_begin(), UE
= N
->use_end();
8394 unsigned Degree
= P
->getNodeId();
8395 assert(Degree
!= 0 && "Invalid node degree");
8398 // All of P's operands are sorted, so P may sorted now.
8399 P
->setNodeId(DAGSize
++);
8400 if (P
->getIterator() != SortedPos
)
8401 SortedPos
= AllNodes
.insert(SortedPos
, AllNodes
.remove(P
));
8402 assert(SortedPos
!= AllNodes
.end() && "Overran node list");
8405 // Update P's outstanding operand count.
8406 P
->setNodeId(Degree
);
8409 if (Node
.getIterator() == SortedPos
) {
8411 allnodes_iterator
I(N
);
8413 dbgs() << "Overran sorted position:\n";
8414 S
->dumprFull(this); dbgs() << "\n";
8415 dbgs() << "Checking if this is due to cycles\n";
8416 checkForCycles(this, true);
8418 llvm_unreachable(nullptr);
8422 assert(SortedPos
== AllNodes
.end() &&
8423 "Topological sort incomplete!");
8424 assert(AllNodes
.front().getOpcode() == ISD::EntryToken
&&
8425 "First node in topological sort is not the entry token!");
8426 assert(AllNodes
.front().getNodeId() == 0 &&
8427 "First node in topological sort has non-zero id!");
8428 assert(AllNodes
.front().getNumOperands() == 0 &&
8429 "First node in topological sort has operands!");
8430 assert(AllNodes
.back().getNodeId() == (int)DAGSize
-1 &&
8431 "Last node in topologic sort has unexpected id!");
8432 assert(AllNodes
.back().use_empty() &&
8433 "Last node in topologic sort has users!");
8434 assert(DAGSize
== allnodes_size() && "Node count mismatch!");
8438 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
8439 /// value is produced by SD.
8440 void SelectionDAG::AddDbgValue(SDDbgValue
*DB
, SDNode
*SD
, bool isParameter
) {
8442 assert(DbgInfo
->getSDDbgValues(SD
).empty() || SD
->getHasDebugValue());
8443 SD
->setHasDebugValue(true);
8445 DbgInfo
->add(DB
, SD
, isParameter
);
8448 void SelectionDAG::AddDbgLabel(SDDbgLabel
*DB
) {
8452 SDValue
SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode
*OldLoad
,
8454 assert(isa
<MemSDNode
>(NewMemOp
.getNode()) && "Expected a memop node");
8455 // The new memory operation must have the same position as the old load in
8456 // terms of memory dependency. Create a TokenFactor for the old load and new
8457 // memory operation and update uses of the old load's output chain to use that
8459 SDValue OldChain
= SDValue(OldLoad
, 1);
8460 SDValue NewChain
= SDValue(NewMemOp
.getNode(), 1);
8461 if (!OldLoad
->hasAnyUseOfValue(1))
8464 SDValue TokenFactor
=
8465 getNode(ISD::TokenFactor
, SDLoc(OldLoad
), MVT::Other
, OldChain
, NewChain
);
8466 ReplaceAllUsesOfValueWith(OldChain
, TokenFactor
);
8467 UpdateNodeOperands(TokenFactor
.getNode(), OldChain
, NewChain
);
8471 SDValue
SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op
,
8472 Function
**OutFunction
) {
8473 assert(isa
<ExternalSymbolSDNode
>(Op
) && "Node should be an ExternalSymbol");
8475 auto *Symbol
= cast
<ExternalSymbolSDNode
>(Op
)->getSymbol();
8476 auto *Module
= MF
->getFunction().getParent();
8477 auto *Function
= Module
->getFunction(Symbol
);
8479 if (OutFunction
!= nullptr)
8480 *OutFunction
= Function
;
8482 if (Function
!= nullptr) {
8483 auto PtrTy
= TLI
->getPointerTy(getDataLayout(), Function
->getAddressSpace());
8484 return getGlobalAddress(Function
, SDLoc(Op
), PtrTy
);
8487 std::string ErrorStr
;
8488 raw_string_ostream
ErrorFormatter(ErrorStr
);
8490 ErrorFormatter
<< "Undefined external symbol ";
8491 ErrorFormatter
<< '"' << Symbol
<< '"';
8492 ErrorFormatter
.flush();
8494 report_fatal_error(ErrorStr
);
8497 //===----------------------------------------------------------------------===//
8499 //===----------------------------------------------------------------------===//
8501 bool llvm::isNullConstant(SDValue V
) {
8502 ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(V
);
8503 return Const
!= nullptr && Const
->isNullValue();
8506 bool llvm::isNullFPConstant(SDValue V
) {
8507 ConstantFPSDNode
*Const
= dyn_cast
<ConstantFPSDNode
>(V
);
8508 return Const
!= nullptr && Const
->isZero() && !Const
->isNegative();
8511 bool llvm::isAllOnesConstant(SDValue V
) {
8512 ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(V
);
8513 return Const
!= nullptr && Const
->isAllOnesValue();
8516 bool llvm::isOneConstant(SDValue V
) {
8517 ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(V
);
8518 return Const
!= nullptr && Const
->isOne();
8521 SDValue
llvm::peekThroughBitcasts(SDValue V
) {
8522 while (V
.getOpcode() == ISD::BITCAST
)
8523 V
= V
.getOperand(0);
8527 SDValue
llvm::peekThroughOneUseBitcasts(SDValue V
) {
8528 while (V
.getOpcode() == ISD::BITCAST
&& V
.getOperand(0).hasOneUse())
8529 V
= V
.getOperand(0);
8533 SDValue
llvm::peekThroughExtractSubvectors(SDValue V
) {
8534 while (V
.getOpcode() == ISD::EXTRACT_SUBVECTOR
)
8535 V
= V
.getOperand(0);
8539 bool llvm::isBitwiseNot(SDValue V
) {
8540 if (V
.getOpcode() != ISD::XOR
)
8542 ConstantSDNode
*C
= isConstOrConstSplat(peekThroughBitcasts(V
.getOperand(1)));
8543 return C
&& C
->isAllOnesValue();
8546 ConstantSDNode
*llvm::isConstOrConstSplat(SDValue N
, bool AllowUndefs
) {
8547 if (ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(N
))
8550 if (BuildVectorSDNode
*BV
= dyn_cast
<BuildVectorSDNode
>(N
)) {
8551 BitVector UndefElements
;
8552 ConstantSDNode
*CN
= BV
->getConstantSplatNode(&UndefElements
);
8554 // BuildVectors can truncate their operands. Ignore that case here.
8555 if (CN
&& (UndefElements
.none() || AllowUndefs
) &&
8556 CN
->getValueType(0) == N
.getValueType().getScalarType())
8563 ConstantSDNode
*llvm::isConstOrConstSplat(SDValue N
, const APInt
&DemandedElts
,
8565 if (ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(N
))
8568 if (BuildVectorSDNode
*BV
= dyn_cast
<BuildVectorSDNode
>(N
)) {
8569 BitVector UndefElements
;
8570 ConstantSDNode
*CN
= BV
->getConstantSplatNode(DemandedElts
, &UndefElements
);
8572 // BuildVectors can truncate their operands. Ignore that case here.
8573 if (CN
&& (UndefElements
.none() || AllowUndefs
) &&
8574 CN
->getValueType(0) == N
.getValueType().getScalarType())
8581 ConstantFPSDNode
*llvm::isConstOrConstSplatFP(SDValue N
, bool AllowUndefs
) {
8582 if (ConstantFPSDNode
*CN
= dyn_cast
<ConstantFPSDNode
>(N
))
8585 if (BuildVectorSDNode
*BV
= dyn_cast
<BuildVectorSDNode
>(N
)) {
8586 BitVector UndefElements
;
8587 ConstantFPSDNode
*CN
= BV
->getConstantFPSplatNode(&UndefElements
);
8588 if (CN
&& (UndefElements
.none() || AllowUndefs
))
8595 ConstantFPSDNode
*llvm::isConstOrConstSplatFP(SDValue N
,
8596 const APInt
&DemandedElts
,
8598 if (ConstantFPSDNode
*CN
= dyn_cast
<ConstantFPSDNode
>(N
))
8601 if (BuildVectorSDNode
*BV
= dyn_cast
<BuildVectorSDNode
>(N
)) {
8602 BitVector UndefElements
;
8603 ConstantFPSDNode
*CN
=
8604 BV
->getConstantFPSplatNode(DemandedElts
, &UndefElements
);
8605 if (CN
&& (UndefElements
.none() || AllowUndefs
))
8612 bool llvm::isNullOrNullSplat(SDValue N
, bool AllowUndefs
) {
8613 // TODO: may want to use peekThroughBitcast() here.
8614 ConstantSDNode
*C
= isConstOrConstSplat(N
, AllowUndefs
);
8615 return C
&& C
->isNullValue();
8618 bool llvm::isOneOrOneSplat(SDValue N
) {
8619 // TODO: may want to use peekThroughBitcast() here.
8620 unsigned BitWidth
= N
.getScalarValueSizeInBits();
8621 ConstantSDNode
*C
= isConstOrConstSplat(N
);
8622 return C
&& C
->isOne() && C
->getValueSizeInBits(0) == BitWidth
;
8625 bool llvm::isAllOnesOrAllOnesSplat(SDValue N
) {
8626 N
= peekThroughBitcasts(N
);
8627 unsigned BitWidth
= N
.getScalarValueSizeInBits();
8628 ConstantSDNode
*C
= isConstOrConstSplat(N
);
8629 return C
&& C
->isAllOnesValue() && C
->getValueSizeInBits(0) == BitWidth
;
8632 HandleSDNode::~HandleSDNode() {
8636 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc
, unsigned Order
,
8638 const GlobalValue
*GA
, EVT VT
,
8639 int64_t o
, unsigned char TF
)
8640 : SDNode(Opc
, Order
, DL
, getSDVTList(VT
)), Offset(o
), TargetFlags(TF
) {
8644 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order
, const DebugLoc
&dl
,
8645 EVT VT
, unsigned SrcAS
,
8647 : SDNode(ISD::ADDRSPACECAST
, Order
, dl
, getSDVTList(VT
)),
8648 SrcAddrSpace(SrcAS
), DestAddrSpace(DestAS
) {}
8650 MemSDNode::MemSDNode(unsigned Opc
, unsigned Order
, const DebugLoc
&dl
,
8651 SDVTList VTs
, EVT memvt
, MachineMemOperand
*mmo
)
8652 : SDNode(Opc
, Order
, dl
, VTs
), MemoryVT(memvt
), MMO(mmo
) {
8653 MemSDNodeBits
.IsVolatile
= MMO
->isVolatile();
8654 MemSDNodeBits
.IsNonTemporal
= MMO
->isNonTemporal();
8655 MemSDNodeBits
.IsDereferenceable
= MMO
->isDereferenceable();
8656 MemSDNodeBits
.IsInvariant
= MMO
->isInvariant();
8658 // We check here that the size of the memory operand fits within the size of
8659 // the MMO. This is because the MMO might indicate only a possible address
8660 // range instead of specifying the affected memory addresses precisely.
8661 assert(memvt
.getStoreSize() <= MMO
->getSize() && "Size mismatch!");
8664 /// Profile - Gather unique data for the node.
8666 void SDNode::Profile(FoldingSetNodeID
&ID
) const {
8667 AddNodeIDNode(ID
, this);
8673 std::vector
<EVT
> VTs
;
8676 VTs
.reserve(MVT::LAST_VALUETYPE
);
8677 for (unsigned i
= 0; i
< MVT::LAST_VALUETYPE
; ++i
)
8678 VTs
.push_back(MVT((MVT::SimpleValueType
)i
));
8682 } // end anonymous namespace
8684 static ManagedStatic
<std::set
<EVT
, EVT::compareRawBits
>> EVTs
;
8685 static ManagedStatic
<EVTArray
> SimpleVTArray
;
8686 static ManagedStatic
<sys::SmartMutex
<true>> VTMutex
;
8688 /// getValueTypeList - Return a pointer to the specified value type.
8690 const EVT
*SDNode::getValueTypeList(EVT VT
) {
8691 if (VT
.isExtended()) {
8692 sys::SmartScopedLock
<true> Lock(*VTMutex
);
8693 return &(*EVTs
->insert(VT
).first
);
8695 assert(VT
.getSimpleVT() < MVT::LAST_VALUETYPE
&&
8696 "Value type out of range!");
8697 return &SimpleVTArray
->VTs
[VT
.getSimpleVT().SimpleTy
];
8701 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
8702 /// indicated value. This method ignores uses of other values defined by this
8704 bool SDNode::hasNUsesOfValue(unsigned NUses
, unsigned Value
) const {
8705 assert(Value
< getNumValues() && "Bad value!");
8707 // TODO: Only iterate over uses of a given value of the node
8708 for (SDNode::use_iterator UI
= use_begin(), E
= use_end(); UI
!= E
; ++UI
) {
8709 if (UI
.getUse().getResNo() == Value
) {
8716 // Found exactly the right number of uses?
8720 /// hasAnyUseOfValue - Return true if there are any use of the indicated
8721 /// value. This method ignores uses of other values defined by this operation.
8722 bool SDNode::hasAnyUseOfValue(unsigned Value
) const {
8723 assert(Value
< getNumValues() && "Bad value!");
8725 for (SDNode::use_iterator UI
= use_begin(), E
= use_end(); UI
!= E
; ++UI
)
8726 if (UI
.getUse().getResNo() == Value
)
8732 /// isOnlyUserOf - Return true if this node is the only use of N.
8733 bool SDNode::isOnlyUserOf(const SDNode
*N
) const {
8735 for (SDNode::use_iterator I
= N
->use_begin(), E
= N
->use_end(); I
!= E
; ++I
) {
8746 /// Return true if the only users of N are contained in Nodes.
8747 bool SDNode::areOnlyUsersOf(ArrayRef
<const SDNode
*> Nodes
, const SDNode
*N
) {
8749 for (SDNode::use_iterator I
= N
->use_begin(), E
= N
->use_end(); I
!= E
; ++I
) {
8751 if (llvm::any_of(Nodes
,
8752 [&User
](const SDNode
*Node
) { return User
== Node
; }))
8761 /// isOperand - Return true if this node is an operand of N.
8762 bool SDValue::isOperandOf(const SDNode
*N
) const {
8763 return any_of(N
->op_values(), [this](SDValue Op
) { return *this == Op
; });
8766 bool SDNode::isOperandOf(const SDNode
*N
) const {
8767 return any_of(N
->op_values(),
8768 [this](SDValue Op
) { return this == Op
.getNode(); });
8771 /// reachesChainWithoutSideEffects - Return true if this operand (which must
8772 /// be a chain) reaches the specified operand without crossing any
8773 /// side-effecting instructions on any chain path. In practice, this looks
8774 /// through token factors and non-volatile loads. In order to remain efficient,
8775 /// this only looks a couple of nodes in, it does not do an exhaustive search.
8777 /// Note that we only need to examine chains when we're searching for
8778 /// side-effects; SelectionDAG requires that all side-effects are represented
8779 /// by chains, even if another operand would force a specific ordering. This
8780 /// constraint is necessary to allow transformations like splitting loads.
8781 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest
,
8782 unsigned Depth
) const {
8783 if (*this == Dest
) return true;
8785 // Don't search too deeply, we just want to be able to see through
8786 // TokenFactor's etc.
8787 if (Depth
== 0) return false;
8789 // If this is a token factor, all inputs to the TF happen in parallel.
8790 if (getOpcode() == ISD::TokenFactor
) {
8791 // First, try a shallow search.
8792 if (is_contained((*this)->ops(), Dest
)) {
8793 // We found the chain we want as an operand of this TokenFactor.
8794 // Essentially, we reach the chain without side-effects if we could
8795 // serialize the TokenFactor into a simple chain of operations with
8796 // Dest as the last operation. This is automatically true if the
8797 // chain has one use: there are no other ordering constraints.
8798 // If the chain has more than one use, we give up: some other
8799 // use of Dest might force a side-effect between Dest and the current
8801 if (Dest
.hasOneUse())
8804 // Next, try a deep search: check whether every operand of the TokenFactor
8806 return llvm::all_of((*this)->ops(), [=](SDValue Op
) {
8807 return Op
.reachesChainWithoutSideEffects(Dest
, Depth
- 1);
8811 // Loads don't have side effects, look through them.
8812 if (LoadSDNode
*Ld
= dyn_cast
<LoadSDNode
>(*this)) {
8813 if (!Ld
->isVolatile())
8814 return Ld
->getChain().reachesChainWithoutSideEffects(Dest
, Depth
-1);
8819 bool SDNode::hasPredecessor(const SDNode
*N
) const {
8820 SmallPtrSet
<const SDNode
*, 32> Visited
;
8821 SmallVector
<const SDNode
*, 16> Worklist
;
8822 Worklist
.push_back(this);
8823 return hasPredecessorHelper(N
, Visited
, Worklist
);
8826 void SDNode::intersectFlagsWith(const SDNodeFlags Flags
) {
8827 this->Flags
.intersectWith(Flags
);
8831 SelectionDAG::matchBinOpReduction(SDNode
*Extract
, ISD::NodeType
&BinOp
,
8832 ArrayRef
<ISD::NodeType
> CandidateBinOps
) {
8833 // The pattern must end in an extract from index 0.
8834 if (Extract
->getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
8835 !isNullConstant(Extract
->getOperand(1)))
8838 SDValue Op
= Extract
->getOperand(0);
8839 unsigned Stages
= Log2_32(Op
.getValueType().getVectorNumElements());
8841 // Match against one of the candidate binary ops.
8842 if (llvm::none_of(CandidateBinOps
, [Op
](ISD::NodeType BinOp
) {
8843 return Op
.getOpcode() == unsigned(BinOp
);
8847 // At each stage, we're looking for something that looks like:
8848 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
8849 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
8850 // i32 undef, i32 undef, i32 undef, i32 undef>
8851 // %a = binop <8 x i32> %op, %s
8852 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
8853 // we expect something like:
8854 // <4,5,6,7,u,u,u,u>
8855 // <2,3,u,u,u,u,u,u>
8856 // <1,u,u,u,u,u,u,u>
8857 unsigned CandidateBinOp
= Op
.getOpcode();
8858 for (unsigned i
= 0; i
< Stages
; ++i
) {
8859 if (Op
.getOpcode() != CandidateBinOp
)
8862 SDValue Op0
= Op
.getOperand(0);
8863 SDValue Op1
= Op
.getOperand(1);
8865 ShuffleVectorSDNode
*Shuffle
= dyn_cast
<ShuffleVectorSDNode
>(Op0
);
8869 Shuffle
= dyn_cast
<ShuffleVectorSDNode
>(Op1
);
8873 // The first operand of the shuffle should be the same as the other operand
8875 if (!Shuffle
|| Shuffle
->getOperand(0) != Op
)
8878 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
8879 for (int Index
= 0, MaskEnd
= 1 << i
; Index
< MaskEnd
; ++Index
)
8880 if (Shuffle
->getMaskElt(Index
) != MaskEnd
+ Index
)
8884 BinOp
= (ISD::NodeType
)CandidateBinOp
;
8888 SDValue
SelectionDAG::UnrollVectorOp(SDNode
*N
, unsigned ResNE
) {
8889 assert(N
->getNumValues() == 1 &&
8890 "Can't unroll a vector with multiple results!");
8892 EVT VT
= N
->getValueType(0);
8893 unsigned NE
= VT
.getVectorNumElements();
8894 EVT EltVT
= VT
.getVectorElementType();
8897 SmallVector
<SDValue
, 8> Scalars
;
8898 SmallVector
<SDValue
, 4> Operands(N
->getNumOperands());
8900 // If ResNE is 0, fully unroll the vector op.
8903 else if (NE
> ResNE
)
8907 for (i
= 0; i
!= NE
; ++i
) {
8908 for (unsigned j
= 0, e
= N
->getNumOperands(); j
!= e
; ++j
) {
8909 SDValue Operand
= N
->getOperand(j
);
8910 EVT OperandVT
= Operand
.getValueType();
8911 if (OperandVT
.isVector()) {
8912 // A vector operand; extract a single element.
8913 EVT OperandEltVT
= OperandVT
.getVectorElementType();
8915 getNode(ISD::EXTRACT_VECTOR_ELT
, dl
, OperandEltVT
, Operand
,
8916 getConstant(i
, dl
, TLI
->getVectorIdxTy(getDataLayout())));
8918 // A scalar operand; just use it as is.
8919 Operands
[j
] = Operand
;
8923 switch (N
->getOpcode()) {
8925 Scalars
.push_back(getNode(N
->getOpcode(), dl
, EltVT
, Operands
,
8930 Scalars
.push_back(getNode(ISD::SELECT
, dl
, EltVT
, Operands
));
8937 Scalars
.push_back(getNode(N
->getOpcode(), dl
, EltVT
, Operands
[0],
8938 getShiftAmountOperand(Operands
[0].getValueType(),
8941 case ISD::SIGN_EXTEND_INREG
:
8942 case ISD::FP_ROUND_INREG
: {
8943 EVT ExtVT
= cast
<VTSDNode
>(Operands
[1])->getVT().getVectorElementType();
8944 Scalars
.push_back(getNode(N
->getOpcode(), dl
, EltVT
,
8946 getValueType(ExtVT
)));
8951 for (; i
< ResNE
; ++i
)
8952 Scalars
.push_back(getUNDEF(EltVT
));
8954 EVT VecVT
= EVT::getVectorVT(*getContext(), EltVT
, ResNE
);
8955 return getBuildVector(VecVT
, dl
, Scalars
);
8958 std::pair
<SDValue
, SDValue
> SelectionDAG::UnrollVectorOverflowOp(
8959 SDNode
*N
, unsigned ResNE
) {
8960 unsigned Opcode
= N
->getOpcode();
8961 assert((Opcode
== ISD::UADDO
|| Opcode
== ISD::SADDO
||
8962 Opcode
== ISD::USUBO
|| Opcode
== ISD::SSUBO
||
8963 Opcode
== ISD::UMULO
|| Opcode
== ISD::SMULO
) &&
8964 "Expected an overflow opcode");
8966 EVT ResVT
= N
->getValueType(0);
8967 EVT OvVT
= N
->getValueType(1);
8968 EVT ResEltVT
= ResVT
.getVectorElementType();
8969 EVT OvEltVT
= OvVT
.getVectorElementType();
8972 // If ResNE is 0, fully unroll the vector op.
8973 unsigned NE
= ResVT
.getVectorNumElements();
8976 else if (NE
> ResNE
)
8979 SmallVector
<SDValue
, 8> LHSScalars
;
8980 SmallVector
<SDValue
, 8> RHSScalars
;
8981 ExtractVectorElements(N
->getOperand(0), LHSScalars
, 0, NE
);
8982 ExtractVectorElements(N
->getOperand(1), RHSScalars
, 0, NE
);
8984 EVT SVT
= TLI
->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT
);
8985 SDVTList VTs
= getVTList(ResEltVT
, SVT
);
8986 SmallVector
<SDValue
, 8> ResScalars
;
8987 SmallVector
<SDValue
, 8> OvScalars
;
8988 for (unsigned i
= 0; i
< NE
; ++i
) {
8989 SDValue Res
= getNode(Opcode
, dl
, VTs
, LHSScalars
[i
], RHSScalars
[i
]);
8991 getSelect(dl
, OvEltVT
, Res
.getValue(1),
8992 getBoolConstant(true, dl
, OvEltVT
, ResVT
),
8993 getConstant(0, dl
, OvEltVT
));
8995 ResScalars
.push_back(Res
);
8996 OvScalars
.push_back(Ov
);
8999 ResScalars
.append(ResNE
- NE
, getUNDEF(ResEltVT
));
9000 OvScalars
.append(ResNE
- NE
, getUNDEF(OvEltVT
));
9002 EVT NewResVT
= EVT::getVectorVT(*getContext(), ResEltVT
, ResNE
);
9003 EVT NewOvVT
= EVT::getVectorVT(*getContext(), OvEltVT
, ResNE
);
9004 return std::make_pair(getBuildVector(NewResVT
, dl
, ResScalars
),
9005 getBuildVector(NewOvVT
, dl
, OvScalars
));
9008 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode
*LD
,
9012 if (LD
->isVolatile() || Base
->isVolatile())
9014 if (LD
->isIndexed() || Base
->isIndexed())
9016 if (LD
->getChain() != Base
->getChain())
9018 EVT VT
= LD
->getValueType(0);
9019 if (VT
.getSizeInBits() / 8 != Bytes
)
9022 auto BaseLocDecomp
= BaseIndexOffset::match(Base
, *this);
9023 auto LocDecomp
= BaseIndexOffset::match(LD
, *this);
9026 if (BaseLocDecomp
.equalBaseIndex(LocDecomp
, *this, Offset
))
9027 return (Dist
* Bytes
== Offset
);
9031 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
9032 /// it cannot be inferred.
9033 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr
) const {
9034 // If this is a GlobalAddress + cst, return the alignment.
9035 const GlobalValue
*GV
;
9036 int64_t GVOffset
= 0;
9037 if (TLI
->isGAPlusOffset(Ptr
.getNode(), GV
, GVOffset
)) {
9038 unsigned IdxWidth
= getDataLayout().getIndexTypeSizeInBits(GV
->getType());
9039 KnownBits
Known(IdxWidth
);
9040 llvm::computeKnownBits(GV
, Known
, getDataLayout());
9041 unsigned AlignBits
= Known
.countMinTrailingZeros();
9042 unsigned Align
= AlignBits
? 1 << std::min(31U, AlignBits
) : 0;
9044 return MinAlign(Align
, GVOffset
);
9047 // If this is a direct reference to a stack slot, use information about the
9048 // stack slot's alignment.
9049 int FrameIdx
= INT_MIN
;
9050 int64_t FrameOffset
= 0;
9051 if (FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(Ptr
)) {
9052 FrameIdx
= FI
->getIndex();
9053 } else if (isBaseWithConstantOffset(Ptr
) &&
9054 isa
<FrameIndexSDNode
>(Ptr
.getOperand(0))) {
9056 FrameIdx
= cast
<FrameIndexSDNode
>(Ptr
.getOperand(0))->getIndex();
9057 FrameOffset
= Ptr
.getConstantOperandVal(1);
9060 if (FrameIdx
!= INT_MIN
) {
9061 const MachineFrameInfo
&MFI
= getMachineFunction().getFrameInfo();
9062 unsigned FIInfoAlign
= MinAlign(MFI
.getObjectAlignment(FrameIdx
),
9070 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9071 /// which is split (or expanded) into two not necessarily identical pieces.
9072 std::pair
<EVT
, EVT
> SelectionDAG::GetSplitDestVTs(const EVT
&VT
) const {
9073 // Currently all types are split in half.
9076 LoVT
= HiVT
= TLI
->getTypeToTransformTo(*getContext(), VT
);
9078 LoVT
= HiVT
= VT
.getHalfNumVectorElementsVT(*getContext());
9080 return std::make_pair(LoVT
, HiVT
);
9083 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9085 std::pair
<SDValue
, SDValue
>
9086 SelectionDAG::SplitVector(const SDValue
&N
, const SDLoc
&DL
, const EVT
&LoVT
,
9088 assert(LoVT
.getVectorNumElements() + HiVT
.getVectorNumElements() <=
9089 N
.getValueType().getVectorNumElements() &&
9090 "More vector elements requested than available!");
9092 Lo
= getNode(ISD::EXTRACT_SUBVECTOR
, DL
, LoVT
, N
,
9093 getConstant(0, DL
, TLI
->getVectorIdxTy(getDataLayout())));
9094 Hi
= getNode(ISD::EXTRACT_SUBVECTOR
, DL
, HiVT
, N
,
9095 getConstant(LoVT
.getVectorNumElements(), DL
,
9096 TLI
->getVectorIdxTy(getDataLayout())));
9097 return std::make_pair(Lo
, Hi
);
9100 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
9101 SDValue
SelectionDAG::WidenVector(const SDValue
&N
, const SDLoc
&DL
) {
9102 EVT VT
= N
.getValueType();
9103 EVT WideVT
= EVT::getVectorVT(*getContext(), VT
.getVectorElementType(),
9104 NextPowerOf2(VT
.getVectorNumElements()));
9105 return getNode(ISD::INSERT_SUBVECTOR
, DL
, WideVT
, getUNDEF(WideVT
), N
,
9106 getConstant(0, DL
, TLI
->getVectorIdxTy(getDataLayout())));
9109 void SelectionDAG::ExtractVectorElements(SDValue Op
,
9110 SmallVectorImpl
<SDValue
> &Args
,
9111 unsigned Start
, unsigned Count
) {
9112 EVT VT
= Op
.getValueType();
9114 Count
= VT
.getVectorNumElements();
9116 EVT EltVT
= VT
.getVectorElementType();
9117 EVT IdxTy
= TLI
->getVectorIdxTy(getDataLayout());
9119 for (unsigned i
= Start
, e
= Start
+ Count
; i
!= e
; ++i
) {
9120 Args
.push_back(getNode(ISD::EXTRACT_VECTOR_ELT
, SL
, EltVT
,
9121 Op
, getConstant(i
, SL
, IdxTy
)));
9125 // getAddressSpace - Return the address space this GlobalAddress belongs to.
9126 unsigned GlobalAddressSDNode::getAddressSpace() const {
9127 return getGlobal()->getType()->getAddressSpace();
9130 Type
*ConstantPoolSDNode::getType() const {
9131 if (isMachineConstantPoolEntry())
9132 return Val
.MachineCPVal
->getType();
9133 return Val
.ConstVal
->getType();
9136 bool BuildVectorSDNode::isConstantSplat(APInt
&SplatValue
, APInt
&SplatUndef
,
9137 unsigned &SplatBitSize
,
9139 unsigned MinSplatBits
,
9140 bool IsBigEndian
) const {
9141 EVT VT
= getValueType(0);
9142 assert(VT
.isVector() && "Expected a vector type");
9143 unsigned VecWidth
= VT
.getSizeInBits();
9144 if (MinSplatBits
> VecWidth
)
9147 // FIXME: The widths are based on this node's type, but build vectors can
9148 // truncate their operands.
9149 SplatValue
= APInt(VecWidth
, 0);
9150 SplatUndef
= APInt(VecWidth
, 0);
9152 // Get the bits. Bits with undefined values (when the corresponding element
9153 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
9154 // in SplatValue. If any of the values are not constant, give up and return
9156 unsigned int NumOps
= getNumOperands();
9157 assert(NumOps
> 0 && "isConstantSplat has 0-size build vector");
9158 unsigned EltWidth
= VT
.getScalarSizeInBits();
9160 for (unsigned j
= 0; j
< NumOps
; ++j
) {
9161 unsigned i
= IsBigEndian
? NumOps
- 1 - j
: j
;
9162 SDValue OpVal
= getOperand(i
);
9163 unsigned BitPos
= j
* EltWidth
;
9165 if (OpVal
.isUndef())
9166 SplatUndef
.setBits(BitPos
, BitPos
+ EltWidth
);
9167 else if (auto *CN
= dyn_cast
<ConstantSDNode
>(OpVal
))
9168 SplatValue
.insertBits(CN
->getAPIntValue().zextOrTrunc(EltWidth
), BitPos
);
9169 else if (auto *CN
= dyn_cast
<ConstantFPSDNode
>(OpVal
))
9170 SplatValue
.insertBits(CN
->getValueAPF().bitcastToAPInt(), BitPos
);
9175 // The build_vector is all constants or undefs. Find the smallest element
9176 // size that splats the vector.
9177 HasAnyUndefs
= (SplatUndef
!= 0);
9179 // FIXME: This does not work for vectors with elements less than 8 bits.
9180 while (VecWidth
> 8) {
9181 unsigned HalfSize
= VecWidth
/ 2;
9182 APInt HighValue
= SplatValue
.lshr(HalfSize
).trunc(HalfSize
);
9183 APInt LowValue
= SplatValue
.trunc(HalfSize
);
9184 APInt HighUndef
= SplatUndef
.lshr(HalfSize
).trunc(HalfSize
);
9185 APInt LowUndef
= SplatUndef
.trunc(HalfSize
);
9187 // If the two halves do not match (ignoring undef bits), stop here.
9188 if ((HighValue
& ~LowUndef
) != (LowValue
& ~HighUndef
) ||
9189 MinSplatBits
> HalfSize
)
9192 SplatValue
= HighValue
| LowValue
;
9193 SplatUndef
= HighUndef
& LowUndef
;
9195 VecWidth
= HalfSize
;
9198 SplatBitSize
= VecWidth
;
9202 SDValue
BuildVectorSDNode::getSplatValue(const APInt
&DemandedElts
,
9203 BitVector
*UndefElements
) const {
9204 if (UndefElements
) {
9205 UndefElements
->clear();
9206 UndefElements
->resize(getNumOperands());
9208 assert(getNumOperands() == DemandedElts
.getBitWidth() &&
9209 "Unexpected vector size");
9213 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
9214 if (!DemandedElts
[i
])
9216 SDValue Op
= getOperand(i
);
9219 (*UndefElements
)[i
] = true;
9220 } else if (!Splatted
) {
9222 } else if (Splatted
!= Op
) {
9228 unsigned FirstDemandedIdx
= DemandedElts
.countTrailingZeros();
9229 assert(getOperand(FirstDemandedIdx
).isUndef() &&
9230 "Can only have a splat without a constant for all undefs.");
9231 return getOperand(FirstDemandedIdx
);
9237 SDValue
BuildVectorSDNode::getSplatValue(BitVector
*UndefElements
) const {
9238 APInt DemandedElts
= APInt::getAllOnesValue(getNumOperands());
9239 return getSplatValue(DemandedElts
, UndefElements
);
9243 BuildVectorSDNode::getConstantSplatNode(const APInt
&DemandedElts
,
9244 BitVector
*UndefElements
) const {
9245 return dyn_cast_or_null
<ConstantSDNode
>(
9246 getSplatValue(DemandedElts
, UndefElements
));
9250 BuildVectorSDNode::getConstantSplatNode(BitVector
*UndefElements
) const {
9251 return dyn_cast_or_null
<ConstantSDNode
>(getSplatValue(UndefElements
));
9255 BuildVectorSDNode::getConstantFPSplatNode(const APInt
&DemandedElts
,
9256 BitVector
*UndefElements
) const {
9257 return dyn_cast_or_null
<ConstantFPSDNode
>(
9258 getSplatValue(DemandedElts
, UndefElements
));
9262 BuildVectorSDNode::getConstantFPSplatNode(BitVector
*UndefElements
) const {
9263 return dyn_cast_or_null
<ConstantFPSDNode
>(getSplatValue(UndefElements
));
9267 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector
*UndefElements
,
9268 uint32_t BitWidth
) const {
9269 if (ConstantFPSDNode
*CN
=
9270 dyn_cast_or_null
<ConstantFPSDNode
>(getSplatValue(UndefElements
))) {
9272 APSInt
IntVal(BitWidth
);
9273 const APFloat
&APF
= CN
->getValueAPF();
9274 if (APF
.convertToInteger(IntVal
, APFloat::rmTowardZero
, &IsExact
) !=
9279 return IntVal
.exactLogBase2();
9284 bool BuildVectorSDNode::isConstant() const {
9285 for (const SDValue
&Op
: op_values()) {
9286 unsigned Opc
= Op
.getOpcode();
9287 if (Opc
!= ISD::UNDEF
&& Opc
!= ISD::Constant
&& Opc
!= ISD::ConstantFP
)
9293 bool ShuffleVectorSDNode::isSplatMask(const int *Mask
, EVT VT
) {
9294 // Find the first non-undef value in the shuffle mask.
9296 for (i
= 0, e
= VT
.getVectorNumElements(); i
!= e
&& Mask
[i
] < 0; ++i
)
9299 // If all elements are undefined, this shuffle can be considered a splat
9300 // (although it should eventually get simplified away completely).
9304 // Make sure all remaining elements are either undef or the same as the first
9306 for (int Idx
= Mask
[i
]; i
!= e
; ++i
)
9307 if (Mask
[i
] >= 0 && Mask
[i
] != Idx
)
9312 // Returns the SDNode if it is a constant integer BuildVector
9313 // or constant integer.
9314 SDNode
*SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N
) {
9315 if (isa
<ConstantSDNode
>(N
))
9317 if (ISD::isBuildVectorOfConstantSDNodes(N
.getNode()))
9319 // Treat a GlobalAddress supporting constant offset folding as a
9320 // constant integer.
9321 if (GlobalAddressSDNode
*GA
= dyn_cast
<GlobalAddressSDNode
>(N
))
9322 if (GA
->getOpcode() == ISD::GlobalAddress
&&
9323 TLI
->isOffsetFoldingLegal(GA
))
9328 SDNode
*SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N
) {
9329 if (isa
<ConstantFPSDNode
>(N
))
9332 if (ISD::isBuildVectorOfConstantFPSDNodes(N
.getNode()))
9338 void SelectionDAG::createOperands(SDNode
*Node
, ArrayRef
<SDValue
> Vals
) {
9339 assert(!Node
->OperandList
&& "Node already has operands");
9340 assert(SDNode::getMaxNumOperands() >= Vals
.size() &&
9341 "too many operands to fit into SDNode");
9342 SDUse
*Ops
= OperandRecycler
.allocate(
9343 ArrayRecycler
<SDUse
>::Capacity::get(Vals
.size()), OperandAllocator
);
9345 bool IsDivergent
= false;
9346 for (unsigned I
= 0; I
!= Vals
.size(); ++I
) {
9347 Ops
[I
].setUser(Node
);
9348 Ops
[I
].setInitial(Vals
[I
]);
9349 if (Ops
[I
].Val
.getValueType() != MVT::Other
) // Skip Chain. It does not carry divergence.
9350 IsDivergent
= IsDivergent
|| Ops
[I
].getNode()->isDivergent();
9352 Node
->NumOperands
= Vals
.size();
9353 Node
->OperandList
= Ops
;
9354 IsDivergent
|= TLI
->isSDNodeSourceOfDivergence(Node
, FLI
, DA
);
9355 if (!TLI
->isSDNodeAlwaysUniform(Node
))
9356 Node
->SDNodeBits
.IsDivergent
= IsDivergent
;
9357 checkForCycles(Node
);
9360 SDValue
SelectionDAG::getTokenFactor(const SDLoc
&DL
,
9361 SmallVectorImpl
<SDValue
> &Vals
) {
9362 size_t Limit
= SDNode::getMaxNumOperands();
9363 while (Vals
.size() > Limit
) {
9364 unsigned SliceIdx
= Vals
.size() - Limit
;
9365 auto ExtractedTFs
= ArrayRef
<SDValue
>(Vals
).slice(SliceIdx
, Limit
);
9366 SDValue NewTF
= getNode(ISD::TokenFactor
, DL
, MVT::Other
, ExtractedTFs
);
9367 Vals
.erase(Vals
.begin() + SliceIdx
, Vals
.end());
9368 Vals
.emplace_back(NewTF
);
9370 return getNode(ISD::TokenFactor
, DL
, MVT::Other
, Vals
);
9374 static void checkForCyclesHelper(const SDNode
*N
,
9375 SmallPtrSetImpl
<const SDNode
*> &Visited
,
9376 SmallPtrSetImpl
<const SDNode
*> &Checked
,
9377 const llvm::SelectionDAG
*DAG
) {
9378 // If this node has already been checked, don't check it again.
9379 if (Checked
.count(N
))
9382 // If a node has already been visited on this depth-first walk, reject it as
9384 if (!Visited
.insert(N
).second
) {
9385 errs() << "Detected cycle in SelectionDAG\n";
9386 dbgs() << "Offending node:\n";
9387 N
->dumprFull(DAG
); dbgs() << "\n";
9391 for (const SDValue
&Op
: N
->op_values())
9392 checkForCyclesHelper(Op
.getNode(), Visited
, Checked
, DAG
);
9399 void llvm::checkForCycles(const llvm::SDNode
*N
,
9400 const llvm::SelectionDAG
*DAG
,
9404 #ifdef EXPENSIVE_CHECKS
9406 #endif // EXPENSIVE_CHECKS
9408 assert(N
&& "Checking nonexistent SDNode");
9409 SmallPtrSet
<const SDNode
*, 32> visited
;
9410 SmallPtrSet
<const SDNode
*, 32> checked
;
9411 checkForCyclesHelper(N
, visited
, checked
, DAG
);
9416 void llvm::checkForCycles(const llvm::SelectionDAG
*DAG
, bool force
) {
9417 checkForCycles(DAG
->getRoot().getNode(), DAG
, force
);