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,
297 bool AllowUndefs, bool AllowTypeMismatch) {
298 if (!AllowTypeMismatch && 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 (!AllowTypeMismatch && (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 SDCallSiteDbgInfo.clear();
1088 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1089 static_cast<CondCodeSDNode*>(nullptr));
1090 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1091 static_cast<SDNode*>(nullptr));
1093 EntryNode.UseList = nullptr;
1094 InsertNode(&EntryNode);
1095 Root = getEntryNode();
1099 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1100 return VT.bitsGT(Op.getValueType())
1101 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1102 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1105 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1106 return VT.bitsGT(Op.getValueType()) ?
1107 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1108 getNode(ISD::TRUNCATE, DL, VT, Op);
1111 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1112 return VT.bitsGT(Op.getValueType()) ?
1113 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1114 getNode(ISD::TRUNCATE, DL, VT, Op);
1117 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1118 return VT.bitsGT(Op.getValueType()) ?
1119 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1120 getNode(ISD::TRUNCATE, DL, VT, Op);
1123 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1125 if (VT.bitsLE(Op.getValueType()))
1126 return getNode(ISD::TRUNCATE, SL, VT, Op);
1128 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1129 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1132 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1133 assert(!VT.isVector() &&
1134 "getZeroExtendInReg should use the vector element type instead of "
1135 "the vector type!");
1136 if (Op.getValueType().getScalarType() == VT) return Op;
1137 unsigned BitWidth = Op.getScalarValueSizeInBits();
1138 APInt Imm = APInt::getLowBitsSet(BitWidth,
1139 VT.getSizeInBits());
1140 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1141 getConstant(Imm, DL, Op.getValueType()));
1144 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1145 // Only unsigned pointer semantics are supported right now. In the future this
1146 // might delegate to TLI to check pointer signedness.
1147 return getZExtOrTrunc(Op, DL, VT);
1150 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1151 // Only unsigned pointer semantics are supported right now. In the future this
1152 // might delegate to TLI to check pointer signedness.
1153 return getZeroExtendInReg(Op, DL, VT);
1156 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1157 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1158 EVT EltVT = VT.getScalarType();
1160 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1161 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1164 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1165 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1166 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1169 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1172 return getConstant(0, DL, VT);
1174 switch (TLI->getBooleanContents(OpVT)) {
1175 case TargetLowering::ZeroOrOneBooleanContent:
1176 case TargetLowering::UndefinedBooleanContent:
1177 return getConstant(1, DL, VT);
1178 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1179 return getAllOnesConstant(DL, VT);
1181 llvm_unreachable("Unexpected boolean content enum!");
1184 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1185 bool isT, bool isO) {
1186 EVT EltVT = VT.getScalarType();
1187 assert((EltVT.getSizeInBits() >= 64 ||
1188 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1189 "getConstant with a uint64_t value that doesn't fit in the type!");
1190 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1193 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1194 bool isT, bool isO) {
1195 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1198 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1199 EVT VT, bool isT, bool isO) {
1200 assert(VT.isInteger() && "Cannot create FP integer constant!");
1202 EVT EltVT = VT.getScalarType();
1203 const ConstantInt *Elt = &Val;
1205 // In some cases the vector type is legal but the element type is illegal and
1206 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1207 // inserted value (the type does not need to match the vector element type).
1208 // Any extra bits introduced will be truncated away.
1209 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1210 TargetLowering::TypePromoteInteger) {
1211 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1212 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1213 Elt = ConstantInt::get(*getContext(), NewVal);
1215 // In other cases the element type is illegal and needs to be expanded, for
1216 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1217 // the value into n parts and use a vector type with n-times the elements.
1218 // Then bitcast to the type requested.
1219 // Legalizing constants too early makes the DAGCombiner's job harder so we
1220 // only legalize if the DAG tells us we must produce legal types.
1221 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1222 TLI->getTypeAction(*getContext(), EltVT) ==
1223 TargetLowering::TypeExpandInteger) {
1224 const APInt &NewVal = Elt->getValue();
1225 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1226 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1227 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1228 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1230 // Check the temporary vector is the correct size. If this fails then
1231 // getTypeToTransformTo() probably returned a type whose size (in bits)
1232 // isn't a power-of-2 factor of the requested type size.
1233 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1235 SmallVector<SDValue, 2> EltParts;
1236 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1237 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1238 .zextOrTrunc(ViaEltSizeInBits), DL,
1239 ViaEltVT, isT, isO));
1242 // EltParts is currently in little endian order. If we actually want
1243 // big-endian order then reverse it now.
1244 if (getDataLayout().isBigEndian())
1245 std::reverse(EltParts.begin(), EltParts.end());
1247 // The elements must be reversed when the element order is different
1248 // to the endianness of the elements (because the BITCAST is itself a
1249 // vector shuffle in this situation). However, we do not need any code to
1250 // perform this reversal because getConstant() is producing a vector
1252 // This situation occurs in MIPS MSA.
1254 SmallVector<SDValue, 8> Ops;
1255 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1256 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1258 SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1262 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1263 "APInt size does not match type size!");
1264 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1265 FoldingSetNodeID ID;
1266 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1270 SDNode *N = nullptr;
1271 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1273 return SDValue(N, 0);
1276 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1277 CSEMap.InsertNode(N, IP);
1279 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1282 SDValue Result(N, 0);
1284 Result = getSplatBuildVector(VT, DL, Result);
1289 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1291 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1294 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1295 const SDLoc &DL, bool LegalTypes) {
1296 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1297 return getConstant(Val, DL, ShiftVT);
1300 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1302 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1305 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1306 EVT VT, bool isTarget) {
1307 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1309 EVT EltVT = VT.getScalarType();
1311 // Do the map lookup using the actual bit pattern for the floating point
1312 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1313 // we don't have issues with SNANs.
1314 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1315 FoldingSetNodeID ID;
1316 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1319 SDNode *N = nullptr;
1320 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1322 return SDValue(N, 0);
1325 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1326 CSEMap.InsertNode(N, IP);
1330 SDValue Result(N, 0);
1332 Result = getSplatBuildVector(VT, DL, Result);
1333 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1337 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1339 EVT EltVT = VT.getScalarType();
1340 if (EltVT == MVT::f32)
1341 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1342 else if (EltVT == MVT::f64)
1343 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1344 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1345 EltVT == MVT::f16) {
1347 APFloat APF = APFloat(Val);
1348 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1350 return getConstantFP(APF, DL, VT, isTarget);
1352 llvm_unreachable("Unsupported type in getConstantFP");
1355 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1356 EVT VT, int64_t Offset, bool isTargetGA,
1357 unsigned char TargetFlags) {
1358 assert((TargetFlags == 0 || isTargetGA) &&
1359 "Cannot set target flags on target-independent globals");
1361 // Truncate (with sign-extension) the offset value to the pointer size.
1362 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1364 Offset = SignExtend64(Offset, BitWidth);
1367 if (GV->isThreadLocal())
1368 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1370 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1372 FoldingSetNodeID ID;
1373 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1375 ID.AddInteger(Offset);
1376 ID.AddInteger(TargetFlags);
1378 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1379 return SDValue(E, 0);
1381 auto *N = newSDNode<GlobalAddressSDNode>(
1382 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1383 CSEMap.InsertNode(N, IP);
1385 return SDValue(N, 0);
1388 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1389 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1390 FoldingSetNodeID ID;
1391 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1394 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1395 return SDValue(E, 0);
1397 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1398 CSEMap.InsertNode(N, IP);
1400 return SDValue(N, 0);
1403 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1404 unsigned char TargetFlags) {
1405 assert((TargetFlags == 0 || isTarget) &&
1406 "Cannot set target flags on target-independent jump tables");
1407 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1408 FoldingSetNodeID ID;
1409 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1411 ID.AddInteger(TargetFlags);
1413 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1414 return SDValue(E, 0);
1416 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1417 CSEMap.InsertNode(N, IP);
1419 return SDValue(N, 0);
1422 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1423 unsigned Alignment, int Offset,
1425 unsigned char TargetFlags) {
1426 assert((TargetFlags == 0 || isTarget) &&
1427 "Cannot set target flags on target-independent globals");
1429 Alignment = MF->getFunction().hasOptSize()
1430 ? getDataLayout().getABITypeAlignment(C->getType())
1431 : getDataLayout().getPrefTypeAlignment(C->getType());
1432 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1433 FoldingSetNodeID ID;
1434 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1435 ID.AddInteger(Alignment);
1436 ID.AddInteger(Offset);
1438 ID.AddInteger(TargetFlags);
1440 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1441 return SDValue(E, 0);
1443 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1445 CSEMap.InsertNode(N, IP);
1447 return SDValue(N, 0);
1450 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1451 unsigned Alignment, int Offset,
1453 unsigned char TargetFlags) {
1454 assert((TargetFlags == 0 || isTarget) &&
1455 "Cannot set target flags on target-independent globals");
1457 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1458 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1459 FoldingSetNodeID ID;
1460 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1461 ID.AddInteger(Alignment);
1462 ID.AddInteger(Offset);
1463 C->addSelectionDAGCSEId(ID);
1464 ID.AddInteger(TargetFlags);
1466 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1467 return SDValue(E, 0);
1469 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1471 CSEMap.InsertNode(N, IP);
1473 return SDValue(N, 0);
1476 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1477 unsigned char TargetFlags) {
1478 FoldingSetNodeID ID;
1479 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1480 ID.AddInteger(Index);
1481 ID.AddInteger(Offset);
1482 ID.AddInteger(TargetFlags);
1484 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1485 return SDValue(E, 0);
1487 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1488 CSEMap.InsertNode(N, IP);
1490 return SDValue(N, 0);
1493 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1494 FoldingSetNodeID ID;
1495 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1498 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1499 return SDValue(E, 0);
1501 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1502 CSEMap.InsertNode(N, IP);
1504 return SDValue(N, 0);
1507 SDValue SelectionDAG::getValueType(EVT VT) {
1508 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1509 ValueTypeNodes.size())
1510 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1512 SDNode *&N = VT.isExtended() ?
1513 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1515 if (N) return SDValue(N, 0);
1516 N = newSDNode<VTSDNode>(VT);
1518 return SDValue(N, 0);
1521 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1522 SDNode *&N = ExternalSymbols[Sym];
1523 if (N) return SDValue(N, 0);
1524 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1526 return SDValue(N, 0);
1529 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1530 SDNode *&N = MCSymbols[Sym];
1532 return SDValue(N, 0);
1533 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1535 return SDValue(N, 0);
1538 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1539 unsigned char TargetFlags) {
1541 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1543 if (N) return SDValue(N, 0);
1544 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1546 return SDValue(N, 0);
1549 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1550 if ((unsigned)Cond >= CondCodeNodes.size())
1551 CondCodeNodes.resize(Cond+1);
1553 if (!CondCodeNodes[Cond]) {
1554 auto *N = newSDNode<CondCodeSDNode>(Cond);
1555 CondCodeNodes[Cond] = N;
1559 return SDValue(CondCodeNodes[Cond], 0);
1562 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1563 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1564 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1566 ShuffleVectorSDNode::commuteMask(M);
1569 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1570 SDValue N2, ArrayRef<int> Mask) {
1571 assert(VT.getVectorNumElements() == Mask.size() &&
1572 "Must have the same number of vector elements as mask elements!");
1573 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1574 "Invalid VECTOR_SHUFFLE");
1576 // Canonicalize shuffle undef, undef -> undef
1577 if (N1.isUndef() && N2.isUndef())
1578 return getUNDEF(VT);
1580 // Validate that all indices in Mask are within the range of the elements
1581 // input to the shuffle.
1582 int NElts = Mask.size();
1583 assert(llvm::all_of(Mask,
1584 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1585 "Index out of range");
1587 // Copy the mask so we can do any needed cleanup.
1588 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1590 // Canonicalize shuffle v, v -> v, undef
1593 for (int i = 0; i != NElts; ++i)
1594 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1597 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1599 commuteShuffle(N1, N2, MaskVec);
1601 if (TLI->hasVectorBlend()) {
1602 // If shuffling a splat, try to blend the splat instead. We do this here so
1603 // that even when this arises during lowering we don't have to re-handle it.
1604 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1605 BitVector UndefElements;
1606 SDValue Splat = BV->getSplatValue(&UndefElements);
1610 for (int i = 0; i < NElts; ++i) {
1611 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1614 // If this input comes from undef, mark it as such.
1615 if (UndefElements[MaskVec[i] - Offset]) {
1620 // If we can blend a non-undef lane, use that instead.
1621 if (!UndefElements[i])
1622 MaskVec[i] = i + Offset;
1625 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1626 BlendSplat(N1BV, 0);
1627 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1628 BlendSplat(N2BV, NElts);
1631 // Canonicalize all index into lhs, -> shuffle lhs, undef
1632 // Canonicalize all index into rhs, -> shuffle rhs, undef
1633 bool AllLHS = true, AllRHS = true;
1634 bool N2Undef = N2.isUndef();
1635 for (int i = 0; i != NElts; ++i) {
1636 if (MaskVec[i] >= NElts) {
1641 } else if (MaskVec[i] >= 0) {
1645 if (AllLHS && AllRHS)
1646 return getUNDEF(VT);
1647 if (AllLHS && !N2Undef)
1651 commuteShuffle(N1, N2, MaskVec);
1653 // Reset our undef status after accounting for the mask.
1654 N2Undef = N2.isUndef();
1655 // Re-check whether both sides ended up undef.
1656 if (N1.isUndef() && N2Undef)
1657 return getUNDEF(VT);
1659 // If Identity shuffle return that node.
1660 bool Identity = true, AllSame = true;
1661 for (int i = 0; i != NElts; ++i) {
1662 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1663 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1665 if (Identity && NElts)
1668 // Shuffling a constant splat doesn't change the result.
1672 // Look through any bitcasts. We check that these don't change the number
1673 // (and size) of elements and just changes their types.
1674 while (V.getOpcode() == ISD::BITCAST)
1675 V = V->getOperand(0);
1677 // A splat should always show up as a build vector node.
1678 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1679 BitVector UndefElements;
1680 SDValue Splat = BV->getSplatValue(&UndefElements);
1681 // If this is a splat of an undef, shuffling it is also undef.
1682 if (Splat && Splat.isUndef())
1683 return getUNDEF(VT);
1686 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1688 // We only have a splat which can skip shuffles if there is a splatted
1689 // value and no undef lanes rearranged by the shuffle.
1690 if (Splat && UndefElements.none()) {
1691 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1692 // number of elements match or the value splatted is a zero constant.
1695 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1696 if (C->isNullValue())
1700 // If the shuffle itself creates a splat, build the vector directly.
1701 if (AllSame && SameNumElts) {
1702 EVT BuildVT = BV->getValueType(0);
1703 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1704 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1706 // We may have jumped through bitcasts, so the type of the
1707 // BUILD_VECTOR may not match the type of the shuffle.
1709 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1715 FoldingSetNodeID ID;
1716 SDValue Ops[2] = { N1, N2 };
1717 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1718 for (int i = 0; i != NElts; ++i)
1719 ID.AddInteger(MaskVec[i]);
1722 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1723 return SDValue(E, 0);
1725 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1726 // SDNode doesn't have access to it. This memory will be "leaked" when
1727 // the node is deallocated, but recovered when the NodeAllocator is released.
1728 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1729 llvm::copy(MaskVec, MaskAlloc);
1731 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1732 dl.getDebugLoc(), MaskAlloc);
1733 createOperands(N, Ops);
1735 CSEMap.InsertNode(N, IP);
1737 SDValue V = SDValue(N, 0);
1738 NewSDValueDbgMsg(V, "Creating new node: ", this);
1742 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1743 EVT VT = SV.getValueType(0);
1744 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1745 ShuffleVectorSDNode::commuteMask(MaskVec);
1747 SDValue Op0 = SV.getOperand(0);
1748 SDValue Op1 = SV.getOperand(1);
1749 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1752 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1753 FoldingSetNodeID ID;
1754 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1755 ID.AddInteger(RegNo);
1757 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758 return SDValue(E, 0);
1760 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1761 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1762 CSEMap.InsertNode(N, IP);
1764 return SDValue(N, 0);
1767 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1768 FoldingSetNodeID ID;
1769 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1770 ID.AddPointer(RegMask);
1772 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1773 return SDValue(E, 0);
1775 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1776 CSEMap.InsertNode(N, IP);
1778 return SDValue(N, 0);
1781 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1783 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1786 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1787 SDValue Root, MCSymbol *Label) {
1788 FoldingSetNodeID ID;
1789 SDValue Ops[] = { Root };
1790 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1791 ID.AddPointer(Label);
1793 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1794 return SDValue(E, 0);
1797 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1798 createOperands(N, Ops);
1800 CSEMap.InsertNode(N, IP);
1802 return SDValue(N, 0);
1805 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1808 unsigned char TargetFlags) {
1809 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1811 FoldingSetNodeID ID;
1812 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1814 ID.AddInteger(Offset);
1815 ID.AddInteger(TargetFlags);
1817 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1818 return SDValue(E, 0);
1820 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1821 CSEMap.InsertNode(N, IP);
1823 return SDValue(N, 0);
1826 SDValue SelectionDAG::getSrcValue(const Value *V) {
1827 assert((!V || V->getType()->isPointerTy()) &&
1828 "SrcValue is not a pointer?");
1830 FoldingSetNodeID ID;
1831 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1835 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1836 return SDValue(E, 0);
1838 auto *N = newSDNode<SrcValueSDNode>(V);
1839 CSEMap.InsertNode(N, IP);
1841 return SDValue(N, 0);
1844 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1845 FoldingSetNodeID ID;
1846 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1850 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1851 return SDValue(E, 0);
1853 auto *N = newSDNode<MDNodeSDNode>(MD);
1854 CSEMap.InsertNode(N, IP);
1856 return SDValue(N, 0);
1859 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1860 if (VT == V.getValueType())
1863 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1866 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1867 unsigned SrcAS, unsigned DestAS) {
1868 SDValue Ops[] = {Ptr};
1869 FoldingSetNodeID ID;
1870 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1871 ID.AddInteger(SrcAS);
1872 ID.AddInteger(DestAS);
1875 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1876 return SDValue(E, 0);
1878 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1880 createOperands(N, Ops);
1882 CSEMap.InsertNode(N, IP);
1884 return SDValue(N, 0);
1887 /// getShiftAmountOperand - Return the specified value casted to
1888 /// the target's desired shift amount type.
1889 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1890 EVT OpTy = Op.getValueType();
1891 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1892 if (OpTy == ShTy || OpTy.isVector()) return Op;
1894 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1897 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1899 const TargetLowering &TLI = getTargetLoweringInfo();
1900 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1901 EVT VT = Node->getValueType(0);
1902 SDValue Tmp1 = Node->getOperand(0);
1903 SDValue Tmp2 = Node->getOperand(1);
1904 unsigned Align = Node->getConstantOperandVal(3);
1906 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1907 Tmp2, MachinePointerInfo(V));
1908 SDValue VAList = VAListLoad;
1910 if (Align > TLI.getMinStackArgumentAlignment()) {
1911 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1913 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1914 getConstant(Align - 1, dl, VAList.getValueType()));
1916 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1917 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1920 // Increment the pointer, VAList, to the next vaarg
1921 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1922 getConstant(getDataLayout().getTypeAllocSize(
1923 VT.getTypeForEVT(*getContext())),
1924 dl, VAList.getValueType()));
1925 // Store the incremented VAList to the legalized pointer
1927 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1928 // Load the actual argument out of the pointer VAList
1929 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1932 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1934 const TargetLowering &TLI = getTargetLoweringInfo();
1935 // This defaults to loading a pointer from the input and storing it to the
1936 // output, returning the chain.
1937 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1938 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1940 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1941 Node->getOperand(2), MachinePointerInfo(VS));
1942 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1943 MachinePointerInfo(VD));
1946 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1947 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1948 unsigned ByteSize = VT.getStoreSize();
1949 Type *Ty = VT.getTypeForEVT(*getContext());
1950 unsigned StackAlign =
1951 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1953 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1954 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1957 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1958 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1959 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1960 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1961 const DataLayout &DL = getDataLayout();
1963 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1965 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1966 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1967 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1970 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1971 ISD::CondCode Cond, const SDLoc &dl) {
1972 EVT OpVT = N1.getValueType();
1974 // These setcc operations always fold.
1978 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
1980 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
1992 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
1996 if (OpVT.isInteger()) {
1997 // For EQ and NE, we can always pick a value for the undef to make the
1998 // predicate pass or fail, so we can return undef.
1999 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2000 // icmp eq/ne X, undef -> undef.
2001 if ((N1.isUndef() || N2.isUndef()) &&
2002 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2003 return getUNDEF(VT);
2005 // If both operands are undef, we can return undef for int comparison.
2006 // icmp undef, undef -> undef.
2007 if (N1.isUndef() && N2.isUndef())
2008 return getUNDEF(VT);
2010 // icmp X, X -> true/false
2011 // icmp X, undef -> true/false because undef could be X.
2013 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2016 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2017 const APInt &C2 = N2C->getAPIntValue();
2018 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2019 const APInt &C1 = N1C->getAPIntValue();
2022 default: llvm_unreachable("Unknown integer setcc!");
2023 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
2024 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
2025 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2026 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2027 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2028 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2029 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2030 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2031 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2032 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2037 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2038 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2040 if (N1CFP && N2CFP) {
2041 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2044 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2045 return getUNDEF(VT);
2047 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2049 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2050 return getUNDEF(VT);
2052 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2053 R==APFloat::cmpLessThan, dl, VT,
2055 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2056 return getUNDEF(VT);
2058 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2060 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2061 return getUNDEF(VT);
2063 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2065 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2066 return getUNDEF(VT);
2068 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2069 R==APFloat::cmpEqual, dl, VT,
2071 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2072 return getUNDEF(VT);
2074 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2075 R==APFloat::cmpEqual, dl, VT, OpVT);
2076 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2078 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2080 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2081 R==APFloat::cmpEqual, dl, VT,
2083 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2085 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2086 R==APFloat::cmpLessThan, dl, VT,
2088 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2089 R==APFloat::cmpUnordered, dl, VT,
2091 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2093 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2096 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2097 // Ensure that the constant occurs on the RHS.
2098 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2099 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2101 return getSetCC(dl, VT, N2, N1, SwappedCond);
2102 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2103 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2104 // If an operand is known to be a nan (or undef that could be a nan), we can
2106 // Choosing NaN for the undef will always make unordered comparison succeed
2107 // and ordered comparison fails.
2108 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2109 switch (ISD::getUnorderedFlavor(Cond)) {
2111 llvm_unreachable("Unknown flavor!");
2112 case 0: // Known false.
2113 return getBoolConstant(false, dl, VT, OpVT);
2114 case 1: // Known true.
2115 return getBoolConstant(true, dl, VT, OpVT);
2116 case 2: // Undefined.
2117 return getUNDEF(VT);
2121 // Could not fold it.
2125 /// See if the specified operand can be simplified with the knowledge that only
2126 /// the bits specified by DemandedBits are used.
2127 /// TODO: really we should be making this into the DAG equivalent of
2128 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2129 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2130 EVT VT = V.getValueType();
2131 APInt DemandedElts = VT.isVector()
2132 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2134 return GetDemandedBits(V, DemandedBits, DemandedElts);
2137 /// See if the specified operand can be simplified with the knowledge that only
2138 /// the bits specified by DemandedBits are used in the elements specified by
2140 /// TODO: really we should be making this into the DAG equivalent of
2141 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2142 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2143 const APInt &DemandedElts) {
2144 switch (V.getOpcode()) {
2147 case ISD::Constant: {
2148 auto *CV = cast<ConstantSDNode>(V.getNode());
2149 assert(CV && "Const value should be ConstSDNode.");
2150 const APInt &CVal = CV->getAPIntValue();
2151 APInt NewVal = CVal & DemandedBits;
2153 return getConstant(NewVal, SDLoc(V), V.getValueType());
2158 // If the LHS or RHS don't contribute bits to the or, drop them.
2159 if (MaskedValueIsZero(V.getOperand(0), DemandedBits))
2160 return V.getOperand(1);
2161 if (MaskedValueIsZero(V.getOperand(1), DemandedBits))
2162 return V.getOperand(0);
2165 // Only look at single-use SRLs.
2166 if (!V.getNode()->hasOneUse())
2168 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2169 // See if we can recursively simplify the LHS.
2170 unsigned Amt = RHSC->getZExtValue();
2172 // Watch out for shift count overflow though.
2173 if (Amt >= DemandedBits.getBitWidth())
2175 APInt SrcDemandedBits = DemandedBits << Amt;
2176 if (SDValue SimplifyLHS =
2177 GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2178 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2183 // X & -1 -> X (ignoring bits which aren't demanded).
2184 // Also handle the case where masked out bits in X are known to be zero.
2185 if (ConstantSDNode *RHSC = isConstOrConstSplat(V.getOperand(1))) {
2186 const APInt &AndVal = RHSC->getAPIntValue();
2187 if (DemandedBits.isSubsetOf(AndVal) ||
2188 DemandedBits.isSubsetOf(computeKnownBits(V.getOperand(0)).Zero |
2190 return V.getOperand(0);
2194 case ISD::ANY_EXTEND: {
2195 SDValue Src = V.getOperand(0);
2196 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
2197 // Being conservative here - only peek through if we only demand bits in the
2198 // non-extended source (even though the extended bits are technically
2200 if (DemandedBits.getActiveBits() > SrcBitWidth)
2202 APInt SrcDemandedBits = DemandedBits.trunc(SrcBitWidth);
2203 if (SDValue DemandedSrc = GetDemandedBits(Src, SrcDemandedBits))
2204 return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
2207 case ISD::SIGN_EXTEND_INREG:
2208 EVT ExVT = cast<VTSDNode>(V.getOperand(1))->getVT();
2209 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2211 // If none of the extended bits are demanded, eliminate the sextinreg.
2212 if (DemandedBits.getActiveBits() <= ExVTBits)
2213 return V.getOperand(0);
2220 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2221 /// use this predicate to simplify operations downstream.
2222 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2223 unsigned BitWidth = Op.getScalarValueSizeInBits();
2224 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2227 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2228 /// this predicate to simplify operations downstream. Mask is known to be zero
2229 /// for bits that V cannot have.
2230 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2231 unsigned Depth) const {
2232 EVT VT = V.getValueType();
2233 APInt DemandedElts = VT.isVector()
2234 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2236 return MaskedValueIsZero(V, Mask, DemandedElts, Depth);
2239 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2240 /// DemandedElts. We use this predicate to simplify operations downstream.
2241 /// Mask is known to be zero for bits that V cannot have.
2242 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2243 const APInt &DemandedElts,
2244 unsigned Depth) const {
2245 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2248 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2249 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2250 unsigned Depth) const {
2251 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2254 /// isSplatValue - Return true if the vector V has the same value
2255 /// across all DemandedElts.
2256 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2259 return false; // No demanded elts, better to assume we don't know anything.
2261 EVT VT = V.getValueType();
2262 assert(VT.isVector() && "Vector type expected");
2264 unsigned NumElts = VT.getVectorNumElements();
2265 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2266 UndefElts = APInt::getNullValue(NumElts);
2268 switch (V.getOpcode()) {
2269 case ISD::BUILD_VECTOR: {
2271 for (unsigned i = 0; i != NumElts; ++i) {
2272 SDValue Op = V.getOperand(i);
2274 UndefElts.setBit(i);
2277 if (!DemandedElts[i])
2279 if (Scl && Scl != Op)
2285 case ISD::VECTOR_SHUFFLE: {
2286 // Check if this is a shuffle node doing a splat.
2287 // TODO: Do we need to handle shuffle(splat, undef, mask)?
2288 int SplatIndex = -1;
2289 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2290 for (int i = 0; i != (int)NumElts; ++i) {
2293 UndefElts.setBit(i);
2296 if (!DemandedElts[i])
2298 if (0 <= SplatIndex && SplatIndex != M)
2304 case ISD::EXTRACT_SUBVECTOR: {
2305 SDValue Src = V.getOperand(0);
2306 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(V.getOperand(1));
2307 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2308 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2309 // Offset the demanded elts by the subvector index.
2310 uint64_t Idx = SubIdx->getZExtValue();
2312 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2313 if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
2314 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2323 APInt UndefLHS, UndefRHS;
2324 SDValue LHS = V.getOperand(0);
2325 SDValue RHS = V.getOperand(1);
2326 if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
2327 isSplatValue(RHS, DemandedElts, UndefRHS)) {
2328 UndefElts = UndefLHS | UndefRHS;
2338 /// Helper wrapper to main isSplatValue function.
2339 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2340 EVT VT = V.getValueType();
2341 assert(VT.isVector() && "Vector type expected");
2342 unsigned NumElts = VT.getVectorNumElements();
2345 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
2346 return isSplatValue(V, DemandedElts, UndefElts) &&
2347 (AllowUndefs || !UndefElts);
2350 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2351 V = peekThroughExtractSubvectors(V);
2353 EVT VT = V.getValueType();
2354 unsigned Opcode = V.getOpcode();
2358 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2359 if (isSplatValue(V, DemandedElts, UndefElts)) {
2360 // Handle case where all demanded elements are UNDEF.
2361 if (DemandedElts.isSubsetOf(UndefElts)) {
2363 return getUNDEF(VT);
2365 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2370 case ISD::VECTOR_SHUFFLE: {
2371 // Check if this is a shuffle node doing a splat.
2372 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2373 // getTargetVShiftNode currently struggles without the splat source.
2374 auto *SVN = cast<ShuffleVectorSDNode>(V);
2375 if (!SVN->isSplat())
2377 int Idx = SVN->getSplatIndex();
2378 int NumElts = V.getValueType().getVectorNumElements();
2379 SplatIdx = Idx % NumElts;
2380 return V.getOperand(Idx / NumElts);
2387 SDValue SelectionDAG::getSplatValue(SDValue V) {
2389 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2390 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2391 SrcVector.getValueType().getScalarType(), SrcVector,
2392 getIntPtrConstant(SplatIdx, SDLoc(V)));
2396 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2397 /// is less than the element bit-width of the shift node, return it.
2398 static const APInt *getValidShiftAmountConstant(SDValue V) {
2399 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2400 // Shifting more than the bitwidth is not valid.
2401 const APInt &ShAmt = SA->getAPIntValue();
2402 if (ShAmt.ult(V.getScalarValueSizeInBits()))
2408 /// Determine which bits of Op are known to be either zero or one and return
2409 /// them in Known. For vectors, the known bits are those that are shared by
2410 /// every vector element.
2411 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2412 EVT VT = Op.getValueType();
2413 APInt DemandedElts = VT.isVector()
2414 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2416 return computeKnownBits(Op, DemandedElts, Depth);
2419 /// Determine which bits of Op are known to be either zero or one and return
2420 /// them in Known. The DemandedElts argument allows us to only collect the known
2421 /// bits that are shared by the requested vector elements.
2422 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2423 unsigned Depth) const {
2424 unsigned BitWidth = Op.getScalarValueSizeInBits();
2426 KnownBits Known(BitWidth); // Don't know anything.
2428 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2429 // We know all of the bits for a constant!
2430 Known.One = C->getAPIntValue();
2431 Known.Zero = ~Known.One;
2434 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2435 // We know all of the bits for a constant fp!
2436 Known.One = C->getValueAPF().bitcastToAPInt();
2437 Known.Zero = ~Known.One;
2442 return Known; // Limit search depth.
2445 unsigned NumElts = DemandedElts.getBitWidth();
2446 assert((!Op.getValueType().isVector() ||
2447 NumElts == Op.getValueType().getVectorNumElements()) &&
2448 "Unexpected vector size");
2451 return Known; // No demanded elts, better to assume we don't know anything.
2453 unsigned Opcode = Op.getOpcode();
2455 case ISD::BUILD_VECTOR:
2456 // Collect the known bits that are shared by every demanded vector element.
2457 Known.Zero.setAllBits(); Known.One.setAllBits();
2458 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2459 if (!DemandedElts[i])
2462 SDValue SrcOp = Op.getOperand(i);
2463 Known2 = computeKnownBits(SrcOp, Depth + 1);
2465 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2466 if (SrcOp.getValueSizeInBits() != BitWidth) {
2467 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2468 "Expected BUILD_VECTOR implicit truncation");
2469 Known2 = Known2.trunc(BitWidth);
2472 // Known bits are the values that are shared by every demanded element.
2473 Known.One &= Known2.One;
2474 Known.Zero &= Known2.Zero;
2476 // If we don't know any bits, early out.
2477 if (Known.isUnknown())
2481 case ISD::VECTOR_SHUFFLE: {
2482 // Collect the known bits that are shared by every vector element referenced
2484 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2485 Known.Zero.setAllBits(); Known.One.setAllBits();
2486 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2487 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2488 for (unsigned i = 0; i != NumElts; ++i) {
2489 if (!DemandedElts[i])
2492 int M = SVN->getMaskElt(i);
2494 // For UNDEF elements, we don't know anything about the common state of
2495 // the shuffle result.
2497 DemandedLHS.clearAllBits();
2498 DemandedRHS.clearAllBits();
2502 if ((unsigned)M < NumElts)
2503 DemandedLHS.setBit((unsigned)M % NumElts);
2505 DemandedRHS.setBit((unsigned)M % NumElts);
2507 // Known bits are the values that are shared by every demanded element.
2508 if (!!DemandedLHS) {
2509 SDValue LHS = Op.getOperand(0);
2510 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2511 Known.One &= Known2.One;
2512 Known.Zero &= Known2.Zero;
2514 // If we don't know any bits, early out.
2515 if (Known.isUnknown())
2517 if (!!DemandedRHS) {
2518 SDValue RHS = Op.getOperand(1);
2519 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2520 Known.One &= Known2.One;
2521 Known.Zero &= Known2.Zero;
2525 case ISD::CONCAT_VECTORS: {
2526 // Split DemandedElts and test each of the demanded subvectors.
2527 Known.Zero.setAllBits(); Known.One.setAllBits();
2528 EVT SubVectorVT = Op.getOperand(0).getValueType();
2529 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2530 unsigned NumSubVectors = Op.getNumOperands();
2531 for (unsigned i = 0; i != NumSubVectors; ++i) {
2532 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2533 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2534 if (!!DemandedSub) {
2535 SDValue Sub = Op.getOperand(i);
2536 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2537 Known.One &= Known2.One;
2538 Known.Zero &= Known2.Zero;
2540 // If we don't know any bits, early out.
2541 if (Known.isUnknown())
2546 case ISD::INSERT_SUBVECTOR: {
2547 // If we know the element index, demand any elements from the subvector and
2548 // the remainder from the src its inserted into, otherwise demand them all.
2549 SDValue Src = Op.getOperand(0);
2550 SDValue Sub = Op.getOperand(1);
2551 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2552 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2553 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
2554 Known.One.setAllBits();
2555 Known.Zero.setAllBits();
2556 uint64_t Idx = SubIdx->getZExtValue();
2557 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2558 if (!!DemandedSubElts) {
2559 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2560 if (Known.isUnknown())
2561 break; // early-out.
2563 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
2564 APInt DemandedSrcElts = DemandedElts & ~SubMask;
2565 if (!!DemandedSrcElts) {
2566 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2567 Known.One &= Known2.One;
2568 Known.Zero &= Known2.Zero;
2571 Known = computeKnownBits(Sub, Depth + 1);
2572 if (Known.isUnknown())
2573 break; // early-out.
2574 Known2 = computeKnownBits(Src, Depth + 1);
2575 Known.One &= Known2.One;
2576 Known.Zero &= Known2.Zero;
2580 case ISD::EXTRACT_SUBVECTOR: {
2581 // If we know the element index, just demand that subvector elements,
2582 // otherwise demand them all.
2583 SDValue Src = Op.getOperand(0);
2584 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2585 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2586 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2587 // Offset the demanded elts by the subvector index.
2588 uint64_t Idx = SubIdx->getZExtValue();
2589 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2590 Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
2592 Known = computeKnownBits(Src, Depth + 1);
2596 case ISD::SCALAR_TO_VECTOR: {
2597 // We know about scalar_to_vector as much as we know about it source,
2598 // which becomes the first element of otherwise unknown vector.
2599 if (DemandedElts != 1)
2602 SDValue N0 = Op.getOperand(0);
2603 Known = computeKnownBits(N0, Depth + 1);
2604 if (N0.getValueSizeInBits() != BitWidth)
2605 Known = Known.trunc(BitWidth);
2609 case ISD::BITCAST: {
2610 SDValue N0 = Op.getOperand(0);
2611 EVT SubVT = N0.getValueType();
2612 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2614 // Ignore bitcasts from unsupported types.
2615 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2618 // Fast handling of 'identity' bitcasts.
2619 if (BitWidth == SubBitWidth) {
2620 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2624 bool IsLE = getDataLayout().isLittleEndian();
2626 // Bitcast 'small element' vector to 'large element' scalar/vector.
2627 if ((BitWidth % SubBitWidth) == 0) {
2628 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2630 // Collect known bits for the (larger) output by collecting the known
2631 // bits from each set of sub elements and shift these into place.
2632 // We need to separately call computeKnownBits for each set of
2633 // sub elements as the knownbits for each is likely to be different.
2634 unsigned SubScale = BitWidth / SubBitWidth;
2635 APInt SubDemandedElts(NumElts * SubScale, 0);
2636 for (unsigned i = 0; i != NumElts; ++i)
2637 if (DemandedElts[i])
2638 SubDemandedElts.setBit(i * SubScale);
2640 for (unsigned i = 0; i != SubScale; ++i) {
2641 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2643 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2644 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2645 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2649 // Bitcast 'large element' scalar/vector to 'small element' vector.
2650 if ((SubBitWidth % BitWidth) == 0) {
2651 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2653 // Collect known bits for the (smaller) output by collecting the known
2654 // bits from the overlapping larger input elements and extracting the
2655 // sub sections we actually care about.
2656 unsigned SubScale = SubBitWidth / BitWidth;
2657 APInt SubDemandedElts(NumElts / SubScale, 0);
2658 for (unsigned i = 0; i != NumElts; ++i)
2659 if (DemandedElts[i])
2660 SubDemandedElts.setBit(i / SubScale);
2662 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2664 Known.Zero.setAllBits(); Known.One.setAllBits();
2665 for (unsigned i = 0; i != NumElts; ++i)
2666 if (DemandedElts[i]) {
2667 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2668 unsigned Offset = (Shifts % SubScale) * BitWidth;
2669 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2670 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2671 // If we don't know any bits, early out.
2672 if (Known.isUnknown())
2679 // If either the LHS or the RHS are Zero, the result is zero.
2680 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2681 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2683 // Output known-1 bits are only known if set in both the LHS & RHS.
2684 Known.One &= Known2.One;
2685 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2686 Known.Zero |= Known2.Zero;
2689 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2690 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2692 // Output known-0 bits are only known if clear in both the LHS & RHS.
2693 Known.Zero &= Known2.Zero;
2694 // Output known-1 are known to be set if set in either the LHS | RHS.
2695 Known.One |= Known2.One;
2698 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2699 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2701 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2702 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2703 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2704 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2705 Known.Zero = KnownZeroOut;
2709 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2710 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2712 // If low bits are zero in either operand, output low known-0 bits.
2713 // Also compute a conservative estimate for high known-0 bits.
2714 // More trickiness is possible, but this is sufficient for the
2715 // interesting case of alignment computation.
2716 unsigned TrailZ = Known.countMinTrailingZeros() +
2717 Known2.countMinTrailingZeros();
2718 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2719 Known2.countMinLeadingZeros(),
2720 BitWidth) - BitWidth;
2723 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2724 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2728 // For the purposes of computing leading zeros we can conservatively
2729 // treat a udiv as a logical right shift by the power of 2 known to
2730 // be less than the denominator.
2731 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2732 unsigned LeadZ = Known2.countMinLeadingZeros();
2734 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2735 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2736 if (RHSMaxLeadingZeros != BitWidth)
2737 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2739 Known.Zero.setHighBits(LeadZ);
2744 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2745 // If we don't know any bits, early out.
2746 if (Known.isUnknown())
2748 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2750 // Only known if known in both the LHS and RHS.
2751 Known.One &= Known2.One;
2752 Known.Zero &= Known2.Zero;
2754 case ISD::SELECT_CC:
2755 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2756 // If we don't know any bits, early out.
2757 if (Known.isUnknown())
2759 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2761 // Only known if known in both the LHS and RHS.
2762 Known.One &= Known2.One;
2763 Known.Zero &= Known2.Zero;
2767 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2768 if (Op.getResNo() != 1)
2770 // The boolean result conforms to getBooleanContents.
2771 // If we know the result of a setcc has the top bits zero, use this info.
2772 // We know that we have an integer-based boolean since these operations
2773 // are only available for integer.
2774 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2775 TargetLowering::ZeroOrOneBooleanContent &&
2777 Known.Zero.setBitsFrom(1);
2780 // If we know the result of a setcc has the top bits zero, use this info.
2781 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2782 TargetLowering::ZeroOrOneBooleanContent &&
2784 Known.Zero.setBitsFrom(1);
2787 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2788 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2789 unsigned Shift = ShAmt->getZExtValue();
2790 Known.Zero <<= Shift;
2791 Known.One <<= Shift;
2792 // Low bits are known zero.
2793 Known.Zero.setLowBits(Shift);
2797 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2798 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2799 unsigned Shift = ShAmt->getZExtValue();
2800 Known.Zero.lshrInPlace(Shift);
2801 Known.One.lshrInPlace(Shift);
2802 // High bits are known zero.
2803 Known.Zero.setHighBits(Shift);
2804 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
2805 // If the shift amount is a vector of constants see if we can bound
2806 // the number of upper zero bits.
2807 unsigned ShiftAmountMin = BitWidth;
2808 for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
2809 if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
2810 const APInt &ShAmt = C->getAPIntValue();
2811 if (ShAmt.ult(BitWidth)) {
2812 ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
2813 ShAmt.getZExtValue());
2817 // Don't know anything.
2822 Known.Zero.setHighBits(ShiftAmountMin);
2826 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2827 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2828 unsigned Shift = ShAmt->getZExtValue();
2829 // Sign extend known zero/one bit (else is unknown).
2830 Known.Zero.ashrInPlace(Shift);
2831 Known.One.ashrInPlace(Shift);
2836 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
2837 unsigned Amt = C->getAPIntValue().urem(BitWidth);
2839 // For fshl, 0-shift returns the 1st arg.
2840 // For fshr, 0-shift returns the 2nd arg.
2842 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
2843 DemandedElts, Depth + 1);
2847 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2848 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2849 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2850 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2851 if (Opcode == ISD::FSHL) {
2854 Known2.One.lshrInPlace(BitWidth - Amt);
2855 Known2.Zero.lshrInPlace(BitWidth - Amt);
2857 Known.One <<= BitWidth - Amt;
2858 Known.Zero <<= BitWidth - Amt;
2859 Known2.One.lshrInPlace(Amt);
2860 Known2.Zero.lshrInPlace(Amt);
2862 Known.One |= Known2.One;
2863 Known.Zero |= Known2.Zero;
2866 case ISD::SIGN_EXTEND_INREG: {
2867 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2868 unsigned EBits = EVT.getScalarSizeInBits();
2870 // Sign extension. Compute the demanded bits in the result that are not
2871 // present in the input.
2872 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2874 APInt InSignMask = APInt::getSignMask(EBits);
2875 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2877 // If the sign extended bits are demanded, we know that the sign
2879 InSignMask = InSignMask.zext(BitWidth);
2880 if (NewBits.getBoolValue())
2881 InputDemandedBits |= InSignMask;
2883 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2884 Known.One &= InputDemandedBits;
2885 Known.Zero &= InputDemandedBits;
2887 // If the sign bit of the input is known set or clear, then we know the
2888 // top bits of the result.
2889 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2890 Known.Zero |= NewBits;
2891 Known.One &= ~NewBits;
2892 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2893 Known.One |= NewBits;
2894 Known.Zero &= ~NewBits;
2895 } else { // Input sign bit unknown
2896 Known.Zero &= ~NewBits;
2897 Known.One &= ~NewBits;
2902 case ISD::CTTZ_ZERO_UNDEF: {
2903 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2904 // If we have a known 1, its position is our upper bound.
2905 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2906 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2907 Known.Zero.setBitsFrom(LowBits);
2911 case ISD::CTLZ_ZERO_UNDEF: {
2912 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2913 // If we have a known 1, its position is our upper bound.
2914 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2915 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2916 Known.Zero.setBitsFrom(LowBits);
2920 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2921 // If we know some of the bits are zero, they can't be one.
2922 unsigned PossibleOnes = Known2.countMaxPopulation();
2923 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2927 LoadSDNode *LD = cast<LoadSDNode>(Op);
2928 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
2929 if (ISD::isNON_EXTLoad(LD) && Cst) {
2930 // Determine any common known bits from the loaded constant pool value.
2931 Type *CstTy = Cst->getType();
2932 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
2933 // If its a vector splat, then we can (quickly) reuse the scalar path.
2934 // NOTE: We assume all elements match and none are UNDEF.
2935 if (CstTy->isVectorTy()) {
2936 if (const Constant *Splat = Cst->getSplatValue()) {
2938 CstTy = Cst->getType();
2941 // TODO - do we need to handle different bitwidths?
2942 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
2943 // Iterate across all vector elements finding common known bits.
2944 Known.One.setAllBits();
2945 Known.Zero.setAllBits();
2946 for (unsigned i = 0; i != NumElts; ++i) {
2947 if (!DemandedElts[i])
2949 if (Constant *Elt = Cst->getAggregateElement(i)) {
2950 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
2951 const APInt &Value = CInt->getValue();
2953 Known.Zero &= ~Value;
2956 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
2957 APInt Value = CFP->getValueAPF().bitcastToAPInt();
2959 Known.Zero &= ~Value;
2963 Known.One.clearAllBits();
2964 Known.Zero.clearAllBits();
2967 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
2968 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
2969 const APInt &Value = CInt->getValue();
2971 Known.Zero = ~Value;
2972 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
2973 APInt Value = CFP->getValueAPF().bitcastToAPInt();
2975 Known.Zero = ~Value;
2979 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2980 // If this is a ZEXTLoad and we are looking at the loaded value.
2981 EVT VT = LD->getMemoryVT();
2982 unsigned MemBits = VT.getScalarSizeInBits();
2983 Known.Zero.setBitsFrom(MemBits);
2984 } else if (const MDNode *Ranges = LD->getRanges()) {
2985 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2986 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2990 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2991 EVT InVT = Op.getOperand(0).getValueType();
2992 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2993 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2994 Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2997 case ISD::ZERO_EXTEND: {
2998 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2999 Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
3002 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3003 EVT InVT = Op.getOperand(0).getValueType();
3004 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3005 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3006 // If the sign bit is known to be zero or one, then sext will extend
3007 // it to the top bits, else it will just zext.
3008 Known = Known.sext(BitWidth);
3011 case ISD::SIGN_EXTEND: {
3012 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3013 // If the sign bit is known to be zero or one, then sext will extend
3014 // it to the top bits, else it will just zext.
3015 Known = Known.sext(BitWidth);
3018 case ISD::ANY_EXTEND: {
3019 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3020 Known = Known.zext(BitWidth, false /* ExtendedBitsAreKnownZero */);
3023 case ISD::TRUNCATE: {
3024 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3025 Known = Known.trunc(BitWidth);
3028 case ISD::AssertZext: {
3029 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3030 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3031 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3032 Known.Zero |= (~InMask);
3033 Known.One &= (~Known.Zero);
3037 // All bits are zero except the low bit.
3038 Known.Zero.setBitsFrom(1);
3042 if (Op.getResNo() == 1) {
3043 // If we know the result of a setcc has the top bits zero, use this info.
3044 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3045 TargetLowering::ZeroOrOneBooleanContent &&
3047 Known.Zero.setBitsFrom(1);
3053 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3054 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3055 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3062 if (Op.getResNo() == 1) {
3063 // If we know the result of a setcc has the top bits zero, use this info.
3064 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3065 TargetLowering::ZeroOrOneBooleanContent &&
3067 Known.Zero.setBitsFrom(1);
3074 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3076 // With ADDE and ADDCARRY, a carry bit may be added in.
3078 if (Opcode == ISD::ADDE)
3079 // Can't track carry from glue, set carry to unknown.
3081 else if (Opcode == ISD::ADDCARRY)
3082 // TODO: Compute known bits for the carry operand. Not sure if it is worth
3083 // the trouble (how often will we find a known carry bit). And I haven't
3084 // tested this very much yet, but something like this might work:
3085 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3086 // Carry = Carry.zextOrTrunc(1, false);
3091 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3092 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3093 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3097 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3098 const APInt &RA = Rem->getAPIntValue().abs();
3099 if (RA.isPowerOf2()) {
3100 APInt LowBits = RA - 1;
3101 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3103 // The low bits of the first operand are unchanged by the srem.
3104 Known.Zero = Known2.Zero & LowBits;
3105 Known.One = Known2.One & LowBits;
3107 // If the first operand is non-negative or has all low bits zero, then
3108 // the upper bits are all zero.
3109 if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
3110 Known.Zero |= ~LowBits;
3112 // If the first operand is negative and not all low bits are zero, then
3113 // the upper bits are all one.
3114 if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
3115 Known.One |= ~LowBits;
3116 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
3121 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3122 const APInt &RA = Rem->getAPIntValue();
3123 if (RA.isPowerOf2()) {
3124 APInt LowBits = (RA - 1);
3125 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3127 // The upper bits are all zero, the lower ones are unchanged.
3128 Known.Zero = Known2.Zero | ~LowBits;
3129 Known.One = Known2.One & LowBits;
3134 // Since the result is less than or equal to either operand, any leading
3135 // zero bits in either operand must also exist in the result.
3136 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3137 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3140 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
3142 Known.Zero.setHighBits(Leaders);
3145 case ISD::EXTRACT_ELEMENT: {
3146 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3147 const unsigned Index = Op.getConstantOperandVal(1);
3148 const unsigned EltBitWidth = Op.getValueSizeInBits();
3150 // Remove low part of known bits mask
3151 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3152 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3154 // Remove high part of known bit mask
3155 Known = Known.trunc(EltBitWidth);
3158 case ISD::EXTRACT_VECTOR_ELT: {
3159 SDValue InVec = Op.getOperand(0);
3160 SDValue EltNo = Op.getOperand(1);
3161 EVT VecVT = InVec.getValueType();
3162 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3163 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3164 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3165 // anything about the extended bits.
3166 if (BitWidth > EltBitWidth)
3167 Known = Known.trunc(EltBitWidth);
3168 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3169 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
3170 // If we know the element index, just demand that vector element.
3171 unsigned Idx = ConstEltNo->getZExtValue();
3172 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
3173 Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
3175 // Unknown element index, so ignore DemandedElts and demand them all.
3176 Known = computeKnownBits(InVec, Depth + 1);
3178 if (BitWidth > EltBitWidth)
3179 Known = Known.zext(BitWidth, false /* => any extend */);
3182 case ISD::INSERT_VECTOR_ELT: {
3183 SDValue InVec = Op.getOperand(0);
3184 SDValue InVal = Op.getOperand(1);
3185 SDValue EltNo = Op.getOperand(2);
3187 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3188 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3189 // If we know the element index, split the demand between the
3190 // source vector and the inserted element.
3191 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
3192 unsigned EltIdx = CEltNo->getZExtValue();
3194 // If we demand the inserted element then add its common known bits.
3195 if (DemandedElts[EltIdx]) {
3196 Known2 = computeKnownBits(InVal, Depth + 1);
3197 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3198 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3201 // If we demand the source vector then add its common known bits, ensuring
3202 // that we don't demand the inserted element.
3203 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
3205 Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
3206 Known.One &= Known2.One;
3207 Known.Zero &= Known2.Zero;
3210 // Unknown element index, so ignore DemandedElts and demand them all.
3211 Known = computeKnownBits(InVec, Depth + 1);
3212 Known2 = computeKnownBits(InVal, Depth + 1);
3213 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3214 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3218 case ISD::BITREVERSE: {
3219 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3220 Known.Zero = Known2.Zero.reverseBits();
3221 Known.One = Known2.One.reverseBits();
3225 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3226 Known.Zero = Known2.Zero.byteSwap();
3227 Known.One = Known2.One.byteSwap();
3231 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3233 // If the source's MSB is zero then we know the rest of the bits already.
3234 if (Known2.isNonNegative()) {
3235 Known.Zero = Known2.Zero;
3236 Known.One = Known2.One;
3240 // We only know that the absolute values's MSB will be zero iff there is
3241 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3242 Known2.One.clearSignBit();
3243 if (Known2.One.getBoolValue()) {
3244 Known.Zero = APInt::getSignMask(BitWidth);
3250 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3251 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3253 // UMIN - we know that the result will have the maximum of the
3254 // known zero leading bits of the inputs.
3255 unsigned LeadZero = Known.countMinLeadingZeros();
3256 LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
3258 Known.Zero &= Known2.Zero;
3259 Known.One &= Known2.One;
3260 Known.Zero.setHighBits(LeadZero);
3264 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3265 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3267 // UMAX - we know that the result will have the maximum of the
3268 // known one leading bits of the inputs.
3269 unsigned LeadOne = Known.countMinLeadingOnes();
3270 LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
3272 Known.Zero &= Known2.Zero;
3273 Known.One &= Known2.One;
3274 Known.One.setHighBits(LeadOne);
3279 // If we have a clamp pattern, we know that the number of sign bits will be
3280 // the minimum of the clamp min/max range.
3281 bool IsMax = (Opcode == ISD::SMAX);
3282 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3283 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3284 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3286 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3287 if (CstLow && CstHigh) {
3289 std::swap(CstLow, CstHigh);
3291 const APInt &ValueLow = CstLow->getAPIntValue();
3292 const APInt &ValueHigh = CstHigh->getAPIntValue();
3293 if (ValueLow.sle(ValueHigh)) {
3294 unsigned LowSignBits = ValueLow.getNumSignBits();
3295 unsigned HighSignBits = ValueHigh.getNumSignBits();
3296 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3297 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3298 Known.One.setHighBits(MinSignBits);
3301 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3302 Known.Zero.setHighBits(MinSignBits);
3308 // Fallback - just get the shared known bits of the operands.
3309 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3310 if (Known.isUnknown()) break; // Early-out
3311 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3312 Known.Zero &= Known2.Zero;
3313 Known.One &= Known2.One;
3316 case ISD::FrameIndex:
3317 case ISD::TargetFrameIndex:
3318 TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
3322 if (Opcode < ISD::BUILTIN_OP_END)
3325 case ISD::INTRINSIC_WO_CHAIN:
3326 case ISD::INTRINSIC_W_CHAIN:
3327 case ISD::INTRINSIC_VOID:
3328 // Allow the target to implement this method for its nodes.
3329 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3333 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3337 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3339 // X + 0 never overflow
3340 if (isNullConstant(N1))
3343 KnownBits N1Known = computeKnownBits(N1);
3344 if (N1Known.Zero.getBoolValue()) {
3345 KnownBits N0Known = computeKnownBits(N0);
3348 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
3353 // mulhi + 1 never overflow
3354 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3355 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
3358 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3359 KnownBits N0Known = computeKnownBits(N0);
3361 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
3365 return OFK_Sometime;
3368 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3369 EVT OpVT = Val.getValueType();
3370 unsigned BitWidth = OpVT.getScalarSizeInBits();
3372 // Is the constant a known power of 2?
3373 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3374 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3376 // A left-shift of a constant one will have exactly one bit set because
3377 // shifting the bit off the end is undefined.
3378 if (Val.getOpcode() == ISD::SHL) {
3379 auto *C = isConstOrConstSplat(Val.getOperand(0));
3380 if (C && C->getAPIntValue() == 1)
3384 // Similarly, a logical right-shift of a constant sign-bit will have exactly
3386 if (Val.getOpcode() == ISD::SRL) {
3387 auto *C = isConstOrConstSplat(Val.getOperand(0));
3388 if (C && C->getAPIntValue().isSignMask())
3392 // Are all operands of a build vector constant powers of two?
3393 if (Val.getOpcode() == ISD::BUILD_VECTOR)
3394 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3395 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3396 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3401 // More could be done here, though the above checks are enough
3402 // to handle some common cases.
3404 // Fall back to computeKnownBits to catch other known cases.
3405 KnownBits Known = computeKnownBits(Val);
3406 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3409 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3410 EVT VT = Op.getValueType();
3411 APInt DemandedElts = VT.isVector()
3412 ? APInt::getAllOnesValue(VT.getVectorNumElements())
3414 return ComputeNumSignBits(Op, DemandedElts, Depth);
3417 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3418 unsigned Depth) const {
3419 EVT VT = Op.getValueType();
3420 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3421 unsigned VTBits = VT.getScalarSizeInBits();
3422 unsigned NumElts = DemandedElts.getBitWidth();
3424 unsigned FirstAnswer = 1;
3426 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3427 const APInt &Val = C->getAPIntValue();
3428 return Val.getNumSignBits();
3432 return 1; // Limit search depth.
3435 return 1; // No demanded elts, better to assume we don't know anything.
3437 unsigned Opcode = Op.getOpcode();
3440 case ISD::AssertSext:
3441 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3442 return VTBits-Tmp+1;
3443 case ISD::AssertZext:
3444 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3447 case ISD::BUILD_VECTOR:
3449 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3450 if (!DemandedElts[i])
3453 SDValue SrcOp = Op.getOperand(i);
3454 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
3456 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3457 if (SrcOp.getValueSizeInBits() != VTBits) {
3458 assert(SrcOp.getValueSizeInBits() > VTBits &&
3459 "Expected BUILD_VECTOR implicit truncation");
3460 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3461 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3463 Tmp = std::min(Tmp, Tmp2);
3467 case ISD::VECTOR_SHUFFLE: {
3468 // Collect the minimum number of sign bits that are shared by every vector
3469 // element referenced by the shuffle.
3470 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3471 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3472 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3473 for (unsigned i = 0; i != NumElts; ++i) {
3474 int M = SVN->getMaskElt(i);
3475 if (!DemandedElts[i])
3477 // For UNDEF elements, we don't know anything about the common state of
3478 // the shuffle result.
3481 if ((unsigned)M < NumElts)
3482 DemandedLHS.setBit((unsigned)M % NumElts);
3484 DemandedRHS.setBit((unsigned)M % NumElts);
3486 Tmp = std::numeric_limits<unsigned>::max();
3488 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3489 if (!!DemandedRHS) {
3490 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3491 Tmp = std::min(Tmp, Tmp2);
3493 // If we don't know anything, early out and try computeKnownBits fall-back.
3496 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3500 case ISD::BITCAST: {
3501 SDValue N0 = Op.getOperand(0);
3502 EVT SrcVT = N0.getValueType();
3503 unsigned SrcBits = SrcVT.getScalarSizeInBits();
3505 // Ignore bitcasts from unsupported types..
3506 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3509 // Fast handling of 'identity' bitcasts.
3510 if (VTBits == SrcBits)
3511 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3513 bool IsLE = getDataLayout().isLittleEndian();
3515 // Bitcast 'large element' scalar/vector to 'small element' vector.
3516 if ((SrcBits % VTBits) == 0) {
3517 assert(VT.isVector() && "Expected bitcast to vector");
3519 unsigned Scale = SrcBits / VTBits;
3520 APInt SrcDemandedElts(NumElts / Scale, 0);
3521 for (unsigned i = 0; i != NumElts; ++i)
3522 if (DemandedElts[i])
3523 SrcDemandedElts.setBit(i / Scale);
3525 // Fast case - sign splat can be simply split across the small elements.
3526 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3530 // Slow case - determine how far the sign extends into each sub-element.
3532 for (unsigned i = 0; i != NumElts; ++i)
3533 if (DemandedElts[i]) {
3534 unsigned SubOffset = i % Scale;
3535 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3536 SubOffset = SubOffset * VTBits;
3537 if (Tmp <= SubOffset)
3539 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3546 case ISD::SIGN_EXTEND:
3547 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3548 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3549 case ISD::SIGN_EXTEND_INREG:
3550 // Max of the input and what this extends.
3551 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3553 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3554 return std::max(Tmp, Tmp2);
3555 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3556 SDValue Src = Op.getOperand(0);
3557 EVT SrcVT = Src.getValueType();
3558 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3559 Tmp = VTBits - SrcVT.getScalarSizeInBits();
3560 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3564 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3565 // SRA X, C -> adds C sign bits.
3566 if (ConstantSDNode *C =
3567 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3568 APInt ShiftVal = C->getAPIntValue();
3570 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3574 if (ConstantSDNode *C =
3575 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3576 // shl destroys sign bits.
3577 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3578 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
3579 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
3580 return Tmp - C->getZExtValue();
3585 case ISD::XOR: // NOT is handled here.
3586 // Logical binary ops preserve the number of sign bits at the worst.
3587 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3589 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3590 FirstAnswer = std::min(Tmp, Tmp2);
3591 // We computed what we know about the sign bits as our first
3592 // answer. Now proceed to the generic code that uses
3593 // computeKnownBits, and pick whichever answer is better.
3599 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3600 if (Tmp == 1) return 1; // Early out.
3601 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3602 return std::min(Tmp, Tmp2);
3603 case ISD::SELECT_CC:
3604 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3605 if (Tmp == 1) return 1; // Early out.
3606 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3607 return std::min(Tmp, Tmp2);
3611 // If we have a clamp pattern, we know that the number of sign bits will be
3612 // the minimum of the clamp min/max range.
3613 bool IsMax = (Opcode == ISD::SMAX);
3614 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3615 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3616 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3618 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3619 if (CstLow && CstHigh) {
3621 std::swap(CstLow, CstHigh);
3622 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3623 Tmp = CstLow->getAPIntValue().getNumSignBits();
3624 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3625 return std::min(Tmp, Tmp2);
3629 // Fallback - just get the minimum number of sign bits of the operands.
3630 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3632 return 1; // Early out.
3633 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3634 return std::min(Tmp, Tmp2);
3638 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3640 return 1; // Early out.
3641 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3642 return std::min(Tmp, Tmp2);
3649 if (Op.getResNo() != 1)
3651 // The boolean result conforms to getBooleanContents. Fall through.
3652 // If setcc returns 0/-1, all bits are sign bits.
3653 // We know that we have an integer-based boolean since these operations
3654 // are only available for integer.
3655 if (TLI->getBooleanContents(VT.isVector(), false) ==
3656 TargetLowering::ZeroOrNegativeOneBooleanContent)
3660 // If setcc returns 0/-1, all bits are sign bits.
3661 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3662 TargetLowering::ZeroOrNegativeOneBooleanContent)
3667 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3668 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3670 // Handle rotate right by N like a rotate left by 32-N.
3671 if (Opcode == ISD::ROTR)
3672 RotAmt = (VTBits - RotAmt) % VTBits;
3674 // If we aren't rotating out all of the known-in sign bits, return the
3675 // number that are left. This handles rotl(sext(x), 1) for example.
3676 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3677 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3682 // Add can have at most one carry bit. Thus we know that the output
3683 // is, at worst, one more bit than the inputs.
3684 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3685 if (Tmp == 1) return 1; // Early out.
3687 // Special case decrementing a value (ADD X, -1):
3688 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3689 if (CRHS->isAllOnesValue()) {
3690 KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
3692 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3694 if ((Known.Zero | 1).isAllOnesValue())
3697 // If we are subtracting one from a positive number, there is no carry
3698 // out of the result.
3699 if (Known.isNonNegative())
3703 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3704 if (Tmp2 == 1) return 1;
3705 return std::min(Tmp, Tmp2)-1;
3708 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3709 if (Tmp2 == 1) return 1;
3712 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3713 if (CLHS->isNullValue()) {
3714 KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
3715 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3717 if ((Known.Zero | 1).isAllOnesValue())
3720 // If the input is known to be positive (the sign bit is known clear),
3721 // the output of the NEG has the same number of sign bits as the input.
3722 if (Known.isNonNegative())
3725 // Otherwise, we treat this like a SUB.
3728 // Sub can have at most one carry bit. Thus we know that the output
3729 // is, at worst, one more bit than the inputs.
3730 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3731 if (Tmp == 1) return 1; // Early out.
3732 return std::min(Tmp, Tmp2)-1;
3733 case ISD::TRUNCATE: {
3734 // Check if the sign bits of source go down as far as the truncated value.
3735 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3736 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3737 if (NumSrcSignBits > (NumSrcBits - VTBits))
3738 return NumSrcSignBits - (NumSrcBits - VTBits);
3741 case ISD::EXTRACT_ELEMENT: {
3742 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3743 const int BitWidth = Op.getValueSizeInBits();
3744 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3746 // Get reverse index (starting from 1), Op1 value indexes elements from
3747 // little end. Sign starts at big end.
3748 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3750 // If the sign portion ends in our element the subtraction gives correct
3751 // result. Otherwise it gives either negative or > bitwidth result
3752 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3754 case ISD::INSERT_VECTOR_ELT: {
3755 SDValue InVec = Op.getOperand(0);
3756 SDValue InVal = Op.getOperand(1);
3757 SDValue EltNo = Op.getOperand(2);
3759 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3760 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3761 // If we know the element index, split the demand between the
3762 // source vector and the inserted element.
3763 unsigned EltIdx = CEltNo->getZExtValue();
3765 // If we demand the inserted element then get its sign bits.
3766 Tmp = std::numeric_limits<unsigned>::max();
3767 if (DemandedElts[EltIdx]) {
3768 // TODO - handle implicit truncation of inserted elements.
3769 if (InVal.getScalarValueSizeInBits() != VTBits)
3771 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3774 // If we demand the source vector then get its sign bits, and determine
3776 APInt VectorElts = DemandedElts;
3777 VectorElts.clearBit(EltIdx);
3779 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3780 Tmp = std::min(Tmp, Tmp2);
3783 // Unknown element index, so ignore DemandedElts and demand them all.
3784 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3785 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3786 Tmp = std::min(Tmp, Tmp2);
3788 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3791 case ISD::EXTRACT_VECTOR_ELT: {
3792 SDValue InVec = Op.getOperand(0);
3793 SDValue EltNo = Op.getOperand(1);
3794 EVT VecVT = InVec.getValueType();
3795 const unsigned BitWidth = Op.getValueSizeInBits();
3796 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3797 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3799 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3800 // anything about sign bits. But if the sizes match we can derive knowledge
3801 // about sign bits from the vector operand.
3802 if (BitWidth != EltBitWidth)
3805 // If we know the element index, just demand that vector element, else for
3806 // an unknown element index, ignore DemandedElts and demand them all.
3807 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3808 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3809 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3811 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3813 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3815 case ISD::EXTRACT_SUBVECTOR: {
3816 // If we know the element index, just demand that subvector elements,
3817 // otherwise demand them all.
3818 SDValue Src = Op.getOperand(0);
3819 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3820 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3821 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3822 // Offset the demanded elts by the subvector index.
3823 uint64_t Idx = SubIdx->getZExtValue();
3824 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3825 return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3827 return ComputeNumSignBits(Src, Depth + 1);
3829 case ISD::CONCAT_VECTORS: {
3830 // Determine the minimum number of sign bits across all demanded
3831 // elts of the input vectors. Early out if the result is already 1.
3832 Tmp = std::numeric_limits<unsigned>::max();
3833 EVT SubVectorVT = Op.getOperand(0).getValueType();
3834 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3835 unsigned NumSubVectors = Op.getNumOperands();
3836 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3837 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3838 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3841 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3842 Tmp = std::min(Tmp, Tmp2);
3844 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3847 case ISD::INSERT_SUBVECTOR: {
3848 // If we know the element index, demand any elements from the subvector and
3849 // the remainder from the src its inserted into, otherwise demand them all.
3850 SDValue Src = Op.getOperand(0);
3851 SDValue Sub = Op.getOperand(1);
3852 auto *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3853 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3854 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
3855 Tmp = std::numeric_limits<unsigned>::max();
3856 uint64_t Idx = SubIdx->getZExtValue();
3857 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3858 if (!!DemandedSubElts) {
3859 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
3860 if (Tmp == 1) return 1; // early-out
3862 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
3863 APInt DemandedSrcElts = DemandedElts & ~SubMask;
3864 if (!!DemandedSrcElts) {
3865 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
3866 Tmp = std::min(Tmp, Tmp2);
3868 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3872 // Not able to determine the index so just assume worst case.
3873 Tmp = ComputeNumSignBits(Sub, Depth + 1);
3874 if (Tmp == 1) return 1; // early-out
3875 Tmp2 = ComputeNumSignBits(Src, Depth + 1);
3876 Tmp = std::min(Tmp, Tmp2);
3877 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3882 // If we are looking at the loaded value of the SDNode.
3883 if (Op.getResNo() == 0) {
3884 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3885 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3886 unsigned ExtType = LD->getExtensionType();
3889 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
3890 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3891 return VTBits - Tmp + 1;
3892 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
3893 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3894 return VTBits - Tmp;
3895 case ISD::NON_EXTLOAD:
3896 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
3897 // We only need to handle vectors - computeKnownBits should handle
3899 Type *CstTy = Cst->getType();
3900 if (CstTy->isVectorTy() &&
3901 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
3903 for (unsigned i = 0; i != NumElts; ++i) {
3904 if (!DemandedElts[i])
3906 if (Constant *Elt = Cst->getAggregateElement(i)) {
3907 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3908 const APInt &Value = CInt->getValue();
3909 Tmp = std::min(Tmp, Value.getNumSignBits());
3912 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3913 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3914 Tmp = std::min(Tmp, Value.getNumSignBits());
3918 // Unknown type. Conservatively assume no bits match sign bit.
3929 // Allow the target to implement this method for its nodes.
3930 if (Opcode >= ISD::BUILTIN_OP_END ||
3931 Opcode == ISD::INTRINSIC_WO_CHAIN ||
3932 Opcode == ISD::INTRINSIC_W_CHAIN ||
3933 Opcode == ISD::INTRINSIC_VOID) {
3935 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3937 FirstAnswer = std::max(FirstAnswer, NumBits);
3940 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3941 // use this information.
3942 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
3945 if (Known.isNonNegative()) { // sign bit is 0
3947 } else if (Known.isNegative()) { // sign bit is 1;
3954 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3955 // the number of identical bits in the top of the input value.
3957 Mask <<= Mask.getBitWidth()-VTBits;
3958 // Return # leading zeros. We use 'min' here in case Val was zero before
3959 // shifting. We don't want to return '64' as for an i32 "0".
3960 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3963 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3964 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3965 !isa<ConstantSDNode>(Op.getOperand(1)))
3968 if (Op.getOpcode() == ISD::OR &&
3969 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
3975 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
3976 // If we're told that NaNs won't happen, assume they won't.
3977 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
3981 return false; // Limit search depth.
3983 // TODO: Handle vectors.
3984 // If the value is a constant, we can obviously see if it is a NaN or not.
3985 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
3986 return !C->getValueAPF().isNaN() ||
3987 (SNaN && !C->getValueAPF().isSignaling());
3990 unsigned Opcode = Op.getOpcode();
4001 // TODO: Need isKnownNeverInfinity
4004 case ISD::FCANONICALIZE:
4012 case ISD::FNEARBYINT: {
4015 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4019 case ISD::FCOPYSIGN: {
4020 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4023 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4024 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4025 case ISD::FP_EXTEND:
4026 case ISD::FP_ROUND: {
4029 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4031 case ISD::SINT_TO_FP:
4032 case ISD::UINT_TO_FP:
4038 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4039 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4040 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4042 case ISD::FSQRT: // Need is known positive
4050 // TODO: Refine on operand
4054 case ISD::FMAXNUM: {
4055 // Only one needs to be known not-nan, since it will be returned if the
4056 // other ends up being one.
4057 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4058 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4060 case ISD::FMINNUM_IEEE:
4061 case ISD::FMAXNUM_IEEE: {
4064 // This can return a NaN if either operand is an sNaN, or if both operands
4066 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4067 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4068 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4069 isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4072 case ISD::FMAXIMUM: {
4073 // TODO: Does this quiet or return the origina NaN as-is?
4074 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4075 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4077 case ISD::EXTRACT_VECTOR_ELT: {
4078 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4081 if (Opcode >= ISD::BUILTIN_OP_END ||
4082 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4083 Opcode == ISD::INTRINSIC_W_CHAIN ||
4084 Opcode == ISD::INTRINSIC_VOID) {
4085 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4092 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4093 assert(Op.getValueType().isFloatingPoint() &&
4094 "Floating point type expected");
4096 // If the value is a constant, we can obviously see if it is a zero or not.
4097 // TODO: Add BuildVector support.
4098 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4099 return !C->isZero();
4103 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4104 assert(!Op.getValueType().isFloatingPoint() &&
4105 "Floating point types unsupported - use isKnownNeverZeroFloat");
4107 // If the value is a constant, we can obviously see if it is a zero or not.
4108 if (ISD::matchUnaryPredicate(
4109 Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4112 // TODO: Recognize more cases here.
4113 switch (Op.getOpcode()) {
4116 if (isKnownNeverZero(Op.getOperand(1)) ||
4117 isKnownNeverZero(Op.getOperand(0)))
4125 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4126 // Check the obvious case.
4127 if (A == B) return true;
4129 // For for negative and positive zero.
4130 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4131 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4132 if (CA->isZero() && CB->isZero()) return true;
4134 // Otherwise they may not be equal.
4138 // FIXME: unify with llvm::haveNoCommonBitsSet.
4139 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4140 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4141 assert(A.getValueType() == B.getValueType() &&
4142 "Values must have the same type");
4143 return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4146 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4147 ArrayRef<SDValue> Ops,
4148 SelectionDAG &DAG) {
4149 int NumOps = Ops.size();
4150 assert(NumOps != 0 && "Can't build an empty vector!");
4151 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4152 "Incorrect element count in BUILD_VECTOR!");
4154 // BUILD_VECTOR of UNDEFs is UNDEF.
4155 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4156 return DAG.getUNDEF(VT);
4158 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4159 SDValue IdentitySrc;
4160 bool IsIdentity = true;
4161 for (int i = 0; i != NumOps; ++i) {
4162 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4163 Ops[i].getOperand(0).getValueType() != VT ||
4164 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4165 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4166 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4170 IdentitySrc = Ops[i].getOperand(0);
4178 /// Try to simplify vector concatenation to an input value, undef, or build
4180 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4181 ArrayRef<SDValue> Ops,
4182 SelectionDAG &DAG) {
4183 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4184 assert(llvm::all_of(Ops,
4186 return Ops[0].getValueType() == Op.getValueType();
4188 "Concatenation of vectors with inconsistent value types!");
4189 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
4190 VT.getVectorNumElements() &&
4191 "Incorrect element count in vector concatenation!");
4193 if (Ops.size() == 1)
4196 // Concat of UNDEFs is UNDEF.
4197 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4198 return DAG.getUNDEF(VT);
4200 // Scan the operands and look for extract operations from a single source
4201 // that correspond to insertion at the same location via this concatenation:
4202 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4203 SDValue IdentitySrc;
4204 bool IsIdentity = true;
4205 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4206 SDValue Op = Ops[i];
4207 unsigned IdentityIndex = i * Op.getValueType().getVectorNumElements();
4208 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4209 Op.getOperand(0).getValueType() != VT ||
4210 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4211 !isa<ConstantSDNode>(Op.getOperand(1)) ||
4212 Op.getConstantOperandVal(1) != IdentityIndex) {
4216 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4217 "Unexpected identity source vector for concat of extracts");
4218 IdentitySrc = Op.getOperand(0);
4221 assert(IdentitySrc && "Failed to set source vector of extracts");
4225 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4226 // simplified to one big BUILD_VECTOR.
4227 // FIXME: Add support for SCALAR_TO_VECTOR as well.
4228 EVT SVT = VT.getScalarType();
4229 SmallVector<SDValue, 16> Elts;
4230 for (SDValue Op : Ops) {
4231 EVT OpVT = Op.getValueType();
4233 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4234 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4235 Elts.append(Op->op_begin(), Op->op_end());
4240 // BUILD_VECTOR requires all inputs to be of the same type, find the
4241 // maximum type and extend them all.
4242 for (SDValue Op : Elts)
4243 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4245 if (SVT.bitsGT(VT.getScalarType()))
4246 for (SDValue &Op : Elts)
4247 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4248 ? DAG.getZExtOrTrunc(Op, DL, SVT)
4249 : DAG.getSExtOrTrunc(Op, DL, SVT);
4251 SDValue V = DAG.getBuildVector(VT, DL, Elts);
4252 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4256 /// Gets or creates the specified node.
4257 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4258 FoldingSetNodeID ID;
4259 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4261 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4262 return SDValue(E, 0);
4264 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4266 CSEMap.InsertNode(N, IP);
4269 SDValue V = SDValue(N, 0);
4270 NewSDValueDbgMsg(V, "Creating new node: ", this);
4274 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4275 SDValue Operand, const SDNodeFlags Flags) {
4276 // Constant fold unary operations with an integer constant operand. Even
4277 // opaque constant will be folded, because the folding of unary operations
4278 // doesn't create new constants with different values. Nevertheless, the
4279 // opaque flag is preserved during folding to prevent future folding with
4281 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4282 const APInt &Val = C->getAPIntValue();
4285 case ISD::SIGN_EXTEND:
4286 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4287 C->isTargetOpcode(), C->isOpaque());
4292 case ISD::ANY_EXTEND:
4293 case ISD::ZERO_EXTEND:
4294 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4295 C->isTargetOpcode(), C->isOpaque());
4296 case ISD::UINT_TO_FP:
4297 case ISD::SINT_TO_FP: {
4298 APFloat apf(EVTToAPFloatSemantics(VT),
4299 APInt::getNullValue(VT.getSizeInBits()));
4300 (void)apf.convertFromAPInt(Val,
4301 Opcode==ISD::SINT_TO_FP,
4302 APFloat::rmNearestTiesToEven);
4303 return getConstantFP(apf, DL, VT);
4306 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4307 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4308 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4309 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4310 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4311 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4312 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4313 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4316 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4318 case ISD::BITREVERSE:
4319 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4322 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4325 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4328 case ISD::CTLZ_ZERO_UNDEF:
4329 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4332 case ISD::CTTZ_ZERO_UNDEF:
4333 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4335 case ISD::FP16_TO_FP: {
4337 APFloat FPV(APFloat::IEEEhalf(),
4338 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4340 // This can return overflow, underflow, or inexact; we don't care.
4341 // FIXME need to be more flexible about rounding mode.
4342 (void)FPV.convert(EVTToAPFloatSemantics(VT),
4343 APFloat::rmNearestTiesToEven, &Ignored);
4344 return getConstantFP(FPV, DL, VT);
4349 // Constant fold unary operations with a floating point constant operand.
4350 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4351 APFloat V = C->getValueAPF(); // make copy
4355 return getConstantFP(V, DL, VT);
4358 return getConstantFP(V, DL, VT);
4360 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4361 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4362 return getConstantFP(V, DL, VT);
4366 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4367 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4368 return getConstantFP(V, DL, VT);
4372 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4373 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4374 return getConstantFP(V, DL, VT);
4377 case ISD::FP_EXTEND: {
4379 // This can return overflow, underflow, or inexact; we don't care.
4380 // FIXME need to be more flexible about rounding mode.
4381 (void)V.convert(EVTToAPFloatSemantics(VT),
4382 APFloat::rmNearestTiesToEven, &ignored);
4383 return getConstantFP(V, DL, VT);
4385 case ISD::FP_TO_SINT:
4386 case ISD::FP_TO_UINT: {
4388 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4389 // FIXME need to be more flexible about rounding mode.
4390 APFloat::opStatus s =
4391 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4392 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4394 return getConstant(IntVal, DL, VT);
4397 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4398 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4399 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4400 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4401 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4402 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4404 case ISD::FP_TO_FP16: {
4406 // This can return overflow, underflow, or inexact; we don't care.
4407 // FIXME need to be more flexible about rounding mode.
4408 (void)V.convert(APFloat::IEEEhalf(),
4409 APFloat::rmNearestTiesToEven, &Ignored);
4410 return getConstant(V.bitcastToAPInt(), DL, VT);
4415 // Constant fold unary operations with a vector integer or float operand.
4416 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4417 if (BV->isConstant()) {
4420 // FIXME: Entirely reasonable to perform folding of other unary
4421 // operations here as the need arises.
4428 case ISD::FP_EXTEND:
4429 case ISD::FP_TO_SINT:
4430 case ISD::FP_TO_UINT:
4432 case ISD::ANY_EXTEND:
4433 case ISD::ZERO_EXTEND:
4434 case ISD::SIGN_EXTEND:
4435 case ISD::UINT_TO_FP:
4436 case ISD::SINT_TO_FP:
4438 case ISD::BITREVERSE:
4441 case ISD::CTLZ_ZERO_UNDEF:
4443 case ISD::CTTZ_ZERO_UNDEF:
4445 SDValue Ops = { Operand };
4446 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4453 unsigned OpOpcode = Operand.getNode()->getOpcode();
4455 case ISD::TokenFactor:
4456 case ISD::MERGE_VALUES:
4457 case ISD::CONCAT_VECTORS:
4458 return Operand; // Factor, merge or concat of one node? No need.
4459 case ISD::BUILD_VECTOR: {
4460 // Attempt to simplify BUILD_VECTOR.
4461 SDValue Ops[] = {Operand};
4462 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4466 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4467 case ISD::FP_EXTEND:
4468 assert(VT.isFloatingPoint() &&
4469 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4470 if (Operand.getValueType() == VT) return Operand; // noop conversion.
4471 assert((!VT.isVector() ||
4472 VT.getVectorNumElements() ==
4473 Operand.getValueType().getVectorNumElements()) &&
4474 "Vector element count mismatch!");
4475 assert(Operand.getValueType().bitsLT(VT) &&
4476 "Invalid fpext node, dst < src!");
4477 if (Operand.isUndef())
4478 return getUNDEF(VT);
4480 case ISD::FP_TO_SINT:
4481 case ISD::FP_TO_UINT:
4482 if (Operand.isUndef())
4483 return getUNDEF(VT);
4485 case ISD::SINT_TO_FP:
4486 case ISD::UINT_TO_FP:
4487 // [us]itofp(undef) = 0, because the result value is bounded.
4488 if (Operand.isUndef())
4489 return getConstantFP(0.0, DL, VT);
4491 case ISD::SIGN_EXTEND:
4492 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4493 "Invalid SIGN_EXTEND!");
4494 assert(VT.isVector() == Operand.getValueType().isVector() &&
4495 "SIGN_EXTEND result type type should be vector iff the operand "
4497 if (Operand.getValueType() == VT) return Operand; // noop extension
4498 assert((!VT.isVector() ||
4499 VT.getVectorNumElements() ==
4500 Operand.getValueType().getVectorNumElements()) &&
4501 "Vector element count mismatch!");
4502 assert(Operand.getValueType().bitsLT(VT) &&
4503 "Invalid sext node, dst < src!");
4504 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4505 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4506 else if (OpOpcode == ISD::UNDEF)
4507 // sext(undef) = 0, because the top bits will all be the same.
4508 return getConstant(0, DL, VT);
4510 case ISD::ZERO_EXTEND:
4511 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4512 "Invalid ZERO_EXTEND!");
4513 assert(VT.isVector() == Operand.getValueType().isVector() &&
4514 "ZERO_EXTEND result type type should be vector iff the operand "
4516 if (Operand.getValueType() == VT) return Operand; // noop extension
4517 assert((!VT.isVector() ||
4518 VT.getVectorNumElements() ==
4519 Operand.getValueType().getVectorNumElements()) &&
4520 "Vector element count mismatch!");
4521 assert(Operand.getValueType().bitsLT(VT) &&
4522 "Invalid zext node, dst < src!");
4523 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
4524 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4525 else if (OpOpcode == ISD::UNDEF)
4526 // zext(undef) = 0, because the top bits will be zero.
4527 return getConstant(0, DL, VT);
4529 case ISD::ANY_EXTEND:
4530 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4531 "Invalid ANY_EXTEND!");
4532 assert(VT.isVector() == Operand.getValueType().isVector() &&
4533 "ANY_EXTEND result type type should be vector iff the operand "
4535 if (Operand.getValueType() == VT) return Operand; // noop extension
4536 assert((!VT.isVector() ||
4537 VT.getVectorNumElements() ==
4538 Operand.getValueType().getVectorNumElements()) &&
4539 "Vector element count mismatch!");
4540 assert(Operand.getValueType().bitsLT(VT) &&
4541 "Invalid anyext node, dst < src!");
4543 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4544 OpOpcode == ISD::ANY_EXTEND)
4545 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
4546 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4547 else if (OpOpcode == ISD::UNDEF)
4548 return getUNDEF(VT);
4550 // (ext (trunc x)) -> x
4551 if (OpOpcode == ISD::TRUNCATE) {
4552 SDValue OpOp = Operand.getOperand(0);
4553 if (OpOp.getValueType() == VT) {
4554 transferDbgValues(Operand, OpOp);
4560 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4561 "Invalid TRUNCATE!");
4562 assert(VT.isVector() == Operand.getValueType().isVector() &&
4563 "TRUNCATE result type type should be vector iff the operand "
4565 if (Operand.getValueType() == VT) return Operand; // noop truncate
4566 assert((!VT.isVector() ||
4567 VT.getVectorNumElements() ==
4568 Operand.getValueType().getVectorNumElements()) &&
4569 "Vector element count mismatch!");
4570 assert(Operand.getValueType().bitsGT(VT) &&
4571 "Invalid truncate node, src < dst!");
4572 if (OpOpcode == ISD::TRUNCATE)
4573 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4574 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4575 OpOpcode == ISD::ANY_EXTEND) {
4576 // If the source is smaller than the dest, we still need an extend.
4577 if (Operand.getOperand(0).getValueType().getScalarType()
4578 .bitsLT(VT.getScalarType()))
4579 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4580 if (Operand.getOperand(0).getValueType().bitsGT(VT))
4581 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4582 return Operand.getOperand(0);
4584 if (OpOpcode == ISD::UNDEF)
4585 return getUNDEF(VT);
4587 case ISD::ANY_EXTEND_VECTOR_INREG:
4588 case ISD::ZERO_EXTEND_VECTOR_INREG:
4589 case ISD::SIGN_EXTEND_VECTOR_INREG:
4590 assert(VT.isVector() && "This DAG node is restricted to vector types.");
4591 assert(Operand.getValueType().bitsLE(VT) &&
4592 "The input must be the same size or smaller than the result.");
4593 assert(VT.getVectorNumElements() <
4594 Operand.getValueType().getVectorNumElements() &&
4595 "The destination vector type must have fewer lanes than the input.");
4598 assert(VT.isInteger() && VT == Operand.getValueType() &&
4600 if (OpOpcode == ISD::UNDEF)
4601 return getUNDEF(VT);
4604 assert(VT.isInteger() && VT == Operand.getValueType() &&
4606 assert((VT.getScalarSizeInBits() % 16 == 0) &&
4607 "BSWAP types must be a multiple of 16 bits!");
4608 if (OpOpcode == ISD::UNDEF)
4609 return getUNDEF(VT);
4611 case ISD::BITREVERSE:
4612 assert(VT.isInteger() && VT == Operand.getValueType() &&
4613 "Invalid BITREVERSE!");
4614 if (OpOpcode == ISD::UNDEF)
4615 return getUNDEF(VT);
4618 // Basic sanity checking.
4619 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4620 "Cannot BITCAST between types of different sizes!");
4621 if (VT == Operand.getValueType()) return Operand; // noop conversion.
4622 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
4623 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4624 if (OpOpcode == ISD::UNDEF)
4625 return getUNDEF(VT);
4627 case ISD::SCALAR_TO_VECTOR:
4628 assert(VT.isVector() && !Operand.getValueType().isVector() &&
4629 (VT.getVectorElementType() == Operand.getValueType() ||
4630 (VT.getVectorElementType().isInteger() &&
4631 Operand.getValueType().isInteger() &&
4632 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4633 "Illegal SCALAR_TO_VECTOR node!");
4634 if (OpOpcode == ISD::UNDEF)
4635 return getUNDEF(VT);
4636 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4637 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4638 isa<ConstantSDNode>(Operand.getOperand(1)) &&
4639 Operand.getConstantOperandVal(1) == 0 &&
4640 Operand.getOperand(0).getValueType() == VT)
4641 return Operand.getOperand(0);
4644 // Negation of an unknown bag of bits is still completely undefined.
4645 if (OpOpcode == ISD::UNDEF)
4646 return getUNDEF(VT);
4648 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4649 if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) &&
4650 OpOpcode == ISD::FSUB)
4651 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
4652 Operand.getOperand(0), Flags);
4653 if (OpOpcode == ISD::FNEG) // --X -> X
4654 return Operand.getOperand(0);
4657 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
4658 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4663 SDVTList VTs = getVTList(VT);
4664 SDValue Ops[] = {Operand};
4665 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4666 FoldingSetNodeID ID;
4667 AddNodeIDNode(ID, Opcode, VTs, Ops);
4669 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4670 E->intersectFlagsWith(Flags);
4671 return SDValue(E, 0);
4674 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4676 createOperands(N, Ops);
4677 CSEMap.InsertNode(N, IP);
4679 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4680 createOperands(N, Ops);
4684 SDValue V = SDValue(N, 0);
4685 NewSDValueDbgMsg(V, "Creating new node: ", this);
4689 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
4692 case ISD::ADD: return std::make_pair(C1 + C2, true);
4693 case ISD::SUB: return std::make_pair(C1 - C2, true);
4694 case ISD::MUL: return std::make_pair(C1 * C2, true);
4695 case ISD::AND: return std::make_pair(C1 & C2, true);
4696 case ISD::OR: return std::make_pair(C1 | C2, true);
4697 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
4698 case ISD::SHL: return std::make_pair(C1 << C2, true);
4699 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
4700 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
4701 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
4702 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
4703 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
4704 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
4705 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
4706 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
4707 case ISD::SADDSAT: return std::make_pair(C1.sadd_sat(C2), true);
4708 case ISD::UADDSAT: return std::make_pair(C1.uadd_sat(C2), true);
4709 case ISD::SSUBSAT: return std::make_pair(C1.ssub_sat(C2), true);
4710 case ISD::USUBSAT: return std::make_pair(C1.usub_sat(C2), true);
4712 if (!C2.getBoolValue())
4714 return std::make_pair(C1.udiv(C2), true);
4716 if (!C2.getBoolValue())
4718 return std::make_pair(C1.urem(C2), true);
4720 if (!C2.getBoolValue())
4722 return std::make_pair(C1.sdiv(C2), true);
4724 if (!C2.getBoolValue())
4726 return std::make_pair(C1.srem(C2), true);
4728 return std::make_pair(APInt(1, 0), false);
4731 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4732 EVT VT, const ConstantSDNode *C1,
4733 const ConstantSDNode *C2) {
4734 if (C1->isOpaque() || C2->isOpaque())
4737 std::pair<APInt, bool> Folded = FoldValue(Opcode, C1->getAPIntValue(),
4738 C2->getAPIntValue());
4741 return getConstant(Folded.first, DL, VT);
4744 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4745 const GlobalAddressSDNode *GA,
4747 if (GA->getOpcode() != ISD::GlobalAddress)
4749 if (!TLI->isOffsetFoldingLegal(GA))
4751 auto *C2 = dyn_cast<ConstantSDNode>(N2);
4754 int64_t Offset = C2->getSExtValue();
4756 case ISD::ADD: break;
4757 case ISD::SUB: Offset = -uint64_t(Offset); break;
4758 default: return SDValue();
4760 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4761 GA->getOffset() + uint64_t(Offset));
4764 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4770 // If a divisor is zero/undef or any element of a divisor vector is
4771 // zero/undef, the whole op is undef.
4772 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4773 SDValue Divisor = Ops[1];
4774 if (Divisor.isUndef() || isNullConstant(Divisor))
4777 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4778 llvm::any_of(Divisor->op_values(),
4779 [](SDValue V) { return V.isUndef() ||
4780 isNullConstant(V); });
4781 // TODO: Handle signed overflow.
4783 // TODO: Handle oversized shifts.
4789 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4790 EVT VT, SDNode *N1, SDNode *N2) {
4791 // If the opcode is a target-specific ISD node, there's nothing we can
4792 // do here and the operand rules may not line up with the below, so
4794 if (Opcode >= ISD::BUILTIN_OP_END)
4797 if (isUndef(Opcode, {SDValue(N1, 0), SDValue(N2, 0)}))
4798 return getUNDEF(VT);
4800 // Handle the case of two scalars.
4801 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
4802 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
4803 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, C1, C2);
4804 assert((!Folded || !VT.isVector()) &&
4805 "Can't fold vectors ops with scalar operands");
4810 // fold (add Sym, c) -> Sym+c
4811 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
4812 return FoldSymbolOffset(Opcode, VT, GA, N2);
4813 if (TLI->isCommutativeBinOp(Opcode))
4814 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
4815 return FoldSymbolOffset(Opcode, VT, GA, N1);
4817 // For vectors, extract each constant element and fold them individually.
4818 // Either input may be an undef value.
4819 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
4820 if (!BV1 && !N1->isUndef())
4822 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
4823 if (!BV2 && !N2->isUndef())
4825 // If both operands are undef, that's handled the same way as scalars.
4829 assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
4830 "Vector binop with different number of elements in operands?");
4832 EVT SVT = VT.getScalarType();
4834 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4835 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4836 if (LegalSVT.bitsLT(SVT))
4839 SmallVector<SDValue, 4> Outputs;
4840 unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
4841 for (unsigned I = 0; I != NumOps; ++I) {
4842 SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
4843 SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
4844 if (SVT.isInteger()) {
4845 if (V1->getValueType(0).bitsGT(SVT))
4846 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4847 if (V2->getValueType(0).bitsGT(SVT))
4848 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4851 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4854 // Fold one vector element.
4855 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4856 if (LegalSVT != SVT)
4857 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4859 // Scalar folding only succeeded if the result is a constant or UNDEF.
4860 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4861 ScalarResult.getOpcode() != ISD::ConstantFP)
4863 Outputs.push_back(ScalarResult);
4866 assert(VT.getVectorNumElements() == Outputs.size() &&
4867 "Vector size mismatch!");
4869 // We may have a vector type but a scalar result. Create a splat.
4870 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
4872 // Build a big vector out of the scalar elements we generated.
4873 return getBuildVector(VT, SDLoc(), Outputs);
4876 // TODO: Merge with FoldConstantArithmetic
4877 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
4878 const SDLoc &DL, EVT VT,
4879 ArrayRef<SDValue> Ops,
4880 const SDNodeFlags Flags) {
4881 // If the opcode is a target-specific ISD node, there's nothing we can
4882 // do here and the operand rules may not line up with the below, so
4884 if (Opcode >= ISD::BUILTIN_OP_END)
4887 if (isUndef(Opcode, Ops))
4888 return getUNDEF(VT);
4890 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4894 unsigned NumElts = VT.getVectorNumElements();
4896 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
4897 return !Op.getValueType().isVector() ||
4898 Op.getValueType().getVectorNumElements() == NumElts;
4901 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
4902 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
4903 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
4904 (BV && BV->isConstant());
4907 // All operands must be vector types with the same number of elements as
4908 // the result type and must be either UNDEF or a build vector of constant
4909 // or UNDEF scalars.
4910 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
4911 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
4914 // If we are comparing vectors, then the result needs to be a i1 boolean
4915 // that is then sign-extended back to the legal result type.
4916 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
4918 // Find legal integer scalar type for constant promotion and
4919 // ensure that its scalar size is at least as large as source.
4920 EVT LegalSVT = VT.getScalarType();
4921 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4922 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4923 if (LegalSVT.bitsLT(VT.getScalarType()))
4927 // Constant fold each scalar lane separately.
4928 SmallVector<SDValue, 4> ScalarResults;
4929 for (unsigned i = 0; i != NumElts; i++) {
4930 SmallVector<SDValue, 4> ScalarOps;
4931 for (SDValue Op : Ops) {
4932 EVT InSVT = Op.getValueType().getScalarType();
4933 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
4935 // We've checked that this is UNDEF or a constant of some kind.
4937 ScalarOps.push_back(getUNDEF(InSVT));
4939 ScalarOps.push_back(Op);
4943 SDValue ScalarOp = InBV->getOperand(i);
4944 EVT ScalarVT = ScalarOp.getValueType();
4946 // Build vector (integer) scalar operands may need implicit
4947 // truncation - do this before constant folding.
4948 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4949 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4951 ScalarOps.push_back(ScalarOp);
4954 // Constant fold the scalar operands.
4955 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4957 // Legalize the (integer) scalar constant if necessary.
4958 if (LegalSVT != SVT)
4959 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4961 // Scalar folding only succeeded if the result is a constant or UNDEF.
4962 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4963 ScalarResult.getOpcode() != ISD::ConstantFP)
4965 ScalarResults.push_back(ScalarResult);
4968 SDValue V = getBuildVector(VT, DL, ScalarResults);
4969 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
4973 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
4974 EVT VT, SDValue N1, SDValue N2) {
4975 // TODO: We don't do any constant folding for strict FP opcodes here, but we
4976 // should. That will require dealing with a potentially non-default
4977 // rounding mode, checking the "opStatus" return value from the APFloat
4978 // math calculations, and possibly other variations.
4979 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
4980 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
4981 if (N1CFP && N2CFP) {
4982 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
4985 C1.add(C2, APFloat::rmNearestTiesToEven);
4986 return getConstantFP(C1, DL, VT);
4988 C1.subtract(C2, APFloat::rmNearestTiesToEven);
4989 return getConstantFP(C1, DL, VT);
4991 C1.multiply(C2, APFloat::rmNearestTiesToEven);
4992 return getConstantFP(C1, DL, VT);
4994 C1.divide(C2, APFloat::rmNearestTiesToEven);
4995 return getConstantFP(C1, DL, VT);
4998 return getConstantFP(C1, DL, VT);
4999 case ISD::FCOPYSIGN:
5001 return getConstantFP(C1, DL, VT);
5005 if (N1CFP && Opcode == ISD::FP_ROUND) {
5006 APFloat C1 = N1CFP->getValueAPF(); // make copy
5008 // This can return overflow, underflow, or inexact; we don't care.
5009 // FIXME need to be more flexible about rounding mode.
5010 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5012 return getConstantFP(C1, DL, VT);
5021 // If both operands are undef, the result is undef. If 1 operand is undef,
5022 // the result is NaN. This should match the behavior of the IR optimizer.
5023 if (N1.isUndef() && N2.isUndef())
5024 return getUNDEF(VT);
5025 if (N1.isUndef() || N2.isUndef())
5026 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5031 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5032 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5033 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5034 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5035 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5036 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5038 // Canonicalize constant to RHS if commutative.
5039 if (TLI->isCommutativeBinOp(Opcode)) {
5041 std::swap(N1C, N2C);
5043 } else if (N1CFP && !N2CFP) {
5044 std::swap(N1CFP, N2CFP);
5051 case ISD::TokenFactor:
5052 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5053 N2.getValueType() == MVT::Other && "Invalid token factor!");
5054 // Fold trivial token factors.
5055 if (N1.getOpcode() == ISD::EntryToken) return N2;
5056 if (N2.getOpcode() == ISD::EntryToken) return N1;
5057 if (N1 == N2) return N1;
5059 case ISD::BUILD_VECTOR: {
5060 // Attempt to simplify BUILD_VECTOR.
5061 SDValue Ops[] = {N1, N2};
5062 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5066 case ISD::CONCAT_VECTORS: {
5067 SDValue Ops[] = {N1, N2};
5068 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5073 assert(VT.isInteger() && "This operator does not apply to FP types!");
5074 assert(N1.getValueType() == N2.getValueType() &&
5075 N1.getValueType() == VT && "Binary operator types must match!");
5076 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
5077 // worth handling here.
5078 if (N2C && N2C->isNullValue())
5080 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
5087 assert(VT.isInteger() && "This operator does not apply to FP types!");
5088 assert(N1.getValueType() == N2.getValueType() &&
5089 N1.getValueType() == VT && "Binary operator types must match!");
5090 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
5091 // it's worth handling here.
5092 if (N2C && N2C->isNullValue())
5110 assert(VT.isInteger() && "This operator does not apply to FP types!");
5111 assert(N1.getValueType() == N2.getValueType() &&
5112 N1.getValueType() == VT && "Binary operator types must match!");
5119 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5120 assert(N1.getValueType() == N2.getValueType() &&
5121 N1.getValueType() == VT && "Binary operator types must match!");
5122 if (SDValue V = simplifyFPBinop(Opcode, N1, N2))
5125 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
5126 assert(N1.getValueType() == VT &&
5127 N1.getValueType().isFloatingPoint() &&
5128 N2.getValueType().isFloatingPoint() &&
5129 "Invalid FCOPYSIGN!");
5134 if (SDValue V = simplifyShift(N1, N2))
5139 assert(VT == N1.getValueType() &&
5140 "Shift operators return type must be the same as their first arg");
5141 assert(VT.isInteger() && N2.getValueType().isInteger() &&
5142 "Shifts only work on integers");
5143 assert((!VT.isVector() || VT == N2.getValueType()) &&
5144 "Vector shift amounts must be in the same as their first arg");
5145 // Verify that the shift amount VT is big enough to hold valid shift
5146 // amounts. This catches things like trying to shift an i1024 value by an
5147 // i8, which is easy to fall into in generic code that uses
5148 // TLI.getShiftAmount().
5149 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
5150 "Invalid use of small shift amount with oversized value!");
5152 // Always fold shifts of i1 values so the code generator doesn't need to
5153 // handle them. Since we know the size of the shift has to be less than the
5154 // size of the value, the shift/rotate count is guaranteed to be zero.
5157 if (N2C && N2C->isNullValue())
5160 case ISD::FP_ROUND_INREG: {
5161 EVT EVT = cast<VTSDNode>(N2)->getVT();
5162 assert(VT == N1.getValueType() && "Not an inreg round!");
5163 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
5164 "Cannot FP_ROUND_INREG integer types");
5165 assert(EVT.isVector() == VT.isVector() &&
5166 "FP_ROUND_INREG type should be vector iff the operand "
5168 assert((!EVT.isVector() ||
5169 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
5170 "Vector element counts must match in FP_ROUND_INREG");
5171 assert(EVT.bitsLE(VT) && "Not rounding down!");
5173 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
5177 assert(VT.isFloatingPoint() &&
5178 N1.getValueType().isFloatingPoint() &&
5179 VT.bitsLE(N1.getValueType()) &&
5180 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5181 "Invalid FP_ROUND!");
5182 if (N1.getValueType() == VT) return N1; // noop conversion.
5184 case ISD::AssertSext:
5185 case ISD::AssertZext: {
5186 EVT EVT = cast<VTSDNode>(N2)->getVT();
5187 assert(VT == N1.getValueType() && "Not an inreg extend!");
5188 assert(VT.isInteger() && EVT.isInteger() &&
5189 "Cannot *_EXTEND_INREG FP types");
5190 assert(!EVT.isVector() &&
5191 "AssertSExt/AssertZExt type should be the vector element type "
5192 "rather than the vector type!");
5193 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5194 if (VT.getScalarType() == EVT) return N1; // noop assertion.
5197 case ISD::SIGN_EXTEND_INREG: {
5198 EVT EVT = cast<VTSDNode>(N2)->getVT();
5199 assert(VT == N1.getValueType() && "Not an inreg extend!");
5200 assert(VT.isInteger() && EVT.isInteger() &&
5201 "Cannot *_EXTEND_INREG FP types");
5202 assert(EVT.isVector() == VT.isVector() &&
5203 "SIGN_EXTEND_INREG type should be vector iff the operand "
5205 assert((!EVT.isVector() ||
5206 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
5207 "Vector element counts must match in SIGN_EXTEND_INREG");
5208 assert(EVT.bitsLE(VT) && "Not extending!");
5209 if (EVT == VT) return N1; // Not actually extending
5211 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5212 unsigned FromBits = EVT.getScalarSizeInBits();
5213 Val <<= Val.getBitWidth() - FromBits;
5214 Val.ashrInPlace(Val.getBitWidth() - FromBits);
5215 return getConstant(Val, DL, ConstantVT);
5219 const APInt &Val = N1C->getAPIntValue();
5220 return SignExtendInReg(Val, VT);
5222 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5223 SmallVector<SDValue, 8> Ops;
5224 llvm::EVT OpVT = N1.getOperand(0).getValueType();
5225 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5226 SDValue Op = N1.getOperand(i);
5228 Ops.push_back(getUNDEF(OpVT));
5231 ConstantSDNode *C = cast<ConstantSDNode>(Op);
5232 APInt Val = C->getAPIntValue();
5233 Ops.push_back(SignExtendInReg(Val, OpVT));
5235 return getBuildVector(VT, DL, Ops);
5239 case ISD::EXTRACT_VECTOR_ELT:
5240 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5241 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5242 element type of the vector.");
5244 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
5246 return getUNDEF(VT);
5248 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
5249 if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5250 return getUNDEF(VT);
5252 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5253 // expanding copies of large vectors from registers.
5255 N1.getOpcode() == ISD::CONCAT_VECTORS &&
5256 N1.getNumOperands() > 0) {
5258 N1.getOperand(0).getValueType().getVectorNumElements();
5259 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5260 N1.getOperand(N2C->getZExtValue() / Factor),
5261 getConstant(N2C->getZExtValue() % Factor, DL,
5262 N2.getValueType()));
5265 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
5266 // expanding large vector constants.
5267 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
5268 SDValue Elt = N1.getOperand(N2C->getZExtValue());
5270 if (VT != Elt.getValueType())
5271 // If the vector element type is not legal, the BUILD_VECTOR operands
5272 // are promoted and implicitly truncated, and the result implicitly
5273 // extended. Make that explicit here.
5274 Elt = getAnyExtOrTrunc(Elt, DL, VT);
5279 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5280 // operations are lowered to scalars.
5281 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5282 // If the indices are the same, return the inserted element else
5283 // if the indices are known different, extract the element from
5284 // the original vector.
5285 SDValue N1Op2 = N1.getOperand(2);
5286 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5288 if (N1Op2C && N2C) {
5289 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5290 if (VT == N1.getOperand(1).getValueType())
5291 return N1.getOperand(1);
5293 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5296 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5300 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5301 // when vector types are scalarized and v1iX is legal.
5302 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
5303 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5304 N1.getValueType().getVectorNumElements() == 1) {
5305 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5309 case ISD::EXTRACT_ELEMENT:
5310 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5311 assert(!N1.getValueType().isVector() && !VT.isVector() &&
5312 (N1.getValueType().isInteger() == VT.isInteger()) &&
5313 N1.getValueType() != VT &&
5314 "Wrong types for EXTRACT_ELEMENT!");
5316 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5317 // 64-bit integers into 32-bit parts. Instead of building the extract of
5318 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5319 if (N1.getOpcode() == ISD::BUILD_PAIR)
5320 return N1.getOperand(N2C->getZExtValue());
5322 // EXTRACT_ELEMENT of a constant int is also very common.
5324 unsigned ElementSize = VT.getSizeInBits();
5325 unsigned Shift = ElementSize * N2C->getZExtValue();
5326 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
5327 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
5330 case ISD::EXTRACT_SUBVECTOR:
5331 if (VT.isSimple() && N1.getValueType().isSimple()) {
5332 assert(VT.isVector() && N1.getValueType().isVector() &&
5333 "Extract subvector VTs must be a vectors!");
5334 assert(VT.getVectorElementType() ==
5335 N1.getValueType().getVectorElementType() &&
5336 "Extract subvector VTs must have the same element type!");
5337 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
5338 "Extract subvector must be from larger vector to smaller vector!");
5341 assert((VT.getVectorNumElements() + N2C->getZExtValue()
5342 <= N1.getValueType().getVectorNumElements())
5343 && "Extract subvector overflow!");
5346 // Trivial extraction.
5347 if (VT.getSimpleVT() == N1.getSimpleValueType())
5350 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5352 return getUNDEF(VT);
5354 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5355 // the concat have the same type as the extract.
5356 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
5357 N1.getNumOperands() > 0 &&
5358 VT == N1.getOperand(0).getValueType()) {
5359 unsigned Factor = VT.getVectorNumElements();
5360 return N1.getOperand(N2C->getZExtValue() / Factor);
5363 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5364 // during shuffle legalization.
5365 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5366 VT == N1.getOperand(1).getValueType())
5367 return N1.getOperand(1);
5372 // Perform trivial constant folding.
5374 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
5377 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5380 // Canonicalize an UNDEF to the RHS, even over a constant.
5382 if (TLI->isCommutativeBinOp(Opcode)) {
5386 case ISD::FP_ROUND_INREG:
5387 case ISD::SIGN_EXTEND_INREG:
5389 return getUNDEF(VT); // fold op(undef, arg2) -> undef
5396 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
5401 // Fold a bunch of operators when the RHS is undef.
5406 // Handle undef ^ undef -> 0 special case. This is a common
5408 return getConstant(0, DL, VT);
5416 return getUNDEF(VT); // fold op(arg1, undef) -> undef
5421 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
5425 return getAllOnesConstant(DL, VT);
5429 // Memoize this node if possible.
5431 SDVTList VTs = getVTList(VT);
5432 SDValue Ops[] = {N1, N2};
5433 if (VT != MVT::Glue) {
5434 FoldingSetNodeID ID;
5435 AddNodeIDNode(ID, Opcode, VTs, Ops);
5437 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5438 E->intersectFlagsWith(Flags);
5439 return SDValue(E, 0);
5442 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5444 createOperands(N, Ops);
5445 CSEMap.InsertNode(N, IP);
5447 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5448 createOperands(N, Ops);
5452 SDValue V = SDValue(N, 0);
5453 NewSDValueDbgMsg(V, "Creating new node: ", this);
5457 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5458 SDValue N1, SDValue N2, SDValue N3,
5459 const SDNodeFlags Flags) {
5460 // Perform various simplifications.
5463 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5464 assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5465 N3.getValueType() == VT && "FMA types must match!");
5466 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5467 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5468 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5469 if (N1CFP && N2CFP && N3CFP) {
5470 APFloat V1 = N1CFP->getValueAPF();
5471 const APFloat &V2 = N2CFP->getValueAPF();
5472 const APFloat &V3 = N3CFP->getValueAPF();
5473 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5474 return getConstantFP(V1, DL, VT);
5478 case ISD::BUILD_VECTOR: {
5479 // Attempt to simplify BUILD_VECTOR.
5480 SDValue Ops[] = {N1, N2, N3};
5481 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5485 case ISD::CONCAT_VECTORS: {
5486 SDValue Ops[] = {N1, N2, N3};
5487 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5492 assert(VT.isInteger() && "SETCC result type must be an integer!");
5493 assert(N1.getValueType() == N2.getValueType() &&
5494 "SETCC operands must have the same type!");
5495 assert(VT.isVector() == N1.getValueType().isVector() &&
5496 "SETCC type should be vector iff the operand type is vector!");
5497 assert((!VT.isVector() ||
5498 VT.getVectorNumElements() == N1.getValueType().getVectorNumElements()) &&
5499 "SETCC vector element counts must match!");
5500 // Use FoldSetCC to simplify SETCC's.
5501 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5503 // Vector constant folding.
5504 SDValue Ops[] = {N1, N2, N3};
5505 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5506 NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5513 if (SDValue V = simplifySelect(N1, N2, N3))
5516 case ISD::VECTOR_SHUFFLE:
5517 llvm_unreachable("should use getVectorShuffle constructor!");
5518 case ISD::INSERT_VECTOR_ELT: {
5519 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5520 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
5521 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5522 return getUNDEF(VT);
5525 case ISD::INSERT_SUBVECTOR: {
5526 // Inserting undef into undef is still undef.
5527 if (N1.isUndef() && N2.isUndef())
5528 return getUNDEF(VT);
5530 if (VT.isSimple() && N1.getValueType().isSimple()
5531 && N2.getValueType().isSimple()) {
5532 assert(VT.isVector() && N1.getValueType().isVector() &&
5533 N2.getValueType().isVector() &&
5534 "Insert subvector VTs must be a vectors");
5535 assert(VT == N1.getValueType() &&
5536 "Dest and insert subvector source types must match!");
5537 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
5538 "Insert subvector must be from smaller vector to larger vector!");
5539 if (isa<ConstantSDNode>(Index)) {
5540 assert((N2.getValueType().getVectorNumElements() +
5541 cast<ConstantSDNode>(Index)->getZExtValue()
5542 <= VT.getVectorNumElements())
5543 && "Insert subvector overflow!");
5546 // Trivial insertion.
5547 if (VT.getSimpleVT() == N2.getSimpleValueType())
5550 // If this is an insert of an extracted vector into an undef vector, we
5551 // can just use the input to the extract.
5552 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5553 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5554 return N2.getOperand(0);
5559 // Fold bit_convert nodes from a type to themselves.
5560 if (N1.getValueType() == VT)
5565 // Memoize node if it doesn't produce a flag.
5567 SDVTList VTs = getVTList(VT);
5568 SDValue Ops[] = {N1, N2, N3};
5569 if (VT != MVT::Glue) {
5570 FoldingSetNodeID ID;
5571 AddNodeIDNode(ID, Opcode, VTs, Ops);
5573 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5574 E->intersectFlagsWith(Flags);
5575 return SDValue(E, 0);
5578 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5580 createOperands(N, Ops);
5581 CSEMap.InsertNode(N, IP);
5583 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5584 createOperands(N, Ops);
5588 SDValue V = SDValue(N, 0);
5589 NewSDValueDbgMsg(V, "Creating new node: ", this);
5593 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5594 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5595 SDValue Ops[] = { N1, N2, N3, N4 };
5596 return getNode(Opcode, DL, VT, Ops);
5599 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5600 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5602 SDValue Ops[] = { N1, N2, N3, N4, N5 };
5603 return getNode(Opcode, DL, VT, Ops);
5606 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5607 /// the incoming stack arguments to be loaded from the stack.
5608 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5609 SmallVector<SDValue, 8> ArgChains;
5611 // Include the original chain at the beginning of the list. When this is
5612 // used by target LowerCall hooks, this helps legalize find the
5613 // CALLSEQ_BEGIN node.
5614 ArgChains.push_back(Chain);
5616 // Add a chain value for each stack argument.
5617 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5618 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5619 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5620 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5621 if (FI->getIndex() < 0)
5622 ArgChains.push_back(SDValue(L, 1));
5624 // Build a tokenfactor for all the chains.
5625 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5628 /// getMemsetValue - Vectorized representation of the memset value
5630 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5632 assert(!Value.isUndef());
5634 unsigned NumBits = VT.getScalarSizeInBits();
5635 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5636 assert(C->getAPIntValue().getBitWidth() == 8);
5637 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5638 if (VT.isInteger()) {
5639 bool IsOpaque = VT.getSizeInBits() > 64 ||
5640 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
5641 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
5643 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5647 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5648 EVT IntVT = VT.getScalarType();
5649 if (!IntVT.isInteger())
5650 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5652 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5654 // Use a multiplication with 0x010101... to extend the input to the
5656 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5657 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5658 DAG.getConstant(Magic, dl, IntVT));
5661 if (VT != Value.getValueType() && !VT.isInteger())
5662 Value = DAG.getBitcast(VT.getScalarType(), Value);
5663 if (VT != Value.getValueType())
5664 Value = DAG.getSplatBuildVector(VT, dl, Value);
5669 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5670 /// used when a memcpy is turned into a memset when the source is a constant
5672 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
5673 const TargetLowering &TLI,
5674 const ConstantDataArraySlice &Slice) {
5675 // Handle vector with all elements zero.
5676 if (Slice.Array == nullptr) {
5678 return DAG.getConstant(0, dl, VT);
5679 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
5680 return DAG.getConstantFP(0.0, dl, VT);
5681 else if (VT.isVector()) {
5682 unsigned NumElts = VT.getVectorNumElements();
5683 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5684 return DAG.getNode(ISD::BITCAST, dl, VT,
5685 DAG.getConstant(0, dl,
5686 EVT::getVectorVT(*DAG.getContext(),
5689 llvm_unreachable("Expected type!");
5692 assert(!VT.isVector() && "Can't handle vector type here!");
5693 unsigned NumVTBits = VT.getSizeInBits();
5694 unsigned NumVTBytes = NumVTBits / 8;
5695 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
5697 APInt Val(NumVTBits, 0);
5698 if (DAG.getDataLayout().isLittleEndian()) {
5699 for (unsigned i = 0; i != NumBytes; ++i)
5700 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
5702 for (unsigned i = 0; i != NumBytes; ++i)
5703 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
5706 // If the "cost" of materializing the integer immediate is less than the cost
5707 // of a load, then it is cost effective to turn the load into the immediate.
5708 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
5709 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
5710 return DAG.getConstant(Val, dl, VT);
5711 return SDValue(nullptr, 0);
5714 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
5716 EVT VT = Base.getValueType();
5717 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
5720 /// Returns true if memcpy source is constant data.
5721 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
5722 uint64_t SrcDelta = 0;
5723 GlobalAddressSDNode *G = nullptr;
5724 if (Src.getOpcode() == ISD::GlobalAddress)
5725 G = cast<GlobalAddressSDNode>(Src);
5726 else if (Src.getOpcode() == ISD::ADD &&
5727 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
5728 Src.getOperand(1).getOpcode() == ISD::Constant) {
5729 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
5730 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
5735 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
5736 SrcDelta + G->getOffset());
5739 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
5740 // On Darwin, -Os means optimize for size without hurting performance, so
5741 // only really optimize for size when -Oz (MinSize) is used.
5742 if (MF.getTarget().getTargetTriple().isOSDarwin())
5743 return MF.getFunction().hasMinSize();
5744 return MF.getFunction().hasOptSize();
5747 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
5748 SmallVector<SDValue, 32> &OutChains, unsigned From,
5749 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
5750 SmallVector<SDValue, 16> &OutStoreChains) {
5751 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
5752 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
5753 SmallVector<SDValue, 16> GluedLoadChains;
5754 for (unsigned i = From; i < To; ++i) {
5755 OutChains.push_back(OutLoadChains[i]);
5756 GluedLoadChains.push_back(OutLoadChains[i]);
5759 // Chain for all loads.
5760 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5763 for (unsigned i = From; i < To; ++i) {
5764 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
5765 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
5766 ST->getBasePtr(), ST->getMemoryVT(),
5767 ST->getMemOperand());
5768 OutChains.push_back(NewStore);
5772 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5773 SDValue Chain, SDValue Dst, SDValue Src,
5774 uint64_t Size, unsigned Align,
5775 bool isVol, bool AlwaysInline,
5776 MachinePointerInfo DstPtrInfo,
5777 MachinePointerInfo SrcPtrInfo) {
5778 // Turn a memcpy of undef to nop.
5779 // FIXME: We need to honor volatile even is Src is undef.
5783 // Expand memcpy to a series of load and store ops if the size operand falls
5784 // below a certain threshold.
5785 // TODO: In the AlwaysInline case, if the size is big then generate a loop
5786 // rather than maybe a humongous number of loads and stores.
5787 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5788 const DataLayout &DL = DAG.getDataLayout();
5789 LLVMContext &C = *DAG.getContext();
5790 std::vector<EVT> MemOps;
5791 bool DstAlignCanChange = false;
5792 MachineFunction &MF = DAG.getMachineFunction();
5793 MachineFrameInfo &MFI = MF.getFrameInfo();
5794 bool OptSize = shouldLowerMemFuncForSize(MF);
5795 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5796 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5797 DstAlignCanChange = true;
5798 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5799 if (Align > SrcAlign)
5801 ConstantDataArraySlice Slice;
5802 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
5803 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
5804 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
5806 if (!TLI.findOptimalMemOpLowering(
5807 MemOps, Limit, Size, (DstAlignCanChange ? 0 : Align),
5808 (isZeroConstant ? 0 : SrcAlign), /*IsMemset=*/false,
5809 /*ZeroMemset=*/false, /*MemcpyStrSrc=*/CopyFromConstant,
5810 /*AllowOverlap=*/!isVol, DstPtrInfo.getAddrSpace(),
5811 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
5814 if (DstAlignCanChange) {
5815 Type *Ty = MemOps[0].getTypeForEVT(C);
5816 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5818 // Don't promote to an alignment that would require dynamic stack
5820 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
5821 if (!TRI->needsStackRealignment(MF))
5822 while (NewAlign > Align &&
5823 DL.exceedsNaturalStackAlignment(NewAlign))
5826 if (NewAlign > Align) {
5827 // Give the stack frame object a larger alignment if needed.
5828 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5829 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5834 MachineMemOperand::Flags MMOFlags =
5835 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5836 SmallVector<SDValue, 16> OutLoadChains;
5837 SmallVector<SDValue, 16> OutStoreChains;
5838 SmallVector<SDValue, 32> OutChains;
5839 unsigned NumMemOps = MemOps.size();
5840 uint64_t SrcOff = 0, DstOff = 0;
5841 for (unsigned i = 0; i != NumMemOps; ++i) {
5843 unsigned VTSize = VT.getSizeInBits() / 8;
5844 SDValue Value, Store;
5846 if (VTSize > Size) {
5847 // Issuing an unaligned load / store pair that overlaps with the previous
5848 // pair. Adjust the offset accordingly.
5849 assert(i == NumMemOps-1 && i != 0);
5850 SrcOff -= VTSize - Size;
5851 DstOff -= VTSize - Size;
5854 if (CopyFromConstant &&
5855 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
5856 // It's unlikely a store of a vector immediate can be done in a single
5857 // instruction. It would require a load from a constantpool first.
5858 // We only handle zero vectors here.
5859 // FIXME: Handle other cases where store of vector immediate is done in
5860 // a single instruction.
5861 ConstantDataArraySlice SubSlice;
5862 if (SrcOff < Slice.Length) {
5864 SubSlice.move(SrcOff);
5866 // This is an out-of-bounds access and hence UB. Pretend we read zero.
5867 SubSlice.Array = nullptr;
5868 SubSlice.Offset = 0;
5869 SubSlice.Length = VTSize;
5871 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
5872 if (Value.getNode()) {
5873 Store = DAG.getStore(Chain, dl, Value,
5874 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5875 DstPtrInfo.getWithOffset(DstOff), Align,
5877 OutChains.push_back(Store);
5881 if (!Store.getNode()) {
5882 // The type might not be legal for the target. This should only happen
5883 // if the type is smaller than a legal type, as on PPC, so the right
5884 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
5885 // to Load/Store if NVT==VT.
5886 // FIXME does the case above also need this?
5887 EVT NVT = TLI.getTypeToTransformTo(C, VT);
5888 assert(NVT.bitsGE(VT));
5890 bool isDereferenceable =
5891 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5892 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5893 if (isDereferenceable)
5894 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5896 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5897 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5898 SrcPtrInfo.getWithOffset(SrcOff), VT,
5899 MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5900 OutLoadChains.push_back(Value.getValue(1));
5902 Store = DAG.getTruncStore(
5903 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5904 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5905 OutStoreChains.push_back(Store);
5912 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
5913 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
5914 unsigned NumLdStInMemcpy = OutStoreChains.size();
5916 if (NumLdStInMemcpy) {
5917 // It may be that memcpy might be converted to memset if it's memcpy
5918 // of constants. In such a case, we won't have loads and stores, but
5919 // just stores. In the absence of loads, there is nothing to gang up.
5920 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
5921 // If target does not care, just leave as it.
5922 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
5923 OutChains.push_back(OutLoadChains[i]);
5924 OutChains.push_back(OutStoreChains[i]);
5927 // Ld/St less than/equal limit set by target.
5928 if (NumLdStInMemcpy <= GluedLdStLimit) {
5929 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5930 NumLdStInMemcpy, OutLoadChains,
5933 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
5934 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
5935 unsigned GlueIter = 0;
5937 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
5938 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
5939 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
5941 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
5942 OutLoadChains, OutStoreChains);
5943 GlueIter += GluedLdStLimit;
5947 if (RemainingLdStInMemcpy) {
5948 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5949 RemainingLdStInMemcpy, OutLoadChains,
5955 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5958 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5959 SDValue Chain, SDValue Dst, SDValue Src,
5960 uint64_t Size, unsigned Align,
5961 bool isVol, bool AlwaysInline,
5962 MachinePointerInfo DstPtrInfo,
5963 MachinePointerInfo SrcPtrInfo) {
5964 // Turn a memmove of undef to nop.
5965 // FIXME: We need to honor volatile even is Src is undef.
5969 // Expand memmove to a series of load and store ops if the size operand falls
5970 // below a certain threshold.
5971 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5972 const DataLayout &DL = DAG.getDataLayout();
5973 LLVMContext &C = *DAG.getContext();
5974 std::vector<EVT> MemOps;
5975 bool DstAlignCanChange = false;
5976 MachineFunction &MF = DAG.getMachineFunction();
5977 MachineFrameInfo &MFI = MF.getFrameInfo();
5978 bool OptSize = shouldLowerMemFuncForSize(MF);
5979 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5980 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5981 DstAlignCanChange = true;
5982 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5983 if (Align > SrcAlign)
5985 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5986 // FIXME: `AllowOverlap` should really be `!isVol` but there is a bug in
5987 // findOptimalMemOpLowering. Meanwhile, setting it to `false` produces the
5989 bool AllowOverlap = false;
5990 if (!TLI.findOptimalMemOpLowering(
5991 MemOps, Limit, Size, (DstAlignCanChange ? 0 : Align), SrcAlign,
5992 /*IsMemset=*/false, /*ZeroMemset=*/false, /*MemcpyStrSrc=*/false,
5993 AllowOverlap, DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
5994 MF.getFunction().getAttributes()))
5997 if (DstAlignCanChange) {
5998 Type *Ty = MemOps[0].getTypeForEVT(C);
5999 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
6000 if (NewAlign > Align) {
6001 // Give the stack frame object a larger alignment if needed.
6002 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
6003 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6008 MachineMemOperand::Flags MMOFlags =
6009 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6010 uint64_t SrcOff = 0, DstOff = 0;
6011 SmallVector<SDValue, 8> LoadValues;
6012 SmallVector<SDValue, 8> LoadChains;
6013 SmallVector<SDValue, 8> OutChains;
6014 unsigned NumMemOps = MemOps.size();
6015 for (unsigned i = 0; i < NumMemOps; i++) {
6017 unsigned VTSize = VT.getSizeInBits() / 8;
6020 bool isDereferenceable =
6021 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6022 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6023 if (isDereferenceable)
6024 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6027 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
6028 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
6029 LoadValues.push_back(Value);
6030 LoadChains.push_back(Value.getValue(1));
6033 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6035 for (unsigned i = 0; i < NumMemOps; i++) {
6037 unsigned VTSize = VT.getSizeInBits() / 8;
6040 Store = DAG.getStore(Chain, dl, LoadValues[i],
6041 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6042 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
6043 OutChains.push_back(Store);
6047 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6050 /// Lower the call to 'memset' intrinsic function into a series of store
6053 /// \param DAG Selection DAG where lowered code is placed.
6054 /// \param dl Link to corresponding IR location.
6055 /// \param Chain Control flow dependency.
6056 /// \param Dst Pointer to destination memory location.
6057 /// \param Src Value of byte to write into the memory.
6058 /// \param Size Number of bytes to write.
6059 /// \param Align Alignment of the destination in bytes.
6060 /// \param isVol True if destination is volatile.
6061 /// \param DstPtrInfo IR information on the memory pointer.
6062 /// \returns New head in the control flow, if lowering was successful, empty
6063 /// SDValue otherwise.
6065 /// The function tries to replace 'llvm.memset' intrinsic with several store
6066 /// operations and value calculation code. This is usually profitable for small
6068 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6069 SDValue Chain, SDValue Dst, SDValue Src,
6070 uint64_t Size, unsigned Align, bool isVol,
6071 MachinePointerInfo DstPtrInfo) {
6072 // Turn a memset of undef to nop.
6073 // FIXME: We need to honor volatile even is Src is undef.
6077 // Expand memset to a series of load/store ops if the size operand
6078 // falls below a certain threshold.
6079 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6080 std::vector<EVT> MemOps;
6081 bool DstAlignCanChange = false;
6082 MachineFunction &MF = DAG.getMachineFunction();
6083 MachineFrameInfo &MFI = MF.getFrameInfo();
6084 bool OptSize = shouldLowerMemFuncForSize(MF);
6085 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6086 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6087 DstAlignCanChange = true;
6089 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6090 if (!TLI.findOptimalMemOpLowering(
6091 MemOps, TLI.getMaxStoresPerMemset(OptSize), Size,
6092 (DstAlignCanChange ? 0 : Align), 0, /*IsMemset=*/true,
6093 /*ZeroMemset=*/IsZeroVal, /*MemcpyStrSrc=*/false,
6094 /*AllowOverlap=*/!isVol, DstPtrInfo.getAddrSpace(), ~0u,
6095 MF.getFunction().getAttributes()))
6098 if (DstAlignCanChange) {
6099 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6100 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
6101 if (NewAlign > Align) {
6102 // Give the stack frame object a larger alignment if needed.
6103 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
6104 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6109 SmallVector<SDValue, 8> OutChains;
6110 uint64_t DstOff = 0;
6111 unsigned NumMemOps = MemOps.size();
6113 // Find the largest store and generate the bit pattern for it.
6114 EVT LargestVT = MemOps[0];
6115 for (unsigned i = 1; i < NumMemOps; i++)
6116 if (MemOps[i].bitsGT(LargestVT))
6117 LargestVT = MemOps[i];
6118 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6120 for (unsigned i = 0; i < NumMemOps; i++) {
6122 unsigned VTSize = VT.getSizeInBits() / 8;
6123 if (VTSize > Size) {
6124 // Issuing an unaligned load / store pair that overlaps with the previous
6125 // pair. Adjust the offset accordingly.
6126 assert(i == NumMemOps-1 && i != 0);
6127 DstOff -= VTSize - Size;
6130 // If this store is smaller than the largest store see whether we can get
6131 // the smaller value for free with a truncate.
6132 SDValue Value = MemSetValue;
6133 if (VT.bitsLT(LargestVT)) {
6134 if (!LargestVT.isVector() && !VT.isVector() &&
6135 TLI.isTruncateFree(LargestVT, VT))
6136 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6138 Value = getMemsetValue(Src, VT, DAG, dl);
6140 assert(Value.getValueType() == VT && "Value with wrong type.");
6141 SDValue Store = DAG.getStore(
6142 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6143 DstPtrInfo.getWithOffset(DstOff), Align,
6144 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6145 OutChains.push_back(Store);
6146 DstOff += VT.getSizeInBits() / 8;
6150 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6153 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6155 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6156 // pointer operands can be losslessly bitcasted to pointers of address space 0
6157 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
6158 report_fatal_error("cannot lower memory intrinsic in address space " +
6163 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6164 SDValue Src, SDValue Size, unsigned Align,
6165 bool isVol, bool AlwaysInline, bool isTailCall,
6166 MachinePointerInfo DstPtrInfo,
6167 MachinePointerInfo SrcPtrInfo) {
6168 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6170 // Check to see if we should lower the memcpy to loads and stores first.
6171 // For cases within the target-specified limits, this is the best choice.
6172 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6174 // Memcpy with size zero? Just return the original chain.
6175 if (ConstantSize->isNullValue())
6178 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6179 ConstantSize->getZExtValue(),Align,
6180 isVol, false, DstPtrInfo, SrcPtrInfo);
6181 if (Result.getNode())
6185 // Then check to see if we should lower the memcpy with target-specific
6186 // code. If the target chooses to do this, this is the next best.
6188 SDValue Result = TSI->EmitTargetCodeForMemcpy(
6189 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
6190 DstPtrInfo, SrcPtrInfo);
6191 if (Result.getNode())
6195 // If we really need inline code and the target declined to provide it,
6196 // use a (potentially long) sequence of loads and stores.
6198 assert(ConstantSize && "AlwaysInline requires a constant size!");
6199 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6200 ConstantSize->getZExtValue(), Align, isVol,
6201 true, DstPtrInfo, SrcPtrInfo);
6204 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6205 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6207 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6208 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6209 // respect volatile, so they may do things like read or write memory
6210 // beyond the given memory regions. But fixing this isn't easy, and most
6211 // people don't care.
6213 // Emit a library call.
6214 TargetLowering::ArgListTy Args;
6215 TargetLowering::ArgListEntry Entry;
6216 Entry.Ty = Type::getInt8PtrTy(*getContext());
6217 Entry.Node = Dst; Args.push_back(Entry);
6218 Entry.Node = Src; Args.push_back(Entry);
6220 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6221 Entry.Node = Size; Args.push_back(Entry);
6222 // FIXME: pass in SDLoc
6223 TargetLowering::CallLoweringInfo CLI(*this);
6226 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6227 Dst.getValueType().getTypeForEVT(*getContext()),
6228 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6229 TLI->getPointerTy(getDataLayout())),
6232 .setTailCall(isTailCall);
6234 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6235 return CallResult.second;
6238 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6239 SDValue Dst, unsigned DstAlign,
6240 SDValue Src, unsigned SrcAlign,
6241 SDValue Size, Type *SizeTy,
6242 unsigned ElemSz, bool isTailCall,
6243 MachinePointerInfo DstPtrInfo,
6244 MachinePointerInfo SrcPtrInfo) {
6245 // Emit a library call.
6246 TargetLowering::ArgListTy Args;
6247 TargetLowering::ArgListEntry Entry;
6248 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6250 Args.push_back(Entry);
6253 Args.push_back(Entry);
6257 Args.push_back(Entry);
6259 RTLIB::Libcall LibraryCall =
6260 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6261 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6262 report_fatal_error("Unsupported element size");
6264 TargetLowering::CallLoweringInfo CLI(*this);
6267 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6268 Type::getVoidTy(*getContext()),
6269 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6270 TLI->getPointerTy(getDataLayout())),
6273 .setTailCall(isTailCall);
6275 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6276 return CallResult.second;
6279 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6280 SDValue Src, SDValue Size, unsigned Align,
6281 bool isVol, bool isTailCall,
6282 MachinePointerInfo DstPtrInfo,
6283 MachinePointerInfo SrcPtrInfo) {
6284 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6286 // Check to see if we should lower the memmove to loads and stores first.
6287 // For cases within the target-specified limits, this is the best choice.
6288 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6290 // Memmove with size zero? Just return the original chain.
6291 if (ConstantSize->isNullValue())
6295 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
6296 ConstantSize->getZExtValue(), Align, isVol,
6297 false, DstPtrInfo, SrcPtrInfo);
6298 if (Result.getNode())
6302 // Then check to see if we should lower the memmove with target-specific
6303 // code. If the target chooses to do this, this is the next best.
6305 SDValue Result = TSI->EmitTargetCodeForMemmove(
6306 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
6307 if (Result.getNode())
6311 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6312 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6314 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6315 // not be safe. See memcpy above for more details.
6317 // Emit a library call.
6318 TargetLowering::ArgListTy Args;
6319 TargetLowering::ArgListEntry Entry;
6320 Entry.Ty = Type::getInt8PtrTy(*getContext());
6321 Entry.Node = Dst; Args.push_back(Entry);
6322 Entry.Node = Src; Args.push_back(Entry);
6324 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6325 Entry.Node = Size; Args.push_back(Entry);
6326 // FIXME: pass in SDLoc
6327 TargetLowering::CallLoweringInfo CLI(*this);
6330 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6331 Dst.getValueType().getTypeForEVT(*getContext()),
6332 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6333 TLI->getPointerTy(getDataLayout())),
6336 .setTailCall(isTailCall);
6338 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6339 return CallResult.second;
6342 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6343 SDValue Dst, unsigned DstAlign,
6344 SDValue Src, unsigned SrcAlign,
6345 SDValue Size, Type *SizeTy,
6346 unsigned ElemSz, bool isTailCall,
6347 MachinePointerInfo DstPtrInfo,
6348 MachinePointerInfo SrcPtrInfo) {
6349 // Emit a library call.
6350 TargetLowering::ArgListTy Args;
6351 TargetLowering::ArgListEntry Entry;
6352 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6354 Args.push_back(Entry);
6357 Args.push_back(Entry);
6361 Args.push_back(Entry);
6363 RTLIB::Libcall LibraryCall =
6364 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6365 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6366 report_fatal_error("Unsupported element size");
6368 TargetLowering::CallLoweringInfo CLI(*this);
6371 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6372 Type::getVoidTy(*getContext()),
6373 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6374 TLI->getPointerTy(getDataLayout())),
6377 .setTailCall(isTailCall);
6379 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6380 return CallResult.second;
6383 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6384 SDValue Src, SDValue Size, unsigned Align,
6385 bool isVol, bool isTailCall,
6386 MachinePointerInfo DstPtrInfo) {
6387 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6389 // Check to see if we should lower the memset to stores first.
6390 // For cases within the target-specified limits, this is the best choice.
6391 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6393 // Memset with size zero? Just return the original chain.
6394 if (ConstantSize->isNullValue())
6398 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
6399 Align, isVol, DstPtrInfo);
6401 if (Result.getNode())
6405 // Then check to see if we should lower the memset with target-specific
6406 // code. If the target chooses to do this, this is the next best.
6408 SDValue Result = TSI->EmitTargetCodeForMemset(
6409 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
6410 if (Result.getNode())
6414 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6416 // Emit a library call.
6417 TargetLowering::ArgListTy Args;
6418 TargetLowering::ArgListEntry Entry;
6419 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6420 Args.push_back(Entry);
6422 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6423 Args.push_back(Entry);
6425 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6426 Args.push_back(Entry);
6428 // FIXME: pass in SDLoc
6429 TargetLowering::CallLoweringInfo CLI(*this);
6432 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6433 Dst.getValueType().getTypeForEVT(*getContext()),
6434 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6435 TLI->getPointerTy(getDataLayout())),
6438 .setTailCall(isTailCall);
6440 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6441 return CallResult.second;
6444 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6445 SDValue Dst, unsigned DstAlign,
6446 SDValue Value, SDValue Size, Type *SizeTy,
6447 unsigned ElemSz, bool isTailCall,
6448 MachinePointerInfo DstPtrInfo) {
6449 // Emit a library call.
6450 TargetLowering::ArgListTy Args;
6451 TargetLowering::ArgListEntry Entry;
6452 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6454 Args.push_back(Entry);
6456 Entry.Ty = Type::getInt8Ty(*getContext());
6458 Args.push_back(Entry);
6462 Args.push_back(Entry);
6464 RTLIB::Libcall LibraryCall =
6465 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6466 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6467 report_fatal_error("Unsupported element size");
6469 TargetLowering::CallLoweringInfo CLI(*this);
6472 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6473 Type::getVoidTy(*getContext()),
6474 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6475 TLI->getPointerTy(getDataLayout())),
6478 .setTailCall(isTailCall);
6480 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6481 return CallResult.second;
6484 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6485 SDVTList VTList, ArrayRef<SDValue> Ops,
6486 MachineMemOperand *MMO) {
6487 FoldingSetNodeID ID;
6488 ID.AddInteger(MemVT.getRawBits());
6489 AddNodeIDNode(ID, Opcode, VTList, Ops);
6490 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6492 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6493 cast<AtomicSDNode>(E)->refineAlignment(MMO);
6494 return SDValue(E, 0);
6497 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6498 VTList, MemVT, MMO);
6499 createOperands(N, Ops);
6501 CSEMap.InsertNode(N, IP);
6503 return SDValue(N, 0);
6506 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6507 EVT MemVT, SDVTList VTs, SDValue Chain,
6508 SDValue Ptr, SDValue Cmp, SDValue Swp,
6509 MachineMemOperand *MMO) {
6510 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6511 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6512 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6514 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6515 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6518 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6519 SDValue Chain, SDValue Ptr, SDValue Val,
6520 MachineMemOperand *MMO) {
6521 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6522 Opcode == ISD::ATOMIC_LOAD_SUB ||
6523 Opcode == ISD::ATOMIC_LOAD_AND ||
6524 Opcode == ISD::ATOMIC_LOAD_CLR ||
6525 Opcode == ISD::ATOMIC_LOAD_OR ||
6526 Opcode == ISD::ATOMIC_LOAD_XOR ||
6527 Opcode == ISD::ATOMIC_LOAD_NAND ||
6528 Opcode == ISD::ATOMIC_LOAD_MIN ||
6529 Opcode == ISD::ATOMIC_LOAD_MAX ||
6530 Opcode == ISD::ATOMIC_LOAD_UMIN ||
6531 Opcode == ISD::ATOMIC_LOAD_UMAX ||
6532 Opcode == ISD::ATOMIC_LOAD_FADD ||
6533 Opcode == ISD::ATOMIC_LOAD_FSUB ||
6534 Opcode == ISD::ATOMIC_SWAP ||
6535 Opcode == ISD::ATOMIC_STORE) &&
6536 "Invalid Atomic Op");
6538 EVT VT = Val.getValueType();
6540 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6541 getVTList(VT, MVT::Other);
6542 SDValue Ops[] = {Chain, Ptr, Val};
6543 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6546 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6547 EVT VT, SDValue Chain, SDValue Ptr,
6548 MachineMemOperand *MMO) {
6549 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6551 SDVTList VTs = getVTList(VT, MVT::Other);
6552 SDValue Ops[] = {Chain, Ptr};
6553 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6556 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6557 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6558 if (Ops.size() == 1)
6561 SmallVector<EVT, 4> VTs;
6562 VTs.reserve(Ops.size());
6563 for (unsigned i = 0; i < Ops.size(); ++i)
6564 VTs.push_back(Ops[i].getValueType());
6565 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6568 SDValue SelectionDAG::getMemIntrinsicNode(
6569 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6570 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align,
6571 MachineMemOperand::Flags Flags, unsigned Size, const AAMDNodes &AAInfo) {
6572 if (Align == 0) // Ensure that codegen never sees alignment 0
6573 Align = getEVTAlignment(MemVT);
6576 Size = MemVT.getStoreSize();
6578 MachineFunction &MF = getMachineFunction();
6579 MachineMemOperand *MMO =
6580 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align, AAInfo);
6582 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6585 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6587 ArrayRef<SDValue> Ops, EVT MemVT,
6588 MachineMemOperand *MMO) {
6589 assert((Opcode == ISD::INTRINSIC_VOID ||
6590 Opcode == ISD::INTRINSIC_W_CHAIN ||
6591 Opcode == ISD::PREFETCH ||
6592 Opcode == ISD::LIFETIME_START ||
6593 Opcode == ISD::LIFETIME_END ||
6594 ((int)Opcode <= std::numeric_limits<int>::max() &&
6595 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6596 "Opcode is not a memory-accessing opcode!");
6598 // Memoize the node unless it returns a flag.
6599 MemIntrinsicSDNode *N;
6600 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6601 FoldingSetNodeID ID;
6602 AddNodeIDNode(ID, Opcode, VTList, Ops);
6603 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6604 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6605 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6607 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6608 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6609 return SDValue(E, 0);
6612 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6613 VTList, MemVT, MMO);
6614 createOperands(N, Ops);
6616 CSEMap.InsertNode(N, IP);
6618 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6619 VTList, MemVT, MMO);
6620 createOperands(N, Ops);
6623 return SDValue(N, 0);
6626 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
6627 SDValue Chain, int FrameIndex,
6628 int64_t Size, int64_t Offset) {
6629 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
6630 const auto VTs = getVTList(MVT::Other);
6633 getFrameIndex(FrameIndex,
6634 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
6637 FoldingSetNodeID ID;
6638 AddNodeIDNode(ID, Opcode, VTs, Ops);
6639 ID.AddInteger(FrameIndex);
6640 ID.AddInteger(Size);
6641 ID.AddInteger(Offset);
6643 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6644 return SDValue(E, 0);
6646 LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
6647 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
6648 createOperands(N, Ops);
6649 CSEMap.InsertNode(N, IP);
6652 NewSDValueDbgMsg(V, "Creating new node: ", this);
6656 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6657 /// MachinePointerInfo record from it. This is particularly useful because the
6658 /// code generator has many cases where it doesn't bother passing in a
6659 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6660 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6661 SelectionDAG &DAG, SDValue Ptr,
6662 int64_t Offset = 0) {
6663 // If this is FI+Offset, we can model it.
6664 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
6665 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
6666 FI->getIndex(), Offset);
6668 // If this is (FI+Offset1)+Offset2, we can model it.
6669 if (Ptr.getOpcode() != ISD::ADD ||
6670 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
6671 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
6674 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6675 return MachinePointerInfo::getFixedStack(
6676 DAG.getMachineFunction(), FI,
6677 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
6680 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6681 /// MachinePointerInfo record from it. This is particularly useful because the
6682 /// code generator has many cases where it doesn't bother passing in a
6683 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6684 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6685 SelectionDAG &DAG, SDValue Ptr,
6687 // If the 'Offset' value isn't a constant, we can't handle this.
6688 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
6689 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
6690 if (OffsetOp.isUndef())
6691 return InferPointerInfo(Info, DAG, Ptr);
6695 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6696 EVT VT, const SDLoc &dl, SDValue Chain,
6697 SDValue Ptr, SDValue Offset,
6698 MachinePointerInfo PtrInfo, EVT MemVT,
6700 MachineMemOperand::Flags MMOFlags,
6701 const AAMDNodes &AAInfo, const MDNode *Ranges) {
6702 assert(Chain.getValueType() == MVT::Other &&
6703 "Invalid chain type");
6704 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6705 Alignment = getEVTAlignment(MemVT);
6707 MMOFlags |= MachineMemOperand::MOLoad;
6708 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
6709 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
6711 if (PtrInfo.V.isNull())
6712 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
6714 MachineFunction &MF = getMachineFunction();
6715 MachineMemOperand *MMO = MF.getMachineMemOperand(
6716 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
6717 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
6720 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6721 EVT VT, const SDLoc &dl, SDValue Chain,
6722 SDValue Ptr, SDValue Offset, EVT MemVT,
6723 MachineMemOperand *MMO) {
6725 ExtType = ISD::NON_EXTLOAD;
6726 } else if (ExtType == ISD::NON_EXTLOAD) {
6727 assert(VT == MemVT && "Non-extending load from different memory type!");
6730 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
6731 "Should only be an extending load, not truncating!");
6732 assert(VT.isInteger() == MemVT.isInteger() &&
6733 "Cannot convert from FP to Int or Int -> FP!");
6734 assert(VT.isVector() == MemVT.isVector() &&
6735 "Cannot use an ext load to convert to or from a vector!");
6736 assert((!VT.isVector() ||
6737 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
6738 "Cannot use an ext load to change the number of vector elements!");
6741 bool Indexed = AM != ISD::UNINDEXED;
6742 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
6744 SDVTList VTs = Indexed ?
6745 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
6746 SDValue Ops[] = { Chain, Ptr, Offset };
6747 FoldingSetNodeID ID;
6748 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
6749 ID.AddInteger(MemVT.getRawBits());
6750 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
6751 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
6752 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6754 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6755 cast<LoadSDNode>(E)->refineAlignment(MMO);
6756 return SDValue(E, 0);
6758 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6759 ExtType, MemVT, MMO);
6760 createOperands(N, Ops);
6762 CSEMap.InsertNode(N, IP);
6765 NewSDValueDbgMsg(V, "Creating new node: ", this);
6769 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6770 SDValue Ptr, MachinePointerInfo PtrInfo,
6772 MachineMemOperand::Flags MMOFlags,
6773 const AAMDNodes &AAInfo, const MDNode *Ranges) {
6774 SDValue Undef = getUNDEF(Ptr.getValueType());
6775 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6776 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
6779 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6780 SDValue Ptr, MachineMemOperand *MMO) {
6781 SDValue Undef = getUNDEF(Ptr.getValueType());
6782 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6786 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6787 EVT VT, SDValue Chain, SDValue Ptr,
6788 MachinePointerInfo PtrInfo, EVT MemVT,
6790 MachineMemOperand::Flags MMOFlags,
6791 const AAMDNodes &AAInfo) {
6792 SDValue Undef = getUNDEF(Ptr.getValueType());
6793 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
6794 MemVT, Alignment, MMOFlags, AAInfo);
6797 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6798 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
6799 MachineMemOperand *MMO) {
6800 SDValue Undef = getUNDEF(Ptr.getValueType());
6801 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
6805 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
6806 SDValue Base, SDValue Offset,
6807 ISD::MemIndexedMode AM) {
6808 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
6809 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
6810 // Don't propagate the invariant or dereferenceable flags.
6812 LD->getMemOperand()->getFlags() &
6813 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6814 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
6815 LD->getChain(), Base, Offset, LD->getPointerInfo(),
6816 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
6820 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6821 SDValue Ptr, MachinePointerInfo PtrInfo,
6823 MachineMemOperand::Flags MMOFlags,
6824 const AAMDNodes &AAInfo) {
6825 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
6826 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6827 Alignment = getEVTAlignment(Val.getValueType());
6829 MMOFlags |= MachineMemOperand::MOStore;
6830 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6832 if (PtrInfo.V.isNull())
6833 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6835 MachineFunction &MF = getMachineFunction();
6836 MachineMemOperand *MMO = MF.getMachineMemOperand(
6837 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
6838 return getStore(Chain, dl, Val, Ptr, MMO);
6841 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6842 SDValue Ptr, MachineMemOperand *MMO) {
6843 assert(Chain.getValueType() == MVT::Other &&
6844 "Invalid chain type");
6845 EVT VT = Val.getValueType();
6846 SDVTList VTs = getVTList(MVT::Other);
6847 SDValue Undef = getUNDEF(Ptr.getValueType());
6848 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6849 FoldingSetNodeID ID;
6850 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6851 ID.AddInteger(VT.getRawBits());
6852 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6853 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
6854 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6856 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6857 cast<StoreSDNode>(E)->refineAlignment(MMO);
6858 return SDValue(E, 0);
6860 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6861 ISD::UNINDEXED, false, VT, MMO);
6862 createOperands(N, Ops);
6864 CSEMap.InsertNode(N, IP);
6867 NewSDValueDbgMsg(V, "Creating new node: ", this);
6871 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6872 SDValue Ptr, MachinePointerInfo PtrInfo,
6873 EVT SVT, unsigned Alignment,
6874 MachineMemOperand::Flags MMOFlags,
6875 const AAMDNodes &AAInfo) {
6876 assert(Chain.getValueType() == MVT::Other &&
6877 "Invalid chain type");
6878 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6879 Alignment = getEVTAlignment(SVT);
6881 MMOFlags |= MachineMemOperand::MOStore;
6882 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6884 if (PtrInfo.V.isNull())
6885 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6887 MachineFunction &MF = getMachineFunction();
6888 MachineMemOperand *MMO = MF.getMachineMemOperand(
6889 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
6890 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
6893 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6894 SDValue Ptr, EVT SVT,
6895 MachineMemOperand *MMO) {
6896 EVT VT = Val.getValueType();
6898 assert(Chain.getValueType() == MVT::Other &&
6899 "Invalid chain type");
6901 return getStore(Chain, dl, Val, Ptr, MMO);
6903 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
6904 "Should only be a truncating store, not extending!");
6905 assert(VT.isInteger() == SVT.isInteger() &&
6906 "Can't do FP-INT conversion!");
6907 assert(VT.isVector() == SVT.isVector() &&
6908 "Cannot use trunc store to convert to or from a vector!");
6909 assert((!VT.isVector() ||
6910 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
6911 "Cannot use trunc store to change the number of vector elements!");
6913 SDVTList VTs = getVTList(MVT::Other);
6914 SDValue Undef = getUNDEF(Ptr.getValueType());
6915 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6916 FoldingSetNodeID ID;
6917 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6918 ID.AddInteger(SVT.getRawBits());
6919 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6920 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
6921 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6923 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6924 cast<StoreSDNode>(E)->refineAlignment(MMO);
6925 return SDValue(E, 0);
6927 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6928 ISD::UNINDEXED, true, SVT, MMO);
6929 createOperands(N, Ops);
6931 CSEMap.InsertNode(N, IP);
6934 NewSDValueDbgMsg(V, "Creating new node: ", this);
6938 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
6939 SDValue Base, SDValue Offset,
6940 ISD::MemIndexedMode AM) {
6941 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
6942 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
6943 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
6944 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
6945 FoldingSetNodeID ID;
6946 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6947 ID.AddInteger(ST->getMemoryVT().getRawBits());
6948 ID.AddInteger(ST->getRawSubclassData());
6949 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
6951 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6952 return SDValue(E, 0);
6954 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6955 ST->isTruncatingStore(), ST->getMemoryVT(),
6956 ST->getMemOperand());
6957 createOperands(N, Ops);
6959 CSEMap.InsertNode(N, IP);
6962 NewSDValueDbgMsg(V, "Creating new node: ", this);
6966 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6967 SDValue Ptr, SDValue Mask, SDValue PassThru,
6968 EVT MemVT, MachineMemOperand *MMO,
6969 ISD::LoadExtType ExtTy, bool isExpanding) {
6970 SDVTList VTs = getVTList(VT, MVT::Other);
6971 SDValue Ops[] = { Chain, Ptr, Mask, PassThru };
6972 FoldingSetNodeID ID;
6973 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
6974 ID.AddInteger(MemVT.getRawBits());
6975 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
6976 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
6977 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6979 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6980 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
6981 return SDValue(E, 0);
6983 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6984 ExtTy, isExpanding, MemVT, MMO);
6985 createOperands(N, Ops);
6987 CSEMap.InsertNode(N, IP);
6990 NewSDValueDbgMsg(V, "Creating new node: ", this);
6994 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
6995 SDValue Val, SDValue Ptr, SDValue Mask,
6996 EVT MemVT, MachineMemOperand *MMO,
6997 bool IsTruncating, bool IsCompressing) {
6998 assert(Chain.getValueType() == MVT::Other &&
6999 "Invalid chain type");
7000 SDVTList VTs = getVTList(MVT::Other);
7001 SDValue Ops[] = { Chain, Val, Ptr, Mask };
7002 FoldingSetNodeID ID;
7003 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7004 ID.AddInteger(MemVT.getRawBits());
7005 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7006 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
7007 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7009 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7010 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7011 return SDValue(E, 0);
7013 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7014 IsTruncating, IsCompressing, MemVT, MMO);
7015 createOperands(N, Ops);
7017 CSEMap.InsertNode(N, IP);
7020 NewSDValueDbgMsg(V, "Creating new node: ", this);
7024 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7025 ArrayRef<SDValue> Ops,
7026 MachineMemOperand *MMO) {
7027 assert(Ops.size() == 6 && "Incompatible number of operands");
7029 FoldingSetNodeID ID;
7030 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7031 ID.AddInteger(VT.getRawBits());
7032 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7033 dl.getIROrder(), VTs, VT, MMO));
7034 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7036 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7037 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7038 return SDValue(E, 0);
7041 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7043 createOperands(N, Ops);
7045 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7046 "Incompatible type of the PassThru value in MaskedGatherSDNode");
7047 assert(N->getMask().getValueType().getVectorNumElements() ==
7048 N->getValueType(0).getVectorNumElements() &&
7049 "Vector width mismatch between mask and data");
7050 assert(N->getIndex().getValueType().getVectorNumElements() >=
7051 N->getValueType(0).getVectorNumElements() &&
7052 "Vector width mismatch between index and data");
7053 assert(isa<ConstantSDNode>(N->getScale()) &&
7054 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7055 "Scale should be a constant power of 2");
7057 CSEMap.InsertNode(N, IP);
7060 NewSDValueDbgMsg(V, "Creating new node: ", this);
7064 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7065 ArrayRef<SDValue> Ops,
7066 MachineMemOperand *MMO) {
7067 assert(Ops.size() == 6 && "Incompatible number of operands");
7069 FoldingSetNodeID ID;
7070 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7071 ID.AddInteger(VT.getRawBits());
7072 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7073 dl.getIROrder(), VTs, VT, MMO));
7074 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7076 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7077 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7078 return SDValue(E, 0);
7080 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7082 createOperands(N, Ops);
7084 assert(N->getMask().getValueType().getVectorNumElements() ==
7085 N->getValue().getValueType().getVectorNumElements() &&
7086 "Vector width mismatch between mask and data");
7087 assert(N->getIndex().getValueType().getVectorNumElements() >=
7088 N->getValue().getValueType().getVectorNumElements() &&
7089 "Vector width mismatch between index and data");
7090 assert(isa<ConstantSDNode>(N->getScale()) &&
7091 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7092 "Scale should be a constant power of 2");
7094 CSEMap.InsertNode(N, IP);
7097 NewSDValueDbgMsg(V, "Creating new node: ", this);
7101 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7102 // select undef, T, F --> T (if T is a constant), otherwise F
7103 // select, ?, undef, F --> F
7104 // select, ?, T, undef --> T
7106 return isConstantValueOfAnyType(T) ? T : F;
7112 // select true, T, F --> T
7113 // select false, T, F --> F
7114 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7115 return CondC->isNullValue() ? F : T;
7117 // TODO: This should simplify VSELECT with constant condition using something
7118 // like this (but check boolean contents to be complete?):
7119 // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7121 // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7124 // select ?, T, T --> T
7131 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7132 // shift undef, Y --> 0 (can always assume that the undef value is 0)
7134 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7135 // shift X, undef --> undef (because it may shift by the bitwidth)
7137 return getUNDEF(X.getValueType());
7141 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7144 // shift X, C >= bitwidth(X) --> undef
7145 // All vector elements must be too big (or undef) to avoid partial undefs.
7146 auto isShiftTooBig = [X](ConstantSDNode *Val) {
7147 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7149 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7150 return getUNDEF(X.getValueType());
7155 // TODO: Use fast-math-flags to enable more simplifications.
7156 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y) {
7157 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7162 if (Opcode == ISD::FADD)
7163 if (YC->getValueAPF().isNegZero())
7167 if (Opcode == ISD::FSUB)
7168 if (YC->getValueAPF().isPosZero())
7173 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7174 if (YC->getValueAPF().isExactlyValue(1.0))
7180 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7181 SDValue Ptr, SDValue SV, unsigned Align) {
7182 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7183 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7186 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7187 ArrayRef<SDUse> Ops) {
7188 switch (Ops.size()) {
7189 case 0: return getNode(Opcode, DL, VT);
7190 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7191 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7192 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7196 // Copy from an SDUse array into an SDValue array for use with
7197 // the regular getNode logic.
7198 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7199 return getNode(Opcode, DL, VT, NewOps);
7202 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7203 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7204 unsigned NumOps = Ops.size();
7206 case 0: return getNode(Opcode, DL, VT);
7207 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7208 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7209 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7215 case ISD::BUILD_VECTOR:
7216 // Attempt to simplify BUILD_VECTOR.
7217 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7220 case ISD::CONCAT_VECTORS:
7221 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7224 case ISD::SELECT_CC:
7225 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7226 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7227 "LHS and RHS of condition must have same type!");
7228 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7229 "True and False arms of SelectCC must have same type!");
7230 assert(Ops[2].getValueType() == VT &&
7231 "select_cc node must be of same type as true and false value!");
7234 assert(NumOps == 5 && "BR_CC takes 5 operands!");
7235 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7236 "LHS/RHS of comparison should match types!");
7242 SDVTList VTs = getVTList(VT);
7244 if (VT != MVT::Glue) {
7245 FoldingSetNodeID ID;
7246 AddNodeIDNode(ID, Opcode, VTs, Ops);
7249 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7250 return SDValue(E, 0);
7252 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7253 createOperands(N, Ops);
7255 CSEMap.InsertNode(N, IP);
7257 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7258 createOperands(N, Ops);
7263 NewSDValueDbgMsg(V, "Creating new node: ", this);
7267 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7268 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7269 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7272 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7273 ArrayRef<SDValue> Ops) {
7274 if (VTList.NumVTs == 1)
7275 return getNode(Opcode, DL, VTList.VTs[0], Ops);
7279 // FIXME: figure out how to safely handle things like
7280 // int foo(int x) { return 1 << (x & 255); }
7281 // int bar() { return foo(256); }
7282 case ISD::SRA_PARTS:
7283 case ISD::SRL_PARTS:
7284 case ISD::SHL_PARTS:
7285 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7286 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7287 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7288 else if (N3.getOpcode() == ISD::AND)
7289 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7290 // If the and is only masking out bits that cannot effect the shift,
7291 // eliminate the and.
7292 unsigned NumBits = VT.getScalarSizeInBits()*2;
7293 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7294 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7300 // Memoize the node unless it returns a flag.
7302 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7303 FoldingSetNodeID ID;
7304 AddNodeIDNode(ID, Opcode, VTList, Ops);
7306 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7307 return SDValue(E, 0);
7309 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7310 createOperands(N, Ops);
7311 CSEMap.InsertNode(N, IP);
7313 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7314 createOperands(N, Ops);
7318 NewSDValueDbgMsg(V, "Creating new node: ", this);
7322 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7324 return getNode(Opcode, DL, VTList, None);
7327 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7329 SDValue Ops[] = { N1 };
7330 return getNode(Opcode, DL, VTList, Ops);
7333 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7334 SDValue N1, SDValue N2) {
7335 SDValue Ops[] = { N1, N2 };
7336 return getNode(Opcode, DL, VTList, Ops);
7339 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7340 SDValue N1, SDValue N2, SDValue N3) {
7341 SDValue Ops[] = { N1, N2, N3 };
7342 return getNode(Opcode, DL, VTList, Ops);
7345 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7346 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7347 SDValue Ops[] = { N1, N2, N3, N4 };
7348 return getNode(Opcode, DL, VTList, Ops);
7351 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7352 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7354 SDValue Ops[] = { N1, N2, N3, N4, N5 };
7355 return getNode(Opcode, DL, VTList, Ops);
7358 SDVTList SelectionDAG::getVTList(EVT VT) {
7359 return makeVTList(SDNode::getValueTypeList(VT), 1);
7362 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7363 FoldingSetNodeID ID;
7365 ID.AddInteger(VT1.getRawBits());
7366 ID.AddInteger(VT2.getRawBits());
7369 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7371 EVT *Array = Allocator.Allocate<EVT>(2);
7374 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7375 VTListMap.InsertNode(Result, IP);
7377 return Result->getSDVTList();
7380 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7381 FoldingSetNodeID ID;
7383 ID.AddInteger(VT1.getRawBits());
7384 ID.AddInteger(VT2.getRawBits());
7385 ID.AddInteger(VT3.getRawBits());
7388 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7390 EVT *Array = Allocator.Allocate<EVT>(3);
7394 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7395 VTListMap.InsertNode(Result, IP);
7397 return Result->getSDVTList();
7400 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7401 FoldingSetNodeID ID;
7403 ID.AddInteger(VT1.getRawBits());
7404 ID.AddInteger(VT2.getRawBits());
7405 ID.AddInteger(VT3.getRawBits());
7406 ID.AddInteger(VT4.getRawBits());
7409 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7411 EVT *Array = Allocator.Allocate<EVT>(4);
7416 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7417 VTListMap.InsertNode(Result, IP);
7419 return Result->getSDVTList();
7422 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7423 unsigned NumVTs = VTs.size();
7424 FoldingSetNodeID ID;
7425 ID.AddInteger(NumVTs);
7426 for (unsigned index = 0; index < NumVTs; index++) {
7427 ID.AddInteger(VTs[index].getRawBits());
7431 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7433 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7434 llvm::copy(VTs, Array);
7435 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7436 VTListMap.InsertNode(Result, IP);
7438 return Result->getSDVTList();
7442 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7443 /// specified operands. If the resultant node already exists in the DAG,
7444 /// this does not modify the specified node, instead it returns the node that
7445 /// already exists. If the resultant node does not exist in the DAG, the
7446 /// input node is returned. As a degenerate case, if you specify the same
7447 /// input operands as the node already has, the input node is returned.
7448 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7449 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7451 // Check to see if there is no change.
7452 if (Op == N->getOperand(0)) return N;
7454 // See if the modified node already exists.
7455 void *InsertPos = nullptr;
7456 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7459 // Nope it doesn't. Remove the node from its current place in the maps.
7461 if (!RemoveNodeFromCSEMaps(N))
7462 InsertPos = nullptr;
7464 // Now we update the operands.
7465 N->OperandList[0].set(Op);
7467 updateDivergence(N);
7468 // If this gets put into a CSE map, add it.
7469 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7473 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7474 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7476 // Check to see if there is no change.
7477 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
7478 return N; // No operands changed, just return the input node.
7480 // See if the modified node already exists.
7481 void *InsertPos = nullptr;
7482 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
7485 // Nope it doesn't. Remove the node from its current place in the maps.
7487 if (!RemoveNodeFromCSEMaps(N))
7488 InsertPos = nullptr;
7490 // Now we update the operands.
7491 if (N->OperandList[0] != Op1)
7492 N->OperandList[0].set(Op1);
7493 if (N->OperandList[1] != Op2)
7494 N->OperandList[1].set(Op2);
7496 updateDivergence(N);
7497 // If this gets put into a CSE map, add it.
7498 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7502 SDNode *SelectionDAG::
7503 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
7504 SDValue Ops[] = { Op1, Op2, Op3 };
7505 return UpdateNodeOperands(N, Ops);
7508 SDNode *SelectionDAG::
7509 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7510 SDValue Op3, SDValue Op4) {
7511 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
7512 return UpdateNodeOperands(N, Ops);
7515 SDNode *SelectionDAG::
7516 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7517 SDValue Op3, SDValue Op4, SDValue Op5) {
7518 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
7519 return UpdateNodeOperands(N, Ops);
7522 SDNode *SelectionDAG::
7523 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
7524 unsigned NumOps = Ops.size();
7525 assert(N->getNumOperands() == NumOps &&
7526 "Update with wrong number of operands");
7528 // If no operands changed just return the input node.
7529 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
7532 // See if the modified node already exists.
7533 void *InsertPos = nullptr;
7534 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
7537 // Nope it doesn't. Remove the node from its current place in the maps.
7539 if (!RemoveNodeFromCSEMaps(N))
7540 InsertPos = nullptr;
7542 // Now we update the operands.
7543 for (unsigned i = 0; i != NumOps; ++i)
7544 if (N->OperandList[i] != Ops[i])
7545 N->OperandList[i].set(Ops[i]);
7547 updateDivergence(N);
7548 // If this gets put into a CSE map, add it.
7549 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7553 /// DropOperands - Release the operands and set this node to have
7555 void SDNode::DropOperands() {
7556 // Unlike the code in MorphNodeTo that does this, we don't need to
7557 // watch for dead nodes here.
7558 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
7564 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
7565 ArrayRef<MachineMemOperand *> NewMemRefs) {
7566 if (NewMemRefs.empty()) {
7571 // Check if we can avoid allocating by storing a single reference directly.
7572 if (NewMemRefs.size() == 1) {
7573 N->MemRefs = NewMemRefs[0];
7578 MachineMemOperand **MemRefsBuffer =
7579 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
7580 llvm::copy(NewMemRefs, MemRefsBuffer);
7581 N->MemRefs = MemRefsBuffer;
7582 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
7585 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
7588 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7590 SDVTList VTs = getVTList(VT);
7591 return SelectNodeTo(N, MachineOpc, VTs, None);
7594 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7595 EVT VT, SDValue Op1) {
7596 SDVTList VTs = getVTList(VT);
7597 SDValue Ops[] = { Op1 };
7598 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7601 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7602 EVT VT, SDValue Op1,
7604 SDVTList VTs = getVTList(VT);
7605 SDValue Ops[] = { Op1, Op2 };
7606 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7609 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7610 EVT VT, SDValue Op1,
7611 SDValue Op2, SDValue Op3) {
7612 SDVTList VTs = getVTList(VT);
7613 SDValue Ops[] = { Op1, Op2, Op3 };
7614 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7617 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7618 EVT VT, ArrayRef<SDValue> Ops) {
7619 SDVTList VTs = getVTList(VT);
7620 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7623 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7624 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
7625 SDVTList VTs = getVTList(VT1, VT2);
7626 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7629 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7631 SDVTList VTs = getVTList(VT1, VT2);
7632 return SelectNodeTo(N, MachineOpc, VTs, None);
7635 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7636 EVT VT1, EVT VT2, EVT VT3,
7637 ArrayRef<SDValue> Ops) {
7638 SDVTList VTs = getVTList(VT1, VT2, VT3);
7639 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7642 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7644 SDValue Op1, SDValue Op2) {
7645 SDVTList VTs = getVTList(VT1, VT2);
7646 SDValue Ops[] = { Op1, Op2 };
7647 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7650 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7651 SDVTList VTs,ArrayRef<SDValue> Ops) {
7652 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
7653 // Reset the NodeID to -1.
7656 ReplaceAllUsesWith(N, New);
7662 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
7663 /// the line number information on the merged node since it is not possible to
7664 /// preserve the information that operation is associated with multiple lines.
7665 /// This will make the debugger working better at -O0, were there is a higher
7666 /// probability having other instructions associated with that line.
7668 /// For IROrder, we keep the smaller of the two
7669 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
7670 DebugLoc NLoc = N->getDebugLoc();
7671 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
7672 N->setDebugLoc(DebugLoc());
7674 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
7675 N->setIROrder(Order);
7679 /// MorphNodeTo - This *mutates* the specified node to have the specified
7680 /// return type, opcode, and operands.
7682 /// Note that MorphNodeTo returns the resultant node. If there is already a
7683 /// node of the specified opcode and operands, it returns that node instead of
7684 /// the current one. Note that the SDLoc need not be the same.
7686 /// Using MorphNodeTo is faster than creating a new node and swapping it in
7687 /// with ReplaceAllUsesWith both because it often avoids allocating a new
7688 /// node, and because it doesn't require CSE recalculation for any of
7689 /// the node's users.
7691 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
7692 /// As a consequence it isn't appropriate to use from within the DAG combiner or
7693 /// the legalizer which maintain worklists that would need to be updated when
7694 /// deleting things.
7695 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
7696 SDVTList VTs, ArrayRef<SDValue> Ops) {
7697 // If an identical node already exists, use it.
7699 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
7700 FoldingSetNodeID ID;
7701 AddNodeIDNode(ID, Opc, VTs, Ops);
7702 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
7703 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
7706 if (!RemoveNodeFromCSEMaps(N))
7709 // Start the morphing.
7711 N->ValueList = VTs.VTs;
7712 N->NumValues = VTs.NumVTs;
7714 // Clear the operands list, updating used nodes to remove this from their
7715 // use list. Keep track of any operands that become dead as a result.
7716 SmallPtrSet<SDNode*, 16> DeadNodeSet;
7717 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
7719 SDNode *Used = Use.getNode();
7721 if (Used->use_empty())
7722 DeadNodeSet.insert(Used);
7725 // For MachineNode, initialize the memory references information.
7726 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
7729 // Swap for an appropriately sized array from the recycler.
7731 createOperands(N, Ops);
7733 // Delete any nodes that are still dead after adding the uses for the
7735 if (!DeadNodeSet.empty()) {
7736 SmallVector<SDNode *, 16> DeadNodes;
7737 for (SDNode *N : DeadNodeSet)
7739 DeadNodes.push_back(N);
7740 RemoveDeadNodes(DeadNodes);
7744 CSEMap.InsertNode(N, IP); // Memoize the new node.
7748 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
7749 unsigned OrigOpc = Node->getOpcode();
7753 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
7754 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
7755 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
7756 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
7757 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
7758 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
7759 case ISD::STRICT_FMA: NewOpc = ISD::FMA; break;
7760 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; break;
7761 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
7762 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
7763 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; break;
7764 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; break;
7765 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; break;
7766 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; break;
7767 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; break;
7768 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; break;
7769 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; break;
7770 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; break;
7771 case ISD::STRICT_FNEARBYINT: NewOpc = ISD::FNEARBYINT; break;
7772 case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break;
7773 case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break;
7774 case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; break;
7775 case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; break;
7776 case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; break;
7777 case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; break;
7778 case ISD::STRICT_FP_ROUND: NewOpc = ISD::FP_ROUND; break;
7779 case ISD::STRICT_FP_EXTEND: NewOpc = ISD::FP_EXTEND; break;
7782 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
7784 // We're taking this node out of the chain, so we need to re-link things.
7785 SDValue InputChain = Node->getOperand(0);
7786 SDValue OutputChain = SDValue(Node, 1);
7787 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
7789 SmallVector<SDValue, 3> Ops;
7790 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
7791 Ops.push_back(Node->getOperand(i));
7793 SDVTList VTs = getVTList(Node->getValueType(0));
7794 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
7796 // MorphNodeTo can operate in two ways: if an existing node with the
7797 // specified operands exists, it can just return it. Otherwise, it
7798 // updates the node in place to have the requested operands.
7800 // If we updated the node in place, reset the node ID. To the isel,
7801 // this should be just like a newly allocated machine node.
7804 ReplaceAllUsesWith(Node, Res);
7805 RemoveDeadNode(Node);
7811 /// getMachineNode - These are used for target selectors to create a new node
7812 /// with specified return type(s), MachineInstr opcode, and operands.
7814 /// Note that getMachineNode returns the resultant node. If there is already a
7815 /// node of the specified opcode and operands, it returns that node instead of
7816 /// the current one.
7817 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7819 SDVTList VTs = getVTList(VT);
7820 return getMachineNode(Opcode, dl, VTs, None);
7823 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7824 EVT VT, SDValue Op1) {
7825 SDVTList VTs = getVTList(VT);
7826 SDValue Ops[] = { Op1 };
7827 return getMachineNode(Opcode, dl, VTs, Ops);
7830 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7831 EVT VT, SDValue Op1, SDValue Op2) {
7832 SDVTList VTs = getVTList(VT);
7833 SDValue Ops[] = { Op1, Op2 };
7834 return getMachineNode(Opcode, dl, VTs, Ops);
7837 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7838 EVT VT, SDValue Op1, SDValue Op2,
7840 SDVTList VTs = getVTList(VT);
7841 SDValue Ops[] = { Op1, Op2, Op3 };
7842 return getMachineNode(Opcode, dl, VTs, Ops);
7845 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7846 EVT VT, ArrayRef<SDValue> Ops) {
7847 SDVTList VTs = getVTList(VT);
7848 return getMachineNode(Opcode, dl, VTs, Ops);
7851 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7852 EVT VT1, EVT VT2, SDValue Op1,
7854 SDVTList VTs = getVTList(VT1, VT2);
7855 SDValue Ops[] = { Op1, Op2 };
7856 return getMachineNode(Opcode, dl, VTs, Ops);
7859 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7860 EVT VT1, EVT VT2, SDValue Op1,
7861 SDValue Op2, SDValue Op3) {
7862 SDVTList VTs = getVTList(VT1, VT2);
7863 SDValue Ops[] = { Op1, Op2, Op3 };
7864 return getMachineNode(Opcode, dl, VTs, Ops);
7867 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7869 ArrayRef<SDValue> Ops) {
7870 SDVTList VTs = getVTList(VT1, VT2);
7871 return getMachineNode(Opcode, dl, VTs, Ops);
7874 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7875 EVT VT1, EVT VT2, EVT VT3,
7876 SDValue Op1, SDValue Op2) {
7877 SDVTList VTs = getVTList(VT1, VT2, VT3);
7878 SDValue Ops[] = { Op1, Op2 };
7879 return getMachineNode(Opcode, dl, VTs, Ops);
7882 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7883 EVT VT1, EVT VT2, EVT VT3,
7884 SDValue Op1, SDValue Op2,
7886 SDVTList VTs = getVTList(VT1, VT2, VT3);
7887 SDValue Ops[] = { Op1, Op2, Op3 };
7888 return getMachineNode(Opcode, dl, VTs, Ops);
7891 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7892 EVT VT1, EVT VT2, EVT VT3,
7893 ArrayRef<SDValue> Ops) {
7894 SDVTList VTs = getVTList(VT1, VT2, VT3);
7895 return getMachineNode(Opcode, dl, VTs, Ops);
7898 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7899 ArrayRef<EVT> ResultTys,
7900 ArrayRef<SDValue> Ops) {
7901 SDVTList VTs = getVTList(ResultTys);
7902 return getMachineNode(Opcode, dl, VTs, Ops);
7905 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
7907 ArrayRef<SDValue> Ops) {
7908 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
7913 FoldingSetNodeID ID;
7914 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
7916 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7917 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
7921 // Allocate a new MachineSDNode.
7922 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7923 createOperands(N, Ops);
7926 CSEMap.InsertNode(N, IP);
7932 /// getTargetExtractSubreg - A convenience function for creating
7933 /// TargetOpcode::EXTRACT_SUBREG nodes.
7934 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7936 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7937 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
7938 VT, Operand, SRIdxVal);
7939 return SDValue(Subreg, 0);
7942 /// getTargetInsertSubreg - A convenience function for creating
7943 /// TargetOpcode::INSERT_SUBREG nodes.
7944 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7945 SDValue Operand, SDValue Subreg) {
7946 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7947 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
7948 VT, Operand, Subreg, SRIdxVal);
7949 return SDValue(Result, 0);
7952 /// getNodeIfExists - Get the specified node if it's already available, or
7953 /// else return NULL.
7954 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
7955 ArrayRef<SDValue> Ops,
7956 const SDNodeFlags Flags) {
7957 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
7958 FoldingSetNodeID ID;
7959 AddNodeIDNode(ID, Opcode, VTList, Ops);
7961 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
7962 E->intersectFlagsWith(Flags);
7969 /// getDbgValue - Creates a SDDbgValue node.
7972 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
7973 SDNode *N, unsigned R, bool IsIndirect,
7974 const DebugLoc &DL, unsigned O) {
7975 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7976 "Expected inlined-at fields to agree");
7977 return new (DbgInfo->getAlloc())
7978 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
7982 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
7985 const DebugLoc &DL, unsigned O) {
7986 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7987 "Expected inlined-at fields to agree");
7988 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
7992 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
7993 DIExpression *Expr, unsigned FI,
7997 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7998 "Expected inlined-at fields to agree");
7999 return new (DbgInfo->getAlloc())
8000 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
8004 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
8006 unsigned VReg, bool IsIndirect,
8007 const DebugLoc &DL, unsigned O) {
8008 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8009 "Expected inlined-at fields to agree");
8010 return new (DbgInfo->getAlloc())
8011 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
8014 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8015 unsigned OffsetInBits, unsigned SizeInBits,
8016 bool InvalidateDbg) {
8017 SDNode *FromNode = From.getNode();
8018 SDNode *ToNode = To.getNode();
8019 assert(FromNode && ToNode && "Can't modify dbg values");
8022 // TODO: assert(From != To && "Redundant dbg value transfer");
8023 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8024 if (From == To || FromNode == ToNode)
8027 if (!FromNode->getHasDebugValue())
8030 SmallVector<SDDbgValue *, 2> ClonedDVs;
8031 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8032 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
8035 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8037 // Just transfer the dbg value attached to From.
8038 if (Dbg->getResNo() != From.getResNo())
8041 DIVariable *Var = Dbg->getVariable();
8042 auto *Expr = Dbg->getExpression();
8043 // If a fragment is requested, update the expression.
8045 // When splitting a larger (e.g., sign-extended) value whose
8046 // lower bits are described with an SDDbgValue, do not attempt
8047 // to transfer the SDDbgValue to the upper bits.
8048 if (auto FI = Expr->getFragmentInfo())
8049 if (OffsetInBits + SizeInBits > FI->SizeInBits)
8051 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8057 // Clone the SDDbgValue and move it to To.
8059 getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
8060 Dbg->getDebugLoc(), Dbg->getOrder());
8061 ClonedDVs.push_back(Clone);
8063 if (InvalidateDbg) {
8064 // Invalidate value and indicate the SDDbgValue should not be emitted.
8065 Dbg->setIsInvalidated();
8066 Dbg->setIsEmitted();
8070 for (SDDbgValue *Dbg : ClonedDVs)
8071 AddDbgValue(Dbg, ToNode, false);
8074 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8075 if (!N.getHasDebugValue())
8078 SmallVector<SDDbgValue *, 2> ClonedDVs;
8079 for (auto DV : GetDbgValues(&N)) {
8080 if (DV->isInvalidated())
8082 switch (N.getOpcode()) {
8086 SDValue N0 = N.getOperand(0);
8087 SDValue N1 = N.getOperand(1);
8088 if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8089 isConstantIntBuildVectorOrConstantInt(N1)) {
8090 uint64_t Offset = N.getConstantOperandVal(1);
8091 // Rewrite an ADD constant node into a DIExpression. Since we are
8092 // performing arithmetic to compute the variable's *value* in the
8093 // DIExpression, we need to mark the expression with a
8094 // DW_OP_stack_value.
8095 auto *DIExpr = DV->getExpression();
8097 DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset);
8099 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
8100 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
8101 ClonedDVs.push_back(Clone);
8102 DV->setIsInvalidated();
8104 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8105 N0.getNode()->dumprFull(this);
8106 dbgs() << " into " << *DIExpr << '\n');
8111 for (SDDbgValue *Dbg : ClonedDVs)
8112 AddDbgValue(Dbg, Dbg->getSDNode(), false);
8115 /// Creates a SDDbgLabel node.
8116 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8117 const DebugLoc &DL, unsigned O) {
8118 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8119 "Expected inlined-at fields to agree");
8120 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8125 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8126 /// pointed to by a use iterator is deleted, increment the use iterator
8127 /// so that it doesn't dangle.
8129 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8130 SDNode::use_iterator &UI;
8131 SDNode::use_iterator &UE;
8133 void NodeDeleted(SDNode *N, SDNode *E) override {
8134 // Increment the iterator as needed.
8135 while (UI != UE && N == *UI)
8140 RAUWUpdateListener(SelectionDAG &d,
8141 SDNode::use_iterator &ui,
8142 SDNode::use_iterator &ue)
8143 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8146 } // end anonymous namespace
8148 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8149 /// This can cause recursive merging of nodes in the DAG.
8151 /// This version assumes From has a single result value.
8153 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8154 SDNode *From = FromN.getNode();
8155 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8156 "Cannot replace with this method!");
8157 assert(From != To.getNode() && "Cannot replace uses of with self");
8159 // Preserve Debug Values
8160 transferDbgValues(FromN, To);
8162 // Iterate over all the existing uses of From. New uses will be added
8163 // to the beginning of the use list, which we avoid visiting.
8164 // This specifically avoids visiting uses of From that arise while the
8165 // replacement is happening, because any such uses would be the result
8166 // of CSE: If an existing node looks like From after one of its operands
8167 // is replaced by To, we don't want to replace of all its users with To
8168 // too. See PR3018 for more info.
8169 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8170 RAUWUpdateListener Listener(*this, UI, UE);
8174 // This node is about to morph, remove its old self from the CSE maps.
8175 RemoveNodeFromCSEMaps(User);
8177 // A user can appear in a use list multiple times, and when this
8178 // happens the uses are usually next to each other in the list.
8179 // To help reduce the number of CSE recomputations, process all
8180 // the uses of this user that we can find this way.
8182 SDUse &Use = UI.getUse();
8185 if (To->isDivergent() != From->isDivergent())
8186 updateDivergence(User);
8187 } while (UI != UE && *UI == User);
8188 // Now that we have modified User, add it back to the CSE maps. If it
8189 // already exists there, recursively merge the results together.
8190 AddModifiedNodeToCSEMaps(User);
8193 // If we just RAUW'd the root, take note.
8194 if (FromN == getRoot())
8198 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8199 /// This can cause recursive merging of nodes in the DAG.
8201 /// This version assumes that for each value of From, there is a
8202 /// corresponding value in To in the same position with the same type.
8204 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8206 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8207 assert((!From->hasAnyUseOfValue(i) ||
8208 From->getValueType(i) == To->getValueType(i)) &&
8209 "Cannot use this version of ReplaceAllUsesWith!");
8212 // Handle the trivial case.
8216 // Preserve Debug Info. Only do this if there's a use.
8217 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8218 if (From->hasAnyUseOfValue(i)) {
8219 assert((i < To->getNumValues()) && "Invalid To location");
8220 transferDbgValues(SDValue(From, i), SDValue(To, i));
8223 // Iterate over just the existing users of From. See the comments in
8224 // the ReplaceAllUsesWith above.
8225 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8226 RAUWUpdateListener Listener(*this, UI, UE);
8230 // This node is about to morph, remove its old self from the CSE maps.
8231 RemoveNodeFromCSEMaps(User);
8233 // A user can appear in a use list multiple times, and when this
8234 // happens the uses are usually next to each other in the list.
8235 // To help reduce the number of CSE recomputations, process all
8236 // the uses of this user that we can find this way.
8238 SDUse &Use = UI.getUse();
8241 if (To->isDivergent() != From->isDivergent())
8242 updateDivergence(User);
8243 } while (UI != UE && *UI == User);
8245 // Now that we have modified User, add it back to the CSE maps. If it
8246 // already exists there, recursively merge the results together.
8247 AddModifiedNodeToCSEMaps(User);
8250 // If we just RAUW'd the root, take note.
8251 if (From == getRoot().getNode())
8252 setRoot(SDValue(To, getRoot().getResNo()));
8255 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8256 /// This can cause recursive merging of nodes in the DAG.
8258 /// This version can replace From with any result values. To must match the
8259 /// number and types of values returned by From.
8260 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8261 if (From->getNumValues() == 1) // Handle the simple case efficiently.
8262 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8264 // Preserve Debug Info.
8265 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8266 transferDbgValues(SDValue(From, i), To[i]);
8268 // Iterate over just the existing users of From. See the comments in
8269 // the ReplaceAllUsesWith above.
8270 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8271 RAUWUpdateListener Listener(*this, UI, UE);
8275 // This node is about to morph, remove its old self from the CSE maps.
8276 RemoveNodeFromCSEMaps(User);
8278 // A user can appear in a use list multiple times, and when this happens the
8279 // uses are usually next to each other in the list. To help reduce the
8280 // number of CSE and divergence recomputations, process all the uses of this
8281 // user that we can find this way.
8282 bool To_IsDivergent = false;
8284 SDUse &Use = UI.getUse();
8285 const SDValue &ToOp = To[Use.getResNo()];
8288 To_IsDivergent |= ToOp->isDivergent();
8289 } while (UI != UE && *UI == User);
8291 if (To_IsDivergent != From->isDivergent())
8292 updateDivergence(User);
8294 // Now that we have modified User, add it back to the CSE maps. If it
8295 // already exists there, recursively merge the results together.
8296 AddModifiedNodeToCSEMaps(User);
8299 // If we just RAUW'd the root, take note.
8300 if (From == getRoot().getNode())
8301 setRoot(SDValue(To[getRoot().getResNo()]));
8304 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8305 /// uses of other values produced by From.getNode() alone. The Deleted
8306 /// vector is handled the same way as for ReplaceAllUsesWith.
8307 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8308 // Handle the really simple, really trivial case efficiently.
8309 if (From == To) return;
8311 // Handle the simple, trivial, case efficiently.
8312 if (From.getNode()->getNumValues() == 1) {
8313 ReplaceAllUsesWith(From, To);
8317 // Preserve Debug Info.
8318 transferDbgValues(From, To);
8320 // Iterate over just the existing users of From. See the comments in
8321 // the ReplaceAllUsesWith above.
8322 SDNode::use_iterator UI = From.getNode()->use_begin(),
8323 UE = From.getNode()->use_end();
8324 RAUWUpdateListener Listener(*this, UI, UE);
8327 bool UserRemovedFromCSEMaps = false;
8329 // A user can appear in a use list multiple times, and when this
8330 // happens the uses are usually next to each other in the list.
8331 // To help reduce the number of CSE recomputations, process all
8332 // the uses of this user that we can find this way.
8334 SDUse &Use = UI.getUse();
8336 // Skip uses of different values from the same node.
8337 if (Use.getResNo() != From.getResNo()) {
8342 // If this node hasn't been modified yet, it's still in the CSE maps,
8343 // so remove its old self from the CSE maps.
8344 if (!UserRemovedFromCSEMaps) {
8345 RemoveNodeFromCSEMaps(User);
8346 UserRemovedFromCSEMaps = true;
8351 if (To->isDivergent() != From->isDivergent())
8352 updateDivergence(User);
8353 } while (UI != UE && *UI == User);
8354 // We are iterating over all uses of the From node, so if a use
8355 // doesn't use the specific value, no changes are made.
8356 if (!UserRemovedFromCSEMaps)
8359 // Now that we have modified User, add it back to the CSE maps. If it
8360 // already exists there, recursively merge the results together.
8361 AddModifiedNodeToCSEMaps(User);
8364 // If we just RAUW'd the root, take note.
8365 if (From == getRoot())
8371 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8372 /// to record information about a use.
8379 /// operator< - Sort Memos by User.
8380 bool operator<(const UseMemo &L, const UseMemo &R) {
8381 return (intptr_t)L.User < (intptr_t)R.User;
8384 } // end anonymous namespace
8386 void SelectionDAG::updateDivergence(SDNode * N)
8388 if (TLI->isSDNodeAlwaysUniform(N))
8390 bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
8391 for (auto &Op : N->ops()) {
8392 if (Op.Val.getValueType() != MVT::Other)
8393 IsDivergent |= Op.getNode()->isDivergent();
8395 if (N->SDNodeBits.IsDivergent != IsDivergent) {
8396 N->SDNodeBits.IsDivergent = IsDivergent;
8397 for (auto U : N->uses()) {
8398 updateDivergence(U);
8403 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
8404 DenseMap<SDNode *, unsigned> Degree;
8405 Order.reserve(AllNodes.size());
8406 for (auto &N : allnodes()) {
8407 unsigned NOps = N.getNumOperands();
8410 Order.push_back(&N);
8412 for (size_t I = 0; I != Order.size(); ++I) {
8413 SDNode *N = Order[I];
8414 for (auto U : N->uses()) {
8415 unsigned &UnsortedOps = Degree[U];
8416 if (0 == --UnsortedOps)
8423 void SelectionDAG::VerifyDAGDiverence() {
8424 std::vector<SDNode *> TopoOrder;
8425 CreateTopologicalOrder(TopoOrder);
8426 const TargetLowering &TLI = getTargetLoweringInfo();
8427 DenseMap<const SDNode *, bool> DivergenceMap;
8428 for (auto &N : allnodes()) {
8429 DivergenceMap[&N] = false;
8431 for (auto N : TopoOrder) {
8432 bool IsDivergent = DivergenceMap[N];
8433 bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
8434 for (auto &Op : N->ops()) {
8435 if (Op.Val.getValueType() != MVT::Other)
8436 IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
8438 if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
8439 DivergenceMap[N] = true;
8442 for (auto &N : allnodes()) {
8444 assert(DivergenceMap[&N] == N.isDivergent() &&
8445 "Divergence bit inconsistency detected\n");
8450 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
8451 /// uses of other values produced by From.getNode() alone. The same value
8452 /// may appear in both the From and To list. The Deleted vector is
8453 /// handled the same way as for ReplaceAllUsesWith.
8454 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
8457 // Handle the simple, trivial case efficiently.
8459 return ReplaceAllUsesOfValueWith(*From, *To);
8461 transferDbgValues(*From, *To);
8463 // Read up all the uses and make records of them. This helps
8464 // processing new uses that are introduced during the
8465 // replacement process.
8466 SmallVector<UseMemo, 4> Uses;
8467 for (unsigned i = 0; i != Num; ++i) {
8468 unsigned FromResNo = From[i].getResNo();
8469 SDNode *FromNode = From[i].getNode();
8470 for (SDNode::use_iterator UI = FromNode->use_begin(),
8471 E = FromNode->use_end(); UI != E; ++UI) {
8472 SDUse &Use = UI.getUse();
8473 if (Use.getResNo() == FromResNo) {
8474 UseMemo Memo = { *UI, i, &Use };
8475 Uses.push_back(Memo);
8480 // Sort the uses, so that all the uses from a given User are together.
8483 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
8484 UseIndex != UseIndexEnd; ) {
8485 // We know that this user uses some value of From. If it is the right
8486 // value, update it.
8487 SDNode *User = Uses[UseIndex].User;
8489 // This node is about to morph, remove its old self from the CSE maps.
8490 RemoveNodeFromCSEMaps(User);
8492 // The Uses array is sorted, so all the uses for a given User
8493 // are next to each other in the list.
8494 // To help reduce the number of CSE recomputations, process all
8495 // the uses of this user that we can find this way.
8497 unsigned i = Uses[UseIndex].Index;
8498 SDUse &Use = *Uses[UseIndex].Use;
8502 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
8504 // Now that we have modified User, add it back to the CSE maps. If it
8505 // already exists there, recursively merge the results together.
8506 AddModifiedNodeToCSEMaps(User);
8510 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
8511 /// based on their topological order. It returns the maximum id and a vector
8512 /// of the SDNodes* in assigned order by reference.
8513 unsigned SelectionDAG::AssignTopologicalOrder() {
8514 unsigned DAGSize = 0;
8516 // SortedPos tracks the progress of the algorithm. Nodes before it are
8517 // sorted, nodes after it are unsorted. When the algorithm completes
8518 // it is at the end of the list.
8519 allnodes_iterator SortedPos = allnodes_begin();
8521 // Visit all the nodes. Move nodes with no operands to the front of
8522 // the list immediately. Annotate nodes that do have operands with their
8523 // operand count. Before we do this, the Node Id fields of the nodes
8524 // may contain arbitrary values. After, the Node Id fields for nodes
8525 // before SortedPos will contain the topological sort index, and the
8526 // Node Id fields for nodes At SortedPos and after will contain the
8527 // count of outstanding operands.
8528 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
8530 checkForCycles(N, this);
8531 unsigned Degree = N->getNumOperands();
8533 // A node with no uses, add it to the result array immediately.
8534 N->setNodeId(DAGSize++);
8535 allnodes_iterator Q(N);
8537 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
8538 assert(SortedPos != AllNodes.end() && "Overran node list");
8541 // Temporarily use the Node Id as scratch space for the degree count.
8542 N->setNodeId(Degree);
8546 // Visit all the nodes. As we iterate, move nodes into sorted order,
8547 // such that by the time the end is reached all nodes will be sorted.
8548 for (SDNode &Node : allnodes()) {
8550 checkForCycles(N, this);
8551 // N is in sorted position, so all its uses have one less operand
8552 // that needs to be sorted.
8553 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8556 unsigned Degree = P->getNodeId();
8557 assert(Degree != 0 && "Invalid node degree");
8560 // All of P's operands are sorted, so P may sorted now.
8561 P->setNodeId(DAGSize++);
8562 if (P->getIterator() != SortedPos)
8563 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
8564 assert(SortedPos != AllNodes.end() && "Overran node list");
8567 // Update P's outstanding operand count.
8568 P->setNodeId(Degree);
8571 if (Node.getIterator() == SortedPos) {
8573 allnodes_iterator I(N);
8575 dbgs() << "Overran sorted position:\n";
8576 S->dumprFull(this); dbgs() << "\n";
8577 dbgs() << "Checking if this is due to cycles\n";
8578 checkForCycles(this, true);
8580 llvm_unreachable(nullptr);
8584 assert(SortedPos == AllNodes.end() &&
8585 "Topological sort incomplete!");
8586 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
8587 "First node in topological sort is not the entry token!");
8588 assert(AllNodes.front().getNodeId() == 0 &&
8589 "First node in topological sort has non-zero id!");
8590 assert(AllNodes.front().getNumOperands() == 0 &&
8591 "First node in topological sort has operands!");
8592 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
8593 "Last node in topologic sort has unexpected id!");
8594 assert(AllNodes.back().use_empty() &&
8595 "Last node in topologic sort has users!");
8596 assert(DAGSize == allnodes_size() && "Node count mismatch!");
8600 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
8601 /// value is produced by SD.
8602 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
8604 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
8605 SD->setHasDebugValue(true);
8607 DbgInfo->add(DB, SD, isParameter);
8610 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
8614 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
8616 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
8617 // The new memory operation must have the same position as the old load in
8618 // terms of memory dependency. Create a TokenFactor for the old load and new
8619 // memory operation and update uses of the old load's output chain to use that
8621 SDValue OldChain = SDValue(OldLoad, 1);
8622 SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
8623 if (!OldLoad->hasAnyUseOfValue(1))
8626 SDValue TokenFactor =
8627 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
8628 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
8629 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
8633 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
8634 Function **OutFunction) {
8635 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
8637 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8638 auto *Module = MF->getFunction().getParent();
8639 auto *Function = Module->getFunction(Symbol);
8641 if (OutFunction != nullptr)
8642 *OutFunction = Function;
8644 if (Function != nullptr) {
8645 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
8646 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
8649 std::string ErrorStr;
8650 raw_string_ostream ErrorFormatter(ErrorStr);
8652 ErrorFormatter << "Undefined external symbol ";
8653 ErrorFormatter << '"' << Symbol << '"';
8654 ErrorFormatter.flush();
8656 report_fatal_error(ErrorStr);
8659 //===----------------------------------------------------------------------===//
8661 //===----------------------------------------------------------------------===//
8663 bool llvm::isNullConstant(SDValue V) {
8664 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8665 return Const != nullptr && Const->isNullValue();
8668 bool llvm::isNullFPConstant(SDValue V) {
8669 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
8670 return Const != nullptr && Const->isZero() && !Const->isNegative();
8673 bool llvm::isAllOnesConstant(SDValue V) {
8674 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8675 return Const != nullptr && Const->isAllOnesValue();
8678 bool llvm::isOneConstant(SDValue V) {
8679 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8680 return Const != nullptr && Const->isOne();
8683 SDValue llvm::peekThroughBitcasts(SDValue V) {
8684 while (V.getOpcode() == ISD::BITCAST)
8685 V = V.getOperand(0);
8689 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
8690 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
8691 V = V.getOperand(0);
8695 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
8696 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8697 V = V.getOperand(0);
8701 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
8702 if (V.getOpcode() != ISD::XOR)
8704 V = peekThroughBitcasts(V.getOperand(1));
8705 unsigned NumBits = V.getScalarValueSizeInBits();
8707 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
8708 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
8711 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
8712 bool AllowTruncation) {
8713 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8716 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8717 BitVector UndefElements;
8718 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
8720 // BuildVectors can truncate their operands. Ignore that case here unless
8721 // AllowTruncation is set.
8722 if (CN && (UndefElements.none() || AllowUndefs)) {
8723 EVT CVT = CN->getValueType(0);
8724 EVT NSVT = N.getValueType().getScalarType();
8725 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
8726 if (AllowTruncation || (CVT == NSVT))
8734 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
8736 bool AllowTruncation) {
8737 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8740 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8741 BitVector UndefElements;
8742 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
8744 // BuildVectors can truncate their operands. Ignore that case here unless
8745 // AllowTruncation is set.
8746 if (CN && (UndefElements.none() || AllowUndefs)) {
8747 EVT CVT = CN->getValueType(0);
8748 EVT NSVT = N.getValueType().getScalarType();
8749 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
8750 if (AllowTruncation || (CVT == NSVT))
8758 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
8759 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8762 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8763 BitVector UndefElements;
8764 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
8765 if (CN && (UndefElements.none() || AllowUndefs))
8772 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
8773 const APInt &DemandedElts,
8775 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8778 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8779 BitVector UndefElements;
8780 ConstantFPSDNode *CN =
8781 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
8782 if (CN && (UndefElements.none() || AllowUndefs))
8789 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
8790 // TODO: may want to use peekThroughBitcast() here.
8791 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
8792 return C && C->isNullValue();
8795 bool llvm::isOneOrOneSplat(SDValue N) {
8796 // TODO: may want to use peekThroughBitcast() here.
8797 unsigned BitWidth = N.getScalarValueSizeInBits();
8798 ConstantSDNode *C = isConstOrConstSplat(N);
8799 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
8802 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
8803 N = peekThroughBitcasts(N);
8804 unsigned BitWidth = N.getScalarValueSizeInBits();
8805 ConstantSDNode *C = isConstOrConstSplat(N);
8806 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
8809 HandleSDNode::~HandleSDNode() {
8813 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
8815 const GlobalValue *GA, EVT VT,
8816 int64_t o, unsigned char TF)
8817 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
8821 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
8822 EVT VT, unsigned SrcAS,
8824 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
8825 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
8827 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
8828 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
8829 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
8830 MemSDNodeBits.IsVolatile = MMO->isVolatile();
8831 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
8832 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
8833 MemSDNodeBits.IsInvariant = MMO->isInvariant();
8835 // We check here that the size of the memory operand fits within the size of
8836 // the MMO. This is because the MMO might indicate only a possible address
8837 // range instead of specifying the affected memory addresses precisely.
8838 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
8841 /// Profile - Gather unique data for the node.
8843 void SDNode::Profile(FoldingSetNodeID &ID) const {
8844 AddNodeIDNode(ID, this);
8850 std::vector<EVT> VTs;
8853 VTs.reserve(MVT::LAST_VALUETYPE);
8854 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
8855 VTs.push_back(MVT((MVT::SimpleValueType)i));
8859 } // end anonymous namespace
8861 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
8862 static ManagedStatic<EVTArray> SimpleVTArray;
8863 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
8865 /// getValueTypeList - Return a pointer to the specified value type.
8867 const EVT *SDNode::getValueTypeList(EVT VT) {
8868 if (VT.isExtended()) {
8869 sys::SmartScopedLock<true> Lock(*VTMutex);
8870 return &(*EVTs->insert(VT).first);
8872 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
8873 "Value type out of range!");
8874 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
8878 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
8879 /// indicated value. This method ignores uses of other values defined by this
8881 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
8882 assert(Value < getNumValues() && "Bad value!");
8884 // TODO: Only iterate over uses of a given value of the node
8885 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
8886 if (UI.getUse().getResNo() == Value) {
8893 // Found exactly the right number of uses?
8897 /// hasAnyUseOfValue - Return true if there are any use of the indicated
8898 /// value. This method ignores uses of other values defined by this operation.
8899 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
8900 assert(Value < getNumValues() && "Bad value!");
8902 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
8903 if (UI.getUse().getResNo() == Value)
8909 /// isOnlyUserOf - Return true if this node is the only use of N.
8910 bool SDNode::isOnlyUserOf(const SDNode *N) const {
8912 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8923 /// Return true if the only users of N are contained in Nodes.
8924 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
8926 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8928 if (llvm::any_of(Nodes,
8929 [&User](const SDNode *Node) { return User == Node; }))
8938 /// isOperand - Return true if this node is an operand of N.
8939 bool SDValue::isOperandOf(const SDNode *N) const {
8940 return any_of(N->op_values(), [this](SDValue Op) { return *this == Op; });
8943 bool SDNode::isOperandOf(const SDNode *N) const {
8944 return any_of(N->op_values(),
8945 [this](SDValue Op) { return this == Op.getNode(); });
8948 /// reachesChainWithoutSideEffects - Return true if this operand (which must
8949 /// be a chain) reaches the specified operand without crossing any
8950 /// side-effecting instructions on any chain path. In practice, this looks
8951 /// through token factors and non-volatile loads. In order to remain efficient,
8952 /// this only looks a couple of nodes in, it does not do an exhaustive search.
8954 /// Note that we only need to examine chains when we're searching for
8955 /// side-effects; SelectionDAG requires that all side-effects are represented
8956 /// by chains, even if another operand would force a specific ordering. This
8957 /// constraint is necessary to allow transformations like splitting loads.
8958 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
8959 unsigned Depth) const {
8960 if (*this == Dest) return true;
8962 // Don't search too deeply, we just want to be able to see through
8963 // TokenFactor's etc.
8964 if (Depth == 0) return false;
8966 // If this is a token factor, all inputs to the TF happen in parallel.
8967 if (getOpcode() == ISD::TokenFactor) {
8968 // First, try a shallow search.
8969 if (is_contained((*this)->ops(), Dest)) {
8970 // We found the chain we want as an operand of this TokenFactor.
8971 // Essentially, we reach the chain without side-effects if we could
8972 // serialize the TokenFactor into a simple chain of operations with
8973 // Dest as the last operation. This is automatically true if the
8974 // chain has one use: there are no other ordering constraints.
8975 // If the chain has more than one use, we give up: some other
8976 // use of Dest might force a side-effect between Dest and the current
8978 if (Dest.hasOneUse())
8981 // Next, try a deep search: check whether every operand of the TokenFactor
8983 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
8984 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
8988 // Loads don't have side effects, look through them.
8989 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
8990 if (!Ld->isVolatile())
8991 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
8996 bool SDNode::hasPredecessor(const SDNode *N) const {
8997 SmallPtrSet<const SDNode *, 32> Visited;
8998 SmallVector<const SDNode *, 16> Worklist;
8999 Worklist.push_back(this);
9000 return hasPredecessorHelper(N, Visited, Worklist);
9003 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9004 this->Flags.intersectWith(Flags);
9008 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9009 ArrayRef<ISD::NodeType> CandidateBinOps) {
9010 // The pattern must end in an extract from index 0.
9011 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9012 !isNullConstant(Extract->getOperand(1)))
9015 SDValue Op = Extract->getOperand(0);
9016 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9018 // Match against one of the candidate binary ops.
9019 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9020 return Op.getOpcode() == unsigned(BinOp);
9024 // At each stage, we're looking for something that looks like:
9025 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9026 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9027 // i32 undef, i32 undef, i32 undef, i32 undef>
9028 // %a = binop <8 x i32> %op, %s
9029 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9030 // we expect something like:
9031 // <4,5,6,7,u,u,u,u>
9032 // <2,3,u,u,u,u,u,u>
9033 // <1,u,u,u,u,u,u,u>
9034 unsigned CandidateBinOp = Op.getOpcode();
9035 for (unsigned i = 0; i < Stages; ++i) {
9036 if (Op.getOpcode() != CandidateBinOp)
9039 SDValue Op0 = Op.getOperand(0);
9040 SDValue Op1 = Op.getOperand(1);
9042 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9046 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9050 // The first operand of the shuffle should be the same as the other operand
9052 if (!Shuffle || Shuffle->getOperand(0) != Op)
9055 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9056 for (int Index = 0, MaskEnd = 1 << i; Index < MaskEnd; ++Index)
9057 if (Shuffle->getMaskElt(Index) != MaskEnd + Index)
9061 BinOp = (ISD::NodeType)CandidateBinOp;
9065 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9066 assert(N->getNumValues() == 1 &&
9067 "Can't unroll a vector with multiple results!");
9069 EVT VT = N->getValueType(0);
9070 unsigned NE = VT.getVectorNumElements();
9071 EVT EltVT = VT.getVectorElementType();
9074 SmallVector<SDValue, 8> Scalars;
9075 SmallVector<SDValue, 4> Operands(N->getNumOperands());
9077 // If ResNE is 0, fully unroll the vector op.
9080 else if (NE > ResNE)
9084 for (i= 0; i != NE; ++i) {
9085 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9086 SDValue Operand = N->getOperand(j);
9087 EVT OperandVT = Operand.getValueType();
9088 if (OperandVT.isVector()) {
9089 // A vector operand; extract a single element.
9090 EVT OperandEltVT = OperandVT.getVectorElementType();
9092 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
9093 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
9095 // A scalar operand; just use it as is.
9096 Operands[j] = Operand;
9100 switch (N->getOpcode()) {
9102 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9107 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9114 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9115 getShiftAmountOperand(Operands[0].getValueType(),
9118 case ISD::SIGN_EXTEND_INREG:
9119 case ISD::FP_ROUND_INREG: {
9120 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9121 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9123 getValueType(ExtVT)));
9128 for (; i < ResNE; ++i)
9129 Scalars.push_back(getUNDEF(EltVT));
9131 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9132 return getBuildVector(VecVT, dl, Scalars);
9135 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9136 SDNode *N, unsigned ResNE) {
9137 unsigned Opcode = N->getOpcode();
9138 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9139 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9140 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9141 "Expected an overflow opcode");
9143 EVT ResVT = N->getValueType(0);
9144 EVT OvVT = N->getValueType(1);
9145 EVT ResEltVT = ResVT.getVectorElementType();
9146 EVT OvEltVT = OvVT.getVectorElementType();
9149 // If ResNE is 0, fully unroll the vector op.
9150 unsigned NE = ResVT.getVectorNumElements();
9153 else if (NE > ResNE)
9156 SmallVector<SDValue, 8> LHSScalars;
9157 SmallVector<SDValue, 8> RHSScalars;
9158 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9159 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9161 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9162 SDVTList VTs = getVTList(ResEltVT, SVT);
9163 SmallVector<SDValue, 8> ResScalars;
9164 SmallVector<SDValue, 8> OvScalars;
9165 for (unsigned i = 0; i < NE; ++i) {
9166 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9168 getSelect(dl, OvEltVT, Res.getValue(1),
9169 getBoolConstant(true, dl, OvEltVT, ResVT),
9170 getConstant(0, dl, OvEltVT));
9172 ResScalars.push_back(Res);
9173 OvScalars.push_back(Ov);
9176 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9177 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9179 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9180 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9181 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9182 getBuildVector(NewOvVT, dl, OvScalars));
9185 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9189 if (LD->isVolatile() || Base->isVolatile())
9191 if (LD->isIndexed() || Base->isIndexed())
9193 if (LD->getChain() != Base->getChain())
9195 EVT VT = LD->getValueType(0);
9196 if (VT.getSizeInBits() / 8 != Bytes)
9199 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9200 auto LocDecomp = BaseIndexOffset::match(LD, *this);
9203 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9204 return (Dist * Bytes == Offset);
9208 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
9209 /// it cannot be inferred.
9210 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
9211 // If this is a GlobalAddress + cst, return the alignment.
9212 const GlobalValue *GV;
9213 int64_t GVOffset = 0;
9214 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9215 unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
9216 KnownBits Known(IdxWidth);
9217 llvm::computeKnownBits(GV, Known, getDataLayout());
9218 unsigned AlignBits = Known.countMinTrailingZeros();
9219 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
9221 return MinAlign(Align, GVOffset);
9224 // If this is a direct reference to a stack slot, use information about the
9225 // stack slot's alignment.
9226 int FrameIdx = INT_MIN;
9227 int64_t FrameOffset = 0;
9228 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9229 FrameIdx = FI->getIndex();
9230 } else if (isBaseWithConstantOffset(Ptr) &&
9231 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9233 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9234 FrameOffset = Ptr.getConstantOperandVal(1);
9237 if (FrameIdx != INT_MIN) {
9238 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9239 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
9247 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9248 /// which is split (or expanded) into two not necessarily identical pieces.
9249 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
9250 // Currently all types are split in half.
9253 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
9255 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
9257 return std::make_pair(LoVT, HiVT);
9260 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9262 std::pair<SDValue, SDValue>
9263 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9265 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
9266 N.getValueType().getVectorNumElements() &&
9267 "More vector elements requested than available!");
9269 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
9270 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
9271 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9272 getConstant(LoVT.getVectorNumElements(), DL,
9273 TLI->getVectorIdxTy(getDataLayout())));
9274 return std::make_pair(Lo, Hi);
9277 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
9278 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
9279 EVT VT = N.getValueType();
9280 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
9281 NextPowerOf2(VT.getVectorNumElements()));
9282 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
9283 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
9286 void SelectionDAG::ExtractVectorElements(SDValue Op,
9287 SmallVectorImpl<SDValue> &Args,
9288 unsigned Start, unsigned Count) {
9289 EVT VT = Op.getValueType();
9291 Count = VT.getVectorNumElements();
9293 EVT EltVT = VT.getVectorElementType();
9294 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
9296 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
9297 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9298 Op, getConstant(i, SL, IdxTy)));
9302 // getAddressSpace - Return the address space this GlobalAddress belongs to.
9303 unsigned GlobalAddressSDNode::getAddressSpace() const {
9304 return getGlobal()->getType()->getAddressSpace();
9307 Type *ConstantPoolSDNode::getType() const {
9308 if (isMachineConstantPoolEntry())
9309 return Val.MachineCPVal->getType();
9310 return Val.ConstVal->getType();
9313 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
9314 unsigned &SplatBitSize,
9316 unsigned MinSplatBits,
9317 bool IsBigEndian) const {
9318 EVT VT = getValueType(0);
9319 assert(VT.isVector() && "Expected a vector type");
9320 unsigned VecWidth = VT.getSizeInBits();
9321 if (MinSplatBits > VecWidth)
9324 // FIXME: The widths are based on this node's type, but build vectors can
9325 // truncate their operands.
9326 SplatValue = APInt(VecWidth, 0);
9327 SplatUndef = APInt(VecWidth, 0);
9329 // Get the bits. Bits with undefined values (when the corresponding element
9330 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
9331 // in SplatValue. If any of the values are not constant, give up and return
9333 unsigned int NumOps = getNumOperands();
9334 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
9335 unsigned EltWidth = VT.getScalarSizeInBits();
9337 for (unsigned j = 0; j < NumOps; ++j) {
9338 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
9339 SDValue OpVal = getOperand(i);
9340 unsigned BitPos = j * EltWidth;
9342 if (OpVal.isUndef())
9343 SplatUndef.setBits(BitPos, BitPos + EltWidth);
9344 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
9345 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
9346 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
9347 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
9352 // The build_vector is all constants or undefs. Find the smallest element
9353 // size that splats the vector.
9354 HasAnyUndefs = (SplatUndef != 0);
9356 // FIXME: This does not work for vectors with elements less than 8 bits.
9357 while (VecWidth > 8) {
9358 unsigned HalfSize = VecWidth / 2;
9359 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
9360 APInt LowValue = SplatValue.trunc(HalfSize);
9361 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
9362 APInt LowUndef = SplatUndef.trunc(HalfSize);
9364 // If the two halves do not match (ignoring undef bits), stop here.
9365 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
9366 MinSplatBits > HalfSize)
9369 SplatValue = HighValue | LowValue;
9370 SplatUndef = HighUndef & LowUndef;
9372 VecWidth = HalfSize;
9375 SplatBitSize = VecWidth;
9379 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
9380 BitVector *UndefElements) const {
9381 if (UndefElements) {
9382 UndefElements->clear();
9383 UndefElements->resize(getNumOperands());
9385 assert(getNumOperands() == DemandedElts.getBitWidth() &&
9386 "Unexpected vector size");
9390 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
9391 if (!DemandedElts[i])
9393 SDValue Op = getOperand(i);
9396 (*UndefElements)[i] = true;
9397 } else if (!Splatted) {
9399 } else if (Splatted != Op) {
9405 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
9406 assert(getOperand(FirstDemandedIdx).isUndef() &&
9407 "Can only have a splat without a constant for all undefs.");
9408 return getOperand(FirstDemandedIdx);
9414 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
9415 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
9416 return getSplatValue(DemandedElts, UndefElements);
9420 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
9421 BitVector *UndefElements) const {
9422 return dyn_cast_or_null<ConstantSDNode>(
9423 getSplatValue(DemandedElts, UndefElements));
9427 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
9428 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
9432 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
9433 BitVector *UndefElements) const {
9434 return dyn_cast_or_null<ConstantFPSDNode>(
9435 getSplatValue(DemandedElts, UndefElements));
9439 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
9440 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
9444 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
9445 uint32_t BitWidth) const {
9446 if (ConstantFPSDNode *CN =
9447 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
9449 APSInt IntVal(BitWidth);
9450 const APFloat &APF = CN->getValueAPF();
9451 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
9456 return IntVal.exactLogBase2();
9461 bool BuildVectorSDNode::isConstant() const {
9462 for (const SDValue &Op : op_values()) {
9463 unsigned Opc = Op.getOpcode();
9464 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
9470 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
9471 // Find the first non-undef value in the shuffle mask.
9473 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
9476 // If all elements are undefined, this shuffle can be considered a splat
9477 // (although it should eventually get simplified away completely).
9481 // Make sure all remaining elements are either undef or the same as the first
9483 for (int Idx = Mask[i]; i != e; ++i)
9484 if (Mask[i] >= 0 && Mask[i] != Idx)
9489 // Returns the SDNode if it is a constant integer BuildVector
9490 // or constant integer.
9491 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
9492 if (isa<ConstantSDNode>(N))
9494 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
9496 // Treat a GlobalAddress supporting constant offset folding as a
9497 // constant integer.
9498 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
9499 if (GA->getOpcode() == ISD::GlobalAddress &&
9500 TLI->isOffsetFoldingLegal(GA))
9505 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
9506 if (isa<ConstantFPSDNode>(N))
9509 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
9515 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
9516 assert(!Node->OperandList && "Node already has operands");
9517 assert(SDNode::getMaxNumOperands() >= Vals.size() &&
9518 "too many operands to fit into SDNode");
9519 SDUse *Ops = OperandRecycler.allocate(
9520 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
9522 bool IsDivergent = false;
9523 for (unsigned I = 0; I != Vals.size(); ++I) {
9524 Ops[I].setUser(Node);
9525 Ops[I].setInitial(Vals[I]);
9526 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
9527 IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
9529 Node->NumOperands = Vals.size();
9530 Node->OperandList = Ops;
9531 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
9532 if (!TLI->isSDNodeAlwaysUniform(Node))
9533 Node->SDNodeBits.IsDivergent = IsDivergent;
9534 checkForCycles(Node);
9537 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
9538 SmallVectorImpl<SDValue> &Vals) {
9539 size_t Limit = SDNode::getMaxNumOperands();
9540 while (Vals.size() > Limit) {
9541 unsigned SliceIdx = Vals.size() - Limit;
9542 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
9543 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
9544 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
9545 Vals.emplace_back(NewTF);
9547 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
9551 static void checkForCyclesHelper(const SDNode *N,
9552 SmallPtrSetImpl<const SDNode*> &Visited,
9553 SmallPtrSetImpl<const SDNode*> &Checked,
9554 const llvm::SelectionDAG *DAG) {
9555 // If this node has already been checked, don't check it again.
9556 if (Checked.count(N))
9559 // If a node has already been visited on this depth-first walk, reject it as
9561 if (!Visited.insert(N).second) {
9562 errs() << "Detected cycle in SelectionDAG\n";
9563 dbgs() << "Offending node:\n";
9564 N->dumprFull(DAG); dbgs() << "\n";
9568 for (const SDValue &Op : N->op_values())
9569 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
9576 void llvm::checkForCycles(const llvm::SDNode *N,
9577 const llvm::SelectionDAG *DAG,
9581 #ifdef EXPENSIVE_CHECKS
9583 #endif // EXPENSIVE_CHECKS
9585 assert(N && "Checking nonexistent SDNode");
9586 SmallPtrSet<const SDNode*, 32> visited;
9587 SmallPtrSet<const SDNode*, 32> checked;
9588 checkForCyclesHelper(N, visited, checked, DAG);
9593 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
9594 checkForCycles(DAG->getRoot().getNode(), DAG, force);