1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/APSInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/ISDOpcodes.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineConstantPool.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineValueType.h"
36 #include "llvm/CodeGen/RuntimeLibcalls.h"
37 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
38 #include "llvm/CodeGen/SelectionDAGNodes.h"
39 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
40 #include "llvm/CodeGen/ValueTypes.h"
41 #include "llvm/IR/Constant.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DebugInfoMetadata.h"
45 #include "llvm/IR/DebugLoc.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/GlobalValue.h"
49 #include "llvm/IR/Metadata.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/CodeGen.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/KnownBits.h"
58 #include "llvm/Support/ManagedStatic.h"
59 #include "llvm/Support/MathExtras.h"
60 #include "llvm/Support/Mutex.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Target/TargetOptions.h"
65 #include "llvm/Target/TargetRegisterInfo.h"
66 #include "llvm/Target/TargetSubtargetInfo.h"
79 /// makeVTList - Return an instance of the SDVTList struct initialized with the
80 /// specified members.
81 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
82 SDVTList Res = {VTs, NumVTs};
86 // Default null implementations of the callbacks.
87 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
88 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
90 //===----------------------------------------------------------------------===//
91 // ConstantFPSDNode Class
92 //===----------------------------------------------------------------------===//
94 /// isExactlyValue - We don't rely on operator== working on double values, as
95 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
96 /// As such, this method can be used to do an exact bit-for-bit comparison of
97 /// two floating point values.
98 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
99 return getValueAPF().bitwiseIsEqual(V);
102 bool ConstantFPSDNode::isValueValidForType(EVT VT,
103 const APFloat& Val) {
104 assert(VT.isFloatingPoint() && "Can only convert between FP types");
106 // convert modifies in place, so make a copy.
107 APFloat Val2 = APFloat(Val);
109 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
110 APFloat::rmNearestTiesToEven,
115 //===----------------------------------------------------------------------===//
117 //===----------------------------------------------------------------------===//
119 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal,
121 auto *BV = dyn_cast<BuildVectorSDNode>(N);
126 unsigned SplatBitSize;
128 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
129 unsigned MinSplatBits = AllowShrink ? 0 : EltSize;
130 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
132 EltSize >= SplatBitSize;
135 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
136 // specializations of the more general isConstantSplatVector()?
138 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
139 // Look through a bit convert.
140 while (N->getOpcode() == ISD::BITCAST)
141 N = N->getOperand(0).getNode();
143 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
145 unsigned i = 0, e = N->getNumOperands();
147 // Skip over all of the undef values.
148 while (i != e && N->getOperand(i).isUndef())
151 // Do not accept an all-undef vector.
152 if (i == e) return false;
154 // Do not accept build_vectors that aren't all constants or which have non-~0
155 // elements. We have to be a bit careful here, as the type of the constant
156 // may not be the same as the type of the vector elements due to type
157 // legalization (the elements are promoted to a legal type for the target and
158 // a vector of a type may be legal when the base element type is not).
159 // We only want to check enough bits to cover the vector elements, because
160 // we care if the resultant vector is all ones, not whether the individual
162 SDValue NotZero = N->getOperand(i);
163 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
164 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
165 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
167 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
168 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
173 // Okay, we have at least one ~0 value, check to see if the rest match or are
174 // undefs. Even with the above element type twiddling, this should be OK, as
175 // the same type legalization should have applied to all the elements.
176 for (++i; i != e; ++i)
177 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
182 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
183 // Look through a bit convert.
184 while (N->getOpcode() == ISD::BITCAST)
185 N = N->getOperand(0).getNode();
187 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
189 bool IsAllUndef = true;
190 for (const SDValue &Op : N->op_values()) {
194 // Do not accept build_vectors that aren't all constants or which have non-0
195 // elements. We have to be a bit careful here, as the type of the constant
196 // may not be the same as the type of the vector elements due to type
197 // legalization (the elements are promoted to a legal type for the target
198 // and a vector of a type may be legal when the base element type is not).
199 // We only want to check enough bits to cover the vector elements, because
200 // we care if the resultant vector is all zeros, not whether the individual
202 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
203 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
204 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
206 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
207 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
213 // Do not accept an all-undef vector.
219 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
220 if (N->getOpcode() != ISD::BUILD_VECTOR)
223 for (const SDValue &Op : N->op_values()) {
226 if (!isa<ConstantSDNode>(Op))
232 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
233 if (N->getOpcode() != ISD::BUILD_VECTOR)
236 for (const SDValue &Op : N->op_values()) {
239 if (!isa<ConstantFPSDNode>(Op))
245 bool ISD::allOperandsUndef(const SDNode *N) {
246 // Return false if the node has no operands.
247 // This is "logically inconsistent" with the definition of "all" but
248 // is probably the desired behavior.
249 if (N->getNumOperands() == 0)
252 for (const SDValue &Op : N->op_values())
259 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
262 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
264 return ISD::SIGN_EXTEND;
266 return ISD::ZERO_EXTEND;
271 llvm_unreachable("Invalid LoadExtType");
274 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
275 // To perform this operation, we just need to swap the L and G bits of the
277 unsigned OldL = (Operation >> 2) & 1;
278 unsigned OldG = (Operation >> 1) & 1;
279 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
280 (OldL << 1) | // New G bit
281 (OldG << 2)); // New L bit.
284 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
285 unsigned Operation = Op;
287 Operation ^= 7; // Flip L, G, E bits, but not U.
289 Operation ^= 15; // Flip all of the condition bits.
291 if (Operation > ISD::SETTRUE2)
292 Operation &= ~8; // Don't let N and U bits get set.
294 return ISD::CondCode(Operation);
297 /// For an integer comparison, return 1 if the comparison is a signed operation
298 /// and 2 if the result is an unsigned comparison. Return zero if the operation
299 /// does not depend on the sign of the input (setne and seteq).
300 static int isSignedOp(ISD::CondCode Opcode) {
302 default: llvm_unreachable("Illegal integer setcc operation!");
304 case ISD::SETNE: return 0;
308 case ISD::SETGE: return 1;
312 case ISD::SETUGE: return 2;
316 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
318 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
319 // Cannot fold a signed integer setcc with an unsigned integer setcc.
320 return ISD::SETCC_INVALID;
322 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
324 // If the N and U bits get set, then the resultant comparison DOES suddenly
325 // care about orderedness, and it is true when ordered.
326 if (Op > ISD::SETTRUE2)
327 Op &= ~16; // Clear the U bit if the N bit is set.
329 // Canonicalize illegal integer setcc's.
330 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
333 return ISD::CondCode(Op);
336 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
338 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
339 // Cannot fold a signed setcc with an unsigned setcc.
340 return ISD::SETCC_INVALID;
342 // Combine all of the condition bits.
343 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
345 // Canonicalize illegal integer setcc's.
349 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
350 case ISD::SETOEQ: // SETEQ & SETU[LG]E
351 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
352 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
353 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
360 //===----------------------------------------------------------------------===//
361 // SDNode Profile Support
362 //===----------------------------------------------------------------------===//
364 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
365 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
369 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
370 /// solely with their pointer.
371 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
372 ID.AddPointer(VTList.VTs);
375 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
376 static void AddNodeIDOperands(FoldingSetNodeID &ID,
377 ArrayRef<SDValue> Ops) {
378 for (auto& Op : Ops) {
379 ID.AddPointer(Op.getNode());
380 ID.AddInteger(Op.getResNo());
384 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
385 static void AddNodeIDOperands(FoldingSetNodeID &ID,
386 ArrayRef<SDUse> Ops) {
387 for (auto& Op : Ops) {
388 ID.AddPointer(Op.getNode());
389 ID.AddInteger(Op.getResNo());
393 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
394 SDVTList VTList, ArrayRef<SDValue> OpList) {
395 AddNodeIDOpcode(ID, OpC);
396 AddNodeIDValueTypes(ID, VTList);
397 AddNodeIDOperands(ID, OpList);
400 /// If this is an SDNode with special info, add this info to the NodeID data.
401 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
402 switch (N->getOpcode()) {
403 case ISD::TargetExternalSymbol:
404 case ISD::ExternalSymbol:
406 llvm_unreachable("Should only be used on nodes with operands");
407 default: break; // Normal nodes don't need extra info.
408 case ISD::TargetConstant:
409 case ISD::Constant: {
410 const ConstantSDNode *C = cast<ConstantSDNode>(N);
411 ID.AddPointer(C->getConstantIntValue());
412 ID.AddBoolean(C->isOpaque());
415 case ISD::TargetConstantFP:
416 case ISD::ConstantFP:
417 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
419 case ISD::TargetGlobalAddress:
420 case ISD::GlobalAddress:
421 case ISD::TargetGlobalTLSAddress:
422 case ISD::GlobalTLSAddress: {
423 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
424 ID.AddPointer(GA->getGlobal());
425 ID.AddInteger(GA->getOffset());
426 ID.AddInteger(GA->getTargetFlags());
429 case ISD::BasicBlock:
430 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
433 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
435 case ISD::RegisterMask:
436 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
439 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
441 case ISD::FrameIndex:
442 case ISD::TargetFrameIndex:
443 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
446 case ISD::TargetJumpTable:
447 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
448 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
450 case ISD::ConstantPool:
451 case ISD::TargetConstantPool: {
452 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
453 ID.AddInteger(CP->getAlignment());
454 ID.AddInteger(CP->getOffset());
455 if (CP->isMachineConstantPoolEntry())
456 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
458 ID.AddPointer(CP->getConstVal());
459 ID.AddInteger(CP->getTargetFlags());
462 case ISD::TargetIndex: {
463 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
464 ID.AddInteger(TI->getIndex());
465 ID.AddInteger(TI->getOffset());
466 ID.AddInteger(TI->getTargetFlags());
470 const LoadSDNode *LD = cast<LoadSDNode>(N);
471 ID.AddInteger(LD->getMemoryVT().getRawBits());
472 ID.AddInteger(LD->getRawSubclassData());
473 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
477 const StoreSDNode *ST = cast<StoreSDNode>(N);
478 ID.AddInteger(ST->getMemoryVT().getRawBits());
479 ID.AddInteger(ST->getRawSubclassData());
480 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
483 case ISD::ATOMIC_CMP_SWAP:
484 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
485 case ISD::ATOMIC_SWAP:
486 case ISD::ATOMIC_LOAD_ADD:
487 case ISD::ATOMIC_LOAD_SUB:
488 case ISD::ATOMIC_LOAD_AND:
489 case ISD::ATOMIC_LOAD_OR:
490 case ISD::ATOMIC_LOAD_XOR:
491 case ISD::ATOMIC_LOAD_NAND:
492 case ISD::ATOMIC_LOAD_MIN:
493 case ISD::ATOMIC_LOAD_MAX:
494 case ISD::ATOMIC_LOAD_UMIN:
495 case ISD::ATOMIC_LOAD_UMAX:
496 case ISD::ATOMIC_LOAD:
497 case ISD::ATOMIC_STORE: {
498 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
499 ID.AddInteger(AT->getMemoryVT().getRawBits());
500 ID.AddInteger(AT->getRawSubclassData());
501 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
504 case ISD::PREFETCH: {
505 const MemSDNode *PF = cast<MemSDNode>(N);
506 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
509 case ISD::VECTOR_SHUFFLE: {
510 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
511 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
513 ID.AddInteger(SVN->getMaskElt(i));
516 case ISD::TargetBlockAddress:
517 case ISD::BlockAddress: {
518 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
519 ID.AddPointer(BA->getBlockAddress());
520 ID.AddInteger(BA->getOffset());
521 ID.AddInteger(BA->getTargetFlags());
524 } // end switch (N->getOpcode())
526 // Target specific memory nodes could also have address spaces to check.
527 if (N->isTargetMemoryOpcode())
528 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
531 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
533 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
534 AddNodeIDOpcode(ID, N->getOpcode());
535 // Add the return value info.
536 AddNodeIDValueTypes(ID, N->getVTList());
537 // Add the operand info.
538 AddNodeIDOperands(ID, N->ops());
540 // Handle SDNode leafs with special info.
541 AddNodeIDCustom(ID, N);
544 //===----------------------------------------------------------------------===//
545 // SelectionDAG Class
546 //===----------------------------------------------------------------------===//
548 /// doNotCSE - Return true if CSE should not be performed for this node.
549 static bool doNotCSE(SDNode *N) {
550 if (N->getValueType(0) == MVT::Glue)
551 return true; // Never CSE anything that produces a flag.
553 switch (N->getOpcode()) {
555 case ISD::HANDLENODE:
557 return true; // Never CSE these nodes.
560 // Check that remaining values produced are not flags.
561 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
562 if (N->getValueType(i) == MVT::Glue)
563 return true; // Never CSE anything that produces a flag.
568 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
570 void SelectionDAG::RemoveDeadNodes() {
571 // Create a dummy node (which is not added to allnodes), that adds a reference
572 // to the root node, preventing it from being deleted.
573 HandleSDNode Dummy(getRoot());
575 SmallVector<SDNode*, 128> DeadNodes;
577 // Add all obviously-dead nodes to the DeadNodes worklist.
578 for (SDNode &Node : allnodes())
579 if (Node.use_empty())
580 DeadNodes.push_back(&Node);
582 RemoveDeadNodes(DeadNodes);
584 // If the root changed (e.g. it was a dead load, update the root).
585 setRoot(Dummy.getValue());
588 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
589 /// given list, and any nodes that become unreachable as a result.
590 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
592 // Process the worklist, deleting the nodes and adding their uses to the
594 while (!DeadNodes.empty()) {
595 SDNode *N = DeadNodes.pop_back_val();
596 // Skip to next node if we've already managed to delete the node. This could
597 // happen if replacing a node causes a node previously added to the node to
599 if (N->getOpcode() == ISD::DELETED_NODE)
602 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
603 DUL->NodeDeleted(N, nullptr);
605 // Take the node out of the appropriate CSE map.
606 RemoveNodeFromCSEMaps(N);
608 // Next, brutally remove the operand list. This is safe to do, as there are
609 // no cycles in the graph.
610 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
612 SDNode *Operand = Use.getNode();
615 // Now that we removed this operand, see if there are no uses of it left.
616 if (Operand->use_empty())
617 DeadNodes.push_back(Operand);
624 void SelectionDAG::RemoveDeadNode(SDNode *N){
625 SmallVector<SDNode*, 16> DeadNodes(1, N);
627 // Create a dummy node that adds a reference to the root node, preventing
628 // it from being deleted. (This matters if the root is an operand of the
630 HandleSDNode Dummy(getRoot());
632 RemoveDeadNodes(DeadNodes);
635 void SelectionDAG::DeleteNode(SDNode *N) {
636 // First take this out of the appropriate CSE map.
637 RemoveNodeFromCSEMaps(N);
639 // Finally, remove uses due to operands of this node, remove from the
640 // AllNodes list, and delete the node.
641 DeleteNodeNotInCSEMaps(N);
644 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
645 assert(N->getIterator() != AllNodes.begin() &&
646 "Cannot delete the entry node!");
647 assert(N->use_empty() && "Cannot delete a node that is not dead!");
649 // Drop all of the operands and decrement used node's use counts.
655 void SDDbgInfo::erase(const SDNode *Node) {
656 DbgValMapType::iterator I = DbgValMap.find(Node);
657 if (I == DbgValMap.end())
659 for (auto &Val: I->second)
660 Val->setIsInvalidated();
664 void SelectionDAG::DeallocateNode(SDNode *N) {
665 // If we have operands, deallocate them.
668 NodeAllocator.Deallocate(AllNodes.remove(N));
670 // Set the opcode to DELETED_NODE to help catch bugs when node
671 // memory is reallocated.
672 // FIXME: There are places in SDag that have grown a dependency on the opcode
673 // value in the released node.
674 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
675 N->NodeType = ISD::DELETED_NODE;
677 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
678 // them and forget about that node.
683 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
684 static void VerifySDNode(SDNode *N) {
685 switch (N->getOpcode()) {
688 case ISD::BUILD_PAIR: {
689 EVT VT = N->getValueType(0);
690 assert(N->getNumValues() == 1 && "Too many results!");
691 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
692 "Wrong return type!");
693 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
694 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
695 "Mismatched operand types!");
696 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
697 "Wrong operand type!");
698 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
699 "Wrong return type size");
702 case ISD::BUILD_VECTOR: {
703 assert(N->getNumValues() == 1 && "Too many results!");
704 assert(N->getValueType(0).isVector() && "Wrong return type!");
705 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
706 "Wrong number of operands!");
707 EVT EltVT = N->getValueType(0).getVectorElementType();
708 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
709 assert((I->getValueType() == EltVT ||
710 (EltVT.isInteger() && I->getValueType().isInteger() &&
711 EltVT.bitsLE(I->getValueType()))) &&
712 "Wrong operand type!");
713 assert(I->getValueType() == N->getOperand(0).getValueType() &&
714 "Operands must all have the same type");
722 /// \brief Insert a newly allocated node into the DAG.
724 /// Handles insertion into the all nodes list and CSE map, as well as
725 /// verification and other common operations when a new node is allocated.
726 void SelectionDAG::InsertNode(SDNode *N) {
727 AllNodes.push_back(N);
729 N->PersistentId = NextPersistentId++;
734 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
735 /// correspond to it. This is useful when we're about to delete or repurpose
736 /// the node. We don't want future request for structurally identical nodes
737 /// to return N anymore.
738 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
740 switch (N->getOpcode()) {
741 case ISD::HANDLENODE: return false; // noop.
743 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
744 "Cond code doesn't exist!");
745 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
746 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
748 case ISD::ExternalSymbol:
749 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
751 case ISD::TargetExternalSymbol: {
752 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
753 Erased = TargetExternalSymbols.erase(
754 std::pair<std::string,unsigned char>(ESN->getSymbol(),
755 ESN->getTargetFlags()));
758 case ISD::MCSymbol: {
759 auto *MCSN = cast<MCSymbolSDNode>(N);
760 Erased = MCSymbols.erase(MCSN->getMCSymbol());
763 case ISD::VALUETYPE: {
764 EVT VT = cast<VTSDNode>(N)->getVT();
765 if (VT.isExtended()) {
766 Erased = ExtendedValueTypeNodes.erase(VT);
768 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
769 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
774 // Remove it from the CSE Map.
775 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
776 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
777 Erased = CSEMap.RemoveNode(N);
781 // Verify that the node was actually in one of the CSE maps, unless it has a
782 // flag result (which cannot be CSE'd) or is one of the special cases that are
783 // not subject to CSE.
784 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
785 !N->isMachineOpcode() && !doNotCSE(N)) {
788 llvm_unreachable("Node is not in map!");
794 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
795 /// maps and modified in place. Add it back to the CSE maps, unless an identical
796 /// node already exists, in which case transfer all its users to the existing
797 /// node. This transfer can potentially trigger recursive merging.
799 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
800 // For node types that aren't CSE'd, just act as if no identical node
803 SDNode *Existing = CSEMap.GetOrInsertNode(N);
805 // If there was already an existing matching node, use ReplaceAllUsesWith
806 // to replace the dead one with the existing one. This can cause
807 // recursive merging of other unrelated nodes down the line.
808 ReplaceAllUsesWith(N, Existing);
810 // N is now dead. Inform the listeners and delete it.
811 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
812 DUL->NodeDeleted(N, Existing);
813 DeleteNodeNotInCSEMaps(N);
818 // If the node doesn't already exist, we updated it. Inform listeners.
819 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
823 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
824 /// were replaced with those specified. If this node is never memoized,
825 /// return null, otherwise return a pointer to the slot it would take. If a
826 /// node already exists with these operands, the slot will be non-null.
827 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
832 SDValue Ops[] = { Op };
834 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
835 AddNodeIDCustom(ID, N);
836 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
838 Node->intersectFlagsWith(N->getFlags());
842 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
843 /// were replaced with those specified. If this node is never memoized,
844 /// return null, otherwise return a pointer to the slot it would take. If a
845 /// node already exists with these operands, the slot will be non-null.
846 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
847 SDValue Op1, SDValue Op2,
852 SDValue Ops[] = { Op1, Op2 };
854 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
855 AddNodeIDCustom(ID, N);
856 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
858 Node->intersectFlagsWith(N->getFlags());
862 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
863 /// were replaced with those specified. If this node is never memoized,
864 /// return null, otherwise return a pointer to the slot it would take. If a
865 /// node already exists with these operands, the slot will be non-null.
866 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
872 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
873 AddNodeIDCustom(ID, N);
874 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
876 Node->intersectFlagsWith(N->getFlags());
880 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
881 Type *Ty = VT == MVT::iPTR ?
882 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
883 VT.getTypeForEVT(*getContext());
885 return getDataLayout().getABITypeAlignment(Ty);
888 // EntryNode could meaningfully have debug info if we can find it...
889 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
890 : TM(tm), OptLevel(OL),
891 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
892 Root(getEntryNode()) {
893 InsertNode(&EntryNode);
894 DbgInfo = new SDDbgInfo();
897 void SelectionDAG::init(MachineFunction &NewMF,
898 OptimizationRemarkEmitter &NewORE) {
901 TLI = getSubtarget().getTargetLowering();
902 TSI = getSubtarget().getSelectionDAGInfo();
903 Context = &MF->getFunction()->getContext();
906 SelectionDAG::~SelectionDAG() {
907 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
909 OperandRecycler.clear(OperandAllocator);
913 void SelectionDAG::allnodes_clear() {
914 assert(&*AllNodes.begin() == &EntryNode);
915 AllNodes.remove(AllNodes.begin());
916 while (!AllNodes.empty())
917 DeallocateNode(&AllNodes.front());
919 NextPersistentId = 0;
923 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
925 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
927 switch (N->getOpcode()) {
930 case ISD::ConstantFP:
931 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
932 "debug location. Use another overload.");
938 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
939 const SDLoc &DL, void *&InsertPos) {
940 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
942 switch (N->getOpcode()) {
944 case ISD::ConstantFP:
945 // Erase debug location from the node if the node is used at several
946 // different places. Do not propagate one location to all uses as it
947 // will cause a worse single stepping debugging experience.
948 if (N->getDebugLoc() != DL.getDebugLoc())
949 N->setDebugLoc(DebugLoc());
952 // When the node's point of use is located earlier in the instruction
953 // sequence than its prior point of use, update its debug info to the
955 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
956 N->setDebugLoc(DL.getDebugLoc());
963 void SelectionDAG::clear() {
965 OperandRecycler.clear(OperandAllocator);
966 OperandAllocator.Reset();
969 ExtendedValueTypeNodes.clear();
970 ExternalSymbols.clear();
971 TargetExternalSymbols.clear();
973 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
974 static_cast<CondCodeSDNode*>(nullptr));
975 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
976 static_cast<SDNode*>(nullptr));
978 EntryNode.UseList = nullptr;
979 InsertNode(&EntryNode);
980 Root = getEntryNode();
984 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
985 return VT.bitsGT(Op.getValueType())
986 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
987 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
990 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
991 return VT.bitsGT(Op.getValueType()) ?
992 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
993 getNode(ISD::TRUNCATE, DL, VT, Op);
996 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
997 return VT.bitsGT(Op.getValueType()) ?
998 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
999 getNode(ISD::TRUNCATE, DL, VT, Op);
1002 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1003 return VT.bitsGT(Op.getValueType()) ?
1004 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1005 getNode(ISD::TRUNCATE, DL, VT, Op);
1008 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1010 if (VT.bitsLE(Op.getValueType()))
1011 return getNode(ISD::TRUNCATE, SL, VT, Op);
1013 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1014 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1017 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1018 assert(!VT.isVector() &&
1019 "getZeroExtendInReg should use the vector element type instead of "
1020 "the vector type!");
1021 if (Op.getValueType() == VT) return Op;
1022 unsigned BitWidth = Op.getScalarValueSizeInBits();
1023 APInt Imm = APInt::getLowBitsSet(BitWidth,
1024 VT.getSizeInBits());
1025 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1026 getConstant(Imm, DL, Op.getValueType()));
1029 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1031 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1032 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1033 "The sizes of the input and result must match in order to perform the "
1034 "extend in-register.");
1035 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1036 "The destination vector type must have fewer lanes than the input.");
1037 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1040 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1042 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1043 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1044 "The sizes of the input and result must match in order to perform the "
1045 "extend in-register.");
1046 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1047 "The destination vector type must have fewer lanes than the input.");
1048 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1051 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1053 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1054 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1055 "The sizes of the input and result must match in order to perform the "
1056 "extend in-register.");
1057 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1058 "The destination vector type must have fewer lanes than the input.");
1059 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1062 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1063 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1064 EVT EltVT = VT.getScalarType();
1066 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1067 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1070 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1071 EVT EltVT = VT.getScalarType();
1073 switch (TLI->getBooleanContents(VT)) {
1074 case TargetLowering::ZeroOrOneBooleanContent:
1075 case TargetLowering::UndefinedBooleanContent:
1076 TrueValue = getConstant(1, DL, VT);
1078 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1079 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1083 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1086 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1087 bool isT, bool isO) {
1088 EVT EltVT = VT.getScalarType();
1089 assert((EltVT.getSizeInBits() >= 64 ||
1090 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1091 "getConstant with a uint64_t value that doesn't fit in the type!");
1092 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1095 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1096 bool isT, bool isO) {
1097 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1100 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1101 EVT VT, bool isT, bool isO) {
1102 assert(VT.isInteger() && "Cannot create FP integer constant!");
1104 EVT EltVT = VT.getScalarType();
1105 const ConstantInt *Elt = &Val;
1107 // In some cases the vector type is legal but the element type is illegal and
1108 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1109 // inserted value (the type does not need to match the vector element type).
1110 // Any extra bits introduced will be truncated away.
1111 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1112 TargetLowering::TypePromoteInteger) {
1113 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1114 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1115 Elt = ConstantInt::get(*getContext(), NewVal);
1117 // In other cases the element type is illegal and needs to be expanded, for
1118 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1119 // the value into n parts and use a vector type with n-times the elements.
1120 // Then bitcast to the type requested.
1121 // Legalizing constants too early makes the DAGCombiner's job harder so we
1122 // only legalize if the DAG tells us we must produce legal types.
1123 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1124 TLI->getTypeAction(*getContext(), EltVT) ==
1125 TargetLowering::TypeExpandInteger) {
1126 const APInt &NewVal = Elt->getValue();
1127 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1128 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1129 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1130 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1132 // Check the temporary vector is the correct size. If this fails then
1133 // getTypeToTransformTo() probably returned a type whose size (in bits)
1134 // isn't a power-of-2 factor of the requested type size.
1135 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1137 SmallVector<SDValue, 2> EltParts;
1138 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1139 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1140 .zextOrTrunc(ViaEltSizeInBits), DL,
1141 ViaEltVT, isT, isO));
1144 // EltParts is currently in little endian order. If we actually want
1145 // big-endian order then reverse it now.
1146 if (getDataLayout().isBigEndian())
1147 std::reverse(EltParts.begin(), EltParts.end());
1149 // The elements must be reversed when the element order is different
1150 // to the endianness of the elements (because the BITCAST is itself a
1151 // vector shuffle in this situation). However, we do not need any code to
1152 // perform this reversal because getConstant() is producing a vector
1154 // This situation occurs in MIPS MSA.
1156 SmallVector<SDValue, 8> Ops;
1157 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1158 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1159 return getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1162 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1163 "APInt size does not match type size!");
1164 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1165 FoldingSetNodeID ID;
1166 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1170 SDNode *N = nullptr;
1171 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1173 return SDValue(N, 0);
1176 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1177 CSEMap.InsertNode(N, IP);
1181 SDValue Result(N, 0);
1183 Result = getSplatBuildVector(VT, DL, Result);
1187 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1189 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1192 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1194 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1197 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1198 EVT VT, bool isTarget) {
1199 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1201 EVT EltVT = VT.getScalarType();
1203 // Do the map lookup using the actual bit pattern for the floating point
1204 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1205 // we don't have issues with SNANs.
1206 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1207 FoldingSetNodeID ID;
1208 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1211 SDNode *N = nullptr;
1212 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1214 return SDValue(N, 0);
1217 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1218 CSEMap.InsertNode(N, IP);
1222 SDValue Result(N, 0);
1224 Result = getSplatBuildVector(VT, DL, Result);
1228 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1230 EVT EltVT = VT.getScalarType();
1231 if (EltVT == MVT::f32)
1232 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1233 else if (EltVT == MVT::f64)
1234 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1235 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1236 EltVT == MVT::f16) {
1238 APFloat APF = APFloat(Val);
1239 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1241 return getConstantFP(APF, DL, VT, isTarget);
1243 llvm_unreachable("Unsupported type in getConstantFP");
1246 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1247 EVT VT, int64_t Offset, bool isTargetGA,
1248 unsigned char TargetFlags) {
1249 assert((TargetFlags == 0 || isTargetGA) &&
1250 "Cannot set target flags on target-independent globals");
1252 // Truncate (with sign-extension) the offset value to the pointer size.
1253 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1255 Offset = SignExtend64(Offset, BitWidth);
1258 if (GV->isThreadLocal())
1259 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1261 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1263 FoldingSetNodeID ID;
1264 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1266 ID.AddInteger(Offset);
1267 ID.AddInteger(TargetFlags);
1269 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1270 return SDValue(E, 0);
1272 auto *N = newSDNode<GlobalAddressSDNode>(
1273 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1274 CSEMap.InsertNode(N, IP);
1276 return SDValue(N, 0);
1279 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1280 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1281 FoldingSetNodeID ID;
1282 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1285 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1286 return SDValue(E, 0);
1288 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1289 CSEMap.InsertNode(N, IP);
1291 return SDValue(N, 0);
1294 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1295 unsigned char TargetFlags) {
1296 assert((TargetFlags == 0 || isTarget) &&
1297 "Cannot set target flags on target-independent jump tables");
1298 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1299 FoldingSetNodeID ID;
1300 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1302 ID.AddInteger(TargetFlags);
1304 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1305 return SDValue(E, 0);
1307 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1308 CSEMap.InsertNode(N, IP);
1310 return SDValue(N, 0);
1313 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1314 unsigned Alignment, int Offset,
1316 unsigned char TargetFlags) {
1317 assert((TargetFlags == 0 || isTarget) &&
1318 "Cannot set target flags on target-independent globals");
1320 Alignment = MF->getFunction()->optForSize()
1321 ? getDataLayout().getABITypeAlignment(C->getType())
1322 : getDataLayout().getPrefTypeAlignment(C->getType());
1323 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1324 FoldingSetNodeID ID;
1325 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1326 ID.AddInteger(Alignment);
1327 ID.AddInteger(Offset);
1329 ID.AddInteger(TargetFlags);
1331 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1332 return SDValue(E, 0);
1334 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1336 CSEMap.InsertNode(N, IP);
1338 return SDValue(N, 0);
1341 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1342 unsigned Alignment, int Offset,
1344 unsigned char TargetFlags) {
1345 assert((TargetFlags == 0 || isTarget) &&
1346 "Cannot set target flags on target-independent globals");
1348 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1349 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1350 FoldingSetNodeID ID;
1351 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1352 ID.AddInteger(Alignment);
1353 ID.AddInteger(Offset);
1354 C->addSelectionDAGCSEId(ID);
1355 ID.AddInteger(TargetFlags);
1357 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1358 return SDValue(E, 0);
1360 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1362 CSEMap.InsertNode(N, IP);
1364 return SDValue(N, 0);
1367 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1368 unsigned char TargetFlags) {
1369 FoldingSetNodeID ID;
1370 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1371 ID.AddInteger(Index);
1372 ID.AddInteger(Offset);
1373 ID.AddInteger(TargetFlags);
1375 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1376 return SDValue(E, 0);
1378 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1379 CSEMap.InsertNode(N, IP);
1381 return SDValue(N, 0);
1384 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1385 FoldingSetNodeID ID;
1386 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1389 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1390 return SDValue(E, 0);
1392 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1393 CSEMap.InsertNode(N, IP);
1395 return SDValue(N, 0);
1398 SDValue SelectionDAG::getValueType(EVT VT) {
1399 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1400 ValueTypeNodes.size())
1401 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1403 SDNode *&N = VT.isExtended() ?
1404 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1406 if (N) return SDValue(N, 0);
1407 N = newSDNode<VTSDNode>(VT);
1409 return SDValue(N, 0);
1412 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1413 SDNode *&N = ExternalSymbols[Sym];
1414 if (N) return SDValue(N, 0);
1415 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1417 return SDValue(N, 0);
1420 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1421 SDNode *&N = MCSymbols[Sym];
1423 return SDValue(N, 0);
1424 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1426 return SDValue(N, 0);
1429 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1430 unsigned char TargetFlags) {
1432 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1434 if (N) return SDValue(N, 0);
1435 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1437 return SDValue(N, 0);
1440 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1441 if ((unsigned)Cond >= CondCodeNodes.size())
1442 CondCodeNodes.resize(Cond+1);
1444 if (!CondCodeNodes[Cond]) {
1445 auto *N = newSDNode<CondCodeSDNode>(Cond);
1446 CondCodeNodes[Cond] = N;
1450 return SDValue(CondCodeNodes[Cond], 0);
1453 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1454 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1455 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1457 ShuffleVectorSDNode::commuteMask(M);
1460 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1461 SDValue N2, ArrayRef<int> Mask) {
1462 assert(VT.getVectorNumElements() == Mask.size() &&
1463 "Must have the same number of vector elements as mask elements!");
1464 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1465 "Invalid VECTOR_SHUFFLE");
1467 // Canonicalize shuffle undef, undef -> undef
1468 if (N1.isUndef() && N2.isUndef())
1469 return getUNDEF(VT);
1471 // Validate that all indices in Mask are within the range of the elements
1472 // input to the shuffle.
1473 int NElts = Mask.size();
1474 assert(llvm::all_of(Mask, [&](int M) { return M < (NElts * 2); }) &&
1475 "Index out of range");
1477 // Copy the mask so we can do any needed cleanup.
1478 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1480 // Canonicalize shuffle v, v -> v, undef
1483 for (int i = 0; i != NElts; ++i)
1484 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1487 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1489 commuteShuffle(N1, N2, MaskVec);
1491 // If shuffling a splat, try to blend the splat instead. We do this here so
1492 // that even when this arises during lowering we don't have to re-handle it.
1493 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1494 BitVector UndefElements;
1495 SDValue Splat = BV->getSplatValue(&UndefElements);
1499 for (int i = 0; i < NElts; ++i) {
1500 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1503 // If this input comes from undef, mark it as such.
1504 if (UndefElements[MaskVec[i] - Offset]) {
1509 // If we can blend a non-undef lane, use that instead.
1510 if (!UndefElements[i])
1511 MaskVec[i] = i + Offset;
1514 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1515 BlendSplat(N1BV, 0);
1516 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1517 BlendSplat(N2BV, NElts);
1519 // Canonicalize all index into lhs, -> shuffle lhs, undef
1520 // Canonicalize all index into rhs, -> shuffle rhs, undef
1521 bool AllLHS = true, AllRHS = true;
1522 bool N2Undef = N2.isUndef();
1523 for (int i = 0; i != NElts; ++i) {
1524 if (MaskVec[i] >= NElts) {
1529 } else if (MaskVec[i] >= 0) {
1533 if (AllLHS && AllRHS)
1534 return getUNDEF(VT);
1535 if (AllLHS && !N2Undef)
1539 commuteShuffle(N1, N2, MaskVec);
1541 // Reset our undef status after accounting for the mask.
1542 N2Undef = N2.isUndef();
1543 // Re-check whether both sides ended up undef.
1544 if (N1.isUndef() && N2Undef)
1545 return getUNDEF(VT);
1547 // If Identity shuffle return that node.
1548 bool Identity = true, AllSame = true;
1549 for (int i = 0; i != NElts; ++i) {
1550 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1551 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1553 if (Identity && NElts)
1556 // Shuffling a constant splat doesn't change the result.
1560 // Look through any bitcasts. We check that these don't change the number
1561 // (and size) of elements and just changes their types.
1562 while (V.getOpcode() == ISD::BITCAST)
1563 V = V->getOperand(0);
1565 // A splat should always show up as a build vector node.
1566 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1567 BitVector UndefElements;
1568 SDValue Splat = BV->getSplatValue(&UndefElements);
1569 // If this is a splat of an undef, shuffling it is also undef.
1570 if (Splat && Splat.isUndef())
1571 return getUNDEF(VT);
1574 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1576 // We only have a splat which can skip shuffles if there is a splatted
1577 // value and no undef lanes rearranged by the shuffle.
1578 if (Splat && UndefElements.none()) {
1579 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1580 // number of elements match or the value splatted is a zero constant.
1583 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1584 if (C->isNullValue())
1588 // If the shuffle itself creates a splat, build the vector directly.
1589 if (AllSame && SameNumElts) {
1590 EVT BuildVT = BV->getValueType(0);
1591 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1592 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1594 // We may have jumped through bitcasts, so the type of the
1595 // BUILD_VECTOR may not match the type of the shuffle.
1597 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1603 FoldingSetNodeID ID;
1604 SDValue Ops[2] = { N1, N2 };
1605 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1606 for (int i = 0; i != NElts; ++i)
1607 ID.AddInteger(MaskVec[i]);
1610 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1611 return SDValue(E, 0);
1613 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1614 // SDNode doesn't have access to it. This memory will be "leaked" when
1615 // the node is deallocated, but recovered when the NodeAllocator is released.
1616 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1617 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1619 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1620 dl.getDebugLoc(), MaskAlloc);
1621 createOperands(N, Ops);
1623 CSEMap.InsertNode(N, IP);
1625 return SDValue(N, 0);
1628 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1629 MVT VT = SV.getSimpleValueType(0);
1630 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1631 ShuffleVectorSDNode::commuteMask(MaskVec);
1633 SDValue Op0 = SV.getOperand(0);
1634 SDValue Op1 = SV.getOperand(1);
1635 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1638 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1639 FoldingSetNodeID ID;
1640 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1641 ID.AddInteger(RegNo);
1643 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1644 return SDValue(E, 0);
1646 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1647 CSEMap.InsertNode(N, IP);
1649 return SDValue(N, 0);
1652 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1653 FoldingSetNodeID ID;
1654 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1655 ID.AddPointer(RegMask);
1657 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1658 return SDValue(E, 0);
1660 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1661 CSEMap.InsertNode(N, IP);
1663 return SDValue(N, 0);
1666 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1668 FoldingSetNodeID ID;
1669 SDValue Ops[] = { Root };
1670 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1671 ID.AddPointer(Label);
1673 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1674 return SDValue(E, 0);
1676 auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1677 createOperands(N, Ops);
1679 CSEMap.InsertNode(N, IP);
1681 return SDValue(N, 0);
1684 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1687 unsigned char TargetFlags) {
1688 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1690 FoldingSetNodeID ID;
1691 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1693 ID.AddInteger(Offset);
1694 ID.AddInteger(TargetFlags);
1696 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1697 return SDValue(E, 0);
1699 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1700 CSEMap.InsertNode(N, IP);
1702 return SDValue(N, 0);
1705 SDValue SelectionDAG::getSrcValue(const Value *V) {
1706 assert((!V || V->getType()->isPointerTy()) &&
1707 "SrcValue is not a pointer?");
1709 FoldingSetNodeID ID;
1710 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1714 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1715 return SDValue(E, 0);
1717 auto *N = newSDNode<SrcValueSDNode>(V);
1718 CSEMap.InsertNode(N, IP);
1720 return SDValue(N, 0);
1723 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1724 FoldingSetNodeID ID;
1725 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1729 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1730 return SDValue(E, 0);
1732 auto *N = newSDNode<MDNodeSDNode>(MD);
1733 CSEMap.InsertNode(N, IP);
1735 return SDValue(N, 0);
1738 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1739 if (VT == V.getValueType())
1742 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1745 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1746 unsigned SrcAS, unsigned DestAS) {
1747 SDValue Ops[] = {Ptr};
1748 FoldingSetNodeID ID;
1749 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1750 ID.AddInteger(SrcAS);
1751 ID.AddInteger(DestAS);
1754 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1755 return SDValue(E, 0);
1757 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1759 createOperands(N, Ops);
1761 CSEMap.InsertNode(N, IP);
1763 return SDValue(N, 0);
1766 /// getShiftAmountOperand - Return the specified value casted to
1767 /// the target's desired shift amount type.
1768 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1769 EVT OpTy = Op.getValueType();
1770 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1771 if (OpTy == ShTy || OpTy.isVector()) return Op;
1773 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1776 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1778 const TargetLowering &TLI = getTargetLoweringInfo();
1779 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1780 EVT VT = Node->getValueType(0);
1781 SDValue Tmp1 = Node->getOperand(0);
1782 SDValue Tmp2 = Node->getOperand(1);
1783 unsigned Align = Node->getConstantOperandVal(3);
1785 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1786 Tmp2, MachinePointerInfo(V));
1787 SDValue VAList = VAListLoad;
1789 if (Align > TLI.getMinStackArgumentAlignment()) {
1790 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1792 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1793 getConstant(Align - 1, dl, VAList.getValueType()));
1795 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1796 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1799 // Increment the pointer, VAList, to the next vaarg
1800 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1801 getConstant(getDataLayout().getTypeAllocSize(
1802 VT.getTypeForEVT(*getContext())),
1803 dl, VAList.getValueType()));
1804 // Store the incremented VAList to the legalized pointer
1806 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1807 // Load the actual argument out of the pointer VAList
1808 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1811 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1813 const TargetLowering &TLI = getTargetLoweringInfo();
1814 // This defaults to loading a pointer from the input and storing it to the
1815 // output, returning the chain.
1816 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1817 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1819 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1820 Node->getOperand(2), MachinePointerInfo(VS));
1821 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1822 MachinePointerInfo(VD));
1825 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1826 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1827 unsigned ByteSize = VT.getStoreSize();
1828 Type *Ty = VT.getTypeForEVT(*getContext());
1829 unsigned StackAlign =
1830 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1832 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1833 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1836 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1837 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1838 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1839 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1840 const DataLayout &DL = getDataLayout();
1842 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1844 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1845 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1846 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1849 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1850 ISD::CondCode Cond, const SDLoc &dl) {
1851 // These setcc operations always fold.
1855 case ISD::SETFALSE2: return getConstant(0, dl, VT);
1857 case ISD::SETTRUE2: {
1858 TargetLowering::BooleanContent Cnt =
1859 TLI->getBooleanContents(N1->getValueType(0));
1861 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1875 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1879 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1880 const APInt &C2 = N2C->getAPIntValue();
1881 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1882 const APInt &C1 = N1C->getAPIntValue();
1885 default: llvm_unreachable("Unknown integer setcc!");
1886 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT);
1887 case ISD::SETNE: return getConstant(C1 != C2, dl, VT);
1888 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1889 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1890 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1891 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1892 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT);
1893 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT);
1894 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT);
1895 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT);
1899 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1900 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1901 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1904 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1905 return getUNDEF(VT);
1907 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1908 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1909 return getUNDEF(VT);
1911 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1912 R==APFloat::cmpLessThan, dl, VT);
1913 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1914 return getUNDEF(VT);
1916 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1917 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1918 return getUNDEF(VT);
1920 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1921 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1922 return getUNDEF(VT);
1924 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1925 R==APFloat::cmpEqual, dl, VT);
1926 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1927 return getUNDEF(VT);
1929 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1930 R==APFloat::cmpEqual, dl, VT);
1931 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1932 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT);
1933 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1934 R==APFloat::cmpEqual, dl, VT);
1935 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1936 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1937 R==APFloat::cmpLessThan, dl, VT);
1938 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1939 R==APFloat::cmpUnordered, dl, VT);
1940 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1941 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1944 // Ensure that the constant occurs on the RHS.
1945 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1946 MVT CompVT = N1.getValueType().getSimpleVT();
1947 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1950 return getSetCC(dl, VT, N2, N1, SwappedCond);
1954 // Could not fold it.
1958 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1959 /// use this predicate to simplify operations downstream.
1960 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1961 unsigned BitWidth = Op.getScalarValueSizeInBits();
1962 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
1965 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1966 /// this predicate to simplify operations downstream. Mask is known to be zero
1967 /// for bits that V cannot have.
1968 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1969 unsigned Depth) const {
1971 computeKnownBits(Op, Known, Depth);
1972 return Mask.isSubsetOf(Known.Zero);
1975 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
1976 /// is less than the element bit-width of the shift node, return it.
1977 static const APInt *getValidShiftAmountConstant(SDValue V) {
1978 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
1979 // Shifting more than the bitwidth is not valid.
1980 const APInt &ShAmt = SA->getAPIntValue();
1981 if (ShAmt.ult(V.getScalarValueSizeInBits()))
1987 /// Determine which bits of Op are known to be either zero or one and return
1988 /// them in Known. For vectors, the known bits are those that are shared by
1989 /// every vector element.
1990 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
1991 unsigned Depth) const {
1992 EVT VT = Op.getValueType();
1993 APInt DemandedElts = VT.isVector()
1994 ? APInt::getAllOnesValue(VT.getVectorNumElements())
1996 computeKnownBits(Op, Known, DemandedElts, Depth);
1999 /// Determine which bits of Op are known to be either zero or one and return
2000 /// them in Known. The DemandedElts argument allows us to only collect the known
2001 /// bits that are shared by the requested vector elements.
2002 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
2003 const APInt &DemandedElts,
2004 unsigned Depth) const {
2005 unsigned BitWidth = Op.getScalarValueSizeInBits();
2007 Known = KnownBits(BitWidth); // Don't know anything.
2009 return; // Limit search depth.
2012 unsigned NumElts = DemandedElts.getBitWidth();
2015 return; // No demanded elts, better to assume we don't know anything.
2017 unsigned Opcode = Op.getOpcode();
2020 // We know all of the bits for a constant!
2021 Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
2022 Known.Zero = ~Known.One;
2024 case ISD::BUILD_VECTOR:
2025 // Collect the known bits that are shared by every demanded vector element.
2026 assert(NumElts == Op.getValueType().getVectorNumElements() &&
2027 "Unexpected vector size");
2028 Known.Zero.setAllBits(); Known.One.setAllBits();
2029 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2030 if (!DemandedElts[i])
2033 SDValue SrcOp = Op.getOperand(i);
2034 computeKnownBits(SrcOp, Known2, Depth + 1);
2036 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2037 if (SrcOp.getValueSizeInBits() != BitWidth) {
2038 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2039 "Expected BUILD_VECTOR implicit truncation");
2040 Known2 = Known2.trunc(BitWidth);
2043 // Known bits are the values that are shared by every demanded element.
2044 Known.One &= Known2.One;
2045 Known.Zero &= Known2.Zero;
2047 // If we don't know any bits, early out.
2048 if (!Known.One && !Known.Zero)
2052 case ISD::VECTOR_SHUFFLE: {
2053 // Collect the known bits that are shared by every vector element referenced
2055 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2056 Known.Zero.setAllBits(); Known.One.setAllBits();
2057 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2058 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2059 for (unsigned i = 0; i != NumElts; ++i) {
2060 if (!DemandedElts[i])
2063 int M = SVN->getMaskElt(i);
2065 // For UNDEF elements, we don't know anything about the common state of
2066 // the shuffle result.
2068 DemandedLHS.clearAllBits();
2069 DemandedRHS.clearAllBits();
2073 if ((unsigned)M < NumElts)
2074 DemandedLHS.setBit((unsigned)M % NumElts);
2076 DemandedRHS.setBit((unsigned)M % NumElts);
2078 // Known bits are the values that are shared by every demanded element.
2079 if (!!DemandedLHS) {
2080 SDValue LHS = Op.getOperand(0);
2081 computeKnownBits(LHS, Known2, DemandedLHS, Depth + 1);
2082 Known.One &= Known2.One;
2083 Known.Zero &= Known2.Zero;
2085 // If we don't know any bits, early out.
2086 if (!Known.One && !Known.Zero)
2088 if (!!DemandedRHS) {
2089 SDValue RHS = Op.getOperand(1);
2090 computeKnownBits(RHS, Known2, DemandedRHS, Depth + 1);
2091 Known.One &= Known2.One;
2092 Known.Zero &= Known2.Zero;
2096 case ISD::CONCAT_VECTORS: {
2097 // Split DemandedElts and test each of the demanded subvectors.
2098 Known.Zero.setAllBits(); Known.One.setAllBits();
2099 EVT SubVectorVT = Op.getOperand(0).getValueType();
2100 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2101 unsigned NumSubVectors = Op.getNumOperands();
2102 for (unsigned i = 0; i != NumSubVectors; ++i) {
2103 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2104 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2105 if (!!DemandedSub) {
2106 SDValue Sub = Op.getOperand(i);
2107 computeKnownBits(Sub, Known2, DemandedSub, Depth + 1);
2108 Known.One &= Known2.One;
2109 Known.Zero &= Known2.Zero;
2111 // If we don't know any bits, early out.
2112 if (!Known.One && !Known.Zero)
2117 case ISD::EXTRACT_SUBVECTOR: {
2118 // If we know the element index, just demand that subvector elements,
2119 // otherwise demand them all.
2120 SDValue Src = Op.getOperand(0);
2121 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2122 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2123 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2124 // Offset the demanded elts by the subvector index.
2125 uint64_t Idx = SubIdx->getZExtValue();
2126 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
2127 computeKnownBits(Src, Known, DemandedSrc, Depth + 1);
2129 computeKnownBits(Src, Known, Depth + 1);
2133 case ISD::BITCAST: {
2134 SDValue N0 = Op.getOperand(0);
2135 unsigned SubBitWidth = N0.getScalarValueSizeInBits();
2137 // Ignore bitcasts from floating point.
2138 if (!N0.getValueType().isInteger())
2141 // Fast handling of 'identity' bitcasts.
2142 if (BitWidth == SubBitWidth) {
2143 computeKnownBits(N0, Known, DemandedElts, Depth + 1);
2147 // Support big-endian targets when it becomes useful.
2148 bool IsLE = getDataLayout().isLittleEndian();
2152 // Bitcast 'small element' vector to 'large element' scalar/vector.
2153 if ((BitWidth % SubBitWidth) == 0) {
2154 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2156 // Collect known bits for the (larger) output by collecting the known
2157 // bits from each set of sub elements and shift these into place.
2158 // We need to separately call computeKnownBits for each set of
2159 // sub elements as the knownbits for each is likely to be different.
2160 unsigned SubScale = BitWidth / SubBitWidth;
2161 APInt SubDemandedElts(NumElts * SubScale, 0);
2162 for (unsigned i = 0; i != NumElts; ++i)
2163 if (DemandedElts[i])
2164 SubDemandedElts.setBit(i * SubScale);
2166 for (unsigned i = 0; i != SubScale; ++i) {
2167 computeKnownBits(N0, Known2, SubDemandedElts.shl(i),
2169 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * i);
2170 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * i);
2174 // Bitcast 'large element' scalar/vector to 'small element' vector.
2175 if ((SubBitWidth % BitWidth) == 0) {
2176 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2178 // Collect known bits for the (smaller) output by collecting the known
2179 // bits from the overlapping larger input elements and extracting the
2180 // sub sections we actually care about.
2181 unsigned SubScale = SubBitWidth / BitWidth;
2182 APInt SubDemandedElts(NumElts / SubScale, 0);
2183 for (unsigned i = 0; i != NumElts; ++i)
2184 if (DemandedElts[i])
2185 SubDemandedElts.setBit(i / SubScale);
2187 computeKnownBits(N0, Known2, SubDemandedElts, Depth + 1);
2189 Known.Zero.setAllBits(); Known.One.setAllBits();
2190 for (unsigned i = 0; i != NumElts; ++i)
2191 if (DemandedElts[i]) {
2192 unsigned Offset = (i % SubScale) * BitWidth;
2193 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2194 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2195 // If we don't know any bits, early out.
2196 if (!Known.One && !Known.Zero)
2203 // If either the LHS or the RHS are Zero, the result is zero.
2204 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2205 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2207 // Output known-1 bits are only known if set in both the LHS & RHS.
2208 Known.One &= Known2.One;
2209 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2210 Known.Zero |= Known2.Zero;
2213 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2214 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2216 // Output known-0 bits are only known if clear in both the LHS & RHS.
2217 Known.Zero &= Known2.Zero;
2218 // Output known-1 are known to be set if set in either the LHS | RHS.
2219 Known.One |= Known2.One;
2222 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2223 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2225 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2226 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2227 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2228 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2229 Known.Zero = KnownZeroOut;
2233 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2234 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2236 // If low bits are zero in either operand, output low known-0 bits.
2237 // Also compute a conservative estimate for high known-0 bits.
2238 // More trickiness is possible, but this is sufficient for the
2239 // interesting case of alignment computation.
2240 unsigned TrailZ = Known.countMinTrailingZeros() +
2241 Known2.countMinTrailingZeros();
2242 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2243 Known2.countMinLeadingZeros(),
2244 BitWidth) - BitWidth;
2247 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2248 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2252 // For the purposes of computing leading zeros we can conservatively
2253 // treat a udiv as a logical right shift by the power of 2 known to
2254 // be less than the denominator.
2255 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2256 unsigned LeadZ = Known2.countMinLeadingZeros();
2258 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2259 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2260 if (RHSMaxLeadingZeros != BitWidth)
2261 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2263 Known.Zero.setHighBits(LeadZ);
2267 computeKnownBits(Op.getOperand(2), Known, Depth+1);
2268 // If we don't know any bits, early out.
2269 if (!Known.One && !Known.Zero)
2271 computeKnownBits(Op.getOperand(1), Known2, Depth+1);
2273 // Only known if known in both the LHS and RHS.
2274 Known.One &= Known2.One;
2275 Known.Zero &= Known2.Zero;
2277 case ISD::SELECT_CC:
2278 computeKnownBits(Op.getOperand(3), Known, Depth+1);
2279 // If we don't know any bits, early out.
2280 if (!Known.One && !Known.Zero)
2282 computeKnownBits(Op.getOperand(2), Known2, Depth+1);
2284 // Only known if known in both the LHS and RHS.
2285 Known.One &= Known2.One;
2286 Known.Zero &= Known2.Zero;
2290 if (Op.getResNo() != 1)
2292 // The boolean result conforms to getBooleanContents.
2293 // If we know the result of a setcc has the top bits zero, use this info.
2294 // We know that we have an integer-based boolean since these operations
2295 // are only available for integer.
2296 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2297 TargetLowering::ZeroOrOneBooleanContent &&
2299 Known.Zero.setBitsFrom(1);
2302 // If we know the result of a setcc has the top bits zero, use this info.
2303 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2304 TargetLowering::ZeroOrOneBooleanContent &&
2306 Known.Zero.setBitsFrom(1);
2309 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2310 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2311 Known.Zero <<= *ShAmt;
2312 Known.One <<= *ShAmt;
2313 // Low bits are known zero.
2314 Known.Zero.setLowBits(ShAmt->getZExtValue());
2318 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2319 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2320 Known.Zero.lshrInPlace(*ShAmt);
2321 Known.One.lshrInPlace(*ShAmt);
2322 // High bits are known zero.
2323 Known.Zero.setHighBits(ShAmt->getZExtValue());
2327 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2328 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2329 Known.Zero.lshrInPlace(*ShAmt);
2330 Known.One.lshrInPlace(*ShAmt);
2331 // If we know the value of the sign bit, then we know it is copied across
2332 // the high bits by the shift amount.
2333 APInt SignMask = APInt::getSignMask(BitWidth);
2334 SignMask.lshrInPlace(*ShAmt); // Adjust to where it is now in the mask.
2335 if (Known.Zero.intersects(SignMask)) {
2336 Known.Zero.setHighBits(ShAmt->getZExtValue());// New bits are known zero.
2337 } else if (Known.One.intersects(SignMask)) {
2338 Known.One.setHighBits(ShAmt->getZExtValue()); // New bits are known one.
2342 case ISD::SIGN_EXTEND_INREG: {
2343 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2344 unsigned EBits = EVT.getScalarSizeInBits();
2346 // Sign extension. Compute the demanded bits in the result that are not
2347 // present in the input.
2348 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2350 APInt InSignMask = APInt::getSignMask(EBits);
2351 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2353 // If the sign extended bits are demanded, we know that the sign
2355 InSignMask = InSignMask.zext(BitWidth);
2356 if (NewBits.getBoolValue())
2357 InputDemandedBits |= InSignMask;
2359 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2360 Known.One &= InputDemandedBits;
2361 Known.Zero &= InputDemandedBits;
2363 // If the sign bit of the input is known set or clear, then we know the
2364 // top bits of the result.
2365 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2366 Known.Zero |= NewBits;
2367 Known.One &= ~NewBits;
2368 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2369 Known.One |= NewBits;
2370 Known.Zero &= ~NewBits;
2371 } else { // Input sign bit unknown
2372 Known.Zero &= ~NewBits;
2373 Known.One &= ~NewBits;
2378 case ISD::CTTZ_ZERO_UNDEF: {
2379 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2380 // If we have a known 1, its position is our upper bound.
2381 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2382 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2383 Known.Zero.setBitsFrom(LowBits);
2387 case ISD::CTLZ_ZERO_UNDEF: {
2388 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2389 // If we have a known 1, its position is our upper bound.
2390 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2391 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2392 Known.Zero.setBitsFrom(LowBits);
2396 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2397 // If we know some of the bits are zero, they can't be one.
2398 unsigned PossibleOnes = Known2.countMaxPopulation();
2399 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2403 LoadSDNode *LD = cast<LoadSDNode>(Op);
2404 // If this is a ZEXTLoad and we are looking at the loaded value.
2405 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2406 EVT VT = LD->getMemoryVT();
2407 unsigned MemBits = VT.getScalarSizeInBits();
2408 Known.Zero.setBitsFrom(MemBits);
2409 } else if (const MDNode *Ranges = LD->getRanges()) {
2410 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2411 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2415 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2416 EVT InVT = Op.getOperand(0).getValueType();
2417 unsigned InBits = InVT.getScalarSizeInBits();
2418 Known = Known.trunc(InBits);
2419 computeKnownBits(Op.getOperand(0), Known,
2420 DemandedElts.zext(InVT.getVectorNumElements()),
2422 Known = Known.zext(BitWidth);
2423 Known.Zero.setBitsFrom(InBits);
2426 case ISD::ZERO_EXTEND: {
2427 EVT InVT = Op.getOperand(0).getValueType();
2428 unsigned InBits = InVT.getScalarSizeInBits();
2429 Known = Known.trunc(InBits);
2430 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2431 Known = Known.zext(BitWidth);
2432 Known.Zero.setBitsFrom(InBits);
2435 // TODO ISD::SIGN_EXTEND_VECTOR_INREG
2436 case ISD::SIGN_EXTEND: {
2437 EVT InVT = Op.getOperand(0).getValueType();
2438 unsigned InBits = InVT.getScalarSizeInBits();
2440 Known = Known.trunc(InBits);
2441 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2443 // If the sign bit is known to be zero or one, then sext will extend
2444 // it to the top bits, else it will just zext.
2445 Known = Known.sext(BitWidth);
2448 case ISD::ANY_EXTEND: {
2449 EVT InVT = Op.getOperand(0).getValueType();
2450 unsigned InBits = InVT.getScalarSizeInBits();
2451 Known = Known.trunc(InBits);
2452 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2453 Known = Known.zext(BitWidth);
2456 case ISD::TRUNCATE: {
2457 EVT InVT = Op.getOperand(0).getValueType();
2458 unsigned InBits = InVT.getScalarSizeInBits();
2459 Known = Known.zext(InBits);
2460 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2461 Known = Known.trunc(BitWidth);
2464 case ISD::AssertZext: {
2465 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2466 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2467 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2468 Known.Zero |= (~InMask);
2469 Known.One &= (~Known.Zero);
2473 // All bits are zero except the low bit.
2474 Known.Zero.setBitsFrom(1);
2478 if (Op.getResNo() == 1) {
2479 // If we know the result of a setcc has the top bits zero, use this info.
2480 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2481 TargetLowering::ZeroOrOneBooleanContent &&
2483 Known.Zero.setBitsFrom(1);
2489 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2490 // We know that the top bits of C-X are clear if X contains less bits
2491 // than C (i.e. no wrap-around can happen). For example, 20-X is
2492 // positive if we can prove that X is >= 0 and < 16.
2493 if (CLHS->getAPIntValue().isNonNegative()) {
2494 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2495 // NLZ can't be BitWidth with no sign bit
2496 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2497 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2500 // If all of the MaskV bits are known to be zero, then we know the
2501 // output top bits are zero, because we now know that the output is
2503 if ((Known2.Zero & MaskV) == MaskV) {
2504 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2505 // Top bits known zero.
2506 Known.Zero.setHighBits(NLZ2);
2511 // If low bits are know to be zero in both operands, then we know they are
2512 // going to be 0 in the result. Both addition and complement operations
2513 // preserve the low zero bits.
2514 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2515 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2516 if (KnownZeroLow == 0)
2519 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2520 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2521 Known.Zero.setLowBits(KnownZeroLow);
2527 if (Op.getResNo() == 1) {
2528 // If we know the result of a setcc has the top bits zero, use this info.
2529 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2530 TargetLowering::ZeroOrOneBooleanContent &&
2532 Known.Zero.setBitsFrom(1);
2539 // Output known-0 bits are known if clear or set in both the low clear bits
2540 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2541 // low 3 bits clear.
2542 // Output known-0 bits are also known if the top bits of each input are
2543 // known to be clear. For example, if one input has the top 10 bits clear
2544 // and the other has the top 8 bits clear, we know the top 7 bits of the
2545 // output must be clear.
2546 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2547 unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
2548 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2550 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2552 KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
2553 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2555 if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) {
2556 // With ADDE and ADDCARRY, a carry bit may be added in, so we can only
2557 // use this information if we know (at least) that the low two bits are
2558 // clear. We then return to the caller that the low bit is unknown but
2559 // that other bits are known zero.
2560 if (KnownZeroLow >= 2)
2561 Known.Zero.setBits(1, KnownZeroLow);
2565 Known.Zero.setLowBits(KnownZeroLow);
2566 if (KnownZeroHigh > 1)
2567 Known.Zero.setHighBits(KnownZeroHigh - 1);
2571 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2572 const APInt &RA = Rem->getAPIntValue().abs();
2573 if (RA.isPowerOf2()) {
2574 APInt LowBits = RA - 1;
2575 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2577 // The low bits of the first operand are unchanged by the srem.
2578 Known.Zero = Known2.Zero & LowBits;
2579 Known.One = Known2.One & LowBits;
2581 // If the first operand is non-negative or has all low bits zero, then
2582 // the upper bits are all zero.
2583 if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
2584 Known.Zero |= ~LowBits;
2586 // If the first operand is negative and not all low bits are zero, then
2587 // the upper bits are all one.
2588 if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
2589 Known.One |= ~LowBits;
2590 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
2595 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2596 const APInt &RA = Rem->getAPIntValue();
2597 if (RA.isPowerOf2()) {
2598 APInt LowBits = (RA - 1);
2599 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2601 // The upper bits are all zero, the lower ones are unchanged.
2602 Known.Zero = Known2.Zero | ~LowBits;
2603 Known.One = Known2.One & LowBits;
2608 // Since the result is less than or equal to either operand, any leading
2609 // zero bits in either operand must also exist in the result.
2610 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2611 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2614 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
2616 Known.Zero.setHighBits(Leaders);
2619 case ISD::EXTRACT_ELEMENT: {
2620 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2621 const unsigned Index = Op.getConstantOperandVal(1);
2622 const unsigned BitWidth = Op.getValueSizeInBits();
2624 // Remove low part of known bits mask
2625 Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
2626 Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
2628 // Remove high part of known bit mask
2629 Known = Known.trunc(BitWidth);
2632 case ISD::EXTRACT_VECTOR_ELT: {
2633 SDValue InVec = Op.getOperand(0);
2634 SDValue EltNo = Op.getOperand(1);
2635 EVT VecVT = InVec.getValueType();
2636 const unsigned BitWidth = Op.getValueSizeInBits();
2637 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
2638 const unsigned NumSrcElts = VecVT.getVectorNumElements();
2639 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2640 // anything about the extended bits.
2641 if (BitWidth > EltBitWidth)
2642 Known = Known.trunc(EltBitWidth);
2643 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
2644 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
2645 // If we know the element index, just demand that vector element.
2646 unsigned Idx = ConstEltNo->getZExtValue();
2647 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
2648 computeKnownBits(InVec, Known, DemandedElt, Depth + 1);
2650 // Unknown element index, so ignore DemandedElts and demand them all.
2651 computeKnownBits(InVec, Known, Depth + 1);
2653 if (BitWidth > EltBitWidth)
2654 Known = Known.zext(BitWidth);
2657 case ISD::INSERT_VECTOR_ELT: {
2658 SDValue InVec = Op.getOperand(0);
2659 SDValue InVal = Op.getOperand(1);
2660 SDValue EltNo = Op.getOperand(2);
2662 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
2663 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
2664 // If we know the element index, split the demand between the
2665 // source vector and the inserted element.
2666 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
2667 unsigned EltIdx = CEltNo->getZExtValue();
2669 // If we demand the inserted element then add its common known bits.
2670 if (DemandedElts[EltIdx]) {
2671 computeKnownBits(InVal, Known2, Depth + 1);
2672 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2673 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
2676 // If we demand the source vector then add its common known bits, ensuring
2677 // that we don't demand the inserted element.
2678 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
2680 computeKnownBits(InVec, Known2, VectorElts, Depth + 1);
2681 Known.One &= Known2.One;
2682 Known.Zero &= Known2.Zero;
2685 // Unknown element index, so ignore DemandedElts and demand them all.
2686 computeKnownBits(InVec, Known, Depth + 1);
2687 computeKnownBits(InVal, Known2, Depth + 1);
2688 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2689 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
2693 case ISD::BITREVERSE: {
2694 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2695 Known.Zero = Known2.Zero.reverseBits();
2696 Known.One = Known2.One.reverseBits();
2700 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2701 Known.Zero = Known2.Zero.byteSwap();
2702 Known.One = Known2.One.byteSwap();
2706 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2708 // If the source's MSB is zero then we know the rest of the bits already.
2709 if (Known2.isNonNegative()) {
2710 Known.Zero = Known2.Zero;
2711 Known.One = Known2.One;
2715 // We only know that the absolute values's MSB will be zero iff there is
2716 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
2717 Known2.One.clearSignBit();
2718 if (Known2.One.getBoolValue()) {
2719 Known.Zero = APInt::getSignMask(BitWidth);
2725 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2726 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2728 // UMIN - we know that the result will have the maximum of the
2729 // known zero leading bits of the inputs.
2730 unsigned LeadZero = Known.countMinLeadingZeros();
2731 LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
2733 Known.Zero &= Known2.Zero;
2734 Known.One &= Known2.One;
2735 Known.Zero.setHighBits(LeadZero);
2739 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2741 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2743 // UMAX - we know that the result will have the maximum of the
2744 // known one leading bits of the inputs.
2745 unsigned LeadOne = Known.countMinLeadingOnes();
2746 LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
2748 Known.Zero &= Known2.Zero;
2749 Known.One &= Known2.One;
2750 Known.One.setHighBits(LeadOne);
2755 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2757 // If we don't know any bits, early out.
2758 if (!Known.One && !Known.Zero)
2760 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2761 Known.Zero &= Known2.Zero;
2762 Known.One &= Known2.One;
2765 case ISD::FrameIndex:
2766 case ISD::TargetFrameIndex:
2767 if (unsigned Align = InferPtrAlignment(Op)) {
2768 // The low bits are known zero if the pointer is aligned.
2769 Known.Zero.setLowBits(Log2_32(Align));
2775 if (Opcode < ISD::BUILTIN_OP_END)
2778 case ISD::INTRINSIC_WO_CHAIN:
2779 case ISD::INTRINSIC_W_CHAIN:
2780 case ISD::INTRINSIC_VOID:
2781 // Allow the target to implement this method for its nodes.
2782 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
2786 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
2789 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
2791 // X + 0 never overflow
2792 if (isNullConstant(N1))
2796 computeKnownBits(N1, N1Known);
2797 if (N1Known.Zero.getBoolValue()) {
2799 computeKnownBits(N0, N0Known);
2802 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
2807 // mulhi + 1 never overflow
2808 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
2809 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
2812 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
2814 computeKnownBits(N0, N0Known);
2816 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
2820 return OFK_Sometime;
2823 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2824 EVT OpVT = Val.getValueType();
2825 unsigned BitWidth = OpVT.getScalarSizeInBits();
2827 // Is the constant a known power of 2?
2828 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
2829 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2831 // A left-shift of a constant one will have exactly one bit set because
2832 // shifting the bit off the end is undefined.
2833 if (Val.getOpcode() == ISD::SHL) {
2834 auto *C = isConstOrConstSplat(Val.getOperand(0));
2835 if (C && C->getAPIntValue() == 1)
2839 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2841 if (Val.getOpcode() == ISD::SRL) {
2842 auto *C = isConstOrConstSplat(Val.getOperand(0));
2843 if (C && C->getAPIntValue().isSignMask())
2847 // Are all operands of a build vector constant powers of two?
2848 if (Val.getOpcode() == ISD::BUILD_VECTOR)
2849 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
2850 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
2851 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2856 // More could be done here, though the above checks are enough
2857 // to handle some common cases.
2859 // Fall back to computeKnownBits to catch other known cases.
2861 computeKnownBits(Val, Known);
2862 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
2865 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2866 EVT VT = Op.getValueType();
2867 APInt DemandedElts = VT.isVector()
2868 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2870 return ComputeNumSignBits(Op, DemandedElts, Depth);
2873 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2874 unsigned Depth) const {
2875 EVT VT = Op.getValueType();
2876 assert(VT.isInteger() && "Invalid VT!");
2877 unsigned VTBits = VT.getScalarSizeInBits();
2878 unsigned NumElts = DemandedElts.getBitWidth();
2880 unsigned FirstAnswer = 1;
2883 return 1; // Limit search depth.
2886 return 1; // No demanded elts, better to assume we don't know anything.
2888 switch (Op.getOpcode()) {
2890 case ISD::AssertSext:
2891 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2892 return VTBits-Tmp+1;
2893 case ISD::AssertZext:
2894 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2897 case ISD::Constant: {
2898 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2899 return Val.getNumSignBits();
2902 case ISD::BUILD_VECTOR:
2904 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
2905 if (!DemandedElts[i])
2908 SDValue SrcOp = Op.getOperand(i);
2909 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
2911 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2912 if (SrcOp.getValueSizeInBits() != VTBits) {
2913 assert(SrcOp.getValueSizeInBits() > VTBits &&
2914 "Expected BUILD_VECTOR implicit truncation");
2915 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
2916 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
2918 Tmp = std::min(Tmp, Tmp2);
2922 case ISD::VECTOR_SHUFFLE: {
2923 // Collect the minimum number of sign bits that are shared by every vector
2924 // element referenced by the shuffle.
2925 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2926 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2927 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2928 for (unsigned i = 0; i != NumElts; ++i) {
2929 int M = SVN->getMaskElt(i);
2930 if (!DemandedElts[i])
2932 // For UNDEF elements, we don't know anything about the common state of
2933 // the shuffle result.
2936 if ((unsigned)M < NumElts)
2937 DemandedLHS.setBit((unsigned)M % NumElts);
2939 DemandedRHS.setBit((unsigned)M % NumElts);
2941 Tmp = std::numeric_limits<unsigned>::max();
2943 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
2944 if (!!DemandedRHS) {
2945 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
2946 Tmp = std::min(Tmp, Tmp2);
2948 // If we don't know anything, early out and try computeKnownBits fall-back.
2951 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
2955 case ISD::SIGN_EXTEND:
2956 case ISD::SIGN_EXTEND_VECTOR_INREG:
2957 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
2958 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2960 case ISD::SIGN_EXTEND_INREG:
2961 // Max of the input and what this extends.
2962 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
2965 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2966 return std::max(Tmp, Tmp2);
2969 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
2970 // SRA X, C -> adds C sign bits.
2971 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2972 APInt ShiftVal = C->getAPIntValue();
2974 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
2978 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2979 // shl destroys sign bits.
2980 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2981 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
2982 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
2983 return Tmp - C->getZExtValue();
2988 case ISD::XOR: // NOT is handled here.
2989 // Logical binary ops preserve the number of sign bits at the worst.
2990 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2992 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2993 FirstAnswer = std::min(Tmp, Tmp2);
2994 // We computed what we know about the sign bits as our first
2995 // answer. Now proceed to the generic code that uses
2996 // computeKnownBits, and pick whichever answer is better.
3001 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3002 if (Tmp == 1) return 1; // Early out.
3003 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3004 return std::min(Tmp, Tmp2);
3005 case ISD::SELECT_CC:
3006 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3007 if (Tmp == 1) return 1; // Early out.
3008 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
3009 return std::min(Tmp, Tmp2);
3014 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3016 return 1; // Early out.
3017 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3018 return std::min(Tmp, Tmp2);
3025 if (Op.getResNo() != 1)
3027 // The boolean result conforms to getBooleanContents. Fall through.
3028 // If setcc returns 0/-1, all bits are sign bits.
3029 // We know that we have an integer-based boolean since these operations
3030 // are only available for integer.
3031 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3032 TargetLowering::ZeroOrNegativeOneBooleanContent)
3036 // If setcc returns 0/-1, all bits are sign bits.
3037 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3038 TargetLowering::ZeroOrNegativeOneBooleanContent)
3043 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3044 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
3046 // Handle rotate right by N like a rotate left by 32-N.
3047 if (Op.getOpcode() == ISD::ROTR)
3048 RotAmt = (VTBits-RotAmt) & (VTBits-1);
3050 // If we aren't rotating out all of the known-in sign bits, return the
3051 // number that are left. This handles rotl(sext(x), 1) for example.
3052 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3053 if (Tmp > RotAmt+1) return Tmp-RotAmt;
3058 // Add can have at most one carry bit. Thus we know that the output
3059 // is, at worst, one more bit than the inputs.
3060 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3061 if (Tmp == 1) return 1; // Early out.
3063 // Special case decrementing a value (ADD X, -1):
3064 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3065 if (CRHS->isAllOnesValue()) {
3067 computeKnownBits(Op.getOperand(0), Known, Depth+1);
3069 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3071 if ((Known.Zero | 1).isAllOnesValue())
3074 // If we are subtracting one from a positive number, there is no carry
3075 // out of the result.
3076 if (Known.isNonNegative())
3080 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3081 if (Tmp2 == 1) return 1;
3082 return std::min(Tmp, Tmp2)-1;
3085 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3086 if (Tmp2 == 1) return 1;
3089 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3090 if (CLHS->isNullValue()) {
3092 computeKnownBits(Op.getOperand(1), Known, Depth+1);
3093 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3095 if ((Known.Zero | 1).isAllOnesValue())
3098 // If the input is known to be positive (the sign bit is known clear),
3099 // the output of the NEG has the same number of sign bits as the input.
3100 if (Known.isNonNegative())
3103 // Otherwise, we treat this like a SUB.
3106 // Sub can have at most one carry bit. Thus we know that the output
3107 // is, at worst, one more bit than the inputs.
3108 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3109 if (Tmp == 1) return 1; // Early out.
3110 return std::min(Tmp, Tmp2)-1;
3111 case ISD::TRUNCATE: {
3112 // Check if the sign bits of source go down as far as the truncated value.
3113 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3114 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3115 if (NumSrcSignBits > (NumSrcBits - VTBits))
3116 return NumSrcSignBits - (NumSrcBits - VTBits);
3119 case ISD::EXTRACT_ELEMENT: {
3120 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3121 const int BitWidth = Op.getValueSizeInBits();
3122 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3124 // Get reverse index (starting from 1), Op1 value indexes elements from
3125 // little end. Sign starts at big end.
3126 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3128 // If the sign portion ends in our element the subtraction gives correct
3129 // result. Otherwise it gives either negative or > bitwidth result
3130 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3132 case ISD::INSERT_VECTOR_ELT: {
3133 SDValue InVec = Op.getOperand(0);
3134 SDValue InVal = Op.getOperand(1);
3135 SDValue EltNo = Op.getOperand(2);
3136 unsigned NumElts = InVec.getValueType().getVectorNumElements();
3138 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3139 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3140 // If we know the element index, split the demand between the
3141 // source vector and the inserted element.
3142 unsigned EltIdx = CEltNo->getZExtValue();
3144 // If we demand the inserted element then get its sign bits.
3145 Tmp = std::numeric_limits<unsigned>::max();
3146 if (DemandedElts[EltIdx]) {
3147 // TODO - handle implicit truncation of inserted elements.
3148 if (InVal.getScalarValueSizeInBits() != VTBits)
3150 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3153 // If we demand the source vector then get its sign bits, and determine
3155 APInt VectorElts = DemandedElts;
3156 VectorElts.clearBit(EltIdx);
3158 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3159 Tmp = std::min(Tmp, Tmp2);
3162 // Unknown element index, so ignore DemandedElts and demand them all.
3163 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3164 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3165 Tmp = std::min(Tmp, Tmp2);
3167 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3170 case ISD::EXTRACT_VECTOR_ELT: {
3171 SDValue InVec = Op.getOperand(0);
3172 SDValue EltNo = Op.getOperand(1);
3173 EVT VecVT = InVec.getValueType();
3174 const unsigned BitWidth = Op.getValueSizeInBits();
3175 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3176 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3178 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3179 // anything about sign bits. But if the sizes match we can derive knowledge
3180 // about sign bits from the vector operand.
3181 if (BitWidth != EltBitWidth)
3184 // If we know the element index, just demand that vector element, else for
3185 // an unknown element index, ignore DemandedElts and demand them all.
3186 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3187 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3188 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3190 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3192 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3194 case ISD::EXTRACT_SUBVECTOR: {
3195 // If we know the element index, just demand that subvector elements,
3196 // otherwise demand them all.
3197 SDValue Src = Op.getOperand(0);
3198 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3199 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3200 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3201 // Offset the demanded elts by the subvector index.
3202 uint64_t Idx = SubIdx->getZExtValue();
3203 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
3204 return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3206 return ComputeNumSignBits(Src, Depth + 1);
3208 case ISD::CONCAT_VECTORS:
3209 // Determine the minimum number of sign bits across all demanded
3210 // elts of the input vectors. Early out if the result is already 1.
3211 Tmp = std::numeric_limits<unsigned>::max();
3212 EVT SubVectorVT = Op.getOperand(0).getValueType();
3213 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3214 unsigned NumSubVectors = Op.getNumOperands();
3215 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3216 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3217 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3220 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3221 Tmp = std::min(Tmp, Tmp2);
3223 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3227 // If we are looking at the loaded value of the SDNode.
3228 if (Op.getResNo() == 0) {
3229 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3230 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3231 unsigned ExtType = LD->getExtensionType();
3234 case ISD::SEXTLOAD: // '17' bits known
3235 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3236 return VTBits-Tmp+1;
3237 case ISD::ZEXTLOAD: // '16' bits known
3238 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3244 // Allow the target to implement this method for its nodes.
3245 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3246 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3247 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3248 Op.getOpcode() == ISD::INTRINSIC_VOID) {
3250 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3252 FirstAnswer = std::max(FirstAnswer, NumBits);
3255 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3256 // use this information.
3258 computeKnownBits(Op, Known, DemandedElts, Depth);
3261 if (Known.isNonNegative()) { // sign bit is 0
3263 } else if (Known.isNegative()) { // sign bit is 1;
3270 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3271 // the number of identical bits in the top of the input value.
3273 Mask <<= Mask.getBitWidth()-VTBits;
3274 // Return # leading zeros. We use 'min' here in case Val was zero before
3275 // shifting. We don't want to return '64' as for an i32 "0".
3276 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3279 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3280 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3281 !isa<ConstantSDNode>(Op.getOperand(1)))
3284 if (Op.getOpcode() == ISD::OR &&
3285 !MaskedValueIsZero(Op.getOperand(0),
3286 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3292 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
3293 // If we're told that NaNs won't happen, assume they won't.
3294 if (getTarget().Options.NoNaNsFPMath)
3297 if (Op->getFlags().hasNoNaNs())
3300 // If the value is a constant, we can obviously see if it is a NaN or not.
3301 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3302 return !C->getValueAPF().isNaN();
3304 // TODO: Recognize more cases here.
3309 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3310 // If the value is a constant, we can obviously see if it is a zero or not.
3311 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3312 return !C->isZero();
3314 // TODO: Recognize more cases here.
3315 switch (Op.getOpcode()) {
3318 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3319 return !C->isNullValue();
3326 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3327 // Check the obvious case.
3328 if (A == B) return true;
3330 // For for negative and positive zero.
3331 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3332 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3333 if (CA->isZero() && CB->isZero()) return true;
3335 // Otherwise they may not be equal.
3339 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3340 assert(A.getValueType() == B.getValueType() &&
3341 "Values must have the same type");
3342 KnownBits AKnown, BKnown;
3343 computeKnownBits(A, AKnown);
3344 computeKnownBits(B, BKnown);
3345 return (AKnown.Zero | BKnown.Zero).isAllOnesValue();
3348 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3349 ArrayRef<SDValue> Ops,
3350 SelectionDAG &DAG) {
3351 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3352 assert(llvm::all_of(Ops,
3354 return Ops[0].getValueType() == Op.getValueType();
3356 "Concatenation of vectors with inconsistent value types!");
3357 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3358 VT.getVectorNumElements() &&
3359 "Incorrect element count in vector concatenation!");
3361 if (Ops.size() == 1)
3364 // Concat of UNDEFs is UNDEF.
3365 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3366 return DAG.getUNDEF(VT);
3368 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3369 // simplified to one big BUILD_VECTOR.
3370 // FIXME: Add support for SCALAR_TO_VECTOR as well.
3371 EVT SVT = VT.getScalarType();
3372 SmallVector<SDValue, 16> Elts;
3373 for (SDValue Op : Ops) {
3374 EVT OpVT = Op.getValueType();
3376 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3377 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3378 Elts.append(Op->op_begin(), Op->op_end());
3383 // BUILD_VECTOR requires all inputs to be of the same type, find the
3384 // maximum type and extend them all.
3385 for (SDValue Op : Elts)
3386 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3388 if (SVT.bitsGT(VT.getScalarType()))
3389 for (SDValue &Op : Elts)
3390 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3391 ? DAG.getZExtOrTrunc(Op, DL, SVT)
3392 : DAG.getSExtOrTrunc(Op, DL, SVT);
3394 return DAG.getBuildVector(VT, DL, Elts);
3397 /// Gets or creates the specified node.
3398 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3399 FoldingSetNodeID ID;
3400 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3402 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3403 return SDValue(E, 0);
3405 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3407 CSEMap.InsertNode(N, IP);
3410 return SDValue(N, 0);
3413 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3414 SDValue Operand, const SDNodeFlags Flags) {
3415 // Constant fold unary operations with an integer constant operand. Even
3416 // opaque constant will be folded, because the folding of unary operations
3417 // doesn't create new constants with different values. Nevertheless, the
3418 // opaque flag is preserved during folding to prevent future folding with
3420 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3421 const APInt &Val = C->getAPIntValue();
3424 case ISD::SIGN_EXTEND:
3425 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3426 C->isTargetOpcode(), C->isOpaque());
3427 case ISD::ANY_EXTEND:
3428 case ISD::ZERO_EXTEND:
3430 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3431 C->isTargetOpcode(), C->isOpaque());
3432 case ISD::UINT_TO_FP:
3433 case ISD::SINT_TO_FP: {
3434 APFloat apf(EVTToAPFloatSemantics(VT),
3435 APInt::getNullValue(VT.getSizeInBits()));
3436 (void)apf.convertFromAPInt(Val,
3437 Opcode==ISD::SINT_TO_FP,
3438 APFloat::rmNearestTiesToEven);
3439 return getConstantFP(apf, DL, VT);
3442 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3443 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3444 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3445 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3446 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3447 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3448 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3449 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3452 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3454 case ISD::BITREVERSE:
3455 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3458 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3461 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3464 case ISD::CTLZ_ZERO_UNDEF:
3465 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3468 case ISD::CTTZ_ZERO_UNDEF:
3469 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3471 case ISD::FP16_TO_FP: {
3473 APFloat FPV(APFloat::IEEEhalf(),
3474 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3476 // This can return overflow, underflow, or inexact; we don't care.
3477 // FIXME need to be more flexible about rounding mode.
3478 (void)FPV.convert(EVTToAPFloatSemantics(VT),
3479 APFloat::rmNearestTiesToEven, &Ignored);
3480 return getConstantFP(FPV, DL, VT);
3485 // Constant fold unary operations with a floating point constant operand.
3486 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3487 APFloat V = C->getValueAPF(); // make copy
3491 return getConstantFP(V, DL, VT);
3494 return getConstantFP(V, DL, VT);
3496 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3497 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3498 return getConstantFP(V, DL, VT);
3502 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3503 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3504 return getConstantFP(V, DL, VT);
3508 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3509 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3510 return getConstantFP(V, DL, VT);
3513 case ISD::FP_EXTEND: {
3515 // This can return overflow, underflow, or inexact; we don't care.
3516 // FIXME need to be more flexible about rounding mode.
3517 (void)V.convert(EVTToAPFloatSemantics(VT),
3518 APFloat::rmNearestTiesToEven, &ignored);
3519 return getConstantFP(V, DL, VT);
3521 case ISD::FP_TO_SINT:
3522 case ISD::FP_TO_UINT: {
3524 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3525 // FIXME need to be more flexible about rounding mode.
3526 APFloat::opStatus s =
3527 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3528 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3530 return getConstant(IntVal, DL, VT);
3533 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3534 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3535 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3536 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3537 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3538 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3540 case ISD::FP_TO_FP16: {
3542 // This can return overflow, underflow, or inexact; we don't care.
3543 // FIXME need to be more flexible about rounding mode.
3544 (void)V.convert(APFloat::IEEEhalf(),
3545 APFloat::rmNearestTiesToEven, &Ignored);
3546 return getConstant(V.bitcastToAPInt(), DL, VT);
3551 // Constant fold unary operations with a vector integer or float operand.
3552 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3553 if (BV->isConstant()) {
3556 // FIXME: Entirely reasonable to perform folding of other unary
3557 // operations here as the need arises.
3564 case ISD::FP_EXTEND:
3565 case ISD::FP_TO_SINT:
3566 case ISD::FP_TO_UINT:
3568 case ISD::UINT_TO_FP:
3569 case ISD::SINT_TO_FP:
3571 case ISD::BITREVERSE:
3574 case ISD::CTLZ_ZERO_UNDEF:
3576 case ISD::CTTZ_ZERO_UNDEF:
3578 SDValue Ops = { Operand };
3579 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3586 unsigned OpOpcode = Operand.getNode()->getOpcode();
3588 case ISD::TokenFactor:
3589 case ISD::MERGE_VALUES:
3590 case ISD::CONCAT_VECTORS:
3591 return Operand; // Factor, merge or concat of one node? No need.
3592 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3593 case ISD::FP_EXTEND:
3594 assert(VT.isFloatingPoint() &&
3595 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3596 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3597 assert((!VT.isVector() ||
3598 VT.getVectorNumElements() ==
3599 Operand.getValueType().getVectorNumElements()) &&
3600 "Vector element count mismatch!");
3601 assert(Operand.getValueType().bitsLT(VT) &&
3602 "Invalid fpext node, dst < src!");
3603 if (Operand.isUndef())
3604 return getUNDEF(VT);
3606 case ISD::SIGN_EXTEND:
3607 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3608 "Invalid SIGN_EXTEND!");
3609 if (Operand.getValueType() == VT) return Operand; // noop extension
3610 assert((!VT.isVector() ||
3611 VT.getVectorNumElements() ==
3612 Operand.getValueType().getVectorNumElements()) &&
3613 "Vector element count mismatch!");
3614 assert(Operand.getValueType().bitsLT(VT) &&
3615 "Invalid sext node, dst < src!");
3616 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3617 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3618 else if (OpOpcode == ISD::UNDEF)
3619 // sext(undef) = 0, because the top bits will all be the same.
3620 return getConstant(0, DL, VT);
3622 case ISD::ZERO_EXTEND:
3623 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3624 "Invalid ZERO_EXTEND!");
3625 if (Operand.getValueType() == VT) return Operand; // noop extension
3626 assert((!VT.isVector() ||
3627 VT.getVectorNumElements() ==
3628 Operand.getValueType().getVectorNumElements()) &&
3629 "Vector element count mismatch!");
3630 assert(Operand.getValueType().bitsLT(VT) &&
3631 "Invalid zext node, dst < src!");
3632 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3633 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
3634 else if (OpOpcode == ISD::UNDEF)
3635 // zext(undef) = 0, because the top bits will be zero.
3636 return getConstant(0, DL, VT);
3638 case ISD::ANY_EXTEND:
3639 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3640 "Invalid ANY_EXTEND!");
3641 if (Operand.getValueType() == VT) return Operand; // noop extension
3642 assert((!VT.isVector() ||
3643 VT.getVectorNumElements() ==
3644 Operand.getValueType().getVectorNumElements()) &&
3645 "Vector element count mismatch!");
3646 assert(Operand.getValueType().bitsLT(VT) &&
3647 "Invalid anyext node, dst < src!");
3649 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3650 OpOpcode == ISD::ANY_EXTEND)
3651 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3652 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3653 else if (OpOpcode == ISD::UNDEF)
3654 return getUNDEF(VT);
3656 // (ext (trunx x)) -> x
3657 if (OpOpcode == ISD::TRUNCATE) {
3658 SDValue OpOp = Operand.getOperand(0);
3659 if (OpOp.getValueType() == VT)
3664 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3665 "Invalid TRUNCATE!");
3666 if (Operand.getValueType() == VT) return Operand; // noop truncate
3667 assert((!VT.isVector() ||
3668 VT.getVectorNumElements() ==
3669 Operand.getValueType().getVectorNumElements()) &&
3670 "Vector element count mismatch!");
3671 assert(Operand.getValueType().bitsGT(VT) &&
3672 "Invalid truncate node, src < dst!");
3673 if (OpOpcode == ISD::TRUNCATE)
3674 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
3675 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3676 OpOpcode == ISD::ANY_EXTEND) {
3677 // If the source is smaller than the dest, we still need an extend.
3678 if (Operand.getOperand(0).getValueType().getScalarType()
3679 .bitsLT(VT.getScalarType()))
3680 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3681 if (Operand.getOperand(0).getValueType().bitsGT(VT))
3682 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
3683 return Operand.getOperand(0);
3685 if (OpOpcode == ISD::UNDEF)
3686 return getUNDEF(VT);
3689 assert(VT.isInteger() && VT == Operand.getValueType() &&
3691 if (OpOpcode == ISD::UNDEF)
3692 return getUNDEF(VT);
3695 assert(VT.isInteger() && VT == Operand.getValueType() &&
3697 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3698 "BSWAP types must be a multiple of 16 bits!");
3699 if (OpOpcode == ISD::UNDEF)
3700 return getUNDEF(VT);
3702 case ISD::BITREVERSE:
3703 assert(VT.isInteger() && VT == Operand.getValueType() &&
3704 "Invalid BITREVERSE!");
3705 if (OpOpcode == ISD::UNDEF)
3706 return getUNDEF(VT);
3709 // Basic sanity checking.
3710 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3711 "Cannot BITCAST between types of different sizes!");
3712 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3713 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3714 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3715 if (OpOpcode == ISD::UNDEF)
3716 return getUNDEF(VT);
3718 case ISD::SCALAR_TO_VECTOR:
3719 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3720 (VT.getVectorElementType() == Operand.getValueType() ||
3721 (VT.getVectorElementType().isInteger() &&
3722 Operand.getValueType().isInteger() &&
3723 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3724 "Illegal SCALAR_TO_VECTOR node!");
3725 if (OpOpcode == ISD::UNDEF)
3726 return getUNDEF(VT);
3727 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3728 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3729 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3730 Operand.getConstantOperandVal(1) == 0 &&
3731 Operand.getOperand(0).getValueType() == VT)
3732 return Operand.getOperand(0);
3735 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3736 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3737 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3738 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
3739 Operand.getOperand(0), Operand.getNode()->getFlags());
3740 if (OpOpcode == ISD::FNEG) // --X -> X
3741 return Operand.getOperand(0);
3744 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3745 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
3750 SDVTList VTs = getVTList(VT);
3751 SDValue Ops[] = {Operand};
3752 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3753 FoldingSetNodeID ID;
3754 AddNodeIDNode(ID, Opcode, VTs, Ops);
3756 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
3757 E->intersectFlagsWith(Flags);
3758 return SDValue(E, 0);
3761 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3763 createOperands(N, Ops);
3764 CSEMap.InsertNode(N, IP);
3766 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3767 createOperands(N, Ops);
3771 return SDValue(N, 0);
3774 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3777 case ISD::ADD: return std::make_pair(C1 + C2, true);
3778 case ISD::SUB: return std::make_pair(C1 - C2, true);
3779 case ISD::MUL: return std::make_pair(C1 * C2, true);
3780 case ISD::AND: return std::make_pair(C1 & C2, true);
3781 case ISD::OR: return std::make_pair(C1 | C2, true);
3782 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3783 case ISD::SHL: return std::make_pair(C1 << C2, true);
3784 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3785 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3786 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3787 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3788 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3789 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3790 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3791 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3793 if (!C2.getBoolValue())
3795 return std::make_pair(C1.udiv(C2), true);
3797 if (!C2.getBoolValue())
3799 return std::make_pair(C1.urem(C2), true);
3801 if (!C2.getBoolValue())
3803 return std::make_pair(C1.sdiv(C2), true);
3805 if (!C2.getBoolValue())
3807 return std::make_pair(C1.srem(C2), true);
3809 return std::make_pair(APInt(1, 0), false);
3812 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3813 EVT VT, const ConstantSDNode *Cst1,
3814 const ConstantSDNode *Cst2) {
3815 if (Cst1->isOpaque() || Cst2->isOpaque())
3818 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3819 Cst2->getAPIntValue());
3822 return getConstant(Folded.first, DL, VT);
3825 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3826 const GlobalAddressSDNode *GA,
3828 if (GA->getOpcode() != ISD::GlobalAddress)
3830 if (!TLI->isOffsetFoldingLegal(GA))
3832 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3835 int64_t Offset = Cst2->getSExtValue();
3837 case ISD::ADD: break;
3838 case ISD::SUB: Offset = -uint64_t(Offset); break;
3839 default: return SDValue();
3841 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3842 GA->getOffset() + uint64_t(Offset));
3845 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
3851 // If a divisor is zero/undef or any element of a divisor vector is
3852 // zero/undef, the whole op is undef.
3853 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
3854 SDValue Divisor = Ops[1];
3855 if (Divisor.isUndef() || isNullConstant(Divisor))
3858 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
3859 llvm::any_of(Divisor->op_values(),
3860 [](SDValue V) { return V.isUndef() ||
3861 isNullConstant(V); });
3862 // TODO: Handle signed overflow.
3864 // TODO: Handle oversized shifts.
3870 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3871 EVT VT, SDNode *Cst1,
3873 // If the opcode is a target-specific ISD node, there's nothing we can
3874 // do here and the operand rules may not line up with the below, so
3876 if (Opcode >= ISD::BUILTIN_OP_END)
3879 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
3880 return getUNDEF(VT);
3882 // Handle the case of two scalars.
3883 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3884 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3885 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3886 assert((!Folded || !VT.isVector()) &&
3887 "Can't fold vectors ops with scalar operands");
3892 // fold (add Sym, c) -> Sym+c
3893 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3894 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3895 if (TLI->isCommutativeBinOp(Opcode))
3896 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3897 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3899 // For vectors extract each constant element into Inputs so we can constant
3900 // fold them individually.
3901 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3902 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3906 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3908 EVT SVT = VT.getScalarType();
3909 SmallVector<SDValue, 4> Outputs;
3910 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3911 SDValue V1 = BV1->getOperand(I);
3912 SDValue V2 = BV2->getOperand(I);
3914 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3915 // FIXME: This is valid and could be handled by truncation.
3916 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3919 // Fold one vector element.
3920 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
3922 // Scalar folding only succeeded if the result is a constant or UNDEF.
3923 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3924 ScalarResult.getOpcode() != ISD::ConstantFP)
3926 Outputs.push_back(ScalarResult);
3929 assert(VT.getVectorNumElements() == Outputs.size() &&
3930 "Vector size mismatch!");
3932 // We may have a vector type but a scalar result. Create a splat.
3933 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3935 // Build a big vector out of the scalar elements we generated.
3936 return getBuildVector(VT, SDLoc(), Outputs);
3939 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3940 const SDLoc &DL, EVT VT,
3941 ArrayRef<SDValue> Ops,
3942 const SDNodeFlags Flags) {
3943 // If the opcode is a target-specific ISD node, there's nothing we can
3944 // do here and the operand rules may not line up with the below, so
3946 if (Opcode >= ISD::BUILTIN_OP_END)
3949 if (isUndef(Opcode, Ops))
3950 return getUNDEF(VT);
3952 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3956 unsigned NumElts = VT.getVectorNumElements();
3958 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3959 return !Op.getValueType().isVector() ||
3960 Op.getValueType().getVectorNumElements() == NumElts;
3963 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3964 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3965 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3966 (BV && BV->isConstant());
3969 // All operands must be vector types with the same number of elements as
3970 // the result type and must be either UNDEF or a build vector of constant
3971 // or UNDEF scalars.
3972 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
3973 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
3976 // If we are comparing vectors, then the result needs to be a i1 boolean
3977 // that is then sign-extended back to the legal result type.
3978 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3980 // Find legal integer scalar type for constant promotion and
3981 // ensure that its scalar size is at least as large as source.
3982 EVT LegalSVT = VT.getScalarType();
3983 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
3984 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3985 if (LegalSVT.bitsLT(VT.getScalarType()))
3989 // Constant fold each scalar lane separately.
3990 SmallVector<SDValue, 4> ScalarResults;
3991 for (unsigned i = 0; i != NumElts; i++) {
3992 SmallVector<SDValue, 4> ScalarOps;
3993 for (SDValue Op : Ops) {
3994 EVT InSVT = Op.getValueType().getScalarType();
3995 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3997 // We've checked that this is UNDEF or a constant of some kind.
3999 ScalarOps.push_back(getUNDEF(InSVT));
4001 ScalarOps.push_back(Op);
4005 SDValue ScalarOp = InBV->getOperand(i);
4006 EVT ScalarVT = ScalarOp.getValueType();
4008 // Build vector (integer) scalar operands may need implicit
4009 // truncation - do this before constant folding.
4010 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4011 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4013 ScalarOps.push_back(ScalarOp);
4016 // Constant fold the scalar operands.
4017 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4019 // Legalize the (integer) scalar constant if necessary.
4020 if (LegalSVT != SVT)
4021 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4023 // Scalar folding only succeeded if the result is a constant or UNDEF.
4024 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4025 ScalarResult.getOpcode() != ISD::ConstantFP)
4027 ScalarResults.push_back(ScalarResult);
4030 return getBuildVector(VT, DL, ScalarResults);
4033 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4034 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
4035 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4036 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4037 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4038 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4040 // Canonicalize constant to RHS if commutative.
4041 if (TLI->isCommutativeBinOp(Opcode)) {
4043 std::swap(N1C, N2C);
4045 } else if (N1CFP && !N2CFP) {
4046 std::swap(N1CFP, N2CFP);
4053 case ISD::TokenFactor:
4054 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4055 N2.getValueType() == MVT::Other && "Invalid token factor!");
4056 // Fold trivial token factors.
4057 if (N1.getOpcode() == ISD::EntryToken) return N2;
4058 if (N2.getOpcode() == ISD::EntryToken) return N1;
4059 if (N1 == N2) return N1;
4061 case ISD::CONCAT_VECTORS: {
4062 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4063 SDValue Ops[] = {N1, N2};
4064 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4069 assert(VT.isInteger() && "This operator does not apply to FP types!");
4070 assert(N1.getValueType() == N2.getValueType() &&
4071 N1.getValueType() == VT && "Binary operator types must match!");
4072 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4073 // worth handling here.
4074 if (N2C && N2C->isNullValue())
4076 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4083 assert(VT.isInteger() && "This operator does not apply to FP types!");
4084 assert(N1.getValueType() == N2.getValueType() &&
4085 N1.getValueType() == VT && "Binary operator types must match!");
4086 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4087 // it's worth handling here.
4088 if (N2C && N2C->isNullValue())
4102 assert(VT.isInteger() && "This operator does not apply to FP types!");
4103 assert(N1.getValueType() == N2.getValueType() &&
4104 N1.getValueType() == VT && "Binary operator types must match!");
4111 if (getTarget().Options.UnsafeFPMath) {
4112 if (Opcode == ISD::FADD) {
4114 if (N2CFP && N2CFP->getValueAPF().isZero())
4116 } else if (Opcode == ISD::FSUB) {
4118 if (N2CFP && N2CFP->getValueAPF().isZero())
4120 } else if (Opcode == ISD::FMUL) {
4122 if (N2CFP && N2CFP->isZero())
4125 if (N2CFP && N2CFP->isExactlyValue(1.0))
4129 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4130 assert(N1.getValueType() == N2.getValueType() &&
4131 N1.getValueType() == VT && "Binary operator types must match!");
4133 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4134 assert(N1.getValueType() == VT &&
4135 N1.getValueType().isFloatingPoint() &&
4136 N2.getValueType().isFloatingPoint() &&
4137 "Invalid FCOPYSIGN!");
4144 assert(VT == N1.getValueType() &&
4145 "Shift operators return type must be the same as their first arg");
4146 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4147 "Shifts only work on integers");
4148 assert((!VT.isVector() || VT == N2.getValueType()) &&
4149 "Vector shift amounts must be in the same as their first arg");
4150 // Verify that the shift amount VT is bit enough to hold valid shift
4151 // amounts. This catches things like trying to shift an i1024 value by an
4152 // i8, which is easy to fall into in generic code that uses
4153 // TLI.getShiftAmount().
4154 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4155 "Invalid use of small shift amount with oversized value!");
4157 // Always fold shifts of i1 values so the code generator doesn't need to
4158 // handle them. Since we know the size of the shift has to be less than the
4159 // size of the value, the shift/rotate count is guaranteed to be zero.
4162 if (N2C && N2C->isNullValue())
4165 case ISD::FP_ROUND_INREG: {
4166 EVT EVT = cast<VTSDNode>(N2)->getVT();
4167 assert(VT == N1.getValueType() && "Not an inreg round!");
4168 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4169 "Cannot FP_ROUND_INREG integer types");
4170 assert(EVT.isVector() == VT.isVector() &&
4171 "FP_ROUND_INREG type should be vector iff the operand "
4173 assert((!EVT.isVector() ||
4174 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4175 "Vector element counts must match in FP_ROUND_INREG");
4176 assert(EVT.bitsLE(VT) && "Not rounding down!");
4178 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4182 assert(VT.isFloatingPoint() &&
4183 N1.getValueType().isFloatingPoint() &&
4184 VT.bitsLE(N1.getValueType()) &&
4185 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4186 "Invalid FP_ROUND!");
4187 if (N1.getValueType() == VT) return N1; // noop conversion.
4189 case ISD::AssertSext:
4190 case ISD::AssertZext: {
4191 EVT EVT = cast<VTSDNode>(N2)->getVT();
4192 assert(VT == N1.getValueType() && "Not an inreg extend!");
4193 assert(VT.isInteger() && EVT.isInteger() &&
4194 "Cannot *_EXTEND_INREG FP types");
4195 assert(!EVT.isVector() &&
4196 "AssertSExt/AssertZExt type should be the vector element type "
4197 "rather than the vector type!");
4198 assert(EVT.bitsLE(VT) && "Not extending!");
4199 if (VT == EVT) return N1; // noop assertion.
4202 case ISD::SIGN_EXTEND_INREG: {
4203 EVT EVT = cast<VTSDNode>(N2)->getVT();
4204 assert(VT == N1.getValueType() && "Not an inreg extend!");
4205 assert(VT.isInteger() && EVT.isInteger() &&
4206 "Cannot *_EXTEND_INREG FP types");
4207 assert(EVT.isVector() == VT.isVector() &&
4208 "SIGN_EXTEND_INREG type should be vector iff the operand "
4210 assert((!EVT.isVector() ||
4211 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4212 "Vector element counts must match in SIGN_EXTEND_INREG");
4213 assert(EVT.bitsLE(VT) && "Not extending!");
4214 if (EVT == VT) return N1; // Not actually extending
4216 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4217 unsigned FromBits = EVT.getScalarSizeInBits();
4218 Val <<= Val.getBitWidth() - FromBits;
4219 Val.ashrInPlace(Val.getBitWidth() - FromBits);
4220 return getConstant(Val, DL, ConstantVT);
4224 const APInt &Val = N1C->getAPIntValue();
4225 return SignExtendInReg(Val, VT);
4227 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4228 SmallVector<SDValue, 8> Ops;
4229 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4230 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4231 SDValue Op = N1.getOperand(i);
4233 Ops.push_back(getUNDEF(OpVT));
4236 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4237 APInt Val = C->getAPIntValue();
4238 Ops.push_back(SignExtendInReg(Val, OpVT));
4240 return getBuildVector(VT, DL, Ops);
4244 case ISD::EXTRACT_VECTOR_ELT:
4245 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4247 return getUNDEF(VT);
4249 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4250 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4251 return getUNDEF(VT);
4253 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4254 // expanding copies of large vectors from registers.
4256 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4257 N1.getNumOperands() > 0) {
4259 N1.getOperand(0).getValueType().getVectorNumElements();
4260 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4261 N1.getOperand(N2C->getZExtValue() / Factor),
4262 getConstant(N2C->getZExtValue() % Factor, DL,
4263 N2.getValueType()));
4266 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4267 // expanding large vector constants.
4268 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4269 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4271 if (VT != Elt.getValueType())
4272 // If the vector element type is not legal, the BUILD_VECTOR operands
4273 // are promoted and implicitly truncated, and the result implicitly
4274 // extended. Make that explicit here.
4275 Elt = getAnyExtOrTrunc(Elt, DL, VT);
4280 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4281 // operations are lowered to scalars.
4282 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4283 // If the indices are the same, return the inserted element else
4284 // if the indices are known different, extract the element from
4285 // the original vector.
4286 SDValue N1Op2 = N1.getOperand(2);
4287 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4289 if (N1Op2C && N2C) {
4290 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4291 if (VT == N1.getOperand(1).getValueType())
4292 return N1.getOperand(1);
4294 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4297 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4301 case ISD::EXTRACT_ELEMENT:
4302 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4303 assert(!N1.getValueType().isVector() && !VT.isVector() &&
4304 (N1.getValueType().isInteger() == VT.isInteger()) &&
4305 N1.getValueType() != VT &&
4306 "Wrong types for EXTRACT_ELEMENT!");
4308 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4309 // 64-bit integers into 32-bit parts. Instead of building the extract of
4310 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4311 if (N1.getOpcode() == ISD::BUILD_PAIR)
4312 return N1.getOperand(N2C->getZExtValue());
4314 // EXTRACT_ELEMENT of a constant int is also very common.
4316 unsigned ElementSize = VT.getSizeInBits();
4317 unsigned Shift = ElementSize * N2C->getZExtValue();
4318 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4319 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4322 case ISD::EXTRACT_SUBVECTOR:
4323 if (VT.isSimple() && N1.getValueType().isSimple()) {
4324 assert(VT.isVector() && N1.getValueType().isVector() &&
4325 "Extract subvector VTs must be a vectors!");
4326 assert(VT.getVectorElementType() ==
4327 N1.getValueType().getVectorElementType() &&
4328 "Extract subvector VTs must have the same element type!");
4329 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4330 "Extract subvector must be from larger vector to smaller vector!");
4333 assert((VT.getVectorNumElements() + N2C->getZExtValue()
4334 <= N1.getValueType().getVectorNumElements())
4335 && "Extract subvector overflow!");
4338 // Trivial extraction.
4339 if (VT.getSimpleVT() == N1.getSimpleValueType())
4342 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4344 return getUNDEF(VT);
4346 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4347 // the concat have the same type as the extract.
4348 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4349 N1.getNumOperands() > 0 &&
4350 VT == N1.getOperand(0).getValueType()) {
4351 unsigned Factor = VT.getVectorNumElements();
4352 return N1.getOperand(N2C->getZExtValue() / Factor);
4355 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4356 // during shuffle legalization.
4357 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4358 VT == N1.getOperand(1).getValueType())
4359 return N1.getOperand(1);
4364 // Perform trivial constant folding.
4366 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4369 // Constant fold FP operations.
4370 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4373 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4374 APFloat::opStatus s;
4377 s = V1.add(V2, APFloat::rmNearestTiesToEven);
4378 if (!HasFPExceptions || s != APFloat::opInvalidOp)
4379 return getConstantFP(V1, DL, VT);
4382 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4383 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4384 return getConstantFP(V1, DL, VT);
4387 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4388 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4389 return getConstantFP(V1, DL, VT);
4392 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4393 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4394 s!=APFloat::opDivByZero)) {
4395 return getConstantFP(V1, DL, VT);
4400 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4401 s!=APFloat::opDivByZero)) {
4402 return getConstantFP(V1, DL, VT);
4405 case ISD::FCOPYSIGN:
4407 return getConstantFP(V1, DL, VT);
4412 if (Opcode == ISD::FP_ROUND) {
4413 APFloat V = N1CFP->getValueAPF(); // make copy
4415 // This can return overflow, underflow, or inexact; we don't care.
4416 // FIXME need to be more flexible about rounding mode.
4417 (void)V.convert(EVTToAPFloatSemantics(VT),
4418 APFloat::rmNearestTiesToEven, &ignored);
4419 return getConstantFP(V, DL, VT);
4423 // Canonicalize an UNDEF to the RHS, even over a constant.
4425 if (TLI->isCommutativeBinOp(Opcode)) {
4429 case ISD::FP_ROUND_INREG:
4430 case ISD::SIGN_EXTEND_INREG:
4436 return N1; // fold op(undef, arg2) -> undef
4444 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
4445 // For vectors, we can't easily build an all zero vector, just return
4452 // Fold a bunch of operators when the RHS is undef.
4457 // Handle undef ^ undef -> 0 special case. This is a common
4459 return getConstant(0, DL, VT);
4469 return N2; // fold op(arg1, undef) -> undef
4475 if (getTarget().Options.UnsafeFPMath)
4483 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
4484 // For vectors, we can't easily build an all zero vector, just return
4489 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
4490 // For vectors, we can't easily build an all one vector, just return
4498 // Memoize this node if possible.
4500 SDVTList VTs = getVTList(VT);
4501 SDValue Ops[] = {N1, N2};
4502 if (VT != MVT::Glue) {
4503 FoldingSetNodeID ID;
4504 AddNodeIDNode(ID, Opcode, VTs, Ops);
4506 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4507 E->intersectFlagsWith(Flags);
4508 return SDValue(E, 0);
4511 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4513 createOperands(N, Ops);
4514 CSEMap.InsertNode(N, IP);
4516 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4517 createOperands(N, Ops);
4521 return SDValue(N, 0);
4524 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4525 SDValue N1, SDValue N2, SDValue N3) {
4526 // Perform various simplifications.
4529 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4530 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4531 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4532 if (N1CFP && N2CFP && N3CFP) {
4533 APFloat V1 = N1CFP->getValueAPF();
4534 const APFloat &V2 = N2CFP->getValueAPF();
4535 const APFloat &V3 = N3CFP->getValueAPF();
4536 APFloat::opStatus s =
4537 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4538 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4539 return getConstantFP(V1, DL, VT);
4543 case ISD::CONCAT_VECTORS: {
4544 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4545 SDValue Ops[] = {N1, N2, N3};
4546 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4551 // Use FoldSetCC to simplify SETCC's.
4552 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
4554 // Vector constant folding.
4555 SDValue Ops[] = {N1, N2, N3};
4556 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4561 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
4562 if (N1C->getZExtValue())
4563 return N2; // select true, X, Y -> X
4564 return N3; // select false, X, Y -> Y
4567 if (N2 == N3) return N2; // select C, X, X -> X
4569 case ISD::VECTOR_SHUFFLE:
4570 llvm_unreachable("should use getVectorShuffle constructor!");
4571 case ISD::INSERT_VECTOR_ELT: {
4572 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
4573 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
4574 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4575 return getUNDEF(VT);
4578 case ISD::INSERT_SUBVECTOR: {
4580 if (VT.isSimple() && N1.getValueType().isSimple()
4581 && N2.getValueType().isSimple()) {
4582 assert(VT.isVector() && N1.getValueType().isVector() &&
4583 N2.getValueType().isVector() &&
4584 "Insert subvector VTs must be a vectors");
4585 assert(VT == N1.getValueType() &&
4586 "Dest and insert subvector source types must match!");
4587 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4588 "Insert subvector must be from smaller vector to larger vector!");
4589 if (isa<ConstantSDNode>(Index)) {
4590 assert((N2.getValueType().getVectorNumElements() +
4591 cast<ConstantSDNode>(Index)->getZExtValue()
4592 <= VT.getVectorNumElements())
4593 && "Insert subvector overflow!");
4596 // Trivial insertion.
4597 if (VT.getSimpleVT() == N2.getSimpleValueType())
4603 // Fold bit_convert nodes from a type to themselves.
4604 if (N1.getValueType() == VT)
4609 // Memoize node if it doesn't produce a flag.
4611 SDVTList VTs = getVTList(VT);
4612 SDValue Ops[] = {N1, N2, N3};
4613 if (VT != MVT::Glue) {
4614 FoldingSetNodeID ID;
4615 AddNodeIDNode(ID, Opcode, VTs, Ops);
4617 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4618 return SDValue(E, 0);
4620 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4621 createOperands(N, Ops);
4622 CSEMap.InsertNode(N, IP);
4624 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4625 createOperands(N, Ops);
4629 return SDValue(N, 0);
4632 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4633 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4634 SDValue Ops[] = { N1, N2, N3, N4 };
4635 return getNode(Opcode, DL, VT, Ops);
4638 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4639 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4641 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4642 return getNode(Opcode, DL, VT, Ops);
4645 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4646 /// the incoming stack arguments to be loaded from the stack.
4647 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4648 SmallVector<SDValue, 8> ArgChains;
4650 // Include the original chain at the beginning of the list. When this is
4651 // used by target LowerCall hooks, this helps legalize find the
4652 // CALLSEQ_BEGIN node.
4653 ArgChains.push_back(Chain);
4655 // Add a chain value for each stack argument.
4656 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4657 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4658 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4659 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4660 if (FI->getIndex() < 0)
4661 ArgChains.push_back(SDValue(L, 1));
4663 // Build a tokenfactor for all the chains.
4664 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4667 /// getMemsetValue - Vectorized representation of the memset value
4669 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4671 assert(!Value.isUndef());
4673 unsigned NumBits = VT.getScalarSizeInBits();
4674 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4675 assert(C->getAPIntValue().getBitWidth() == 8);
4676 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4678 return DAG.getConstant(Val, dl, VT);
4679 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4683 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4684 EVT IntVT = VT.getScalarType();
4685 if (!IntVT.isInteger())
4686 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4688 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4690 // Use a multiplication with 0x010101... to extend the input to the
4692 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4693 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4694 DAG.getConstant(Magic, dl, IntVT));
4697 if (VT != Value.getValueType() && !VT.isInteger())
4698 Value = DAG.getBitcast(VT.getScalarType(), Value);
4699 if (VT != Value.getValueType())
4700 Value = DAG.getSplatBuildVector(VT, dl, Value);
4705 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4706 /// used when a memcpy is turned into a memset when the source is a constant
4708 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4709 const TargetLowering &TLI,
4710 const ConstantDataArraySlice &Slice) {
4711 // Handle vector with all elements zero.
4712 if (Slice.Array == nullptr) {
4714 return DAG.getConstant(0, dl, VT);
4715 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4716 return DAG.getConstantFP(0.0, dl, VT);
4717 else if (VT.isVector()) {
4718 unsigned NumElts = VT.getVectorNumElements();
4719 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4720 return DAG.getNode(ISD::BITCAST, dl, VT,
4721 DAG.getConstant(0, dl,
4722 EVT::getVectorVT(*DAG.getContext(),
4725 llvm_unreachable("Expected type!");
4728 assert(!VT.isVector() && "Can't handle vector type here!");
4729 unsigned NumVTBits = VT.getSizeInBits();
4730 unsigned NumVTBytes = NumVTBits / 8;
4731 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
4733 APInt Val(NumVTBits, 0);
4734 if (DAG.getDataLayout().isLittleEndian()) {
4735 for (unsigned i = 0; i != NumBytes; ++i)
4736 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
4738 for (unsigned i = 0; i != NumBytes; ++i)
4739 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
4742 // If the "cost" of materializing the integer immediate is less than the cost
4743 // of a load, then it is cost effective to turn the load into the immediate.
4744 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4745 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4746 return DAG.getConstant(Val, dl, VT);
4747 return SDValue(nullptr, 0);
4750 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4752 EVT VT = Base.getValueType();
4753 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4756 /// Returns true if memcpy source is constant data.
4757 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
4758 uint64_t SrcDelta = 0;
4759 GlobalAddressSDNode *G = nullptr;
4760 if (Src.getOpcode() == ISD::GlobalAddress)
4761 G = cast<GlobalAddressSDNode>(Src);
4762 else if (Src.getOpcode() == ISD::ADD &&
4763 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4764 Src.getOperand(1).getOpcode() == ISD::Constant) {
4765 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4766 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4771 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
4772 SrcDelta + G->getOffset());
4775 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4776 /// Return true if the number of memory ops is below the threshold (Limit).
4777 /// It returns the types of the sequence of memory ops to perform
4778 /// memset / memcpy by reference.
4779 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4780 unsigned Limit, uint64_t Size,
4781 unsigned DstAlign, unsigned SrcAlign,
4786 unsigned DstAS, unsigned SrcAS,
4788 const TargetLowering &TLI) {
4789 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4790 "Expecting memcpy / memset source to meet alignment requirement!");
4791 // If 'SrcAlign' is zero, that means the memory operation does not need to
4792 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4793 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4794 // is the specified alignment of the memory operation. If it is zero, that
4795 // means it's possible to change the alignment of the destination.
4796 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4797 // not need to be loaded.
4798 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4799 IsMemset, ZeroMemset, MemcpyStrSrc,
4800 DAG.getMachineFunction());
4802 if (VT == MVT::Other) {
4803 // Use the largest integer type whose alignment constraints are satisfied.
4804 // We only need to check DstAlign here as SrcAlign is always greater or
4805 // equal to DstAlign (or zero).
4807 while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
4808 !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
4809 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
4810 assert(VT.isInteger());
4812 // Find the largest legal integer type.
4814 while (!TLI.isTypeLegal(LVT))
4815 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4816 assert(LVT.isInteger());
4818 // If the type we've chosen is larger than the largest legal integer type
4819 // then use that instead.
4824 unsigned NumMemOps = 0;
4826 unsigned VTSize = VT.getSizeInBits() / 8;
4827 while (VTSize > Size) {
4828 // For now, only use non-vector load / store's for the left-over pieces.
4833 if (VT.isVector() || VT.isFloatingPoint()) {
4834 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4835 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4836 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4838 else if (NewVT == MVT::i64 &&
4839 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4840 TLI.isSafeMemOpType(MVT::f64)) {
4841 // i64 is usually not legal on 32-bit targets, but f64 may be.
4849 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4850 if (NewVT == MVT::i8)
4852 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4854 NewVTSize = NewVT.getSizeInBits() / 8;
4856 // If the new VT cannot cover all of the remaining bits, then consider
4857 // issuing a (or a pair of) unaligned and overlapping load / store.
4858 // FIXME: Only does this for 64-bit or more since we don't have proper
4859 // cost model for unaligned load / store.
4861 if (NumMemOps && AllowOverlap &&
4862 VTSize >= 8 && NewVTSize < Size &&
4863 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4871 if (++NumMemOps > Limit)
4874 MemOps.push_back(VT);
4881 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4882 // On Darwin, -Os means optimize for size without hurting performance, so
4883 // only really optimize for size when -Oz (MinSize) is used.
4884 if (MF.getTarget().getTargetTriple().isOSDarwin())
4885 return MF.getFunction()->optForMinSize();
4886 return MF.getFunction()->optForSize();
4889 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4890 SDValue Chain, SDValue Dst, SDValue Src,
4891 uint64_t Size, unsigned Align,
4892 bool isVol, bool AlwaysInline,
4893 MachinePointerInfo DstPtrInfo,
4894 MachinePointerInfo SrcPtrInfo) {
4895 // Turn a memcpy of undef to nop.
4899 // Expand memcpy to a series of load and store ops if the size operand falls
4900 // below a certain threshold.
4901 // TODO: In the AlwaysInline case, if the size is big then generate a loop
4902 // rather than maybe a humongous number of loads and stores.
4903 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4904 const DataLayout &DL = DAG.getDataLayout();
4905 LLVMContext &C = *DAG.getContext();
4906 std::vector<EVT> MemOps;
4907 bool DstAlignCanChange = false;
4908 MachineFunction &MF = DAG.getMachineFunction();
4909 MachineFrameInfo &MFI = MF.getFrameInfo();
4910 bool OptSize = shouldLowerMemFuncForSize(MF);
4911 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4912 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4913 DstAlignCanChange = true;
4914 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4915 if (Align > SrcAlign)
4917 ConstantDataArraySlice Slice;
4918 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
4919 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
4920 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4922 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4923 (DstAlignCanChange ? 0 : Align),
4924 (isZeroConstant ? 0 : SrcAlign),
4925 false, false, CopyFromConstant, true,
4926 DstPtrInfo.getAddrSpace(),
4927 SrcPtrInfo.getAddrSpace(),
4931 if (DstAlignCanChange) {
4932 Type *Ty = MemOps[0].getTypeForEVT(C);
4933 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
4935 // Don't promote to an alignment that would require dynamic stack
4937 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4938 if (!TRI->needsStackRealignment(MF))
4939 while (NewAlign > Align &&
4940 DL.exceedsNaturalStackAlignment(NewAlign))
4943 if (NewAlign > Align) {
4944 // Give the stack frame object a larger alignment if needed.
4945 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4946 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4951 MachineMemOperand::Flags MMOFlags =
4952 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4953 SmallVector<SDValue, 8> OutChains;
4954 unsigned NumMemOps = MemOps.size();
4955 uint64_t SrcOff = 0, DstOff = 0;
4956 for (unsigned i = 0; i != NumMemOps; ++i) {
4958 unsigned VTSize = VT.getSizeInBits() / 8;
4959 SDValue Value, Store;
4961 if (VTSize > Size) {
4962 // Issuing an unaligned load / store pair that overlaps with the previous
4963 // pair. Adjust the offset accordingly.
4964 assert(i == NumMemOps-1 && i != 0);
4965 SrcOff -= VTSize - Size;
4966 DstOff -= VTSize - Size;
4969 if (CopyFromConstant &&
4970 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
4971 // It's unlikely a store of a vector immediate can be done in a single
4972 // instruction. It would require a load from a constantpool first.
4973 // We only handle zero vectors here.
4974 // FIXME: Handle other cases where store of vector immediate is done in
4975 // a single instruction.
4976 ConstantDataArraySlice SubSlice;
4977 if (SrcOff < Slice.Length) {
4979 SubSlice.move(SrcOff);
4981 // This is an out-of-bounds access and hence UB. Pretend we read zero.
4982 SubSlice.Array = nullptr;
4983 SubSlice.Offset = 0;
4984 SubSlice.Length = VTSize;
4986 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
4987 if (Value.getNode())
4988 Store = DAG.getStore(Chain, dl, Value,
4989 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4990 DstPtrInfo.getWithOffset(DstOff), Align,
4994 if (!Store.getNode()) {
4995 // The type might not be legal for the target. This should only happen
4996 // if the type is smaller than a legal type, as on PPC, so the right
4997 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
4998 // to Load/Store if NVT==VT.
4999 // FIXME does the case above also need this?
5000 EVT NVT = TLI.getTypeToTransformTo(C, VT);
5001 assert(NVT.bitsGE(VT));
5003 bool isDereferenceable =
5004 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5005 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5006 if (isDereferenceable)
5007 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5009 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5010 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5011 SrcPtrInfo.getWithOffset(SrcOff), VT,
5012 MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5013 OutChains.push_back(Value.getValue(1));
5014 Store = DAG.getTruncStore(
5015 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5016 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5018 OutChains.push_back(Store);
5024 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5027 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5028 SDValue Chain, SDValue Dst, SDValue Src,
5029 uint64_t Size, unsigned Align,
5030 bool isVol, bool AlwaysInline,
5031 MachinePointerInfo DstPtrInfo,
5032 MachinePointerInfo SrcPtrInfo) {
5033 // Turn a memmove of undef to nop.
5037 // Expand memmove to a series of load and store ops if the size operand falls
5038 // below a certain threshold.
5039 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5040 const DataLayout &DL = DAG.getDataLayout();
5041 LLVMContext &C = *DAG.getContext();
5042 std::vector<EVT> MemOps;
5043 bool DstAlignCanChange = false;
5044 MachineFunction &MF = DAG.getMachineFunction();
5045 MachineFrameInfo &MFI = MF.getFrameInfo();
5046 bool OptSize = shouldLowerMemFuncForSize(MF);
5047 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5048 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5049 DstAlignCanChange = true;
5050 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5051 if (Align > SrcAlign)
5053 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5055 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5056 (DstAlignCanChange ? 0 : Align), SrcAlign,
5057 false, false, false, false,
5058 DstPtrInfo.getAddrSpace(),
5059 SrcPtrInfo.getAddrSpace(),
5063 if (DstAlignCanChange) {
5064 Type *Ty = MemOps[0].getTypeForEVT(C);
5065 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5066 if (NewAlign > Align) {
5067 // Give the stack frame object a larger alignment if needed.
5068 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5069 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5074 MachineMemOperand::Flags MMOFlags =
5075 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5076 uint64_t SrcOff = 0, DstOff = 0;
5077 SmallVector<SDValue, 8> LoadValues;
5078 SmallVector<SDValue, 8> LoadChains;
5079 SmallVector<SDValue, 8> OutChains;
5080 unsigned NumMemOps = MemOps.size();
5081 for (unsigned i = 0; i < NumMemOps; i++) {
5083 unsigned VTSize = VT.getSizeInBits() / 8;
5086 bool isDereferenceable =
5087 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5088 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5089 if (isDereferenceable)
5090 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5093 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5094 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
5095 LoadValues.push_back(Value);
5096 LoadChains.push_back(Value.getValue(1));
5099 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5101 for (unsigned i = 0; i < NumMemOps; i++) {
5103 unsigned VTSize = VT.getSizeInBits() / 8;
5106 Store = DAG.getStore(Chain, dl, LoadValues[i],
5107 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5108 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5109 OutChains.push_back(Store);
5113 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5116 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5119 /// \param DAG Selection DAG where lowered code is placed.
5120 /// \param dl Link to corresponding IR location.
5121 /// \param Chain Control flow dependency.
5122 /// \param Dst Pointer to destination memory location.
5123 /// \param Src Value of byte to write into the memory.
5124 /// \param Size Number of bytes to write.
5125 /// \param Align Alignment of the destination in bytes.
5126 /// \param isVol True if destination is volatile.
5127 /// \param DstPtrInfo IR information on the memory pointer.
5128 /// \returns New head in the control flow, if lowering was successful, empty
5129 /// SDValue otherwise.
5131 /// The function tries to replace 'llvm.memset' intrinsic with several store
5132 /// operations and value calculation code. This is usually profitable for small
5134 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5135 SDValue Chain, SDValue Dst, SDValue Src,
5136 uint64_t Size, unsigned Align, bool isVol,
5137 MachinePointerInfo DstPtrInfo) {
5138 // Turn a memset of undef to nop.
5142 // Expand memset to a series of load/store ops if the size operand
5143 // falls below a certain threshold.
5144 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5145 std::vector<EVT> MemOps;
5146 bool DstAlignCanChange = false;
5147 MachineFunction &MF = DAG.getMachineFunction();
5148 MachineFrameInfo &MFI = MF.getFrameInfo();
5149 bool OptSize = shouldLowerMemFuncForSize(MF);
5150 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5151 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5152 DstAlignCanChange = true;
5154 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5155 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5156 Size, (DstAlignCanChange ? 0 : Align), 0,
5157 true, IsZeroVal, false, true,
5158 DstPtrInfo.getAddrSpace(), ~0u,
5162 if (DstAlignCanChange) {
5163 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5164 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5165 if (NewAlign > Align) {
5166 // Give the stack frame object a larger alignment if needed.
5167 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5168 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5173 SmallVector<SDValue, 8> OutChains;
5174 uint64_t DstOff = 0;
5175 unsigned NumMemOps = MemOps.size();
5177 // Find the largest store and generate the bit pattern for it.
5178 EVT LargestVT = MemOps[0];
5179 for (unsigned i = 1; i < NumMemOps; i++)
5180 if (MemOps[i].bitsGT(LargestVT))
5181 LargestVT = MemOps[i];
5182 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5184 for (unsigned i = 0; i < NumMemOps; i++) {
5186 unsigned VTSize = VT.getSizeInBits() / 8;
5187 if (VTSize > Size) {
5188 // Issuing an unaligned load / store pair that overlaps with the previous
5189 // pair. Adjust the offset accordingly.
5190 assert(i == NumMemOps-1 && i != 0);
5191 DstOff -= VTSize - Size;
5194 // If this store is smaller than the largest store see whether we can get
5195 // the smaller value for free with a truncate.
5196 SDValue Value = MemSetValue;
5197 if (VT.bitsLT(LargestVT)) {
5198 if (!LargestVT.isVector() && !VT.isVector() &&
5199 TLI.isTruncateFree(LargestVT, VT))
5200 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5202 Value = getMemsetValue(Src, VT, DAG, dl);
5204 assert(Value.getValueType() == VT && "Value with wrong type.");
5205 SDValue Store = DAG.getStore(
5206 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5207 DstPtrInfo.getWithOffset(DstOff), Align,
5208 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5209 OutChains.push_back(Store);
5210 DstOff += VT.getSizeInBits() / 8;
5214 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5217 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5219 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5220 // pointer operands can be losslessly bitcasted to pointers of address space 0
5221 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5222 report_fatal_error("cannot lower memory intrinsic in address space " +
5227 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5228 SDValue Src, SDValue Size, unsigned Align,
5229 bool isVol, bool AlwaysInline, bool isTailCall,
5230 MachinePointerInfo DstPtrInfo,
5231 MachinePointerInfo SrcPtrInfo) {
5232 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5234 // Check to see if we should lower the memcpy to loads and stores first.
5235 // For cases within the target-specified limits, this is the best choice.
5236 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5238 // Memcpy with size zero? Just return the original chain.
5239 if (ConstantSize->isNullValue())
5242 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5243 ConstantSize->getZExtValue(),Align,
5244 isVol, false, DstPtrInfo, SrcPtrInfo);
5245 if (Result.getNode())
5249 // Then check to see if we should lower the memcpy with target-specific
5250 // code. If the target chooses to do this, this is the next best.
5252 SDValue Result = TSI->EmitTargetCodeForMemcpy(
5253 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5254 DstPtrInfo, SrcPtrInfo);
5255 if (Result.getNode())
5259 // If we really need inline code and the target declined to provide it,
5260 // use a (potentially long) sequence of loads and stores.
5262 assert(ConstantSize && "AlwaysInline requires a constant size!");
5263 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5264 ConstantSize->getZExtValue(), Align, isVol,
5265 true, DstPtrInfo, SrcPtrInfo);
5268 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5269 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5271 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5272 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5273 // respect volatile, so they may do things like read or write memory
5274 // beyond the given memory regions. But fixing this isn't easy, and most
5275 // people don't care.
5277 // Emit a library call.
5278 TargetLowering::ArgListTy Args;
5279 TargetLowering::ArgListEntry Entry;
5280 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5281 Entry.Node = Dst; Args.push_back(Entry);
5282 Entry.Node = Src; Args.push_back(Entry);
5283 Entry.Node = Size; Args.push_back(Entry);
5284 // FIXME: pass in SDLoc
5285 TargetLowering::CallLoweringInfo CLI(*this);
5288 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5289 Dst.getValueType().getTypeForEVT(*getContext()),
5290 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5291 TLI->getPointerTy(getDataLayout())),
5294 .setTailCall(isTailCall);
5296 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5297 return CallResult.second;
5300 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5301 SDValue Src, SDValue Size, unsigned Align,
5302 bool isVol, bool isTailCall,
5303 MachinePointerInfo DstPtrInfo,
5304 MachinePointerInfo SrcPtrInfo) {
5305 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5307 // Check to see if we should lower the memmove to loads and stores first.
5308 // For cases within the target-specified limits, this is the best choice.
5309 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5311 // Memmove with size zero? Just return the original chain.
5312 if (ConstantSize->isNullValue())
5316 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5317 ConstantSize->getZExtValue(), Align, isVol,
5318 false, DstPtrInfo, SrcPtrInfo);
5319 if (Result.getNode())
5323 // Then check to see if we should lower the memmove with target-specific
5324 // code. If the target chooses to do this, this is the next best.
5326 SDValue Result = TSI->EmitTargetCodeForMemmove(
5327 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5328 if (Result.getNode())
5332 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5333 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5335 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5336 // not be safe. See memcpy above for more details.
5338 // Emit a library call.
5339 TargetLowering::ArgListTy Args;
5340 TargetLowering::ArgListEntry Entry;
5341 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5342 Entry.Node = Dst; Args.push_back(Entry);
5343 Entry.Node = Src; Args.push_back(Entry);
5344 Entry.Node = Size; Args.push_back(Entry);
5345 // FIXME: pass in SDLoc
5346 TargetLowering::CallLoweringInfo CLI(*this);
5349 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5350 Dst.getValueType().getTypeForEVT(*getContext()),
5351 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5352 TLI->getPointerTy(getDataLayout())),
5355 .setTailCall(isTailCall);
5357 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5358 return CallResult.second;
5361 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5362 SDValue Src, SDValue Size, unsigned Align,
5363 bool isVol, bool isTailCall,
5364 MachinePointerInfo DstPtrInfo) {
5365 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5367 // Check to see if we should lower the memset to stores first.
5368 // For cases within the target-specified limits, this is the best choice.
5369 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5371 // Memset with size zero? Just return the original chain.
5372 if (ConstantSize->isNullValue())
5376 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5377 Align, isVol, DstPtrInfo);
5379 if (Result.getNode())
5383 // Then check to see if we should lower the memset with target-specific
5384 // code. If the target chooses to do this, this is the next best.
5386 SDValue Result = TSI->EmitTargetCodeForMemset(
5387 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5388 if (Result.getNode())
5392 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5394 // Emit a library call.
5395 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5396 TargetLowering::ArgListTy Args;
5397 TargetLowering::ArgListEntry Entry;
5398 Entry.Node = Dst; Entry.Ty = IntPtrTy;
5399 Args.push_back(Entry);
5401 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5402 Args.push_back(Entry);
5404 Entry.Ty = IntPtrTy;
5405 Args.push_back(Entry);
5407 // FIXME: pass in SDLoc
5408 TargetLowering::CallLoweringInfo CLI(*this);
5411 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5412 Dst.getValueType().getTypeForEVT(*getContext()),
5413 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5414 TLI->getPointerTy(getDataLayout())),
5417 .setTailCall(isTailCall);
5419 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5420 return CallResult.second;
5423 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5424 SDVTList VTList, ArrayRef<SDValue> Ops,
5425 MachineMemOperand *MMO) {
5426 FoldingSetNodeID ID;
5427 ID.AddInteger(MemVT.getRawBits());
5428 AddNodeIDNode(ID, Opcode, VTList, Ops);
5429 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5431 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5432 cast<AtomicSDNode>(E)->refineAlignment(MMO);
5433 return SDValue(E, 0);
5436 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5437 VTList, MemVT, MMO);
5438 createOperands(N, Ops);
5440 CSEMap.InsertNode(N, IP);
5442 return SDValue(N, 0);
5445 SDValue SelectionDAG::getAtomicCmpSwap(
5446 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5447 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5448 unsigned Alignment, AtomicOrdering SuccessOrdering,
5449 AtomicOrdering FailureOrdering, SyncScope::ID SSID) {
5450 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5451 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5452 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5454 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5455 Alignment = getEVTAlignment(MemVT);
5457 MachineFunction &MF = getMachineFunction();
5459 // FIXME: Volatile isn't really correct; we should keep track of atomic
5460 // orderings in the memoperand.
5461 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5462 MachineMemOperand::MOStore;
5463 MachineMemOperand *MMO =
5464 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5465 AAMDNodes(), nullptr, SSID, SuccessOrdering,
5468 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5471 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5472 EVT MemVT, SDVTList VTs, SDValue Chain,
5473 SDValue Ptr, SDValue Cmp, SDValue Swp,
5474 MachineMemOperand *MMO) {
5475 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5476 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5477 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5479 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5480 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5483 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5484 SDValue Chain, SDValue Ptr, SDValue Val,
5485 const Value *PtrVal, unsigned Alignment,
5486 AtomicOrdering Ordering,
5487 SyncScope::ID SSID) {
5488 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5489 Alignment = getEVTAlignment(MemVT);
5491 MachineFunction &MF = getMachineFunction();
5492 // An atomic store does not load. An atomic load does not store.
5493 // (An atomicrmw obviously both loads and stores.)
5494 // For now, atomics are considered to be volatile always, and they are
5496 // FIXME: Volatile isn't really correct; we should keep track of atomic
5497 // orderings in the memoperand.
5498 auto Flags = MachineMemOperand::MOVolatile;
5499 if (Opcode != ISD::ATOMIC_STORE)
5500 Flags |= MachineMemOperand::MOLoad;
5501 if (Opcode != ISD::ATOMIC_LOAD)
5502 Flags |= MachineMemOperand::MOStore;
5504 MachineMemOperand *MMO =
5505 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5506 MemVT.getStoreSize(), Alignment, AAMDNodes(),
5507 nullptr, SSID, Ordering);
5509 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5512 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5513 SDValue Chain, SDValue Ptr, SDValue Val,
5514 MachineMemOperand *MMO) {
5515 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5516 Opcode == ISD::ATOMIC_LOAD_SUB ||
5517 Opcode == ISD::ATOMIC_LOAD_AND ||
5518 Opcode == ISD::ATOMIC_LOAD_OR ||
5519 Opcode == ISD::ATOMIC_LOAD_XOR ||
5520 Opcode == ISD::ATOMIC_LOAD_NAND ||
5521 Opcode == ISD::ATOMIC_LOAD_MIN ||
5522 Opcode == ISD::ATOMIC_LOAD_MAX ||
5523 Opcode == ISD::ATOMIC_LOAD_UMIN ||
5524 Opcode == ISD::ATOMIC_LOAD_UMAX ||
5525 Opcode == ISD::ATOMIC_SWAP ||
5526 Opcode == ISD::ATOMIC_STORE) &&
5527 "Invalid Atomic Op");
5529 EVT VT = Val.getValueType();
5531 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5532 getVTList(VT, MVT::Other);
5533 SDValue Ops[] = {Chain, Ptr, Val};
5534 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5537 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5538 EVT VT, SDValue Chain, SDValue Ptr,
5539 MachineMemOperand *MMO) {
5540 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5542 SDVTList VTs = getVTList(VT, MVT::Other);
5543 SDValue Ops[] = {Chain, Ptr};
5544 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5547 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5548 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5549 if (Ops.size() == 1)
5552 SmallVector<EVT, 4> VTs;
5553 VTs.reserve(Ops.size());
5554 for (unsigned i = 0; i < Ops.size(); ++i)
5555 VTs.push_back(Ops[i].getValueType());
5556 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5559 SDValue SelectionDAG::getMemIntrinsicNode(
5560 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5561 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5562 bool ReadMem, bool WriteMem, unsigned Size) {
5563 if (Align == 0) // Ensure that codegen never sees alignment 0
5564 Align = getEVTAlignment(MemVT);
5566 MachineFunction &MF = getMachineFunction();
5567 auto Flags = MachineMemOperand::MONone;
5569 Flags |= MachineMemOperand::MOStore;
5571 Flags |= MachineMemOperand::MOLoad;
5573 Flags |= MachineMemOperand::MOVolatile;
5575 Size = MemVT.getStoreSize();
5576 MachineMemOperand *MMO =
5577 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5579 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5582 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5584 ArrayRef<SDValue> Ops, EVT MemVT,
5585 MachineMemOperand *MMO) {
5586 assert((Opcode == ISD::INTRINSIC_VOID ||
5587 Opcode == ISD::INTRINSIC_W_CHAIN ||
5588 Opcode == ISD::PREFETCH ||
5589 Opcode == ISD::LIFETIME_START ||
5590 Opcode == ISD::LIFETIME_END ||
5591 ((int)Opcode <= std::numeric_limits<int>::max() &&
5592 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5593 "Opcode is not a memory-accessing opcode!");
5595 // Memoize the node unless it returns a flag.
5596 MemIntrinsicSDNode *N;
5597 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5598 FoldingSetNodeID ID;
5599 AddNodeIDNode(ID, Opcode, VTList, Ops);
5600 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5602 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5603 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5604 return SDValue(E, 0);
5607 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5608 VTList, MemVT, MMO);
5609 createOperands(N, Ops);
5611 CSEMap.InsertNode(N, IP);
5613 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5614 VTList, MemVT, MMO);
5615 createOperands(N, Ops);
5618 return SDValue(N, 0);
5621 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5622 /// MachinePointerInfo record from it. This is particularly useful because the
5623 /// code generator has many cases where it doesn't bother passing in a
5624 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5625 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5626 int64_t Offset = 0) {
5627 // If this is FI+Offset, we can model it.
5628 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5629 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5630 FI->getIndex(), Offset);
5632 // If this is (FI+Offset1)+Offset2, we can model it.
5633 if (Ptr.getOpcode() != ISD::ADD ||
5634 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5635 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5636 return MachinePointerInfo();
5638 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5639 return MachinePointerInfo::getFixedStack(
5640 DAG.getMachineFunction(), FI,
5641 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5644 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5645 /// MachinePointerInfo record from it. This is particularly useful because the
5646 /// code generator has many cases where it doesn't bother passing in a
5647 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5648 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5650 // If the 'Offset' value isn't a constant, we can't handle this.
5651 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5652 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5653 if (OffsetOp.isUndef())
5654 return InferPointerInfo(DAG, Ptr);
5655 return MachinePointerInfo();
5658 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5659 EVT VT, const SDLoc &dl, SDValue Chain,
5660 SDValue Ptr, SDValue Offset,
5661 MachinePointerInfo PtrInfo, EVT MemVT,
5663 MachineMemOperand::Flags MMOFlags,
5664 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5665 assert(Chain.getValueType() == MVT::Other &&
5666 "Invalid chain type");
5667 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5668 Alignment = getEVTAlignment(MemVT);
5670 MMOFlags |= MachineMemOperand::MOLoad;
5671 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5672 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5674 if (PtrInfo.V.isNull())
5675 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5677 MachineFunction &MF = getMachineFunction();
5678 MachineMemOperand *MMO = MF.getMachineMemOperand(
5679 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5680 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5683 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5684 EVT VT, const SDLoc &dl, SDValue Chain,
5685 SDValue Ptr, SDValue Offset, EVT MemVT,
5686 MachineMemOperand *MMO) {
5688 ExtType = ISD::NON_EXTLOAD;
5689 } else if (ExtType == ISD::NON_EXTLOAD) {
5690 assert(VT == MemVT && "Non-extending load from different memory type!");
5693 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5694 "Should only be an extending load, not truncating!");
5695 assert(VT.isInteger() == MemVT.isInteger() &&
5696 "Cannot convert from FP to Int or Int -> FP!");
5697 assert(VT.isVector() == MemVT.isVector() &&
5698 "Cannot use an ext load to convert to or from a vector!");
5699 assert((!VT.isVector() ||
5700 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5701 "Cannot use an ext load to change the number of vector elements!");
5704 bool Indexed = AM != ISD::UNINDEXED;
5705 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5707 SDVTList VTs = Indexed ?
5708 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5709 SDValue Ops[] = { Chain, Ptr, Offset };
5710 FoldingSetNodeID ID;
5711 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5712 ID.AddInteger(MemVT.getRawBits());
5713 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5714 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5715 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5717 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5718 cast<LoadSDNode>(E)->refineAlignment(MMO);
5719 return SDValue(E, 0);
5721 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5722 ExtType, MemVT, MMO);
5723 createOperands(N, Ops);
5725 CSEMap.InsertNode(N, IP);
5727 return SDValue(N, 0);
5730 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5731 SDValue Ptr, MachinePointerInfo PtrInfo,
5733 MachineMemOperand::Flags MMOFlags,
5734 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5735 SDValue Undef = getUNDEF(Ptr.getValueType());
5736 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5737 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5740 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5741 SDValue Ptr, MachineMemOperand *MMO) {
5742 SDValue Undef = getUNDEF(Ptr.getValueType());
5743 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5747 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5748 EVT VT, SDValue Chain, SDValue Ptr,
5749 MachinePointerInfo PtrInfo, EVT MemVT,
5751 MachineMemOperand::Flags MMOFlags,
5752 const AAMDNodes &AAInfo) {
5753 SDValue Undef = getUNDEF(Ptr.getValueType());
5754 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5755 MemVT, Alignment, MMOFlags, AAInfo);
5758 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5759 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5760 MachineMemOperand *MMO) {
5761 SDValue Undef = getUNDEF(Ptr.getValueType());
5762 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5766 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5767 SDValue Base, SDValue Offset,
5768 ISD::MemIndexedMode AM) {
5769 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5770 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5771 // Don't propagate the invariant or dereferenceable flags.
5773 LD->getMemOperand()->getFlags() &
5774 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5775 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5776 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5777 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5781 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5782 SDValue Ptr, MachinePointerInfo PtrInfo,
5784 MachineMemOperand::Flags MMOFlags,
5785 const AAMDNodes &AAInfo) {
5786 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5787 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5788 Alignment = getEVTAlignment(Val.getValueType());
5790 MMOFlags |= MachineMemOperand::MOStore;
5791 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5793 if (PtrInfo.V.isNull())
5794 PtrInfo = InferPointerInfo(*this, Ptr);
5796 MachineFunction &MF = getMachineFunction();
5797 MachineMemOperand *MMO = MF.getMachineMemOperand(
5798 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5799 return getStore(Chain, dl, Val, Ptr, MMO);
5802 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5803 SDValue Ptr, MachineMemOperand *MMO) {
5804 assert(Chain.getValueType() == MVT::Other &&
5805 "Invalid chain type");
5806 EVT VT = Val.getValueType();
5807 SDVTList VTs = getVTList(MVT::Other);
5808 SDValue Undef = getUNDEF(Ptr.getValueType());
5809 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5810 FoldingSetNodeID ID;
5811 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5812 ID.AddInteger(VT.getRawBits());
5813 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5814 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5815 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5817 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5818 cast<StoreSDNode>(E)->refineAlignment(MMO);
5819 return SDValue(E, 0);
5821 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5822 ISD::UNINDEXED, false, VT, MMO);
5823 createOperands(N, Ops);
5825 CSEMap.InsertNode(N, IP);
5827 return SDValue(N, 0);
5830 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5831 SDValue Ptr, MachinePointerInfo PtrInfo,
5832 EVT SVT, unsigned Alignment,
5833 MachineMemOperand::Flags MMOFlags,
5834 const AAMDNodes &AAInfo) {
5835 assert(Chain.getValueType() == MVT::Other &&
5836 "Invalid chain type");
5837 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5838 Alignment = getEVTAlignment(SVT);
5840 MMOFlags |= MachineMemOperand::MOStore;
5841 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5843 if (PtrInfo.V.isNull())
5844 PtrInfo = InferPointerInfo(*this, Ptr);
5846 MachineFunction &MF = getMachineFunction();
5847 MachineMemOperand *MMO = MF.getMachineMemOperand(
5848 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5849 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5852 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5853 SDValue Ptr, EVT SVT,
5854 MachineMemOperand *MMO) {
5855 EVT VT = Val.getValueType();
5857 assert(Chain.getValueType() == MVT::Other &&
5858 "Invalid chain type");
5860 return getStore(Chain, dl, Val, Ptr, MMO);
5862 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5863 "Should only be a truncating store, not extending!");
5864 assert(VT.isInteger() == SVT.isInteger() &&
5865 "Can't do FP-INT conversion!");
5866 assert(VT.isVector() == SVT.isVector() &&
5867 "Cannot use trunc store to convert to or from a vector!");
5868 assert((!VT.isVector() ||
5869 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5870 "Cannot use trunc store to change the number of vector elements!");
5872 SDVTList VTs = getVTList(MVT::Other);
5873 SDValue Undef = getUNDEF(Ptr.getValueType());
5874 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5875 FoldingSetNodeID ID;
5876 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5877 ID.AddInteger(SVT.getRawBits());
5878 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5879 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5880 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5882 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5883 cast<StoreSDNode>(E)->refineAlignment(MMO);
5884 return SDValue(E, 0);
5886 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5887 ISD::UNINDEXED, true, SVT, MMO);
5888 createOperands(N, Ops);
5890 CSEMap.InsertNode(N, IP);
5892 return SDValue(N, 0);
5895 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5896 SDValue Base, SDValue Offset,
5897 ISD::MemIndexedMode AM) {
5898 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5899 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5900 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5901 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5902 FoldingSetNodeID ID;
5903 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5904 ID.AddInteger(ST->getMemoryVT().getRawBits());
5905 ID.AddInteger(ST->getRawSubclassData());
5906 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5908 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5909 return SDValue(E, 0);
5911 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5912 ST->isTruncatingStore(), ST->getMemoryVT(),
5913 ST->getMemOperand());
5914 createOperands(N, Ops);
5916 CSEMap.InsertNode(N, IP);
5918 return SDValue(N, 0);
5921 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5922 SDValue Ptr, SDValue Mask, SDValue Src0,
5923 EVT MemVT, MachineMemOperand *MMO,
5924 ISD::LoadExtType ExtTy, bool isExpanding) {
5925 SDVTList VTs = getVTList(VT, MVT::Other);
5926 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5927 FoldingSetNodeID ID;
5928 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5929 ID.AddInteger(VT.getRawBits());
5930 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5931 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5932 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5934 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5935 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5936 return SDValue(E, 0);
5938 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5939 ExtTy, isExpanding, MemVT, MMO);
5940 createOperands(N, Ops);
5942 CSEMap.InsertNode(N, IP);
5944 return SDValue(N, 0);
5947 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5948 SDValue Val, SDValue Ptr, SDValue Mask,
5949 EVT MemVT, MachineMemOperand *MMO,
5950 bool IsTruncating, bool IsCompressing) {
5951 assert(Chain.getValueType() == MVT::Other &&
5952 "Invalid chain type");
5953 EVT VT = Val.getValueType();
5954 SDVTList VTs = getVTList(MVT::Other);
5955 SDValue Ops[] = { Chain, Ptr, Mask, Val };
5956 FoldingSetNodeID ID;
5957 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5958 ID.AddInteger(VT.getRawBits());
5959 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5960 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5961 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5963 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5964 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5965 return SDValue(E, 0);
5967 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5968 IsTruncating, IsCompressing, MemVT, MMO);
5969 createOperands(N, Ops);
5971 CSEMap.InsertNode(N, IP);
5973 return SDValue(N, 0);
5976 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5977 ArrayRef<SDValue> Ops,
5978 MachineMemOperand *MMO) {
5979 assert(Ops.size() == 5 && "Incompatible number of operands");
5981 FoldingSetNodeID ID;
5982 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5983 ID.AddInteger(VT.getRawBits());
5984 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5985 dl.getIROrder(), VTs, VT, MMO));
5986 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5988 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5989 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5990 return SDValue(E, 0);
5993 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5995 createOperands(N, Ops);
5997 assert(N->getValue().getValueType() == N->getValueType(0) &&
5998 "Incompatible type of the PassThru value in MaskedGatherSDNode");
5999 assert(N->getMask().getValueType().getVectorNumElements() ==
6000 N->getValueType(0).getVectorNumElements() &&
6001 "Vector width mismatch between mask and data");
6002 assert(N->getIndex().getValueType().getVectorNumElements() ==
6003 N->getValueType(0).getVectorNumElements() &&
6004 "Vector width mismatch between index and data");
6006 CSEMap.InsertNode(N, IP);
6008 return SDValue(N, 0);
6011 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
6012 ArrayRef<SDValue> Ops,
6013 MachineMemOperand *MMO) {
6014 assert(Ops.size() == 5 && "Incompatible number of operands");
6016 FoldingSetNodeID ID;
6017 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
6018 ID.AddInteger(VT.getRawBits());
6019 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
6020 dl.getIROrder(), VTs, VT, MMO));
6021 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6023 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6024 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
6025 return SDValue(E, 0);
6027 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6029 createOperands(N, Ops);
6031 assert(N->getMask().getValueType().getVectorNumElements() ==
6032 N->getValue().getValueType().getVectorNumElements() &&
6033 "Vector width mismatch between mask and data");
6034 assert(N->getIndex().getValueType().getVectorNumElements() ==
6035 N->getValue().getValueType().getVectorNumElements() &&
6036 "Vector width mismatch between index and data");
6038 CSEMap.InsertNode(N, IP);
6040 return SDValue(N, 0);
6043 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
6044 SDValue Ptr, SDValue SV, unsigned Align) {
6045 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
6046 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
6049 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6050 ArrayRef<SDUse> Ops) {
6051 switch (Ops.size()) {
6052 case 0: return getNode(Opcode, DL, VT);
6053 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
6054 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
6055 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6059 // Copy from an SDUse array into an SDValue array for use with
6060 // the regular getNode logic.
6061 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
6062 return getNode(Opcode, DL, VT, NewOps);
6065 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6066 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
6067 unsigned NumOps = Ops.size();
6069 case 0: return getNode(Opcode, DL, VT);
6070 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
6071 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
6072 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6078 case ISD::CONCAT_VECTORS:
6079 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
6080 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
6083 case ISD::SELECT_CC:
6084 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6085 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6086 "LHS and RHS of condition must have same type!");
6087 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6088 "True and False arms of SelectCC must have same type!");
6089 assert(Ops[2].getValueType() == VT &&
6090 "select_cc node must be of same type as true and false value!");
6093 assert(NumOps == 5 && "BR_CC takes 5 operands!");
6094 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6095 "LHS/RHS of comparison should match types!");
6101 SDVTList VTs = getVTList(VT);
6103 if (VT != MVT::Glue) {
6104 FoldingSetNodeID ID;
6105 AddNodeIDNode(ID, Opcode, VTs, Ops);
6108 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6109 return SDValue(E, 0);
6111 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6112 createOperands(N, Ops);
6114 CSEMap.InsertNode(N, IP);
6116 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6117 createOperands(N, Ops);
6121 return SDValue(N, 0);
6124 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6125 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6126 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6129 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6130 ArrayRef<SDValue> Ops) {
6131 if (VTList.NumVTs == 1)
6132 return getNode(Opcode, DL, VTList.VTs[0], Ops);
6136 // FIXME: figure out how to safely handle things like
6137 // int foo(int x) { return 1 << (x & 255); }
6138 // int bar() { return foo(256); }
6139 case ISD::SRA_PARTS:
6140 case ISD::SRL_PARTS:
6141 case ISD::SHL_PARTS:
6142 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6143 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6144 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6145 else if (N3.getOpcode() == ISD::AND)
6146 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6147 // If the and is only masking out bits that cannot effect the shift,
6148 // eliminate the and.
6149 unsigned NumBits = VT.getScalarSizeInBits()*2;
6150 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6151 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6157 // Memoize the node unless it returns a flag.
6159 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6160 FoldingSetNodeID ID;
6161 AddNodeIDNode(ID, Opcode, VTList, Ops);
6163 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6164 return SDValue(E, 0);
6166 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6167 createOperands(N, Ops);
6168 CSEMap.InsertNode(N, IP);
6170 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6171 createOperands(N, Ops);
6174 return SDValue(N, 0);
6177 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6179 return getNode(Opcode, DL, VTList, None);
6182 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6184 SDValue Ops[] = { N1 };
6185 return getNode(Opcode, DL, VTList, Ops);
6188 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6189 SDValue N1, SDValue N2) {
6190 SDValue Ops[] = { N1, N2 };
6191 return getNode(Opcode, DL, VTList, Ops);
6194 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6195 SDValue N1, SDValue N2, SDValue N3) {
6196 SDValue Ops[] = { N1, N2, N3 };
6197 return getNode(Opcode, DL, VTList, Ops);
6200 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6201 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6202 SDValue Ops[] = { N1, N2, N3, N4 };
6203 return getNode(Opcode, DL, VTList, Ops);
6206 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6207 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6209 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6210 return getNode(Opcode, DL, VTList, Ops);
6213 SDVTList SelectionDAG::getVTList(EVT VT) {
6214 return makeVTList(SDNode::getValueTypeList(VT), 1);
6217 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6218 FoldingSetNodeID ID;
6220 ID.AddInteger(VT1.getRawBits());
6221 ID.AddInteger(VT2.getRawBits());
6224 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6226 EVT *Array = Allocator.Allocate<EVT>(2);
6229 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6230 VTListMap.InsertNode(Result, IP);
6232 return Result->getSDVTList();
6235 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6236 FoldingSetNodeID ID;
6238 ID.AddInteger(VT1.getRawBits());
6239 ID.AddInteger(VT2.getRawBits());
6240 ID.AddInteger(VT3.getRawBits());
6243 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6245 EVT *Array = Allocator.Allocate<EVT>(3);
6249 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6250 VTListMap.InsertNode(Result, IP);
6252 return Result->getSDVTList();
6255 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6256 FoldingSetNodeID ID;
6258 ID.AddInteger(VT1.getRawBits());
6259 ID.AddInteger(VT2.getRawBits());
6260 ID.AddInteger(VT3.getRawBits());
6261 ID.AddInteger(VT4.getRawBits());
6264 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6266 EVT *Array = Allocator.Allocate<EVT>(4);
6271 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6272 VTListMap.InsertNode(Result, IP);
6274 return Result->getSDVTList();
6277 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6278 unsigned NumVTs = VTs.size();
6279 FoldingSetNodeID ID;
6280 ID.AddInteger(NumVTs);
6281 for (unsigned index = 0; index < NumVTs; index++) {
6282 ID.AddInteger(VTs[index].getRawBits());
6286 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6288 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6289 std::copy(VTs.begin(), VTs.end(), Array);
6290 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6291 VTListMap.InsertNode(Result, IP);
6293 return Result->getSDVTList();
6297 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6298 /// specified operands. If the resultant node already exists in the DAG,
6299 /// this does not modify the specified node, instead it returns the node that
6300 /// already exists. If the resultant node does not exist in the DAG, the
6301 /// input node is returned. As a degenerate case, if you specify the same
6302 /// input operands as the node already has, the input node is returned.
6303 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6304 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6306 // Check to see if there is no change.
6307 if (Op == N->getOperand(0)) return N;
6309 // See if the modified node already exists.
6310 void *InsertPos = nullptr;
6311 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6314 // Nope it doesn't. Remove the node from its current place in the maps.
6316 if (!RemoveNodeFromCSEMaps(N))
6317 InsertPos = nullptr;
6319 // Now we update the operands.
6320 N->OperandList[0].set(Op);
6322 // If this gets put into a CSE map, add it.
6323 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6327 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6328 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6330 // Check to see if there is no change.
6331 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6332 return N; // No operands changed, just return the input node.
6334 // See if the modified node already exists.
6335 void *InsertPos = nullptr;
6336 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6339 // Nope it doesn't. Remove the node from its current place in the maps.
6341 if (!RemoveNodeFromCSEMaps(N))
6342 InsertPos = nullptr;
6344 // Now we update the operands.
6345 if (N->OperandList[0] != Op1)
6346 N->OperandList[0].set(Op1);
6347 if (N->OperandList[1] != Op2)
6348 N->OperandList[1].set(Op2);
6350 // If this gets put into a CSE map, add it.
6351 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6355 SDNode *SelectionDAG::
6356 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6357 SDValue Ops[] = { Op1, Op2, Op3 };
6358 return UpdateNodeOperands(N, Ops);
6361 SDNode *SelectionDAG::
6362 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6363 SDValue Op3, SDValue Op4) {
6364 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6365 return UpdateNodeOperands(N, Ops);
6368 SDNode *SelectionDAG::
6369 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6370 SDValue Op3, SDValue Op4, SDValue Op5) {
6371 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6372 return UpdateNodeOperands(N, Ops);
6375 SDNode *SelectionDAG::
6376 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6377 unsigned NumOps = Ops.size();
6378 assert(N->getNumOperands() == NumOps &&
6379 "Update with wrong number of operands");
6381 // If no operands changed just return the input node.
6382 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6385 // See if the modified node already exists.
6386 void *InsertPos = nullptr;
6387 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6390 // Nope it doesn't. Remove the node from its current place in the maps.
6392 if (!RemoveNodeFromCSEMaps(N))
6393 InsertPos = nullptr;
6395 // Now we update the operands.
6396 for (unsigned i = 0; i != NumOps; ++i)
6397 if (N->OperandList[i] != Ops[i])
6398 N->OperandList[i].set(Ops[i]);
6400 // If this gets put into a CSE map, add it.
6401 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6405 /// DropOperands - Release the operands and set this node to have
6407 void SDNode::DropOperands() {
6408 // Unlike the code in MorphNodeTo that does this, we don't need to
6409 // watch for dead nodes here.
6410 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6416 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6419 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6421 SDVTList VTs = getVTList(VT);
6422 return SelectNodeTo(N, MachineOpc, VTs, None);
6425 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6426 EVT VT, SDValue Op1) {
6427 SDVTList VTs = getVTList(VT);
6428 SDValue Ops[] = { Op1 };
6429 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6432 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6433 EVT VT, SDValue Op1,
6435 SDVTList VTs = getVTList(VT);
6436 SDValue Ops[] = { Op1, Op2 };
6437 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6440 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6441 EVT VT, SDValue Op1,
6442 SDValue Op2, SDValue Op3) {
6443 SDVTList VTs = getVTList(VT);
6444 SDValue Ops[] = { Op1, Op2, Op3 };
6445 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6448 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6449 EVT VT, ArrayRef<SDValue> Ops) {
6450 SDVTList VTs = getVTList(VT);
6451 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6454 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6455 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6456 SDVTList VTs = getVTList(VT1, VT2);
6457 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6460 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6462 SDVTList VTs = getVTList(VT1, VT2);
6463 return SelectNodeTo(N, MachineOpc, VTs, None);
6466 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6467 EVT VT1, EVT VT2, EVT VT3,
6468 ArrayRef<SDValue> Ops) {
6469 SDVTList VTs = getVTList(VT1, VT2, VT3);
6470 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6473 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6475 SDValue Op1, SDValue Op2) {
6476 SDVTList VTs = getVTList(VT1, VT2);
6477 SDValue Ops[] = { Op1, Op2 };
6478 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6481 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6482 SDVTList VTs,ArrayRef<SDValue> Ops) {
6483 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6484 // Reset the NodeID to -1.
6487 ReplaceAllUsesWith(N, New);
6493 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6494 /// the line number information on the merged node since it is not possible to
6495 /// preserve the information that operation is associated with multiple lines.
6496 /// This will make the debugger working better at -O0, were there is a higher
6497 /// probability having other instructions associated with that line.
6499 /// For IROrder, we keep the smaller of the two
6500 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6501 DebugLoc NLoc = N->getDebugLoc();
6502 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6503 N->setDebugLoc(DebugLoc());
6505 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6506 N->setIROrder(Order);
6510 /// MorphNodeTo - This *mutates* the specified node to have the specified
6511 /// return type, opcode, and operands.
6513 /// Note that MorphNodeTo returns the resultant node. If there is already a
6514 /// node of the specified opcode and operands, it returns that node instead of
6515 /// the current one. Note that the SDLoc need not be the same.
6517 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6518 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6519 /// node, and because it doesn't require CSE recalculation for any of
6520 /// the node's users.
6522 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6523 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6524 /// the legalizer which maintain worklists that would need to be updated when
6525 /// deleting things.
6526 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6527 SDVTList VTs, ArrayRef<SDValue> Ops) {
6528 // If an identical node already exists, use it.
6530 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6531 FoldingSetNodeID ID;
6532 AddNodeIDNode(ID, Opc, VTs, Ops);
6533 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6534 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6537 if (!RemoveNodeFromCSEMaps(N))
6540 // Start the morphing.
6542 N->ValueList = VTs.VTs;
6543 N->NumValues = VTs.NumVTs;
6545 // Clear the operands list, updating used nodes to remove this from their
6546 // use list. Keep track of any operands that become dead as a result.
6547 SmallPtrSet<SDNode*, 16> DeadNodeSet;
6548 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6550 SDNode *Used = Use.getNode();
6552 if (Used->use_empty())
6553 DeadNodeSet.insert(Used);
6556 // For MachineNode, initialize the memory references information.
6557 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6558 MN->setMemRefs(nullptr, nullptr);
6560 // Swap for an appropriately sized array from the recycler.
6562 createOperands(N, Ops);
6564 // Delete any nodes that are still dead after adding the uses for the
6566 if (!DeadNodeSet.empty()) {
6567 SmallVector<SDNode *, 16> DeadNodes;
6568 for (SDNode *N : DeadNodeSet)
6570 DeadNodes.push_back(N);
6571 RemoveDeadNodes(DeadNodes);
6575 CSEMap.InsertNode(N, IP); // Memoize the new node.
6579 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
6580 unsigned OrigOpc = Node->getOpcode();
6582 bool IsUnary = false;
6585 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
6586 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
6587 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
6588 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
6589 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
6590 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
6591 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
6592 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
6593 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
6594 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
6595 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
6596 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
6597 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
6598 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
6599 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
6600 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
6601 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
6602 case ISD::STRICT_FNEARBYINT:
6603 NewOpc = ISD::FNEARBYINT;
6608 // We're taking this node out of the chain, so we need to re-link things.
6609 SDValue InputChain = Node->getOperand(0);
6610 SDValue OutputChain = SDValue(Node, 1);
6611 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
6613 SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
6614 SDNode *Res = nullptr;
6616 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
6618 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
6619 Node->getOperand(2) });
6621 // MorphNodeTo can operate in two ways: if an existing node with the
6622 // specified operands exists, it can just return it. Otherwise, it
6623 // updates the node in place to have the requested operands.
6625 // If we updated the node in place, reset the node ID. To the isel,
6626 // this should be just like a newly allocated machine node.
6629 ReplaceAllUsesWith(Node, Res);
6630 RemoveDeadNode(Node);
6636 /// getMachineNode - These are used for target selectors to create a new node
6637 /// with specified return type(s), MachineInstr opcode, and operands.
6639 /// Note that getMachineNode returns the resultant node. If there is already a
6640 /// node of the specified opcode and operands, it returns that node instead of
6641 /// the current one.
6642 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6644 SDVTList VTs = getVTList(VT);
6645 return getMachineNode(Opcode, dl, VTs, None);
6648 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6649 EVT VT, SDValue Op1) {
6650 SDVTList VTs = getVTList(VT);
6651 SDValue Ops[] = { Op1 };
6652 return getMachineNode(Opcode, dl, VTs, Ops);
6655 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6656 EVT VT, SDValue Op1, SDValue Op2) {
6657 SDVTList VTs = getVTList(VT);
6658 SDValue Ops[] = { Op1, Op2 };
6659 return getMachineNode(Opcode, dl, VTs, Ops);
6662 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6663 EVT VT, SDValue Op1, SDValue Op2,
6665 SDVTList VTs = getVTList(VT);
6666 SDValue Ops[] = { Op1, Op2, Op3 };
6667 return getMachineNode(Opcode, dl, VTs, Ops);
6670 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6671 EVT VT, ArrayRef<SDValue> Ops) {
6672 SDVTList VTs = getVTList(VT);
6673 return getMachineNode(Opcode, dl, VTs, Ops);
6676 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6677 EVT VT1, EVT VT2, SDValue Op1,
6679 SDVTList VTs = getVTList(VT1, VT2);
6680 SDValue Ops[] = { Op1, Op2 };
6681 return getMachineNode(Opcode, dl, VTs, Ops);
6684 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6685 EVT VT1, EVT VT2, SDValue Op1,
6686 SDValue Op2, SDValue Op3) {
6687 SDVTList VTs = getVTList(VT1, VT2);
6688 SDValue Ops[] = { Op1, Op2, Op3 };
6689 return getMachineNode(Opcode, dl, VTs, Ops);
6692 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6694 ArrayRef<SDValue> Ops) {
6695 SDVTList VTs = getVTList(VT1, VT2);
6696 return getMachineNode(Opcode, dl, VTs, Ops);
6699 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6700 EVT VT1, EVT VT2, EVT VT3,
6701 SDValue Op1, SDValue Op2) {
6702 SDVTList VTs = getVTList(VT1, VT2, VT3);
6703 SDValue Ops[] = { Op1, Op2 };
6704 return getMachineNode(Opcode, dl, VTs, Ops);
6707 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6708 EVT VT1, EVT VT2, EVT VT3,
6709 SDValue Op1, SDValue Op2,
6711 SDVTList VTs = getVTList(VT1, VT2, VT3);
6712 SDValue Ops[] = { Op1, Op2, Op3 };
6713 return getMachineNode(Opcode, dl, VTs, Ops);
6716 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6717 EVT VT1, EVT VT2, EVT VT3,
6718 ArrayRef<SDValue> Ops) {
6719 SDVTList VTs = getVTList(VT1, VT2, VT3);
6720 return getMachineNode(Opcode, dl, VTs, Ops);
6723 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6724 ArrayRef<EVT> ResultTys,
6725 ArrayRef<SDValue> Ops) {
6726 SDVTList VTs = getVTList(ResultTys);
6727 return getMachineNode(Opcode, dl, VTs, Ops);
6730 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6732 ArrayRef<SDValue> Ops) {
6733 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6738 FoldingSetNodeID ID;
6739 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6741 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6742 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6746 // Allocate a new MachineSDNode.
6747 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6748 createOperands(N, Ops);
6751 CSEMap.InsertNode(N, IP);
6757 /// getTargetExtractSubreg - A convenience function for creating
6758 /// TargetOpcode::EXTRACT_SUBREG nodes.
6759 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6761 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6762 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6763 VT, Operand, SRIdxVal);
6764 return SDValue(Subreg, 0);
6767 /// getTargetInsertSubreg - A convenience function for creating
6768 /// TargetOpcode::INSERT_SUBREG nodes.
6769 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6770 SDValue Operand, SDValue Subreg) {
6771 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6772 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6773 VT, Operand, Subreg, SRIdxVal);
6774 return SDValue(Result, 0);
6777 /// getNodeIfExists - Get the specified node if it's already available, or
6778 /// else return NULL.
6779 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6780 ArrayRef<SDValue> Ops,
6781 const SDNodeFlags Flags) {
6782 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6783 FoldingSetNodeID ID;
6784 AddNodeIDNode(ID, Opcode, VTList, Ops);
6786 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6787 E->intersectFlagsWith(Flags);
6794 /// getDbgValue - Creates a SDDbgValue node.
6797 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6798 unsigned R, bool IsIndirect, uint64_t Off,
6799 const DebugLoc &DL, unsigned O) {
6800 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6801 "Expected inlined-at fields to agree");
6802 return new (DbgInfo->getAlloc())
6803 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6807 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6808 const Value *C, uint64_t Off,
6809 const DebugLoc &DL, unsigned O) {
6810 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6811 "Expected inlined-at fields to agree");
6812 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6816 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6817 unsigned FI, uint64_t Off,
6820 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6821 "Expected inlined-at fields to agree");
6822 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6827 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6828 /// pointed to by a use iterator is deleted, increment the use iterator
6829 /// so that it doesn't dangle.
6831 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6832 SDNode::use_iterator &UI;
6833 SDNode::use_iterator &UE;
6835 void NodeDeleted(SDNode *N, SDNode *E) override {
6836 // Increment the iterator as needed.
6837 while (UI != UE && N == *UI)
6842 RAUWUpdateListener(SelectionDAG &d,
6843 SDNode::use_iterator &ui,
6844 SDNode::use_iterator &ue)
6845 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6848 } // end anonymous namespace
6850 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6851 /// This can cause recursive merging of nodes in the DAG.
6853 /// This version assumes From has a single result value.
6855 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6856 SDNode *From = FromN.getNode();
6857 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6858 "Cannot replace with this method!");
6859 assert(From != To.getNode() && "Cannot replace uses of with self");
6861 // Preserve Debug Values
6862 TransferDbgValues(FromN, To);
6864 // Iterate over all the existing uses of From. New uses will be added
6865 // to the beginning of the use list, which we avoid visiting.
6866 // This specifically avoids visiting uses of From that arise while the
6867 // replacement is happening, because any such uses would be the result
6868 // of CSE: If an existing node looks like From after one of its operands
6869 // is replaced by To, we don't want to replace of all its users with To
6870 // too. See PR3018 for more info.
6871 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6872 RAUWUpdateListener Listener(*this, UI, UE);
6876 // This node is about to morph, remove its old self from the CSE maps.
6877 RemoveNodeFromCSEMaps(User);
6879 // A user can appear in a use list multiple times, and when this
6880 // happens the uses are usually next to each other in the list.
6881 // To help reduce the number of CSE recomputations, process all
6882 // the uses of this user that we can find this way.
6884 SDUse &Use = UI.getUse();
6887 } while (UI != UE && *UI == User);
6889 // Now that we have modified User, add it back to the CSE maps. If it
6890 // already exists there, recursively merge the results together.
6891 AddModifiedNodeToCSEMaps(User);
6894 // If we just RAUW'd the root, take note.
6895 if (FromN == getRoot())
6899 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6900 /// This can cause recursive merging of nodes in the DAG.
6902 /// This version assumes that for each value of From, there is a
6903 /// corresponding value in To in the same position with the same type.
6905 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6907 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6908 assert((!From->hasAnyUseOfValue(i) ||
6909 From->getValueType(i) == To->getValueType(i)) &&
6910 "Cannot use this version of ReplaceAllUsesWith!");
6913 // Handle the trivial case.
6917 // Preserve Debug Info. Only do this if there's a use.
6918 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6919 if (From->hasAnyUseOfValue(i)) {
6920 assert((i < To->getNumValues()) && "Invalid To location");
6921 TransferDbgValues(SDValue(From, i), SDValue(To, i));
6924 // Iterate over just the existing users of From. See the comments in
6925 // the ReplaceAllUsesWith above.
6926 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6927 RAUWUpdateListener Listener(*this, UI, UE);
6931 // This node is about to morph, remove its old self from the CSE maps.
6932 RemoveNodeFromCSEMaps(User);
6934 // A user can appear in a use list multiple times, and when this
6935 // happens the uses are usually next to each other in the list.
6936 // To help reduce the number of CSE recomputations, process all
6937 // the uses of this user that we can find this way.
6939 SDUse &Use = UI.getUse();
6942 } while (UI != UE && *UI == User);
6944 // Now that we have modified User, add it back to the CSE maps. If it
6945 // already exists there, recursively merge the results together.
6946 AddModifiedNodeToCSEMaps(User);
6949 // If we just RAUW'd the root, take note.
6950 if (From == getRoot().getNode())
6951 setRoot(SDValue(To, getRoot().getResNo()));
6954 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6955 /// This can cause recursive merging of nodes in the DAG.
6957 /// This version can replace From with any result values. To must match the
6958 /// number and types of values returned by From.
6959 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6960 if (From->getNumValues() == 1) // Handle the simple case efficiently.
6961 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6963 // Preserve Debug Info.
6964 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6965 TransferDbgValues(SDValue(From, i), *To);
6967 // Iterate over just the existing users of From. See the comments in
6968 // the ReplaceAllUsesWith above.
6969 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6970 RAUWUpdateListener Listener(*this, UI, UE);
6974 // This node is about to morph, remove its old self from the CSE maps.
6975 RemoveNodeFromCSEMaps(User);
6977 // A user can appear in a use list multiple times, and when this
6978 // happens the uses are usually next to each other in the list.
6979 // To help reduce the number of CSE recomputations, process all
6980 // the uses of this user that we can find this way.
6982 SDUse &Use = UI.getUse();
6983 const SDValue &ToOp = To[Use.getResNo()];
6986 } while (UI != UE && *UI == User);
6988 // Now that we have modified User, add it back to the CSE maps. If it
6989 // already exists there, recursively merge the results together.
6990 AddModifiedNodeToCSEMaps(User);
6993 // If we just RAUW'd the root, take note.
6994 if (From == getRoot().getNode())
6995 setRoot(SDValue(To[getRoot().getResNo()]));
6998 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6999 /// uses of other values produced by From.getNode() alone. The Deleted
7000 /// vector is handled the same way as for ReplaceAllUsesWith.
7001 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
7002 // Handle the really simple, really trivial case efficiently.
7003 if (From == To) return;
7005 // Handle the simple, trivial, case efficiently.
7006 if (From.getNode()->getNumValues() == 1) {
7007 ReplaceAllUsesWith(From, To);
7011 // Preserve Debug Info.
7012 TransferDbgValues(From, To);
7014 // Iterate over just the existing users of From. See the comments in
7015 // the ReplaceAllUsesWith above.
7016 SDNode::use_iterator UI = From.getNode()->use_begin(),
7017 UE = From.getNode()->use_end();
7018 RAUWUpdateListener Listener(*this, UI, UE);
7021 bool UserRemovedFromCSEMaps = false;
7023 // A user can appear in a use list multiple times, and when this
7024 // happens the uses are usually next to each other in the list.
7025 // To help reduce the number of CSE recomputations, process all
7026 // the uses of this user that we can find this way.
7028 SDUse &Use = UI.getUse();
7030 // Skip uses of different values from the same node.
7031 if (Use.getResNo() != From.getResNo()) {
7036 // If this node hasn't been modified yet, it's still in the CSE maps,
7037 // so remove its old self from the CSE maps.
7038 if (!UserRemovedFromCSEMaps) {
7039 RemoveNodeFromCSEMaps(User);
7040 UserRemovedFromCSEMaps = true;
7045 } while (UI != UE && *UI == User);
7047 // We are iterating over all uses of the From node, so if a use
7048 // doesn't use the specific value, no changes are made.
7049 if (!UserRemovedFromCSEMaps)
7052 // Now that we have modified User, add it back to the CSE maps. If it
7053 // already exists there, recursively merge the results together.
7054 AddModifiedNodeToCSEMaps(User);
7057 // If we just RAUW'd the root, take note.
7058 if (From == getRoot())
7064 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
7065 /// to record information about a use.
7072 /// operator< - Sort Memos by User.
7073 bool operator<(const UseMemo &L, const UseMemo &R) {
7074 return (intptr_t)L.User < (intptr_t)R.User;
7077 } // end anonymous namespace
7079 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
7080 /// uses of other values produced by From.getNode() alone. The same value
7081 /// may appear in both the From and To list. The Deleted vector is
7082 /// handled the same way as for ReplaceAllUsesWith.
7083 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
7086 // Handle the simple, trivial case efficiently.
7088 return ReplaceAllUsesOfValueWith(*From, *To);
7090 TransferDbgValues(*From, *To);
7092 // Read up all the uses and make records of them. This helps
7093 // processing new uses that are introduced during the
7094 // replacement process.
7095 SmallVector<UseMemo, 4> Uses;
7096 for (unsigned i = 0; i != Num; ++i) {
7097 unsigned FromResNo = From[i].getResNo();
7098 SDNode *FromNode = From[i].getNode();
7099 for (SDNode::use_iterator UI = FromNode->use_begin(),
7100 E = FromNode->use_end(); UI != E; ++UI) {
7101 SDUse &Use = UI.getUse();
7102 if (Use.getResNo() == FromResNo) {
7103 UseMemo Memo = { *UI, i, &Use };
7104 Uses.push_back(Memo);
7109 // Sort the uses, so that all the uses from a given User are together.
7110 std::sort(Uses.begin(), Uses.end());
7112 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
7113 UseIndex != UseIndexEnd; ) {
7114 // We know that this user uses some value of From. If it is the right
7115 // value, update it.
7116 SDNode *User = Uses[UseIndex].User;
7118 // This node is about to morph, remove its old self from the CSE maps.
7119 RemoveNodeFromCSEMaps(User);
7121 // The Uses array is sorted, so all the uses for a given User
7122 // are next to each other in the list.
7123 // To help reduce the number of CSE recomputations, process all
7124 // the uses of this user that we can find this way.
7126 unsigned i = Uses[UseIndex].Index;
7127 SDUse &Use = *Uses[UseIndex].Use;
7131 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
7133 // Now that we have modified User, add it back to the CSE maps. If it
7134 // already exists there, recursively merge the results together.
7135 AddModifiedNodeToCSEMaps(User);
7139 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
7140 /// based on their topological order. It returns the maximum id and a vector
7141 /// of the SDNodes* in assigned order by reference.
7142 unsigned SelectionDAG::AssignTopologicalOrder() {
7143 unsigned DAGSize = 0;
7145 // SortedPos tracks the progress of the algorithm. Nodes before it are
7146 // sorted, nodes after it are unsorted. When the algorithm completes
7147 // it is at the end of the list.
7148 allnodes_iterator SortedPos = allnodes_begin();
7150 // Visit all the nodes. Move nodes with no operands to the front of
7151 // the list immediately. Annotate nodes that do have operands with their
7152 // operand count. Before we do this, the Node Id fields of the nodes
7153 // may contain arbitrary values. After, the Node Id fields for nodes
7154 // before SortedPos will contain the topological sort index, and the
7155 // Node Id fields for nodes At SortedPos and after will contain the
7156 // count of outstanding operands.
7157 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7159 checkForCycles(N, this);
7160 unsigned Degree = N->getNumOperands();
7162 // A node with no uses, add it to the result array immediately.
7163 N->setNodeId(DAGSize++);
7164 allnodes_iterator Q(N);
7166 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7167 assert(SortedPos != AllNodes.end() && "Overran node list");
7170 // Temporarily use the Node Id as scratch space for the degree count.
7171 N->setNodeId(Degree);
7175 // Visit all the nodes. As we iterate, move nodes into sorted order,
7176 // such that by the time the end is reached all nodes will be sorted.
7177 for (SDNode &Node : allnodes()) {
7179 checkForCycles(N, this);
7180 // N is in sorted position, so all its uses have one less operand
7181 // that needs to be sorted.
7182 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7185 unsigned Degree = P->getNodeId();
7186 assert(Degree != 0 && "Invalid node degree");
7189 // All of P's operands are sorted, so P may sorted now.
7190 P->setNodeId(DAGSize++);
7191 if (P->getIterator() != SortedPos)
7192 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7193 assert(SortedPos != AllNodes.end() && "Overran node list");
7196 // Update P's outstanding operand count.
7197 P->setNodeId(Degree);
7200 if (Node.getIterator() == SortedPos) {
7202 allnodes_iterator I(N);
7204 dbgs() << "Overran sorted position:\n";
7205 S->dumprFull(this); dbgs() << "\n";
7206 dbgs() << "Checking if this is due to cycles\n";
7207 checkForCycles(this, true);
7209 llvm_unreachable(nullptr);
7213 assert(SortedPos == AllNodes.end() &&
7214 "Topological sort incomplete!");
7215 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7216 "First node in topological sort is not the entry token!");
7217 assert(AllNodes.front().getNodeId() == 0 &&
7218 "First node in topological sort has non-zero id!");
7219 assert(AllNodes.front().getNumOperands() == 0 &&
7220 "First node in topological sort has operands!");
7221 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7222 "Last node in topologic sort has unexpected id!");
7223 assert(AllNodes.back().use_empty() &&
7224 "Last node in topologic sort has users!");
7225 assert(DAGSize == allnodes_size() && "Node count mismatch!");
7229 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7230 /// value is produced by SD.
7231 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7233 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7234 SD->setHasDebugValue(true);
7236 DbgInfo->add(DB, SD, isParameter);
7239 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
7240 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
7241 if (From == To || !From.getNode()->getHasDebugValue())
7243 SDNode *FromNode = From.getNode();
7244 SDNode *ToNode = To.getNode();
7245 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
7246 SmallVector<SDDbgValue *, 2> ClonedDVs;
7247 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
7249 SDDbgValue *Dbg = *I;
7250 // Only add Dbgvalues attached to same ResNo.
7251 if (Dbg->getKind() == SDDbgValue::SDNODE &&
7252 Dbg->getSDNode() == From.getNode() &&
7253 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
7254 assert(FromNode != ToNode &&
7255 "Should not transfer Debug Values intranode");
7257 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
7258 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
7259 Dbg->getDebugLoc(), Dbg->getOrder());
7260 ClonedDVs.push_back(Clone);
7261 Dbg->setIsInvalidated();
7264 for (SDDbgValue *I : ClonedDVs)
7265 AddDbgValue(I, ToNode, false);
7268 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
7270 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
7271 // The new memory operation must have the same position as the old load in
7272 // terms of memory dependency. Create a TokenFactor for the old load and new
7273 // memory operation and update uses of the old load's output chain to use that
7275 SDValue OldChain = SDValue(OldLoad, 1);
7276 SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
7277 if (!OldLoad->hasAnyUseOfValue(1))
7280 SDValue TokenFactor =
7281 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
7282 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
7283 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
7287 //===----------------------------------------------------------------------===//
7289 //===----------------------------------------------------------------------===//
7291 bool llvm::isNullConstant(SDValue V) {
7292 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7293 return Const != nullptr && Const->isNullValue();
7296 bool llvm::isNullFPConstant(SDValue V) {
7297 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7298 return Const != nullptr && Const->isZero() && !Const->isNegative();
7301 bool llvm::isAllOnesConstant(SDValue V) {
7302 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7303 return Const != nullptr && Const->isAllOnesValue();
7306 bool llvm::isOneConstant(SDValue V) {
7307 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7308 return Const != nullptr && Const->isOne();
7311 bool llvm::isBitwiseNot(SDValue V) {
7312 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7315 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7316 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7319 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7320 BitVector UndefElements;
7321 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7323 // BuildVectors can truncate their operands. Ignore that case here.
7324 // FIXME: We blindly ignore splats which include undef which is overly
7326 if (CN && UndefElements.none() &&
7327 CN->getValueType(0) == N.getValueType().getScalarType())
7334 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7335 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7338 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7339 BitVector UndefElements;
7340 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7342 if (CN && UndefElements.none())
7349 HandleSDNode::~HandleSDNode() {
7353 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7355 const GlobalValue *GA, EVT VT,
7356 int64_t o, unsigned char TF)
7357 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7361 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7362 EVT VT, unsigned SrcAS,
7364 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7365 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7367 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7368 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7369 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7370 MemSDNodeBits.IsVolatile = MMO->isVolatile();
7371 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7372 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7373 MemSDNodeBits.IsInvariant = MMO->isInvariant();
7375 // We check here that the size of the memory operand fits within the size of
7376 // the MMO. This is because the MMO might indicate only a possible address
7377 // range instead of specifying the affected memory addresses precisely.
7378 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7381 /// Profile - Gather unique data for the node.
7383 void SDNode::Profile(FoldingSetNodeID &ID) const {
7384 AddNodeIDNode(ID, this);
7390 std::vector<EVT> VTs;
7393 VTs.reserve(MVT::LAST_VALUETYPE);
7394 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7395 VTs.push_back(MVT((MVT::SimpleValueType)i));
7399 } // end anonymous namespace
7401 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
7402 static ManagedStatic<EVTArray> SimpleVTArray;
7403 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
7405 /// getValueTypeList - Return a pointer to the specified value type.
7407 const EVT *SDNode::getValueTypeList(EVT VT) {
7408 if (VT.isExtended()) {
7409 sys::SmartScopedLock<true> Lock(*VTMutex);
7410 return &(*EVTs->insert(VT).first);
7412 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7413 "Value type out of range!");
7414 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7418 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7419 /// indicated value. This method ignores uses of other values defined by this
7421 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7422 assert(Value < getNumValues() && "Bad value!");
7424 // TODO: Only iterate over uses of a given value of the node
7425 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7426 if (UI.getUse().getResNo() == Value) {
7433 // Found exactly the right number of uses?
7437 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7438 /// value. This method ignores uses of other values defined by this operation.
7439 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7440 assert(Value < getNumValues() && "Bad value!");
7442 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7443 if (UI.getUse().getResNo() == Value)
7449 /// isOnlyUserOf - Return true if this node is the only use of N.
7450 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7452 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7463 /// Return true if the only users of N are contained in Nodes.
7464 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7466 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7468 if (llvm::any_of(Nodes,
7469 [&User](const SDNode *Node) { return User == Node; }))
7478 /// isOperand - Return true if this node is an operand of N.
7479 bool SDValue::isOperandOf(const SDNode *N) const {
7480 for (const SDValue &Op : N->op_values())
7486 bool SDNode::isOperandOf(const SDNode *N) const {
7487 for (const SDValue &Op : N->op_values())
7488 if (this == Op.getNode())
7493 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7494 /// be a chain) reaches the specified operand without crossing any
7495 /// side-effecting instructions on any chain path. In practice, this looks
7496 /// through token factors and non-volatile loads. In order to remain efficient,
7497 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7499 /// Note that we only need to examine chains when we're searching for
7500 /// side-effects; SelectionDAG requires that all side-effects are represented
7501 /// by chains, even if another operand would force a specific ordering. This
7502 /// constraint is necessary to allow transformations like splitting loads.
7503 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7504 unsigned Depth) const {
7505 if (*this == Dest) return true;
7507 // Don't search too deeply, we just want to be able to see through
7508 // TokenFactor's etc.
7509 if (Depth == 0) return false;
7511 // If this is a token factor, all inputs to the TF happen in parallel.
7512 if (getOpcode() == ISD::TokenFactor) {
7513 // First, try a shallow search.
7514 if (is_contained((*this)->ops(), Dest)) {
7515 // We found the chain we want as an operand of this TokenFactor.
7516 // Essentially, we reach the chain without side-effects if we could
7517 // serialize the TokenFactor into a simple chain of operations with
7518 // Dest as the last operation. This is automatically true if the
7519 // chain has one use: there are no other ordering constraints.
7520 // If the chain has more than one use, we give up: some other
7521 // use of Dest might force a side-effect between Dest and the current
7523 if (Dest.hasOneUse())
7526 // Next, try a deep search: check whether every operand of the TokenFactor
7528 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
7529 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7533 // Loads don't have side effects, look through them.
7534 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7535 if (!Ld->isVolatile())
7536 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7541 bool SDNode::hasPredecessor(const SDNode *N) const {
7542 SmallPtrSet<const SDNode *, 32> Visited;
7543 SmallVector<const SDNode *, 16> Worklist;
7544 Worklist.push_back(this);
7545 return hasPredecessorHelper(N, Visited, Worklist);
7548 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
7549 this->Flags.intersectWith(Flags);
7552 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7553 assert(N->getNumValues() == 1 &&
7554 "Can't unroll a vector with multiple results!");
7556 EVT VT = N->getValueType(0);
7557 unsigned NE = VT.getVectorNumElements();
7558 EVT EltVT = VT.getVectorElementType();
7561 SmallVector<SDValue, 8> Scalars;
7562 SmallVector<SDValue, 4> Operands(N->getNumOperands());
7564 // If ResNE is 0, fully unroll the vector op.
7567 else if (NE > ResNE)
7571 for (i= 0; i != NE; ++i) {
7572 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7573 SDValue Operand = N->getOperand(j);
7574 EVT OperandVT = Operand.getValueType();
7575 if (OperandVT.isVector()) {
7576 // A vector operand; extract a single element.
7577 EVT OperandEltVT = OperandVT.getVectorElementType();
7579 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7580 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7582 // A scalar operand; just use it as is.
7583 Operands[j] = Operand;
7587 switch (N->getOpcode()) {
7589 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7594 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7601 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7602 getShiftAmountOperand(Operands[0].getValueType(),
7605 case ISD::SIGN_EXTEND_INREG:
7606 case ISD::FP_ROUND_INREG: {
7607 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7608 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7610 getValueType(ExtVT)));
7615 for (; i < ResNE; ++i)
7616 Scalars.push_back(getUNDEF(EltVT));
7618 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7619 return getBuildVector(VecVT, dl, Scalars);
7622 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7626 if (LD->isVolatile() || Base->isVolatile())
7628 if (LD->isIndexed() || Base->isIndexed())
7630 if (LD->getChain() != Base->getChain())
7632 EVT VT = LD->getValueType(0);
7633 if (VT.getSizeInBits() / 8 != Bytes)
7636 SDValue Loc = LD->getOperand(1);
7637 SDValue BaseLoc = Base->getOperand(1);
7639 auto BaseLocDecomp = BaseIndexOffset::match(BaseLoc, *this);
7640 auto LocDecomp = BaseIndexOffset::match(Loc, *this);
7643 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
7644 return (Dist * Bytes == Offset);
7648 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7649 /// it cannot be inferred.
7650 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7651 // If this is a GlobalAddress + cst, return the alignment.
7652 const GlobalValue *GV;
7653 int64_t GVOffset = 0;
7654 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7655 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7656 KnownBits Known(PtrWidth);
7657 llvm::computeKnownBits(GV, Known, getDataLayout());
7658 unsigned AlignBits = Known.countMinTrailingZeros();
7659 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7661 return MinAlign(Align, GVOffset);
7664 // If this is a direct reference to a stack slot, use information about the
7665 // stack slot's alignment.
7666 int FrameIdx = 1 << 31;
7667 int64_t FrameOffset = 0;
7668 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7669 FrameIdx = FI->getIndex();
7670 } else if (isBaseWithConstantOffset(Ptr) &&
7671 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7673 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7674 FrameOffset = Ptr.getConstantOperandVal(1);
7677 if (FrameIdx != (1 << 31)) {
7678 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7679 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7687 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7688 /// which is split (or expanded) into two not necessarily identical pieces.
7689 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7690 // Currently all types are split in half.
7693 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7695 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
7697 return std::make_pair(LoVT, HiVT);
7700 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7702 std::pair<SDValue, SDValue>
7703 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7705 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7706 N.getValueType().getVectorNumElements() &&
7707 "More vector elements requested than available!");
7709 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7710 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7711 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7712 getConstant(LoVT.getVectorNumElements(), DL,
7713 TLI->getVectorIdxTy(getDataLayout())));
7714 return std::make_pair(Lo, Hi);
7717 void SelectionDAG::ExtractVectorElements(SDValue Op,
7718 SmallVectorImpl<SDValue> &Args,
7719 unsigned Start, unsigned Count) {
7720 EVT VT = Op.getValueType();
7722 Count = VT.getVectorNumElements();
7724 EVT EltVT = VT.getVectorElementType();
7725 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7727 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7728 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7729 Op, getConstant(i, SL, IdxTy)));
7733 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7734 unsigned GlobalAddressSDNode::getAddressSpace() const {
7735 return getGlobal()->getType()->getAddressSpace();
7738 Type *ConstantPoolSDNode::getType() const {
7739 if (isMachineConstantPoolEntry())
7740 return Val.MachineCPVal->getType();
7741 return Val.ConstVal->getType();
7744 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
7745 unsigned &SplatBitSize,
7747 unsigned MinSplatBits,
7748 bool IsBigEndian) const {
7749 EVT VT = getValueType(0);
7750 assert(VT.isVector() && "Expected a vector type");
7751 unsigned VecWidth = VT.getSizeInBits();
7752 if (MinSplatBits > VecWidth)
7755 // FIXME: The widths are based on this node's type, but build vectors can
7756 // truncate their operands.
7757 SplatValue = APInt(VecWidth, 0);
7758 SplatUndef = APInt(VecWidth, 0);
7760 // Get the bits. Bits with undefined values (when the corresponding element
7761 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7762 // in SplatValue. If any of the values are not constant, give up and return
7764 unsigned int NumOps = getNumOperands();
7765 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
7766 unsigned EltWidth = VT.getScalarSizeInBits();
7768 for (unsigned j = 0; j < NumOps; ++j) {
7769 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
7770 SDValue OpVal = getOperand(i);
7771 unsigned BitPos = j * EltWidth;
7773 if (OpVal.isUndef())
7774 SplatUndef.setBits(BitPos, BitPos + EltWidth);
7775 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
7776 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
7777 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7778 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
7783 // The build_vector is all constants or undefs. Find the smallest element
7784 // size that splats the vector.
7785 HasAnyUndefs = (SplatUndef != 0);
7787 // FIXME: This does not work for vectors with elements less than 8 bits.
7788 while (VecWidth > 8) {
7789 unsigned HalfSize = VecWidth / 2;
7790 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7791 APInt LowValue = SplatValue.trunc(HalfSize);
7792 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7793 APInt LowUndef = SplatUndef.trunc(HalfSize);
7795 // If the two halves do not match (ignoring undef bits), stop here.
7796 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7797 MinSplatBits > HalfSize)
7800 SplatValue = HighValue | LowValue;
7801 SplatUndef = HighUndef & LowUndef;
7803 VecWidth = HalfSize;
7806 SplatBitSize = VecWidth;
7810 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7811 if (UndefElements) {
7812 UndefElements->clear();
7813 UndefElements->resize(getNumOperands());
7816 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7817 SDValue Op = getOperand(i);
7820 (*UndefElements)[i] = true;
7821 } else if (!Splatted) {
7823 } else if (Splatted != Op) {
7829 assert(getOperand(0).isUndef() &&
7830 "Can only have a splat without a constant for all undefs.");
7831 return getOperand(0);
7838 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7839 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7843 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7844 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7848 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7849 uint32_t BitWidth) const {
7850 if (ConstantFPSDNode *CN =
7851 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7853 APSInt IntVal(BitWidth);
7854 const APFloat &APF = CN->getValueAPF();
7855 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7860 return IntVal.exactLogBase2();
7865 bool BuildVectorSDNode::isConstant() const {
7866 for (const SDValue &Op : op_values()) {
7867 unsigned Opc = Op.getOpcode();
7868 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7874 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7875 // Find the first non-undef value in the shuffle mask.
7877 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7880 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7882 // Make sure all remaining elements are either undef or the same as the first
7884 for (int Idx = Mask[i]; i != e; ++i)
7885 if (Mask[i] >= 0 && Mask[i] != Idx)
7890 // \brief Returns the SDNode if it is a constant integer BuildVector
7891 // or constant integer.
7892 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7893 if (isa<ConstantSDNode>(N))
7895 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7897 // Treat a GlobalAddress supporting constant offset folding as a
7898 // constant integer.
7899 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7900 if (GA->getOpcode() == ISD::GlobalAddress &&
7901 TLI->isOffsetFoldingLegal(GA))
7906 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
7907 if (isa<ConstantFPSDNode>(N))
7910 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
7917 static void checkForCyclesHelper(const SDNode *N,
7918 SmallPtrSetImpl<const SDNode*> &Visited,
7919 SmallPtrSetImpl<const SDNode*> &Checked,
7920 const llvm::SelectionDAG *DAG) {
7921 // If this node has already been checked, don't check it again.
7922 if (Checked.count(N))
7925 // If a node has already been visited on this depth-first walk, reject it as
7927 if (!Visited.insert(N).second) {
7928 errs() << "Detected cycle in SelectionDAG\n";
7929 dbgs() << "Offending node:\n";
7930 N->dumprFull(DAG); dbgs() << "\n";
7934 for (const SDValue &Op : N->op_values())
7935 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7942 void llvm::checkForCycles(const llvm::SDNode *N,
7943 const llvm::SelectionDAG *DAG,
7947 #ifdef EXPENSIVE_CHECKS
7949 #endif // EXPENSIVE_CHECKS
7951 assert(N && "Checking nonexistent SDNode");
7952 SmallPtrSet<const SDNode*, 32> visited;
7953 SmallPtrSet<const SDNode*, 32> checked;
7954 checkForCyclesHelper(N, visited, checked, DAG);
7959 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7960 checkForCycles(DAG->getRoot().getNode(), DAG, force);