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/APSInt.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Mutex.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetIntrinsicInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
56 /// makeVTList - Return an instance of the SDVTList struct initialized with the
57 /// specified members.
58 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
59 SDVTList Res = {VTs, NumVTs};
63 // Default null implementations of the callbacks.
64 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
65 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
67 //===----------------------------------------------------------------------===//
68 // ConstantFPSDNode Class
69 //===----------------------------------------------------------------------===//
71 /// isExactlyValue - We don't rely on operator== working on double values, as
72 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
73 /// As such, this method can be used to do an exact bit-for-bit comparison of
74 /// two floating point values.
75 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
76 return getValueAPF().bitwiseIsEqual(V);
79 bool ConstantFPSDNode::isValueValidForType(EVT VT,
81 assert(VT.isFloatingPoint() && "Can only convert between FP types");
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
86 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
87 APFloat::rmNearestTiesToEven,
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
96 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
97 auto *BV = dyn_cast<BuildVectorSDNode>(N);
102 unsigned SplatBitSize;
104 EVT EltVT = N->getValueType(0).getVectorElementType();
105 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs) &&
106 EltVT.getSizeInBits() >= SplatBitSize;
109 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
110 // specializations of the more general isConstantSplatVector()?
112 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
113 // Look through a bit convert.
114 while (N->getOpcode() == ISD::BITCAST)
115 N = N->getOperand(0).getNode();
117 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
119 unsigned i = 0, e = N->getNumOperands();
121 // Skip over all of the undef values.
122 while (i != e && N->getOperand(i).isUndef())
125 // Do not accept an all-undef vector.
126 if (i == e) return false;
128 // Do not accept build_vectors that aren't all constants or which have non-~0
129 // elements. We have to be a bit careful here, as the type of the constant
130 // may not be the same as the type of the vector elements due to type
131 // legalization (the elements are promoted to a legal type for the target and
132 // a vector of a type may be legal when the base element type is not).
133 // We only want to check enough bits to cover the vector elements, because
134 // we care if the resultant vector is all ones, not whether the individual
136 SDValue NotZero = N->getOperand(i);
137 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
138 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
139 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
141 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
142 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
147 // Okay, we have at least one ~0 value, check to see if the rest match or are
148 // undefs. Even with the above element type twiddling, this should be OK, as
149 // the same type legalization should have applied to all the elements.
150 for (++i; i != e; ++i)
151 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
156 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
157 // Look through a bit convert.
158 while (N->getOpcode() == ISD::BITCAST)
159 N = N->getOperand(0).getNode();
161 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
163 bool IsAllUndef = true;
164 for (const SDValue &Op : N->op_values()) {
168 // Do not accept build_vectors that aren't all constants or which have non-0
169 // elements. We have to be a bit careful here, as the type of the constant
170 // may not be the same as the type of the vector elements due to type
171 // legalization (the elements are promoted to a legal type for the target
172 // and a vector of a type may be legal when the base element type is not).
173 // We only want to check enough bits to cover the vector elements, because
174 // we care if the resultant vector is all zeros, not whether the individual
176 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
177 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
178 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
180 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
181 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
187 // Do not accept an all-undef vector.
193 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
194 if (N->getOpcode() != ISD::BUILD_VECTOR)
197 for (const SDValue &Op : N->op_values()) {
200 if (!isa<ConstantSDNode>(Op))
206 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
207 if (N->getOpcode() != ISD::BUILD_VECTOR)
210 for (const SDValue &Op : N->op_values()) {
213 if (!isa<ConstantFPSDNode>(Op))
219 bool ISD::allOperandsUndef(const SDNode *N) {
220 // Return false if the node has no operands.
221 // This is "logically inconsistent" with the definition of "all" but
222 // is probably the desired behavior.
223 if (N->getNumOperands() == 0)
226 for (const SDValue &Op : N->op_values())
233 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
236 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
238 return ISD::SIGN_EXTEND;
240 return ISD::ZERO_EXTEND;
245 llvm_unreachable("Invalid LoadExtType");
248 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
249 // To perform this operation, we just need to swap the L and G bits of the
251 unsigned OldL = (Operation >> 2) & 1;
252 unsigned OldG = (Operation >> 1) & 1;
253 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
254 (OldL << 1) | // New G bit
255 (OldG << 2)); // New L bit.
258 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
259 unsigned Operation = Op;
261 Operation ^= 7; // Flip L, G, E bits, but not U.
263 Operation ^= 15; // Flip all of the condition bits.
265 if (Operation > ISD::SETTRUE2)
266 Operation &= ~8; // Don't let N and U bits get set.
268 return ISD::CondCode(Operation);
272 /// For an integer comparison, return 1 if the comparison is a signed operation
273 /// and 2 if the result is an unsigned comparison. Return zero if the operation
274 /// does not depend on the sign of the input (setne and seteq).
275 static int isSignedOp(ISD::CondCode Opcode) {
277 default: llvm_unreachable("Illegal integer setcc operation!");
279 case ISD::SETNE: return 0;
283 case ISD::SETGE: return 1;
287 case ISD::SETUGE: return 2;
291 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
293 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
294 // Cannot fold a signed integer setcc with an unsigned integer setcc.
295 return ISD::SETCC_INVALID;
297 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
299 // If the N and U bits get set, then the resultant comparison DOES suddenly
300 // care about orderedness, and it is true when ordered.
301 if (Op > ISD::SETTRUE2)
302 Op &= ~16; // Clear the U bit if the N bit is set.
304 // Canonicalize illegal integer setcc's.
305 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
308 return ISD::CondCode(Op);
311 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
313 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
314 // Cannot fold a signed setcc with an unsigned setcc.
315 return ISD::SETCC_INVALID;
317 // Combine all of the condition bits.
318 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
320 // Canonicalize illegal integer setcc's.
324 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
325 case ISD::SETOEQ: // SETEQ & SETU[LG]E
326 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
327 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
328 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
335 //===----------------------------------------------------------------------===//
336 // SDNode Profile Support
337 //===----------------------------------------------------------------------===//
339 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
341 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
345 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
346 /// solely with their pointer.
347 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
348 ID.AddPointer(VTList.VTs);
351 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
353 static void AddNodeIDOperands(FoldingSetNodeID &ID,
354 ArrayRef<SDValue> Ops) {
355 for (auto& Op : Ops) {
356 ID.AddPointer(Op.getNode());
357 ID.AddInteger(Op.getResNo());
361 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
363 static void AddNodeIDOperands(FoldingSetNodeID &ID,
364 ArrayRef<SDUse> Ops) {
365 for (auto& Op : Ops) {
366 ID.AddPointer(Op.getNode());
367 ID.AddInteger(Op.getResNo());
371 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
372 SDVTList VTList, ArrayRef<SDValue> OpList) {
373 AddNodeIDOpcode(ID, OpC);
374 AddNodeIDValueTypes(ID, VTList);
375 AddNodeIDOperands(ID, OpList);
378 /// If this is an SDNode with special info, add this info to the NodeID data.
379 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
380 switch (N->getOpcode()) {
381 case ISD::TargetExternalSymbol:
382 case ISD::ExternalSymbol:
384 llvm_unreachable("Should only be used on nodes with operands");
385 default: break; // Normal nodes don't need extra info.
386 case ISD::TargetConstant:
387 case ISD::Constant: {
388 const ConstantSDNode *C = cast<ConstantSDNode>(N);
389 ID.AddPointer(C->getConstantIntValue());
390 ID.AddBoolean(C->isOpaque());
393 case ISD::TargetConstantFP:
394 case ISD::ConstantFP: {
395 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
398 case ISD::TargetGlobalAddress:
399 case ISD::GlobalAddress:
400 case ISD::TargetGlobalTLSAddress:
401 case ISD::GlobalTLSAddress: {
402 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
403 ID.AddPointer(GA->getGlobal());
404 ID.AddInteger(GA->getOffset());
405 ID.AddInteger(GA->getTargetFlags());
408 case ISD::BasicBlock:
409 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
412 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
414 case ISD::RegisterMask:
415 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
418 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
420 case ISD::FrameIndex:
421 case ISD::TargetFrameIndex:
422 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
425 case ISD::TargetJumpTable:
426 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
427 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
429 case ISD::ConstantPool:
430 case ISD::TargetConstantPool: {
431 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
432 ID.AddInteger(CP->getAlignment());
433 ID.AddInteger(CP->getOffset());
434 if (CP->isMachineConstantPoolEntry())
435 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
437 ID.AddPointer(CP->getConstVal());
438 ID.AddInteger(CP->getTargetFlags());
441 case ISD::TargetIndex: {
442 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
443 ID.AddInteger(TI->getIndex());
444 ID.AddInteger(TI->getOffset());
445 ID.AddInteger(TI->getTargetFlags());
449 const LoadSDNode *LD = cast<LoadSDNode>(N);
450 ID.AddInteger(LD->getMemoryVT().getRawBits());
451 ID.AddInteger(LD->getRawSubclassData());
452 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
456 const StoreSDNode *ST = cast<StoreSDNode>(N);
457 ID.AddInteger(ST->getMemoryVT().getRawBits());
458 ID.AddInteger(ST->getRawSubclassData());
459 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
462 case ISD::ATOMIC_CMP_SWAP:
463 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
464 case ISD::ATOMIC_SWAP:
465 case ISD::ATOMIC_LOAD_ADD:
466 case ISD::ATOMIC_LOAD_SUB:
467 case ISD::ATOMIC_LOAD_AND:
468 case ISD::ATOMIC_LOAD_OR:
469 case ISD::ATOMIC_LOAD_XOR:
470 case ISD::ATOMIC_LOAD_NAND:
471 case ISD::ATOMIC_LOAD_MIN:
472 case ISD::ATOMIC_LOAD_MAX:
473 case ISD::ATOMIC_LOAD_UMIN:
474 case ISD::ATOMIC_LOAD_UMAX:
475 case ISD::ATOMIC_LOAD:
476 case ISD::ATOMIC_STORE: {
477 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
478 ID.AddInteger(AT->getMemoryVT().getRawBits());
479 ID.AddInteger(AT->getRawSubclassData());
480 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
483 case ISD::PREFETCH: {
484 const MemSDNode *PF = cast<MemSDNode>(N);
485 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
488 case ISD::VECTOR_SHUFFLE: {
489 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
490 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
492 ID.AddInteger(SVN->getMaskElt(i));
495 case ISD::TargetBlockAddress:
496 case ISD::BlockAddress: {
497 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
498 ID.AddPointer(BA->getBlockAddress());
499 ID.AddInteger(BA->getOffset());
500 ID.AddInteger(BA->getTargetFlags());
503 } // end switch (N->getOpcode())
505 // Target specific memory nodes could also have address spaces to check.
506 if (N->isTargetMemoryOpcode())
507 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
510 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
512 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
513 AddNodeIDOpcode(ID, N->getOpcode());
514 // Add the return value info.
515 AddNodeIDValueTypes(ID, N->getVTList());
516 // Add the operand info.
517 AddNodeIDOperands(ID, N->ops());
519 // Handle SDNode leafs with special info.
520 AddNodeIDCustom(ID, N);
523 //===----------------------------------------------------------------------===//
524 // SelectionDAG Class
525 //===----------------------------------------------------------------------===//
527 /// doNotCSE - Return true if CSE should not be performed for this node.
528 static bool doNotCSE(SDNode *N) {
529 if (N->getValueType(0) == MVT::Glue)
530 return true; // Never CSE anything that produces a flag.
532 switch (N->getOpcode()) {
534 case ISD::HANDLENODE:
536 return true; // Never CSE these nodes.
539 // Check that remaining values produced are not flags.
540 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
541 if (N->getValueType(i) == MVT::Glue)
542 return true; // Never CSE anything that produces a flag.
547 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
549 void SelectionDAG::RemoveDeadNodes() {
550 // Create a dummy node (which is not added to allnodes), that adds a reference
551 // to the root node, preventing it from being deleted.
552 HandleSDNode Dummy(getRoot());
554 SmallVector<SDNode*, 128> DeadNodes;
556 // Add all obviously-dead nodes to the DeadNodes worklist.
557 for (SDNode &Node : allnodes())
558 if (Node.use_empty())
559 DeadNodes.push_back(&Node);
561 RemoveDeadNodes(DeadNodes);
563 // If the root changed (e.g. it was a dead load, update the root).
564 setRoot(Dummy.getValue());
567 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
568 /// given list, and any nodes that become unreachable as a result.
569 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
571 // Process the worklist, deleting the nodes and adding their uses to the
573 while (!DeadNodes.empty()) {
574 SDNode *N = DeadNodes.pop_back_val();
576 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
577 DUL->NodeDeleted(N, nullptr);
579 // Take the node out of the appropriate CSE map.
580 RemoveNodeFromCSEMaps(N);
582 // Next, brutally remove the operand list. This is safe to do, as there are
583 // no cycles in the graph.
584 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
586 SDNode *Operand = Use.getNode();
589 // Now that we removed this operand, see if there are no uses of it left.
590 if (Operand->use_empty())
591 DeadNodes.push_back(Operand);
598 void SelectionDAG::RemoveDeadNode(SDNode *N){
599 SmallVector<SDNode*, 16> DeadNodes(1, N);
601 // Create a dummy node that adds a reference to the root node, preventing
602 // it from being deleted. (This matters if the root is an operand of the
604 HandleSDNode Dummy(getRoot());
606 RemoveDeadNodes(DeadNodes);
609 void SelectionDAG::DeleteNode(SDNode *N) {
610 // First take this out of the appropriate CSE map.
611 RemoveNodeFromCSEMaps(N);
613 // Finally, remove uses due to operands of this node, remove from the
614 // AllNodes list, and delete the node.
615 DeleteNodeNotInCSEMaps(N);
618 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
619 assert(N->getIterator() != AllNodes.begin() &&
620 "Cannot delete the entry node!");
621 assert(N->use_empty() && "Cannot delete a node that is not dead!");
623 // Drop all of the operands and decrement used node's use counts.
629 void SDDbgInfo::erase(const SDNode *Node) {
630 DbgValMapType::iterator I = DbgValMap.find(Node);
631 if (I == DbgValMap.end())
633 for (auto &Val: I->second)
634 Val->setIsInvalidated();
638 void SelectionDAG::DeallocateNode(SDNode *N) {
639 // If we have operands, deallocate them.
642 NodeAllocator.Deallocate(AllNodes.remove(N));
644 // Set the opcode to DELETED_NODE to help catch bugs when node
645 // memory is reallocated.
646 // FIXME: There are places in SDag that have grown a dependency on the opcode
647 // value in the released node.
648 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
649 N->NodeType = ISD::DELETED_NODE;
651 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
652 // them and forget about that node.
657 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
658 static void VerifySDNode(SDNode *N) {
659 switch (N->getOpcode()) {
662 case ISD::BUILD_PAIR: {
663 EVT VT = N->getValueType(0);
664 assert(N->getNumValues() == 1 && "Too many results!");
665 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
666 "Wrong return type!");
667 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
668 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
669 "Mismatched operand types!");
670 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
671 "Wrong operand type!");
672 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
673 "Wrong return type size");
676 case ISD::BUILD_VECTOR: {
677 assert(N->getNumValues() == 1 && "Too many results!");
678 assert(N->getValueType(0).isVector() && "Wrong return type!");
679 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
680 "Wrong number of operands!");
681 EVT EltVT = N->getValueType(0).getVectorElementType();
682 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
683 assert((I->getValueType() == EltVT ||
684 (EltVT.isInteger() && I->getValueType().isInteger() &&
685 EltVT.bitsLE(I->getValueType()))) &&
686 "Wrong operand type!");
687 assert(I->getValueType() == N->getOperand(0).getValueType() &&
688 "Operands must all have the same type");
696 /// \brief Insert a newly allocated node into the DAG.
698 /// Handles insertion into the all nodes list and CSE map, as well as
699 /// verification and other common operations when a new node is allocated.
700 void SelectionDAG::InsertNode(SDNode *N) {
701 AllNodes.push_back(N);
703 N->PersistentId = NextPersistentId++;
708 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
709 /// correspond to it. This is useful when we're about to delete or repurpose
710 /// the node. We don't want future request for structurally identical nodes
711 /// to return N anymore.
712 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
714 switch (N->getOpcode()) {
715 case ISD::HANDLENODE: return false; // noop.
717 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
718 "Cond code doesn't exist!");
719 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
720 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
722 case ISD::ExternalSymbol:
723 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
725 case ISD::TargetExternalSymbol: {
726 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
727 Erased = TargetExternalSymbols.erase(
728 std::pair<std::string,unsigned char>(ESN->getSymbol(),
729 ESN->getTargetFlags()));
732 case ISD::MCSymbol: {
733 auto *MCSN = cast<MCSymbolSDNode>(N);
734 Erased = MCSymbols.erase(MCSN->getMCSymbol());
737 case ISD::VALUETYPE: {
738 EVT VT = cast<VTSDNode>(N)->getVT();
739 if (VT.isExtended()) {
740 Erased = ExtendedValueTypeNodes.erase(VT);
742 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
743 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
748 // Remove it from the CSE Map.
749 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
750 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
751 Erased = CSEMap.RemoveNode(N);
755 // Verify that the node was actually in one of the CSE maps, unless it has a
756 // flag result (which cannot be CSE'd) or is one of the special cases that are
757 // not subject to CSE.
758 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
759 !N->isMachineOpcode() && !doNotCSE(N)) {
762 llvm_unreachable("Node is not in map!");
768 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
769 /// maps and modified in place. Add it back to the CSE maps, unless an identical
770 /// node already exists, in which case transfer all its users to the existing
771 /// node. This transfer can potentially trigger recursive merging.
774 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
775 // For node types that aren't CSE'd, just act as if no identical node
778 SDNode *Existing = CSEMap.GetOrInsertNode(N);
780 // If there was already an existing matching node, use ReplaceAllUsesWith
781 // to replace the dead one with the existing one. This can cause
782 // recursive merging of other unrelated nodes down the line.
783 ReplaceAllUsesWith(N, Existing);
785 // N is now dead. Inform the listeners and delete it.
786 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
787 DUL->NodeDeleted(N, Existing);
788 DeleteNodeNotInCSEMaps(N);
793 // If the node doesn't already exist, we updated it. Inform listeners.
794 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
798 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
799 /// were replaced with those specified. If this node is never memoized,
800 /// return null, otherwise return a pointer to the slot it would take. If a
801 /// node already exists with these operands, the slot will be non-null.
802 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
807 SDValue Ops[] = { Op };
809 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
810 AddNodeIDCustom(ID, N);
811 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
813 if (const SDNodeFlags *Flags = N->getFlags())
814 Node->intersectFlagsWith(Flags);
818 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
819 /// were replaced with those specified. If this node is never memoized,
820 /// return null, otherwise return a pointer to the slot it would take. If a
821 /// node already exists with these operands, the slot will be non-null.
822 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
823 SDValue Op1, SDValue Op2,
828 SDValue Ops[] = { Op1, Op2 };
830 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
831 AddNodeIDCustom(ID, N);
832 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
834 if (const SDNodeFlags *Flags = N->getFlags())
835 Node->intersectFlagsWith(Flags);
840 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
841 /// were replaced with those specified. If this node is never memoized,
842 /// return null, otherwise return a pointer to the slot it would take. If a
843 /// node already exists with these operands, the slot will be non-null.
844 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
850 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
851 AddNodeIDCustom(ID, N);
852 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
854 if (const SDNodeFlags *Flags = N->getFlags())
855 Node->intersectFlagsWith(Flags);
859 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
860 Type *Ty = VT == MVT::iPTR ?
861 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
862 VT.getTypeForEVT(*getContext());
864 return getDataLayout().getABITypeAlignment(Ty);
867 // EntryNode could meaningfully have debug info if we can find it...
868 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
869 : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL),
870 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
871 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false),
872 UpdateListeners(nullptr) {
873 InsertNode(&EntryNode);
874 DbgInfo = new SDDbgInfo();
877 void SelectionDAG::init(MachineFunction &NewMF,
878 OptimizationRemarkEmitter &NewORE) {
881 TLI = getSubtarget().getTargetLowering();
882 TSI = getSubtarget().getSelectionDAGInfo();
883 Context = &MF->getFunction()->getContext();
886 SelectionDAG::~SelectionDAG() {
887 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
889 OperandRecycler.clear(OperandAllocator);
893 void SelectionDAG::allnodes_clear() {
894 assert(&*AllNodes.begin() == &EntryNode);
895 AllNodes.remove(AllNodes.begin());
896 while (!AllNodes.empty())
897 DeallocateNode(&AllNodes.front());
899 NextPersistentId = 0;
903 SDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, const SDLoc &DL,
904 SDVTList VTs, SDValue N1, SDValue N2,
905 const SDNodeFlags *Flags) {
906 SDValue Ops[] = {N1, N2};
908 if (isBinOpWithFlags(Opcode)) {
909 // If no flags were passed in, use a default flags object.
911 if (Flags == nullptr)
914 auto *FN = newSDNode<BinaryWithFlagsSDNode>(Opcode, DL.getIROrder(),
915 DL.getDebugLoc(), VTs, *Flags);
916 createOperands(FN, Ops);
921 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
922 createOperands(N, Ops);
926 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
928 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
930 switch (N->getOpcode()) {
933 case ISD::ConstantFP:
934 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
935 "debug location. Use another overload.");
941 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
942 const SDLoc &DL, void *&InsertPos) {
943 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
945 switch (N->getOpcode()) {
947 case ISD::ConstantFP:
948 // Erase debug location from the node if the node is used at several
949 // different places. Do not propagate one location to all uses as it
950 // will cause a worse single stepping debugging experience.
951 if (N->getDebugLoc() != DL.getDebugLoc())
952 N->setDebugLoc(DebugLoc());
955 // When the node's point of use is located earlier in the instruction
956 // sequence than its prior point of use, update its debug info to the
958 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
959 N->setDebugLoc(DL.getDebugLoc());
966 void SelectionDAG::clear() {
968 OperandRecycler.clear(OperandAllocator);
969 OperandAllocator.Reset();
972 ExtendedValueTypeNodes.clear();
973 ExternalSymbols.clear();
974 TargetExternalSymbols.clear();
976 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
977 static_cast<CondCodeSDNode*>(nullptr));
978 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
979 static_cast<SDNode*>(nullptr));
981 EntryNode.UseList = nullptr;
982 InsertNode(&EntryNode);
983 Root = getEntryNode();
987 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
988 return VT.bitsGT(Op.getValueType()) ?
989 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
990 getNode(ISD::TRUNCATE, DL, VT, Op);
993 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
994 return VT.bitsGT(Op.getValueType()) ?
995 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
996 getNode(ISD::TRUNCATE, DL, VT, Op);
999 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1000 return VT.bitsGT(Op.getValueType()) ?
1001 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1002 getNode(ISD::TRUNCATE, DL, VT, Op);
1005 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1007 if (VT.bitsLE(Op.getValueType()))
1008 return getNode(ISD::TRUNCATE, SL, VT, Op);
1010 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1011 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1014 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1015 assert(!VT.isVector() &&
1016 "getZeroExtendInReg should use the vector element type instead of "
1017 "the vector type!");
1018 if (Op.getValueType() == VT) return Op;
1019 unsigned BitWidth = Op.getScalarValueSizeInBits();
1020 APInt Imm = APInt::getLowBitsSet(BitWidth,
1021 VT.getSizeInBits());
1022 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1023 getConstant(Imm, DL, Op.getValueType()));
1026 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1028 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1029 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1030 "The sizes of the input and result must match in order to perform the "
1031 "extend in-register.");
1032 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1033 "The destination vector type must have fewer lanes than the input.");
1034 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1037 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1039 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1040 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1041 "The sizes of the input and result must match in order to perform the "
1042 "extend in-register.");
1043 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1044 "The destination vector type must have fewer lanes than the input.");
1045 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1048 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1050 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1051 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1052 "The sizes of the input and result must match in order to perform the "
1053 "extend in-register.");
1054 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1055 "The destination vector type must have fewer lanes than the input.");
1056 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1059 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1061 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1062 EVT EltVT = VT.getScalarType();
1064 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1065 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1068 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1069 EVT EltVT = VT.getScalarType();
1071 switch (TLI->getBooleanContents(VT)) {
1072 case TargetLowering::ZeroOrOneBooleanContent:
1073 case TargetLowering::UndefinedBooleanContent:
1074 TrueValue = getConstant(1, DL, VT);
1076 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1077 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1081 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1084 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1085 bool isT, bool isO) {
1086 EVT EltVT = VT.getScalarType();
1087 assert((EltVT.getSizeInBits() >= 64 ||
1088 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1089 "getConstant with a uint64_t value that doesn't fit in the type!");
1090 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1093 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1094 bool isT, bool isO) {
1095 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1098 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1099 EVT VT, bool isT, bool isO) {
1100 assert(VT.isInteger() && "Cannot create FP integer constant!");
1102 EVT EltVT = VT.getScalarType();
1103 const ConstantInt *Elt = &Val;
1105 // In some cases the vector type is legal but the element type is illegal and
1106 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1107 // inserted value (the type does not need to match the vector element type).
1108 // Any extra bits introduced will be truncated away.
1109 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1110 TargetLowering::TypePromoteInteger) {
1111 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1112 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1113 Elt = ConstantInt::get(*getContext(), NewVal);
1115 // In other cases the element type is illegal and needs to be expanded, for
1116 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1117 // the value into n parts and use a vector type with n-times the elements.
1118 // Then bitcast to the type requested.
1119 // Legalizing constants too early makes the DAGCombiner's job harder so we
1120 // only legalize if the DAG tells us we must produce legal types.
1121 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1122 TLI->getTypeAction(*getContext(), EltVT) ==
1123 TargetLowering::TypeExpandInteger) {
1124 const APInt &NewVal = Elt->getValue();
1125 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1126 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1127 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1128 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1130 // Check the temporary vector is the correct size. If this fails then
1131 // getTypeToTransformTo() probably returned a type whose size (in bits)
1132 // isn't a power-of-2 factor of the requested type size.
1133 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1135 SmallVector<SDValue, 2> EltParts;
1136 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1137 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1138 .zextOrTrunc(ViaEltSizeInBits), DL,
1139 ViaEltVT, isT, isO));
1142 // EltParts is currently in little endian order. If we actually want
1143 // big-endian order then reverse it now.
1144 if (getDataLayout().isBigEndian())
1145 std::reverse(EltParts.begin(), EltParts.end());
1147 // The elements must be reversed when the element order is different
1148 // to the endianness of the elements (because the BITCAST is itself a
1149 // vector shuffle in this situation). However, we do not need any code to
1150 // perform this reversal because getConstant() is producing a vector
1152 // This situation occurs in MIPS MSA.
1154 SmallVector<SDValue, 8> Ops;
1155 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1156 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1157 return getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1160 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1161 "APInt size does not match type size!");
1162 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1163 FoldingSetNodeID ID;
1164 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1168 SDNode *N = nullptr;
1169 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1171 return SDValue(N, 0);
1174 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1175 CSEMap.InsertNode(N, IP);
1179 SDValue Result(N, 0);
1181 Result = getSplatBuildVector(VT, DL, Result);
1185 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1187 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1190 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1192 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1195 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1196 EVT VT, bool isTarget) {
1197 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1199 EVT EltVT = VT.getScalarType();
1201 // Do the map lookup using the actual bit pattern for the floating point
1202 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1203 // we don't have issues with SNANs.
1204 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1205 FoldingSetNodeID ID;
1206 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1209 SDNode *N = nullptr;
1210 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1212 return SDValue(N, 0);
1215 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1216 CSEMap.InsertNode(N, IP);
1220 SDValue Result(N, 0);
1222 Result = getSplatBuildVector(VT, DL, Result);
1226 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1228 EVT EltVT = VT.getScalarType();
1229 if (EltVT == MVT::f32)
1230 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1231 else if (EltVT == MVT::f64)
1232 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1233 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1234 EltVT == MVT::f16) {
1236 APFloat APF = APFloat(Val);
1237 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1239 return getConstantFP(APF, DL, VT, isTarget);
1241 llvm_unreachable("Unsupported type in getConstantFP");
1244 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1245 EVT VT, int64_t Offset, bool isTargetGA,
1246 unsigned char TargetFlags) {
1247 assert((TargetFlags == 0 || isTargetGA) &&
1248 "Cannot set target flags on target-independent globals");
1250 // Truncate (with sign-extension) the offset value to the pointer size.
1251 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1253 Offset = SignExtend64(Offset, BitWidth);
1256 if (GV->isThreadLocal())
1257 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1259 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1261 FoldingSetNodeID ID;
1262 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1264 ID.AddInteger(Offset);
1265 ID.AddInteger(TargetFlags);
1267 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1268 return SDValue(E, 0);
1270 auto *N = newSDNode<GlobalAddressSDNode>(
1271 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1272 CSEMap.InsertNode(N, IP);
1274 return SDValue(N, 0);
1277 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1278 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1279 FoldingSetNodeID ID;
1280 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1283 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1284 return SDValue(E, 0);
1286 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1287 CSEMap.InsertNode(N, IP);
1289 return SDValue(N, 0);
1292 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1293 unsigned char TargetFlags) {
1294 assert((TargetFlags == 0 || isTarget) &&
1295 "Cannot set target flags on target-independent jump tables");
1296 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1297 FoldingSetNodeID ID;
1298 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1300 ID.AddInteger(TargetFlags);
1302 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1303 return SDValue(E, 0);
1305 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1306 CSEMap.InsertNode(N, IP);
1308 return SDValue(N, 0);
1311 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1312 unsigned Alignment, int Offset,
1314 unsigned char TargetFlags) {
1315 assert((TargetFlags == 0 || isTarget) &&
1316 "Cannot set target flags on target-independent globals");
1318 Alignment = MF->getFunction()->optForSize()
1319 ? getDataLayout().getABITypeAlignment(C->getType())
1320 : getDataLayout().getPrefTypeAlignment(C->getType());
1321 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1322 FoldingSetNodeID ID;
1323 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1324 ID.AddInteger(Alignment);
1325 ID.AddInteger(Offset);
1327 ID.AddInteger(TargetFlags);
1329 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1330 return SDValue(E, 0);
1332 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1334 CSEMap.InsertNode(N, IP);
1336 return SDValue(N, 0);
1340 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1341 unsigned Alignment, int Offset,
1343 unsigned char TargetFlags) {
1344 assert((TargetFlags == 0 || isTarget) &&
1345 "Cannot set target flags on target-independent globals");
1347 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1348 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1349 FoldingSetNodeID ID;
1350 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1351 ID.AddInteger(Alignment);
1352 ID.AddInteger(Offset);
1353 C->addSelectionDAGCSEId(ID);
1354 ID.AddInteger(TargetFlags);
1356 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1357 return SDValue(E, 0);
1359 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1361 CSEMap.InsertNode(N, IP);
1363 return SDValue(N, 0);
1366 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1367 unsigned char TargetFlags) {
1368 FoldingSetNodeID ID;
1369 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1370 ID.AddInteger(Index);
1371 ID.AddInteger(Offset);
1372 ID.AddInteger(TargetFlags);
1374 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1375 return SDValue(E, 0);
1377 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1378 CSEMap.InsertNode(N, IP);
1380 return SDValue(N, 0);
1383 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1384 FoldingSetNodeID ID;
1385 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1388 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1389 return SDValue(E, 0);
1391 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1392 CSEMap.InsertNode(N, IP);
1394 return SDValue(N, 0);
1397 SDValue SelectionDAG::getValueType(EVT VT) {
1398 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1399 ValueTypeNodes.size())
1400 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1402 SDNode *&N = VT.isExtended() ?
1403 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1405 if (N) return SDValue(N, 0);
1406 N = newSDNode<VTSDNode>(VT);
1408 return SDValue(N, 0);
1411 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1412 SDNode *&N = ExternalSymbols[Sym];
1413 if (N) return SDValue(N, 0);
1414 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1416 return SDValue(N, 0);
1419 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1420 SDNode *&N = MCSymbols[Sym];
1422 return SDValue(N, 0);
1423 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1425 return SDValue(N, 0);
1428 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1429 unsigned char TargetFlags) {
1431 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1433 if (N) return SDValue(N, 0);
1434 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1436 return SDValue(N, 0);
1439 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1440 if ((unsigned)Cond >= CondCodeNodes.size())
1441 CondCodeNodes.resize(Cond+1);
1443 if (!CondCodeNodes[Cond]) {
1444 auto *N = newSDNode<CondCodeSDNode>(Cond);
1445 CondCodeNodes[Cond] = N;
1449 return SDValue(CondCodeNodes[Cond], 0);
1452 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1453 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1454 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1456 ShuffleVectorSDNode::commuteMask(M);
1459 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1460 SDValue N2, ArrayRef<int> Mask) {
1461 assert(VT.getVectorNumElements() == Mask.size() &&
1462 "Must have the same number of vector elements as mask elements!");
1463 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1464 "Invalid VECTOR_SHUFFLE");
1466 // Canonicalize shuffle undef, undef -> undef
1467 if (N1.isUndef() && N2.isUndef())
1468 return getUNDEF(VT);
1470 // Validate that all indices in Mask are within the range of the elements
1471 // input to the shuffle.
1472 int NElts = Mask.size();
1473 assert(all_of(Mask, [&](int M) { return M < (NElts * 2); }) &&
1474 "Index out of range");
1476 // Copy the mask so we can do any needed cleanup.
1477 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1479 // Canonicalize shuffle v, v -> v, undef
1482 for (int i = 0; i != NElts; ++i)
1483 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1486 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1488 commuteShuffle(N1, N2, MaskVec);
1490 // If shuffling a splat, try to blend the splat instead. We do this here so
1491 // that even when this arises during lowering we don't have to re-handle it.
1492 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1493 BitVector UndefElements;
1494 SDValue Splat = BV->getSplatValue(&UndefElements);
1498 for (int i = 0; i < NElts; ++i) {
1499 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1502 // If this input comes from undef, mark it as such.
1503 if (UndefElements[MaskVec[i] - Offset]) {
1508 // If we can blend a non-undef lane, use that instead.
1509 if (!UndefElements[i])
1510 MaskVec[i] = i + Offset;
1513 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1514 BlendSplat(N1BV, 0);
1515 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1516 BlendSplat(N2BV, NElts);
1518 // Canonicalize all index into lhs, -> shuffle lhs, undef
1519 // Canonicalize all index into rhs, -> shuffle rhs, undef
1520 bool AllLHS = true, AllRHS = true;
1521 bool N2Undef = N2.isUndef();
1522 for (int i = 0; i != NElts; ++i) {
1523 if (MaskVec[i] >= NElts) {
1528 } else if (MaskVec[i] >= 0) {
1532 if (AllLHS && AllRHS)
1533 return getUNDEF(VT);
1534 if (AllLHS && !N2Undef)
1538 commuteShuffle(N1, N2, MaskVec);
1540 // Reset our undef status after accounting for the mask.
1541 N2Undef = N2.isUndef();
1542 // Re-check whether both sides ended up undef.
1543 if (N1.isUndef() && N2Undef)
1544 return getUNDEF(VT);
1546 // If Identity shuffle return that node.
1547 bool Identity = true, AllSame = true;
1548 for (int i = 0; i != NElts; ++i) {
1549 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1550 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1552 if (Identity && NElts)
1555 // Shuffling a constant splat doesn't change the result.
1559 // Look through any bitcasts. We check that these don't change the number
1560 // (and size) of elements and just changes their types.
1561 while (V.getOpcode() == ISD::BITCAST)
1562 V = V->getOperand(0);
1564 // A splat should always show up as a build vector node.
1565 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1566 BitVector UndefElements;
1567 SDValue Splat = BV->getSplatValue(&UndefElements);
1568 // If this is a splat of an undef, shuffling it is also undef.
1569 if (Splat && Splat.isUndef())
1570 return getUNDEF(VT);
1573 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1575 // We only have a splat which can skip shuffles if there is a splatted
1576 // value and no undef lanes rearranged by the shuffle.
1577 if (Splat && UndefElements.none()) {
1578 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1579 // number of elements match or the value splatted is a zero constant.
1582 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1583 if (C->isNullValue())
1587 // If the shuffle itself creates a splat, build the vector directly.
1588 if (AllSame && SameNumElts) {
1589 EVT BuildVT = BV->getValueType(0);
1590 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1591 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1593 // We may have jumped through bitcasts, so the type of the
1594 // BUILD_VECTOR may not match the type of the shuffle.
1596 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1602 FoldingSetNodeID ID;
1603 SDValue Ops[2] = { N1, N2 };
1604 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1605 for (int i = 0; i != NElts; ++i)
1606 ID.AddInteger(MaskVec[i]);
1609 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1610 return SDValue(E, 0);
1612 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1613 // SDNode doesn't have access to it. This memory will be "leaked" when
1614 // the node is deallocated, but recovered when the NodeAllocator is released.
1615 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1616 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1618 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1619 dl.getDebugLoc(), MaskAlloc);
1620 createOperands(N, Ops);
1622 CSEMap.InsertNode(N, IP);
1624 return SDValue(N, 0);
1627 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1628 MVT VT = SV.getSimpleValueType(0);
1629 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1630 ShuffleVectorSDNode::commuteMask(MaskVec);
1632 SDValue Op0 = SV.getOperand(0);
1633 SDValue Op1 = SV.getOperand(1);
1634 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1637 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1638 FoldingSetNodeID ID;
1639 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1640 ID.AddInteger(RegNo);
1642 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1643 return SDValue(E, 0);
1645 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1646 CSEMap.InsertNode(N, IP);
1648 return SDValue(N, 0);
1651 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1652 FoldingSetNodeID ID;
1653 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1654 ID.AddPointer(RegMask);
1656 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1657 return SDValue(E, 0);
1659 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1660 CSEMap.InsertNode(N, IP);
1662 return SDValue(N, 0);
1665 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1667 FoldingSetNodeID ID;
1668 SDValue Ops[] = { Root };
1669 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1670 ID.AddPointer(Label);
1672 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1673 return SDValue(E, 0);
1675 auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1676 createOperands(N, Ops);
1678 CSEMap.InsertNode(N, IP);
1680 return SDValue(N, 0);
1683 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1686 unsigned char TargetFlags) {
1687 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1689 FoldingSetNodeID ID;
1690 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1692 ID.AddInteger(Offset);
1693 ID.AddInteger(TargetFlags);
1695 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1696 return SDValue(E, 0);
1698 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1699 CSEMap.InsertNode(N, IP);
1701 return SDValue(N, 0);
1704 SDValue SelectionDAG::getSrcValue(const Value *V) {
1705 assert((!V || V->getType()->isPointerTy()) &&
1706 "SrcValue is not a pointer?");
1708 FoldingSetNodeID ID;
1709 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1713 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1714 return SDValue(E, 0);
1716 auto *N = newSDNode<SrcValueSDNode>(V);
1717 CSEMap.InsertNode(N, IP);
1719 return SDValue(N, 0);
1722 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1723 FoldingSetNodeID ID;
1724 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1728 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1729 return SDValue(E, 0);
1731 auto *N = newSDNode<MDNodeSDNode>(MD);
1732 CSEMap.InsertNode(N, IP);
1734 return SDValue(N, 0);
1737 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1738 if (VT == V.getValueType())
1741 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1744 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1745 unsigned SrcAS, unsigned DestAS) {
1746 SDValue Ops[] = {Ptr};
1747 FoldingSetNodeID ID;
1748 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1749 ID.AddInteger(SrcAS);
1750 ID.AddInteger(DestAS);
1753 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1754 return SDValue(E, 0);
1756 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1758 createOperands(N, Ops);
1760 CSEMap.InsertNode(N, IP);
1762 return SDValue(N, 0);
1765 /// getShiftAmountOperand - Return the specified value casted to
1766 /// the target's desired shift amount type.
1767 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1768 EVT OpTy = Op.getValueType();
1769 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1770 if (OpTy == ShTy || OpTy.isVector()) return Op;
1772 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1775 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1777 const TargetLowering &TLI = getTargetLoweringInfo();
1778 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1779 EVT VT = Node->getValueType(0);
1780 SDValue Tmp1 = Node->getOperand(0);
1781 SDValue Tmp2 = Node->getOperand(1);
1782 unsigned Align = Node->getConstantOperandVal(3);
1784 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1785 Tmp2, MachinePointerInfo(V));
1786 SDValue VAList = VAListLoad;
1788 if (Align > TLI.getMinStackArgumentAlignment()) {
1789 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1791 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1792 getConstant(Align - 1, dl, VAList.getValueType()));
1794 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1795 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1798 // Increment the pointer, VAList, to the next vaarg
1799 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1800 getConstant(getDataLayout().getTypeAllocSize(
1801 VT.getTypeForEVT(*getContext())),
1802 dl, VAList.getValueType()));
1803 // Store the incremented VAList to the legalized pointer
1805 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1806 // Load the actual argument out of the pointer VAList
1807 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1810 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1812 const TargetLowering &TLI = getTargetLoweringInfo();
1813 // This defaults to loading a pointer from the input and storing it to the
1814 // output, returning the chain.
1815 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1816 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1818 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1819 Node->getOperand(2), MachinePointerInfo(VS));
1820 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1821 MachinePointerInfo(VD));
1824 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1825 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1826 unsigned ByteSize = VT.getStoreSize();
1827 Type *Ty = VT.getTypeForEVT(*getContext());
1828 unsigned StackAlign =
1829 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1831 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1832 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1835 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1836 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1837 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1838 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1839 const DataLayout &DL = getDataLayout();
1841 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1843 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1844 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1845 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1848 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1849 ISD::CondCode Cond, const SDLoc &dl) {
1850 // These setcc operations always fold.
1854 case ISD::SETFALSE2: return getConstant(0, dl, VT);
1856 case ISD::SETTRUE2: {
1857 TargetLowering::BooleanContent Cnt =
1858 TLI->getBooleanContents(N1->getValueType(0));
1860 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1874 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1878 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1879 const APInt &C2 = N2C->getAPIntValue();
1880 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1881 const APInt &C1 = N1C->getAPIntValue();
1884 default: llvm_unreachable("Unknown integer setcc!");
1885 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT);
1886 case ISD::SETNE: return getConstant(C1 != C2, dl, VT);
1887 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1888 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1889 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1890 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1891 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT);
1892 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT);
1893 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT);
1894 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT);
1898 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1899 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1900 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1903 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1904 return getUNDEF(VT);
1906 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1907 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1908 return getUNDEF(VT);
1910 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1911 R==APFloat::cmpLessThan, dl, VT);
1912 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1913 return getUNDEF(VT);
1915 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1916 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1917 return getUNDEF(VT);
1919 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1920 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1921 return getUNDEF(VT);
1923 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1924 R==APFloat::cmpEqual, dl, VT);
1925 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1926 return getUNDEF(VT);
1928 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1929 R==APFloat::cmpEqual, dl, VT);
1930 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1931 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT);
1932 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1933 R==APFloat::cmpEqual, dl, VT);
1934 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1935 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1936 R==APFloat::cmpLessThan, dl, VT);
1937 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1938 R==APFloat::cmpUnordered, dl, VT);
1939 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1940 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1943 // Ensure that the constant occurs on the RHS.
1944 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1945 MVT CompVT = N1.getValueType().getSimpleVT();
1946 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1949 return getSetCC(dl, VT, N2, N1, SwappedCond);
1953 // Could not fold it.
1957 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1958 /// use this predicate to simplify operations downstream.
1959 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1960 unsigned BitWidth = Op.getScalarValueSizeInBits();
1961 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
1964 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1965 /// this predicate to simplify operations downstream. Mask is known to be zero
1966 /// for bits that V cannot have.
1967 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1968 unsigned Depth) const {
1969 APInt KnownZero, KnownOne;
1970 computeKnownBits(Op, KnownZero, KnownOne, Depth);
1971 return (KnownZero & Mask) == Mask;
1974 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
1975 /// is less than the element bit-width of the shift node, return it.
1976 static const APInt *getValidShiftAmountConstant(SDValue V) {
1977 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
1978 // Shifting more than the bitwidth is not valid.
1979 const APInt &ShAmt = SA->getAPIntValue();
1980 if (ShAmt.ult(V.getScalarValueSizeInBits()))
1986 /// Determine which bits of Op are known to be either zero or one and return
1987 /// them in the KnownZero/KnownOne bitsets. For vectors, the known bits are
1988 /// those that are shared by every vector element.
1989 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
1990 APInt &KnownOne, unsigned Depth) const {
1991 EVT VT = Op.getValueType();
1992 APInt DemandedElts = VT.isVector()
1993 ? APInt::getAllOnesValue(VT.getVectorNumElements())
1995 computeKnownBits(Op, KnownZero, KnownOne, DemandedElts, Depth);
1998 /// Determine which bits of Op are known to be either zero or one and return
1999 /// them in the KnownZero/KnownOne bitsets. The DemandedElts argument allows
2000 /// us to only collect the known bits that are shared by the requested vector
2002 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
2003 APInt &KnownOne, const APInt &DemandedElts,
2004 unsigned Depth) const {
2005 unsigned BitWidth = Op.getScalarValueSizeInBits();
2007 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
2009 return; // Limit search depth.
2011 APInt KnownZero2, KnownOne2;
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 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
2022 KnownZero = ~KnownOne;
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 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2029 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2030 if (!DemandedElts[i])
2033 SDValue SrcOp = Op.getOperand(i);
2034 computeKnownBits(SrcOp, KnownZero2, KnownOne2, 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 KnownOne2 = KnownOne2.trunc(BitWidth);
2041 KnownZero2 = KnownZero2.trunc(BitWidth);
2044 // Known bits are the values that are shared by every demanded element.
2045 KnownOne &= KnownOne2;
2046 KnownZero &= KnownZero2;
2048 // If we don't know any bits, early out.
2049 if (!KnownOne && !KnownZero)
2053 case ISD::VECTOR_SHUFFLE: {
2054 // Collect the known bits that are shared by every vector element referenced
2056 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2057 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2058 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2059 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2060 for (unsigned i = 0; i != NumElts; ++i) {
2061 if (!DemandedElts[i])
2064 int M = SVN->getMaskElt(i);
2066 // For UNDEF elements, we don't know anything about the common state of
2067 // the shuffle result.
2068 KnownOne.clearAllBits();
2069 KnownZero.clearAllBits();
2070 DemandedLHS.clearAllBits();
2071 DemandedRHS.clearAllBits();
2075 if ((unsigned)M < NumElts)
2076 DemandedLHS.setBit((unsigned)M % NumElts);
2078 DemandedRHS.setBit((unsigned)M % NumElts);
2080 // Known bits are the values that are shared by every demanded element.
2081 if (!!DemandedLHS) {
2082 SDValue LHS = Op.getOperand(0);
2083 computeKnownBits(LHS, KnownZero2, KnownOne2, DemandedLHS, Depth + 1);
2084 KnownOne &= KnownOne2;
2085 KnownZero &= KnownZero2;
2087 // If we don't know any bits, early out.
2088 if (!KnownOne && !KnownZero)
2090 if (!!DemandedRHS) {
2091 SDValue RHS = Op.getOperand(1);
2092 computeKnownBits(RHS, KnownZero2, KnownOne2, DemandedRHS, Depth + 1);
2093 KnownOne &= KnownOne2;
2094 KnownZero &= KnownZero2;
2098 case ISD::CONCAT_VECTORS: {
2099 // Split DemandedElts and test each of the demanded subvectors.
2100 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2101 EVT SubVectorVT = Op.getOperand(0).getValueType();
2102 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2103 unsigned NumSubVectors = Op.getNumOperands();
2104 for (unsigned i = 0; i != NumSubVectors; ++i) {
2105 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2106 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2107 if (!!DemandedSub) {
2108 SDValue Sub = Op.getOperand(i);
2109 computeKnownBits(Sub, KnownZero2, KnownOne2, DemandedSub, Depth + 1);
2110 KnownOne &= KnownOne2;
2111 KnownZero &= KnownZero2;
2113 // If we don't know any bits, early out.
2114 if (!KnownOne && !KnownZero)
2119 case ISD::EXTRACT_SUBVECTOR: {
2120 // If we know the element index, just demand that subvector elements,
2121 // otherwise demand them all.
2122 SDValue Src = Op.getOperand(0);
2123 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2124 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2125 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2126 // Offset the demanded elts by the subvector index.
2127 uint64_t Idx = SubIdx->getZExtValue();
2128 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
2129 computeKnownBits(Src, KnownZero, KnownOne, DemandedSrc, Depth + 1);
2131 computeKnownBits(Src, KnownZero, KnownOne, Depth + 1);
2135 case ISD::BITCAST: {
2136 SDValue N0 = Op.getOperand(0);
2137 unsigned SubBitWidth = N0.getScalarValueSizeInBits();
2139 // Ignore bitcasts from floating point.
2140 if (!N0.getValueType().isInteger())
2143 // Fast handling of 'identity' bitcasts.
2144 if (BitWidth == SubBitWidth) {
2145 computeKnownBits(N0, KnownZero, KnownOne, DemandedElts, Depth + 1);
2149 // Support big-endian targets when it becomes useful.
2150 bool IsLE = getDataLayout().isLittleEndian();
2154 // Bitcast 'small element' vector to 'large element' scalar/vector.
2155 if ((BitWidth % SubBitWidth) == 0) {
2156 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2158 // Collect known bits for the (larger) output by collecting the known
2159 // bits from each set of sub elements and shift these into place.
2160 // We need to separately call computeKnownBits for each set of
2161 // sub elements as the knownbits for each is likely to be different.
2162 unsigned SubScale = BitWidth / SubBitWidth;
2163 APInt SubDemandedElts(NumElts * SubScale, 0);
2164 for (unsigned i = 0; i != NumElts; ++i)
2165 if (DemandedElts[i])
2166 SubDemandedElts.setBit(i * SubScale);
2168 for (unsigned i = 0; i != SubScale; ++i) {
2169 computeKnownBits(N0, KnownZero2, KnownOne2, SubDemandedElts.shl(i),
2171 KnownOne |= KnownOne2.zext(BitWidth).shl(SubBitWidth * i);
2172 KnownZero |= KnownZero2.zext(BitWidth).shl(SubBitWidth * i);
2176 // Bitcast 'large element' scalar/vector to 'small element' vector.
2177 if ((SubBitWidth % BitWidth) == 0) {
2178 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2180 // Collect known bits for the (smaller) output by collecting the known
2181 // bits from the overlapping larger input elements and extracting the
2182 // sub sections we actually care about.
2183 unsigned SubScale = SubBitWidth / BitWidth;
2184 APInt SubDemandedElts(NumElts / SubScale, 0);
2185 for (unsigned i = 0; i != NumElts; ++i)
2186 if (DemandedElts[i])
2187 SubDemandedElts.setBit(i / SubScale);
2189 computeKnownBits(N0, KnownZero2, KnownOne2, SubDemandedElts, Depth + 1);
2191 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2192 for (unsigned i = 0; i != NumElts; ++i)
2193 if (DemandedElts[i]) {
2194 unsigned Offset = (i % SubScale) * BitWidth;
2195 KnownOne &= KnownOne2.lshr(Offset).trunc(BitWidth);
2196 KnownZero &= KnownZero2.lshr(Offset).trunc(BitWidth);
2197 // If we don't know any bits, early out.
2198 if (!KnownOne && !KnownZero)
2205 // If either the LHS or the RHS are Zero, the result is zero.
2206 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2208 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2211 // Output known-1 bits are only known if set in both the LHS & RHS.
2212 KnownOne &= KnownOne2;
2213 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2214 KnownZero |= KnownZero2;
2217 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2219 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2222 // Output known-0 bits are only known if clear in both the LHS & RHS.
2223 KnownZero &= KnownZero2;
2224 // Output known-1 are known to be set if set in either the LHS | RHS.
2225 KnownOne |= KnownOne2;
2228 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2230 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2233 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2234 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
2235 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2236 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
2237 KnownZero = KnownZeroOut;
2241 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2243 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2246 // If low bits are zero in either operand, output low known-0 bits.
2247 // Also compute a conservative estimate for high known-0 bits.
2248 // More trickiness is possible, but this is sufficient for the
2249 // interesting case of alignment computation.
2250 KnownOne.clearAllBits();
2251 unsigned TrailZ = KnownZero.countTrailingOnes() +
2252 KnownZero2.countTrailingOnes();
2253 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
2254 KnownZero2.countLeadingOnes(),
2255 BitWidth) - BitWidth;
2257 KnownZero.clearAllBits();
2258 KnownZero.setLowBits(std::min(TrailZ, BitWidth));
2259 KnownZero.setHighBits(std::min(LeadZ, BitWidth));
2263 // For the purposes of computing leading zeros we can conservatively
2264 // treat a udiv as a logical right shift by the power of 2 known to
2265 // be less than the denominator.
2266 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2268 unsigned LeadZ = KnownZero2.countLeadingOnes();
2270 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2272 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
2273 if (RHSUnknownLeadingOnes != BitWidth)
2274 LeadZ = std::min(BitWidth,
2275 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
2277 KnownZero.setHighBits(LeadZ);
2281 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
2282 // If we don't know any bits, early out.
2283 if (!KnownOne && !KnownZero)
2285 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2287 // Only known if known in both the LHS and RHS.
2288 KnownOne &= KnownOne2;
2289 KnownZero &= KnownZero2;
2291 case ISD::SELECT_CC:
2292 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
2293 // If we don't know any bits, early out.
2294 if (!KnownOne && !KnownZero)
2296 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
2298 // Only known if known in both the LHS and RHS.
2299 KnownOne &= KnownOne2;
2300 KnownZero &= KnownZero2;
2304 if (Op.getResNo() != 1)
2306 // The boolean result conforms to getBooleanContents.
2307 // If we know the result of a setcc has the top bits zero, use this info.
2308 // We know that we have an integer-based boolean since these operations
2309 // are only available for integer.
2310 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2311 TargetLowering::ZeroOrOneBooleanContent &&
2313 KnownZero.setBitsFrom(1);
2316 // If we know the result of a setcc has the top bits zero, use this info.
2317 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2318 TargetLowering::ZeroOrOneBooleanContent &&
2320 KnownZero.setBitsFrom(1);
2323 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2324 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2326 KnownZero = KnownZero << *ShAmt;
2327 KnownOne = KnownOne << *ShAmt;
2328 // Low bits are known zero.
2329 KnownZero.setLowBits(ShAmt->getZExtValue());
2333 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2334 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2336 KnownZero.lshrInPlace(*ShAmt);
2337 KnownOne.lshrInPlace(*ShAmt);
2338 // High bits are known zero.
2339 KnownZero.setHighBits(ShAmt->getZExtValue());
2343 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2344 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2346 KnownZero.lshrInPlace(*ShAmt);
2347 KnownOne.lshrInPlace(*ShAmt);
2348 // If we know the value of the sign bit, then we know it is copied across
2349 // the high bits by the shift amount.
2350 APInt SignMask = APInt::getSignMask(BitWidth);
2351 SignMask.lshrInPlace(*ShAmt); // Adjust to where it is now in the mask.
2352 if (KnownZero.intersects(SignMask)) {
2353 KnownZero.setHighBits(ShAmt->getZExtValue());// New bits are known zero.
2354 } else if (KnownOne.intersects(SignMask)) {
2355 KnownOne.setHighBits(ShAmt->getZExtValue()); // New bits are known one.
2359 case ISD::SIGN_EXTEND_INREG: {
2360 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2361 unsigned EBits = EVT.getScalarSizeInBits();
2363 // Sign extension. Compute the demanded bits in the result that are not
2364 // present in the input.
2365 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2367 APInt InSignMask = APInt::getSignMask(EBits);
2368 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2370 // If the sign extended bits are demanded, we know that the sign
2372 InSignMask = InSignMask.zext(BitWidth);
2373 if (NewBits.getBoolValue())
2374 InputDemandedBits |= InSignMask;
2376 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2378 KnownOne &= InputDemandedBits;
2379 KnownZero &= InputDemandedBits;
2381 // If the sign bit of the input is known set or clear, then we know the
2382 // top bits of the result.
2383 if (KnownZero.intersects(InSignMask)) { // Input sign bit known clear
2384 KnownZero |= NewBits;
2385 KnownOne &= ~NewBits;
2386 } else if (KnownOne.intersects(InSignMask)) { // Input sign bit known set
2387 KnownOne |= NewBits;
2388 KnownZero &= ~NewBits;
2389 } else { // Input sign bit unknown
2390 KnownZero &= ~NewBits;
2391 KnownOne &= ~NewBits;
2396 case ISD::CTTZ_ZERO_UNDEF:
2398 case ISD::CTLZ_ZERO_UNDEF:
2400 KnownZero.setBitsFrom(Log2_32(BitWidth)+1);
2404 LoadSDNode *LD = cast<LoadSDNode>(Op);
2405 // If this is a ZEXTLoad and we are looking at the loaded value.
2406 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2407 EVT VT = LD->getMemoryVT();
2408 unsigned MemBits = VT.getScalarSizeInBits();
2409 KnownZero.setBitsFrom(MemBits);
2410 } else if (const MDNode *Ranges = LD->getRanges()) {
2411 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2412 computeKnownBitsFromRangeMetadata(*Ranges, KnownZero, KnownOne);
2416 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2417 EVT InVT = Op.getOperand(0).getValueType();
2418 unsigned InBits = InVT.getScalarSizeInBits();
2419 KnownZero = KnownZero.trunc(InBits);
2420 KnownOne = KnownOne.trunc(InBits);
2421 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne,
2422 DemandedElts.zext(InVT.getVectorNumElements()),
2424 KnownZero = KnownZero.zext(BitWidth);
2425 KnownOne = KnownOne.zext(BitWidth);
2426 KnownZero.setBitsFrom(InBits);
2429 case ISD::ZERO_EXTEND: {
2430 EVT InVT = Op.getOperand(0).getValueType();
2431 unsigned InBits = InVT.getScalarSizeInBits();
2432 KnownZero = KnownZero.trunc(InBits);
2433 KnownOne = KnownOne.trunc(InBits);
2434 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2436 KnownZero = KnownZero.zext(BitWidth);
2437 KnownOne = KnownOne.zext(BitWidth);
2438 KnownZero.setBitsFrom(InBits);
2441 // TODO ISD::SIGN_EXTEND_VECTOR_INREG
2442 case ISD::SIGN_EXTEND: {
2443 EVT InVT = Op.getOperand(0).getValueType();
2444 unsigned InBits = InVT.getScalarSizeInBits();
2446 KnownZero = KnownZero.trunc(InBits);
2447 KnownOne = KnownOne.trunc(InBits);
2448 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2451 // If the sign bit is known to be zero or one, then sext will extend
2452 // it to the top bits, else it will just zext.
2453 KnownZero = KnownZero.sext(BitWidth);
2454 KnownOne = KnownOne.sext(BitWidth);
2457 case ISD::ANY_EXTEND: {
2458 EVT InVT = Op.getOperand(0).getValueType();
2459 unsigned InBits = InVT.getScalarSizeInBits();
2460 KnownZero = KnownZero.trunc(InBits);
2461 KnownOne = KnownOne.trunc(InBits);
2462 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2463 KnownZero = KnownZero.zext(BitWidth);
2464 KnownOne = KnownOne.zext(BitWidth);
2467 case ISD::TRUNCATE: {
2468 EVT InVT = Op.getOperand(0).getValueType();
2469 unsigned InBits = InVT.getScalarSizeInBits();
2470 KnownZero = KnownZero.zext(InBits);
2471 KnownOne = KnownOne.zext(InBits);
2472 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2474 KnownZero = KnownZero.trunc(BitWidth);
2475 KnownOne = KnownOne.trunc(BitWidth);
2478 case ISD::AssertZext: {
2479 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2480 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2481 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2482 KnownZero |= (~InMask);
2483 KnownOne &= (~KnownZero);
2487 // All bits are zero except the low bit.
2488 KnownZero.setBitsFrom(1);
2492 if (Op.getResNo() == 1) {
2493 // If we know the result of a setcc has the top bits zero, use this info.
2494 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2495 TargetLowering::ZeroOrOneBooleanContent &&
2497 KnownZero.setBitsFrom(1);
2503 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2504 // We know that the top bits of C-X are clear if X contains less bits
2505 // than C (i.e. no wrap-around can happen). For example, 20-X is
2506 // positive if we can prove that X is >= 0 and < 16.
2507 if (CLHS->getAPIntValue().isNonNegative()) {
2508 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2509 // NLZ can't be BitWidth with no sign bit
2510 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2511 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2514 // If all of the MaskV bits are known to be zero, then we know the
2515 // output top bits are zero, because we now know that the output is
2517 if ((KnownZero2 & MaskV) == MaskV) {
2518 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2519 // Top bits known zero.
2520 KnownZero.setHighBits(NLZ2);
2525 // If low bits are know to be zero in both operands, then we know they are
2526 // going to be 0 in the result. Both addition and complement operations
2527 // preserve the low zero bits.
2528 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2530 unsigned KnownZeroLow = KnownZero2.countTrailingOnes();
2531 if (KnownZeroLow == 0)
2534 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2536 KnownZeroLow = std::min(KnownZeroLow,
2537 KnownZero2.countTrailingOnes());
2538 KnownZero.setBits(0, KnownZeroLow);
2543 if (Op.getResNo() == 1) {
2544 // If we know the result of a setcc has the top bits zero, use this info.
2545 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2546 TargetLowering::ZeroOrOneBooleanContent &&
2548 KnownZero.setBitsFrom(1);
2555 // Output known-0 bits are known if clear or set in both the low clear bits
2556 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2557 // low 3 bits clear.
2558 // Output known-0 bits are also known if the top bits of each input are
2559 // known to be clear. For example, if one input has the top 10 bits clear
2560 // and the other has the top 8 bits clear, we know the top 7 bits of the
2561 // output must be clear.
2562 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2564 unsigned KnownZeroHigh = KnownZero2.countLeadingOnes();
2565 unsigned KnownZeroLow = KnownZero2.countTrailingOnes();
2567 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2569 KnownZeroHigh = std::min(KnownZeroHigh,
2570 KnownZero2.countLeadingOnes());
2571 KnownZeroLow = std::min(KnownZeroLow,
2572 KnownZero2.countTrailingOnes());
2574 if (Opcode == ISD::ADDE) {
2575 // With ADDE, a carry bit may be added in, so we can only use this
2576 // information if we know (at least) that the low two bits are clear.
2577 // We then return to the caller that the low bit is unknown but that
2578 // other bits are known zero.
2579 if (KnownZeroLow >= 2)
2580 KnownZero.setBits(1, KnownZeroLow);
2584 KnownZero.setLowBits(KnownZeroLow);
2585 if (KnownZeroHigh > 1)
2586 KnownZero.setHighBits(KnownZeroHigh - 1);
2590 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2591 const APInt &RA = Rem->getAPIntValue().abs();
2592 if (RA.isPowerOf2()) {
2593 APInt LowBits = RA - 1;
2594 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2597 // The low bits of the first operand are unchanged by the srem.
2598 KnownZero = KnownZero2 & LowBits;
2599 KnownOne = KnownOne2 & LowBits;
2601 // If the first operand is non-negative or has all low bits zero, then
2602 // the upper bits are all zero.
2603 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2604 KnownZero |= ~LowBits;
2606 // If the first operand is negative and not all low bits are zero, then
2607 // the upper bits are all one.
2608 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2609 KnownOne |= ~LowBits;
2610 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2615 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2616 const APInt &RA = Rem->getAPIntValue();
2617 if (RA.isPowerOf2()) {
2618 APInt LowBits = (RA - 1);
2619 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2622 // The upper bits are all zero, the lower ones are unchanged.
2623 KnownZero = KnownZero2 | ~LowBits;
2624 KnownOne = KnownOne2 & LowBits;
2629 // Since the result is less than or equal to either operand, any leading
2630 // zero bits in either operand must also exist in the result.
2631 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2633 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2636 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2637 KnownZero2.countLeadingOnes());
2638 KnownOne.clearAllBits();
2639 KnownZero.clearAllBits();
2640 KnownZero.setHighBits(Leaders);
2643 case ISD::EXTRACT_ELEMENT: {
2644 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2645 const unsigned Index = Op.getConstantOperandVal(1);
2646 const unsigned BitWidth = Op.getValueSizeInBits();
2648 // Remove low part of known bits mask
2649 KnownZero = KnownZero.getHiBits(KnownZero.getBitWidth() - Index * BitWidth);
2650 KnownOne = KnownOne.getHiBits(KnownOne.getBitWidth() - Index * BitWidth);
2652 // Remove high part of known bit mask
2653 KnownZero = KnownZero.trunc(BitWidth);
2654 KnownOne = KnownOne.trunc(BitWidth);
2657 case ISD::EXTRACT_VECTOR_ELT: {
2658 SDValue InVec = Op.getOperand(0);
2659 SDValue EltNo = Op.getOperand(1);
2660 EVT VecVT = InVec.getValueType();
2661 const unsigned BitWidth = Op.getValueSizeInBits();
2662 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
2663 const unsigned NumSrcElts = VecVT.getVectorNumElements();
2664 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2665 // anything about the extended bits.
2666 if (BitWidth > EltBitWidth) {
2667 KnownZero = KnownZero.trunc(EltBitWidth);
2668 KnownOne = KnownOne.trunc(EltBitWidth);
2670 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
2671 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
2672 // If we know the element index, just demand that vector element.
2673 unsigned Idx = ConstEltNo->getZExtValue();
2674 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
2675 computeKnownBits(InVec, KnownZero, KnownOne, DemandedElt, Depth + 1);
2677 // Unknown element index, so ignore DemandedElts and demand them all.
2678 computeKnownBits(InVec, KnownZero, KnownOne, Depth + 1);
2680 if (BitWidth > EltBitWidth) {
2681 KnownZero = KnownZero.zext(BitWidth);
2682 KnownOne = KnownOne.zext(BitWidth);
2686 case ISD::INSERT_VECTOR_ELT: {
2687 SDValue InVec = Op.getOperand(0);
2688 SDValue InVal = Op.getOperand(1);
2689 SDValue EltNo = Op.getOperand(2);
2691 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
2692 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
2693 // If we know the element index, split the demand between the
2694 // source vector and the inserted element.
2695 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2696 unsigned EltIdx = CEltNo->getZExtValue();
2698 // If we demand the inserted element then add its common known bits.
2699 if (DemandedElts[EltIdx]) {
2700 computeKnownBits(InVal, KnownZero2, KnownOne2, Depth + 1);
2701 KnownOne &= KnownOne2.zextOrTrunc(KnownOne.getBitWidth());
2702 KnownZero &= KnownZero2.zextOrTrunc(KnownZero.getBitWidth());;
2705 // If we demand the source vector then add its common known bits, ensuring
2706 // that we don't demand the inserted element.
2707 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
2709 computeKnownBits(InVec, KnownZero2, KnownOne2, VectorElts, Depth + 1);
2710 KnownOne &= KnownOne2;
2711 KnownZero &= KnownZero2;
2714 // Unknown element index, so ignore DemandedElts and demand them all.
2715 computeKnownBits(InVec, KnownZero, KnownOne, Depth + 1);
2716 computeKnownBits(InVal, KnownZero2, KnownOne2, Depth + 1);
2717 KnownOne &= KnownOne2.zextOrTrunc(KnownOne.getBitWidth());
2718 KnownZero &= KnownZero2.zextOrTrunc(KnownZero.getBitWidth());;
2722 case ISD::BITREVERSE: {
2723 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2725 KnownZero = KnownZero2.reverseBits();
2726 KnownOne = KnownOne2.reverseBits();
2730 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2732 KnownZero = KnownZero2.byteSwap();
2733 KnownOne = KnownOne2.byteSwap();
2737 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2740 // If the source's MSB is zero then we know the rest of the bits already.
2741 if (KnownZero2[BitWidth - 1]) {
2742 KnownZero = KnownZero2;
2743 KnownOne = KnownOne2;
2747 // We only know that the absolute values's MSB will be zero iff there is
2748 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
2749 KnownOne2.clearBit(BitWidth - 1);
2750 if (KnownOne2.getBoolValue()) {
2751 KnownZero = APInt::getSignMask(BitWidth);
2757 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2759 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2762 // UMIN - we know that the result will have the maximum of the
2763 // known zero leading bits of the inputs.
2764 unsigned LeadZero = KnownZero.countLeadingOnes();
2765 LeadZero = std::max(LeadZero, KnownZero2.countLeadingOnes());
2767 KnownZero &= KnownZero2;
2768 KnownOne &= KnownOne2;
2769 KnownZero.setHighBits(LeadZero);
2773 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2775 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2778 // UMAX - we know that the result will have the maximum of the
2779 // known one leading bits of the inputs.
2780 unsigned LeadOne = KnownOne.countLeadingOnes();
2781 LeadOne = std::max(LeadOne, KnownOne2.countLeadingOnes());
2783 KnownZero &= KnownZero2;
2784 KnownOne &= KnownOne2;
2785 KnownOne.setHighBits(LeadOne);
2790 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2792 // If we don't know any bits, early out.
2793 if (!KnownOne && !KnownZero)
2795 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2797 KnownZero &= KnownZero2;
2798 KnownOne &= KnownOne2;
2801 case ISD::FrameIndex:
2802 case ISD::TargetFrameIndex:
2803 if (unsigned Align = InferPtrAlignment(Op)) {
2804 // The low bits are known zero if the pointer is aligned.
2805 KnownZero.setLowBits(Log2_32(Align));
2811 if (Opcode < ISD::BUILTIN_OP_END)
2814 case ISD::INTRINSIC_WO_CHAIN:
2815 case ISD::INTRINSIC_W_CHAIN:
2816 case ISD::INTRINSIC_VOID:
2817 // Allow the target to implement this method for its nodes.
2818 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, DemandedElts,
2823 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2826 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
2828 // X + 0 never overflow
2829 if (isNullConstant(N1))
2832 APInt N1Zero, N1One;
2833 computeKnownBits(N1, N1Zero, N1One);
2834 if (N1Zero.getBoolValue()) {
2835 APInt N0Zero, N0One;
2836 computeKnownBits(N0, N0Zero, N0One);
2839 (void)(~N0Zero).uadd_ov(~N1Zero, overflow);
2844 // mulhi + 1 never overflow
2845 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
2846 (~N1Zero & 0x01) == ~N1Zero)
2849 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
2850 APInt N0Zero, N0One;
2851 computeKnownBits(N0, N0Zero, N0One);
2853 if ((~N0Zero & 0x01) == ~N0Zero)
2857 return OFK_Sometime;
2860 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2861 EVT OpVT = Val.getValueType();
2862 unsigned BitWidth = OpVT.getScalarSizeInBits();
2864 // Is the constant a known power of 2?
2865 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
2866 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2868 // A left-shift of a constant one will have exactly one bit set because
2869 // shifting the bit off the end is undefined.
2870 if (Val.getOpcode() == ISD::SHL) {
2871 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
2872 if (C && C->getAPIntValue() == 1)
2876 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2878 if (Val.getOpcode() == ISD::SRL) {
2879 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
2880 if (C && C->getAPIntValue().isSignMask())
2884 // Are all operands of a build vector constant powers of two?
2885 if (Val.getOpcode() == ISD::BUILD_VECTOR)
2886 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
2887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
2888 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2893 // More could be done here, though the above checks are enough
2894 // to handle some common cases.
2896 // Fall back to computeKnownBits to catch other known cases.
2897 APInt KnownZero, KnownOne;
2898 computeKnownBits(Val, KnownZero, KnownOne);
2899 return (KnownZero.countPopulation() == BitWidth - 1) &&
2900 (KnownOne.countPopulation() == 1);
2903 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2904 EVT VT = Op.getValueType();
2905 APInt DemandedElts = VT.isVector()
2906 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2908 return ComputeNumSignBits(Op, DemandedElts, Depth);
2911 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2912 unsigned Depth) const {
2913 EVT VT = Op.getValueType();
2914 assert(VT.isInteger() && "Invalid VT!");
2915 unsigned VTBits = VT.getScalarSizeInBits();
2917 unsigned FirstAnswer = 1;
2920 return 1; // Limit search depth.
2923 return 1; // No demanded elts, better to assume we don't know anything.
2925 switch (Op.getOpcode()) {
2927 case ISD::AssertSext:
2928 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2929 return VTBits-Tmp+1;
2930 case ISD::AssertZext:
2931 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2934 case ISD::Constant: {
2935 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2936 return Val.getNumSignBits();
2939 case ISD::BUILD_VECTOR:
2941 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
2942 if (!DemandedElts[i])
2945 SDValue SrcOp = Op.getOperand(i);
2946 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
2948 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2949 if (SrcOp.getValueSizeInBits() != VTBits) {
2950 assert(SrcOp.getValueSizeInBits() > VTBits &&
2951 "Expected BUILD_VECTOR implicit truncation");
2952 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
2953 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
2955 Tmp = std::min(Tmp, Tmp2);
2959 case ISD::SIGN_EXTEND:
2960 case ISD::SIGN_EXTEND_VECTOR_INREG:
2961 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
2962 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2964 case ISD::SIGN_EXTEND_INREG:
2965 // Max of the input and what this extends.
2966 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
2969 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2970 return std::max(Tmp, Tmp2);
2973 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2974 // SRA X, C -> adds C sign bits.
2975 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2976 APInt ShiftVal = C->getAPIntValue();
2978 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
2982 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2983 // shl destroys sign bits.
2984 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2985 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
2986 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
2987 return Tmp - C->getZExtValue();
2992 case ISD::XOR: // NOT is handled here.
2993 // Logical binary ops preserve the number of sign bits at the worst.
2994 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2996 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2997 FirstAnswer = std::min(Tmp, Tmp2);
2998 // We computed what we know about the sign bits as our first
2999 // answer. Now proceed to the generic code that uses
3000 // computeKnownBits, and pick whichever answer is better.
3005 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3006 if (Tmp == 1) return 1; // Early out.
3007 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3008 return std::min(Tmp, Tmp2);
3009 case ISD::SELECT_CC:
3010 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3011 if (Tmp == 1) return 1; // Early out.
3012 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
3013 return std::min(Tmp, Tmp2);
3018 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3020 return 1; // Early out.
3021 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3022 return std::min(Tmp, Tmp2);
3029 if (Op.getResNo() != 1)
3031 // The boolean result conforms to getBooleanContents. Fall through.
3032 // If setcc returns 0/-1, all bits are sign bits.
3033 // We know that we have an integer-based boolean since these operations
3034 // are only available for integer.
3035 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3036 TargetLowering::ZeroOrNegativeOneBooleanContent)
3040 // If setcc returns 0/-1, all bits are sign bits.
3041 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3042 TargetLowering::ZeroOrNegativeOneBooleanContent)
3047 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3048 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
3050 // Handle rotate right by N like a rotate left by 32-N.
3051 if (Op.getOpcode() == ISD::ROTR)
3052 RotAmt = (VTBits-RotAmt) & (VTBits-1);
3054 // If we aren't rotating out all of the known-in sign bits, return the
3055 // number that are left. This handles rotl(sext(x), 1) for example.
3056 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3057 if (Tmp > RotAmt+1) return Tmp-RotAmt;
3062 // Add can have at most one carry bit. Thus we know that the output
3063 // is, at worst, one more bit than the inputs.
3064 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3065 if (Tmp == 1) return 1; // Early out.
3067 // Special case decrementing a value (ADD X, -1):
3068 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3069 if (CRHS->isAllOnesValue()) {
3070 APInt KnownZero, KnownOne;
3071 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
3073 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3075 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
3078 // If we are subtracting one from a positive number, there is no carry
3079 // out of the result.
3080 if (KnownZero.isNegative())
3084 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3085 if (Tmp2 == 1) return 1;
3086 return std::min(Tmp, Tmp2)-1;
3089 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3090 if (Tmp2 == 1) return 1;
3093 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3094 if (CLHS->isNullValue()) {
3095 APInt KnownZero, KnownOne;
3096 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
3097 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3099 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
3102 // If the input is known to be positive (the sign bit is known clear),
3103 // the output of the NEG has the same number of sign bits as the input.
3104 if (KnownZero.isNegative())
3107 // Otherwise, we treat this like a SUB.
3110 // Sub can have at most one carry bit. Thus we know that the output
3111 // is, at worst, one more bit than the inputs.
3112 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3113 if (Tmp == 1) return 1; // Early out.
3114 return std::min(Tmp, Tmp2)-1;
3115 case ISD::TRUNCATE: {
3116 // Check if the sign bits of source go down as far as the truncated value.
3117 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3118 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3119 if (NumSrcSignBits > (NumSrcBits - VTBits))
3120 return NumSrcSignBits - (NumSrcBits - VTBits);
3123 case ISD::EXTRACT_ELEMENT: {
3124 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3125 const int BitWidth = Op.getValueSizeInBits();
3126 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3128 // Get reverse index (starting from 1), Op1 value indexes elements from
3129 // little end. Sign starts at big end.
3130 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3132 // If the sign portion ends in our element the subtraction gives correct
3133 // result. Otherwise it gives either negative or > bitwidth result
3134 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3136 case ISD::EXTRACT_VECTOR_ELT: {
3137 SDValue InVec = Op.getOperand(0);
3138 SDValue EltNo = Op.getOperand(1);
3139 EVT VecVT = InVec.getValueType();
3140 const unsigned BitWidth = Op.getValueSizeInBits();
3141 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3142 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3144 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3145 // anything about sign bits. But if the sizes match we can derive knowledge
3146 // about sign bits from the vector operand.
3147 if (BitWidth != EltBitWidth)
3150 // If we know the element index, just demand that vector element, else for
3151 // an unknown element index, ignore DemandedElts and demand them all.
3152 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3153 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3154 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3156 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3158 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3160 case ISD::EXTRACT_SUBVECTOR:
3161 return ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3162 case ISD::CONCAT_VECTORS:
3163 // Determine the minimum number of sign bits across all input vectors.
3164 // Early out if the result is already 1.
3165 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3166 for (unsigned i = 1, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i)
3167 Tmp = std::min(Tmp, ComputeNumSignBits(Op.getOperand(i), Depth + 1));
3171 // If we are looking at the loaded value of the SDNode.
3172 if (Op.getResNo() == 0) {
3173 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3174 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3175 unsigned ExtType = LD->getExtensionType();
3178 case ISD::SEXTLOAD: // '17' bits known
3179 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3180 return VTBits-Tmp+1;
3181 case ISD::ZEXTLOAD: // '16' bits known
3182 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3188 // Allow the target to implement this method for its nodes.
3189 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3190 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3191 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3192 Op.getOpcode() == ISD::INTRINSIC_VOID) {
3194 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3196 FirstAnswer = std::max(FirstAnswer, NumBits);
3199 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3200 // use this information.
3201 APInt KnownZero, KnownOne;
3202 computeKnownBits(Op, KnownZero, KnownOne, DemandedElts, Depth);
3205 if (KnownZero.isNegative()) { // sign bit is 0
3207 } else if (KnownOne.isNegative()) { // sign bit is 1;
3214 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3215 // the number of identical bits in the top of the input value.
3217 Mask <<= Mask.getBitWidth()-VTBits;
3218 // Return # leading zeros. We use 'min' here in case Val was zero before
3219 // shifting. We don't want to return '64' as for an i32 "0".
3220 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3223 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3224 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3225 !isa<ConstantSDNode>(Op.getOperand(1)))
3228 if (Op.getOpcode() == ISD::OR &&
3229 !MaskedValueIsZero(Op.getOperand(0),
3230 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3236 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
3237 // If we're told that NaNs won't happen, assume they won't.
3238 if (getTarget().Options.NoNaNsFPMath)
3241 if (const BinaryWithFlagsSDNode *BF = dyn_cast<BinaryWithFlagsSDNode>(Op))
3242 return BF->Flags.hasNoNaNs();
3244 // If the value is a constant, we can obviously see if it is a NaN or not.
3245 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3246 return !C->getValueAPF().isNaN();
3248 // TODO: Recognize more cases here.
3253 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3254 // If the value is a constant, we can obviously see if it is a zero or not.
3255 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3256 return !C->isZero();
3258 // TODO: Recognize more cases here.
3259 switch (Op.getOpcode()) {
3262 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3263 return !C->isNullValue();
3270 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3271 // Check the obvious case.
3272 if (A == B) return true;
3274 // For for negative and positive zero.
3275 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3276 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3277 if (CA->isZero() && CB->isZero()) return true;
3279 // Otherwise they may not be equal.
3283 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3284 assert(A.getValueType() == B.getValueType() &&
3285 "Values must have the same type");
3288 computeKnownBits(A, AZero, AOne);
3289 computeKnownBits(B, BZero, BOne);
3290 return (AZero | BZero).isAllOnesValue();
3293 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3294 ArrayRef<SDValue> Ops,
3295 llvm::SelectionDAG &DAG) {
3296 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3297 assert(llvm::all_of(Ops,
3299 return Ops[0].getValueType() == Op.getValueType();
3301 "Concatenation of vectors with inconsistent value types!");
3302 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3303 VT.getVectorNumElements() &&
3304 "Incorrect element count in vector concatenation!");
3306 if (Ops.size() == 1)
3309 // Concat of UNDEFs is UNDEF.
3310 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3311 return DAG.getUNDEF(VT);
3313 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3314 // simplified to one big BUILD_VECTOR.
3315 // FIXME: Add support for SCALAR_TO_VECTOR as well.
3316 EVT SVT = VT.getScalarType();
3317 SmallVector<SDValue, 16> Elts;
3318 for (SDValue Op : Ops) {
3319 EVT OpVT = Op.getValueType();
3321 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3322 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3323 Elts.append(Op->op_begin(), Op->op_end());
3328 // BUILD_VECTOR requires all inputs to be of the same type, find the
3329 // maximum type and extend them all.
3330 for (SDValue Op : Elts)
3331 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3333 if (SVT.bitsGT(VT.getScalarType()))
3334 for (SDValue &Op : Elts)
3335 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3336 ? DAG.getZExtOrTrunc(Op, DL, SVT)
3337 : DAG.getSExtOrTrunc(Op, DL, SVT);
3339 return DAG.getBuildVector(VT, DL, Elts);
3342 /// Gets or creates the specified node.
3343 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3344 FoldingSetNodeID ID;
3345 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3347 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3348 return SDValue(E, 0);
3350 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3352 CSEMap.InsertNode(N, IP);
3355 return SDValue(N, 0);
3358 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3360 // Constant fold unary operations with an integer constant operand. Even
3361 // opaque constant will be folded, because the folding of unary operations
3362 // doesn't create new constants with different values. Nevertheless, the
3363 // opaque flag is preserved during folding to prevent future folding with
3365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3366 const APInt &Val = C->getAPIntValue();
3369 case ISD::SIGN_EXTEND:
3370 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3371 C->isTargetOpcode(), C->isOpaque());
3372 case ISD::ANY_EXTEND:
3373 case ISD::ZERO_EXTEND:
3375 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3376 C->isTargetOpcode(), C->isOpaque());
3377 case ISD::UINT_TO_FP:
3378 case ISD::SINT_TO_FP: {
3379 APFloat apf(EVTToAPFloatSemantics(VT),
3380 APInt::getNullValue(VT.getSizeInBits()));
3381 (void)apf.convertFromAPInt(Val,
3382 Opcode==ISD::SINT_TO_FP,
3383 APFloat::rmNearestTiesToEven);
3384 return getConstantFP(apf, DL, VT);
3387 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3388 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3389 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3390 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3391 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3392 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3393 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3394 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3397 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3399 case ISD::BITREVERSE:
3400 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3403 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3406 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3409 case ISD::CTLZ_ZERO_UNDEF:
3410 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3413 case ISD::CTTZ_ZERO_UNDEF:
3414 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3416 case ISD::FP16_TO_FP: {
3418 APFloat FPV(APFloat::IEEEhalf(),
3419 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3421 // This can return overflow, underflow, or inexact; we don't care.
3422 // FIXME need to be more flexible about rounding mode.
3423 (void)FPV.convert(EVTToAPFloatSemantics(VT),
3424 APFloat::rmNearestTiesToEven, &Ignored);
3425 return getConstantFP(FPV, DL, VT);
3430 // Constant fold unary operations with a floating point constant operand.
3431 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3432 APFloat V = C->getValueAPF(); // make copy
3436 return getConstantFP(V, DL, VT);
3439 return getConstantFP(V, DL, VT);
3441 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3442 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3443 return getConstantFP(V, DL, VT);
3447 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3448 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3449 return getConstantFP(V, DL, VT);
3453 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3454 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3455 return getConstantFP(V, DL, VT);
3458 case ISD::FP_EXTEND: {
3460 // This can return overflow, underflow, or inexact; we don't care.
3461 // FIXME need to be more flexible about rounding mode.
3462 (void)V.convert(EVTToAPFloatSemantics(VT),
3463 APFloat::rmNearestTiesToEven, &ignored);
3464 return getConstantFP(V, DL, VT);
3466 case ISD::FP_TO_SINT:
3467 case ISD::FP_TO_UINT: {
3469 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3470 // FIXME need to be more flexible about rounding mode.
3471 APFloat::opStatus s =
3472 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3473 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3475 return getConstant(IntVal, DL, VT);
3478 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3479 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3480 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3481 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3482 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3483 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3485 case ISD::FP_TO_FP16: {
3487 // This can return overflow, underflow, or inexact; we don't care.
3488 // FIXME need to be more flexible about rounding mode.
3489 (void)V.convert(APFloat::IEEEhalf(),
3490 APFloat::rmNearestTiesToEven, &Ignored);
3491 return getConstant(V.bitcastToAPInt(), DL, VT);
3496 // Constant fold unary operations with a vector integer or float operand.
3497 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3498 if (BV->isConstant()) {
3501 // FIXME: Entirely reasonable to perform folding of other unary
3502 // operations here as the need arises.
3509 case ISD::FP_EXTEND:
3510 case ISD::FP_TO_SINT:
3511 case ISD::FP_TO_UINT:
3513 case ISD::UINT_TO_FP:
3514 case ISD::SINT_TO_FP:
3516 case ISD::BITREVERSE:
3519 case ISD::CTLZ_ZERO_UNDEF:
3521 case ISD::CTTZ_ZERO_UNDEF:
3523 SDValue Ops = { Operand };
3524 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3531 unsigned OpOpcode = Operand.getNode()->getOpcode();
3533 case ISD::TokenFactor:
3534 case ISD::MERGE_VALUES:
3535 case ISD::CONCAT_VECTORS:
3536 return Operand; // Factor, merge or concat of one node? No need.
3537 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3538 case ISD::FP_EXTEND:
3539 assert(VT.isFloatingPoint() &&
3540 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3541 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3542 assert((!VT.isVector() ||
3543 VT.getVectorNumElements() ==
3544 Operand.getValueType().getVectorNumElements()) &&
3545 "Vector element count mismatch!");
3546 assert(Operand.getValueType().bitsLT(VT) &&
3547 "Invalid fpext node, dst < src!");
3548 if (Operand.isUndef())
3549 return getUNDEF(VT);
3551 case ISD::SIGN_EXTEND:
3552 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3553 "Invalid SIGN_EXTEND!");
3554 if (Operand.getValueType() == VT) return Operand; // noop extension
3555 assert((!VT.isVector() ||
3556 VT.getVectorNumElements() ==
3557 Operand.getValueType().getVectorNumElements()) &&
3558 "Vector element count mismatch!");
3559 assert(Operand.getValueType().bitsLT(VT) &&
3560 "Invalid sext node, dst < src!");
3561 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3562 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3563 else if (OpOpcode == ISD::UNDEF)
3564 // sext(undef) = 0, because the top bits will all be the same.
3565 return getConstant(0, DL, VT);
3567 case ISD::ZERO_EXTEND:
3568 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3569 "Invalid ZERO_EXTEND!");
3570 if (Operand.getValueType() == VT) return Operand; // noop extension
3571 assert((!VT.isVector() ||
3572 VT.getVectorNumElements() ==
3573 Operand.getValueType().getVectorNumElements()) &&
3574 "Vector element count mismatch!");
3575 assert(Operand.getValueType().bitsLT(VT) &&
3576 "Invalid zext node, dst < src!");
3577 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3578 return getNode(ISD::ZERO_EXTEND, DL, VT,
3579 Operand.getNode()->getOperand(0));
3580 else if (OpOpcode == ISD::UNDEF)
3581 // zext(undef) = 0, because the top bits will be zero.
3582 return getConstant(0, DL, VT);
3584 case ISD::ANY_EXTEND:
3585 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3586 "Invalid ANY_EXTEND!");
3587 if (Operand.getValueType() == VT) return Operand; // noop extension
3588 assert((!VT.isVector() ||
3589 VT.getVectorNumElements() ==
3590 Operand.getValueType().getVectorNumElements()) &&
3591 "Vector element count mismatch!");
3592 assert(Operand.getValueType().bitsLT(VT) &&
3593 "Invalid anyext node, dst < src!");
3595 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3596 OpOpcode == ISD::ANY_EXTEND)
3597 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3598 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3599 else if (OpOpcode == ISD::UNDEF)
3600 return getUNDEF(VT);
3602 // (ext (trunx x)) -> x
3603 if (OpOpcode == ISD::TRUNCATE) {
3604 SDValue OpOp = Operand.getNode()->getOperand(0);
3605 if (OpOp.getValueType() == VT)
3610 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3611 "Invalid TRUNCATE!");
3612 if (Operand.getValueType() == VT) return Operand; // noop truncate
3613 assert((!VT.isVector() ||
3614 VT.getVectorNumElements() ==
3615 Operand.getValueType().getVectorNumElements()) &&
3616 "Vector element count mismatch!");
3617 assert(Operand.getValueType().bitsGT(VT) &&
3618 "Invalid truncate node, src < dst!");
3619 if (OpOpcode == ISD::TRUNCATE)
3620 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3621 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3622 OpOpcode == ISD::ANY_EXTEND) {
3623 // If the source is smaller than the dest, we still need an extend.
3624 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
3625 .bitsLT(VT.getScalarType()))
3626 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3627 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
3628 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3629 return Operand.getNode()->getOperand(0);
3631 if (OpOpcode == ISD::UNDEF)
3632 return getUNDEF(VT);
3635 assert(VT.isInteger() && VT == Operand.getValueType() &&
3637 if (OpOpcode == ISD::UNDEF)
3638 return getUNDEF(VT);
3641 assert(VT.isInteger() && VT == Operand.getValueType() &&
3643 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3644 "BSWAP types must be a multiple of 16 bits!");
3645 if (OpOpcode == ISD::UNDEF)
3646 return getUNDEF(VT);
3648 case ISD::BITREVERSE:
3649 assert(VT.isInteger() && VT == Operand.getValueType() &&
3650 "Invalid BITREVERSE!");
3651 if (OpOpcode == ISD::UNDEF)
3652 return getUNDEF(VT);
3655 // Basic sanity checking.
3656 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3657 "Cannot BITCAST between types of different sizes!");
3658 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3659 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3660 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3661 if (OpOpcode == ISD::UNDEF)
3662 return getUNDEF(VT);
3664 case ISD::SCALAR_TO_VECTOR:
3665 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3666 (VT.getVectorElementType() == Operand.getValueType() ||
3667 (VT.getVectorElementType().isInteger() &&
3668 Operand.getValueType().isInteger() &&
3669 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3670 "Illegal SCALAR_TO_VECTOR node!");
3671 if (OpOpcode == ISD::UNDEF)
3672 return getUNDEF(VT);
3673 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3674 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3675 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3676 Operand.getConstantOperandVal(1) == 0 &&
3677 Operand.getOperand(0).getValueType() == VT)
3678 return Operand.getOperand(0);
3681 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3682 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3683 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3684 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
3685 Operand.getNode()->getOperand(0),
3686 &cast<BinaryWithFlagsSDNode>(Operand.getNode())->Flags);
3687 if (OpOpcode == ISD::FNEG) // --X -> X
3688 return Operand.getNode()->getOperand(0);
3691 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3692 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
3697 SDVTList VTs = getVTList(VT);
3698 SDValue Ops[] = {Operand};
3699 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3700 FoldingSetNodeID ID;
3701 AddNodeIDNode(ID, Opcode, VTs, Ops);
3703 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3704 return SDValue(E, 0);
3706 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3707 createOperands(N, Ops);
3708 CSEMap.InsertNode(N, IP);
3710 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3711 createOperands(N, Ops);
3715 return SDValue(N, 0);
3718 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3721 case ISD::ADD: return std::make_pair(C1 + C2, true);
3722 case ISD::SUB: return std::make_pair(C1 - C2, true);
3723 case ISD::MUL: return std::make_pair(C1 * C2, true);
3724 case ISD::AND: return std::make_pair(C1 & C2, true);
3725 case ISD::OR: return std::make_pair(C1 | C2, true);
3726 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3727 case ISD::SHL: return std::make_pair(C1 << C2, true);
3728 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3729 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3730 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3731 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3732 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3733 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3734 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3735 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3737 if (!C2.getBoolValue())
3739 return std::make_pair(C1.udiv(C2), true);
3741 if (!C2.getBoolValue())
3743 return std::make_pair(C1.urem(C2), true);
3745 if (!C2.getBoolValue())
3747 return std::make_pair(C1.sdiv(C2), true);
3749 if (!C2.getBoolValue())
3751 return std::make_pair(C1.srem(C2), true);
3753 return std::make_pair(APInt(1, 0), false);
3756 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3757 EVT VT, const ConstantSDNode *Cst1,
3758 const ConstantSDNode *Cst2) {
3759 if (Cst1->isOpaque() || Cst2->isOpaque())
3762 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3763 Cst2->getAPIntValue());
3766 return getConstant(Folded.first, DL, VT);
3769 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3770 const GlobalAddressSDNode *GA,
3772 if (GA->getOpcode() != ISD::GlobalAddress)
3774 if (!TLI->isOffsetFoldingLegal(GA))
3776 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3779 int64_t Offset = Cst2->getSExtValue();
3781 case ISD::ADD: break;
3782 case ISD::SUB: Offset = -uint64_t(Offset); break;
3783 default: return SDValue();
3785 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3786 GA->getOffset() + uint64_t(Offset));
3789 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
3795 // If a divisor is zero/undef or any element of a divisor vector is
3796 // zero/undef, the whole op is undef.
3797 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
3798 SDValue Divisor = Ops[1];
3799 if (Divisor.isUndef() || isNullConstant(Divisor))
3802 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
3803 any_of(Divisor->op_values(),
3804 [](SDValue V) { return V.isUndef() || isNullConstant(V); });
3805 // TODO: Handle signed overflow.
3807 // TODO: Handle oversized shifts.
3813 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3814 EVT VT, SDNode *Cst1,
3816 // If the opcode is a target-specific ISD node, there's nothing we can
3817 // do here and the operand rules may not line up with the below, so
3819 if (Opcode >= ISD::BUILTIN_OP_END)
3822 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
3823 return getUNDEF(VT);
3825 // Handle the case of two scalars.
3826 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3827 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3828 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3829 assert((!Folded || !VT.isVector()) &&
3830 "Can't fold vectors ops with scalar operands");
3835 // fold (add Sym, c) -> Sym+c
3836 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3837 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3838 if (isCommutativeBinOp(Opcode))
3839 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3840 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3842 // For vectors extract each constant element into Inputs so we can constant
3843 // fold them individually.
3844 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3845 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3849 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3851 EVT SVT = VT.getScalarType();
3852 SmallVector<SDValue, 4> Outputs;
3853 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3854 SDValue V1 = BV1->getOperand(I);
3855 SDValue V2 = BV2->getOperand(I);
3857 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3858 // FIXME: This is valid and could be handled by truncation.
3859 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3862 // Fold one vector element.
3863 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
3865 // Scalar folding only succeeded if the result is a constant or UNDEF.
3866 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3867 ScalarResult.getOpcode() != ISD::ConstantFP)
3869 Outputs.push_back(ScalarResult);
3872 assert(VT.getVectorNumElements() == Outputs.size() &&
3873 "Vector size mismatch!");
3875 // We may have a vector type but a scalar result. Create a splat.
3876 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3878 // Build a big vector out of the scalar elements we generated.
3879 return getBuildVector(VT, SDLoc(), Outputs);
3882 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3883 const SDLoc &DL, EVT VT,
3884 ArrayRef<SDValue> Ops,
3885 const SDNodeFlags *Flags) {
3886 // If the opcode is a target-specific ISD node, there's nothing we can
3887 // do here and the operand rules may not line up with the below, so
3889 if (Opcode >= ISD::BUILTIN_OP_END)
3892 if (isUndef(Opcode, Ops))
3893 return getUNDEF(VT);
3895 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3899 unsigned NumElts = VT.getVectorNumElements();
3901 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3902 return !Op.getValueType().isVector() ||
3903 Op.getValueType().getVectorNumElements() == NumElts;
3906 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3907 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3908 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3909 (BV && BV->isConstant());
3912 // All operands must be vector types with the same number of elements as
3913 // the result type and must be either UNDEF or a build vector of constant
3914 // or UNDEF scalars.
3915 if (!all_of(Ops, IsConstantBuildVectorOrUndef) ||
3916 !all_of(Ops, IsScalarOrSameVectorSize))
3919 // If we are comparing vectors, then the result needs to be a i1 boolean
3920 // that is then sign-extended back to the legal result type.
3921 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3923 // Find legal integer scalar type for constant promotion and
3924 // ensure that its scalar size is at least as large as source.
3925 EVT LegalSVT = VT.getScalarType();
3926 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
3927 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3928 if (LegalSVT.bitsLT(VT.getScalarType()))
3932 // Constant fold each scalar lane separately.
3933 SmallVector<SDValue, 4> ScalarResults;
3934 for (unsigned i = 0; i != NumElts; i++) {
3935 SmallVector<SDValue, 4> ScalarOps;
3936 for (SDValue Op : Ops) {
3937 EVT InSVT = Op.getValueType().getScalarType();
3938 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3940 // We've checked that this is UNDEF or a constant of some kind.
3942 ScalarOps.push_back(getUNDEF(InSVT));
3944 ScalarOps.push_back(Op);
3948 SDValue ScalarOp = InBV->getOperand(i);
3949 EVT ScalarVT = ScalarOp.getValueType();
3951 // Build vector (integer) scalar operands may need implicit
3952 // truncation - do this before constant folding.
3953 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
3954 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
3956 ScalarOps.push_back(ScalarOp);
3959 // Constant fold the scalar operands.
3960 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
3962 // Legalize the (integer) scalar constant if necessary.
3963 if (LegalSVT != SVT)
3964 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
3966 // Scalar folding only succeeded if the result is a constant or UNDEF.
3967 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3968 ScalarResult.getOpcode() != ISD::ConstantFP)
3970 ScalarResults.push_back(ScalarResult);
3973 return getBuildVector(VT, DL, ScalarResults);
3976 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3977 SDValue N1, SDValue N2,
3978 const SDNodeFlags *Flags) {
3979 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3980 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3981 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3982 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3984 // Canonicalize constant to RHS if commutative.
3985 if (isCommutativeBinOp(Opcode)) {
3987 std::swap(N1C, N2C);
3989 } else if (N1CFP && !N2CFP) {
3990 std::swap(N1CFP, N2CFP);
3997 case ISD::TokenFactor:
3998 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
3999 N2.getValueType() == MVT::Other && "Invalid token factor!");
4000 // Fold trivial token factors.
4001 if (N1.getOpcode() == ISD::EntryToken) return N2;
4002 if (N2.getOpcode() == ISD::EntryToken) return N1;
4003 if (N1 == N2) return N1;
4005 case ISD::CONCAT_VECTORS: {
4006 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4007 SDValue Ops[] = {N1, N2};
4008 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4013 assert(VT.isInteger() && "This operator does not apply to FP types!");
4014 assert(N1.getValueType() == N2.getValueType() &&
4015 N1.getValueType() == VT && "Binary operator types must match!");
4016 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4017 // worth handling here.
4018 if (N2C && N2C->isNullValue())
4020 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4027 assert(VT.isInteger() && "This operator does not apply to FP types!");
4028 assert(N1.getValueType() == N2.getValueType() &&
4029 N1.getValueType() == VT && "Binary operator types must match!");
4030 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4031 // it's worth handling here.
4032 if (N2C && N2C->isNullValue())
4046 assert(VT.isInteger() && "This operator does not apply to FP types!");
4047 assert(N1.getValueType() == N2.getValueType() &&
4048 N1.getValueType() == VT && "Binary operator types must match!");
4055 if (getTarget().Options.UnsafeFPMath) {
4056 if (Opcode == ISD::FADD) {
4058 if (N2CFP && N2CFP->getValueAPF().isZero())
4060 } else if (Opcode == ISD::FSUB) {
4062 if (N2CFP && N2CFP->getValueAPF().isZero())
4064 } else if (Opcode == ISD::FMUL) {
4066 if (N2CFP && N2CFP->isZero())
4069 if (N2CFP && N2CFP->isExactlyValue(1.0))
4073 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4074 assert(N1.getValueType() == N2.getValueType() &&
4075 N1.getValueType() == VT && "Binary operator types must match!");
4077 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4078 assert(N1.getValueType() == VT &&
4079 N1.getValueType().isFloatingPoint() &&
4080 N2.getValueType().isFloatingPoint() &&
4081 "Invalid FCOPYSIGN!");
4088 assert(VT == N1.getValueType() &&
4089 "Shift operators return type must be the same as their first arg");
4090 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4091 "Shifts only work on integers");
4092 assert((!VT.isVector() || VT == N2.getValueType()) &&
4093 "Vector shift amounts must be in the same as their first arg");
4094 // Verify that the shift amount VT is bit enough to hold valid shift
4095 // amounts. This catches things like trying to shift an i1024 value by an
4096 // i8, which is easy to fall into in generic code that uses
4097 // TLI.getShiftAmount().
4098 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4099 "Invalid use of small shift amount with oversized value!");
4101 // Always fold shifts of i1 values so the code generator doesn't need to
4102 // handle them. Since we know the size of the shift has to be less than the
4103 // size of the value, the shift/rotate count is guaranteed to be zero.
4106 if (N2C && N2C->isNullValue())
4109 case ISD::FP_ROUND_INREG: {
4110 EVT EVT = cast<VTSDNode>(N2)->getVT();
4111 assert(VT == N1.getValueType() && "Not an inreg round!");
4112 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4113 "Cannot FP_ROUND_INREG integer types");
4114 assert(EVT.isVector() == VT.isVector() &&
4115 "FP_ROUND_INREG type should be vector iff the operand "
4117 assert((!EVT.isVector() ||
4118 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4119 "Vector element counts must match in FP_ROUND_INREG");
4120 assert(EVT.bitsLE(VT) && "Not rounding down!");
4122 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4126 assert(VT.isFloatingPoint() &&
4127 N1.getValueType().isFloatingPoint() &&
4128 VT.bitsLE(N1.getValueType()) &&
4129 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4130 "Invalid FP_ROUND!");
4131 if (N1.getValueType() == VT) return N1; // noop conversion.
4133 case ISD::AssertSext:
4134 case ISD::AssertZext: {
4135 EVT EVT = cast<VTSDNode>(N2)->getVT();
4136 assert(VT == N1.getValueType() && "Not an inreg extend!");
4137 assert(VT.isInteger() && EVT.isInteger() &&
4138 "Cannot *_EXTEND_INREG FP types");
4139 assert(!EVT.isVector() &&
4140 "AssertSExt/AssertZExt type should be the vector element type "
4141 "rather than the vector type!");
4142 assert(EVT.bitsLE(VT) && "Not extending!");
4143 if (VT == EVT) return N1; // noop assertion.
4146 case ISD::SIGN_EXTEND_INREG: {
4147 EVT EVT = cast<VTSDNode>(N2)->getVT();
4148 assert(VT == N1.getValueType() && "Not an inreg extend!");
4149 assert(VT.isInteger() && EVT.isInteger() &&
4150 "Cannot *_EXTEND_INREG FP types");
4151 assert(EVT.isVector() == VT.isVector() &&
4152 "SIGN_EXTEND_INREG type should be vector iff the operand "
4154 assert((!EVT.isVector() ||
4155 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4156 "Vector element counts must match in SIGN_EXTEND_INREG");
4157 assert(EVT.bitsLE(VT) && "Not extending!");
4158 if (EVT == VT) return N1; // Not actually extending
4160 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4161 unsigned FromBits = EVT.getScalarSizeInBits();
4162 Val <<= Val.getBitWidth() - FromBits;
4163 Val = Val.ashr(Val.getBitWidth() - FromBits);
4164 return getConstant(Val, DL, ConstantVT);
4168 const APInt &Val = N1C->getAPIntValue();
4169 return SignExtendInReg(Val, VT);
4171 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4172 SmallVector<SDValue, 8> Ops;
4173 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4174 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4175 SDValue Op = N1.getOperand(i);
4177 Ops.push_back(getUNDEF(OpVT));
4180 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4181 APInt Val = C->getAPIntValue();
4182 Ops.push_back(SignExtendInReg(Val, OpVT));
4184 return getBuildVector(VT, DL, Ops);
4188 case ISD::EXTRACT_VECTOR_ELT:
4189 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4191 return getUNDEF(VT);
4193 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4194 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4195 return getUNDEF(VT);
4197 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4198 // expanding copies of large vectors from registers.
4200 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4201 N1.getNumOperands() > 0) {
4203 N1.getOperand(0).getValueType().getVectorNumElements();
4204 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4205 N1.getOperand(N2C->getZExtValue() / Factor),
4206 getConstant(N2C->getZExtValue() % Factor, DL,
4207 N2.getValueType()));
4210 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4211 // expanding large vector constants.
4212 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4213 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4215 if (VT != Elt.getValueType())
4216 // If the vector element type is not legal, the BUILD_VECTOR operands
4217 // are promoted and implicitly truncated, and the result implicitly
4218 // extended. Make that explicit here.
4219 Elt = getAnyExtOrTrunc(Elt, DL, VT);
4224 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4225 // operations are lowered to scalars.
4226 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4227 // If the indices are the same, return the inserted element else
4228 // if the indices are known different, extract the element from
4229 // the original vector.
4230 SDValue N1Op2 = N1.getOperand(2);
4231 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4233 if (N1Op2C && N2C) {
4234 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4235 if (VT == N1.getOperand(1).getValueType())
4236 return N1.getOperand(1);
4238 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4241 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4245 case ISD::EXTRACT_ELEMENT:
4246 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4247 assert(!N1.getValueType().isVector() && !VT.isVector() &&
4248 (N1.getValueType().isInteger() == VT.isInteger()) &&
4249 N1.getValueType() != VT &&
4250 "Wrong types for EXTRACT_ELEMENT!");
4252 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4253 // 64-bit integers into 32-bit parts. Instead of building the extract of
4254 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4255 if (N1.getOpcode() == ISD::BUILD_PAIR)
4256 return N1.getOperand(N2C->getZExtValue());
4258 // EXTRACT_ELEMENT of a constant int is also very common.
4260 unsigned ElementSize = VT.getSizeInBits();
4261 unsigned Shift = ElementSize * N2C->getZExtValue();
4262 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4263 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4266 case ISD::EXTRACT_SUBVECTOR:
4267 if (VT.isSimple() && N1.getValueType().isSimple()) {
4268 assert(VT.isVector() && N1.getValueType().isVector() &&
4269 "Extract subvector VTs must be a vectors!");
4270 assert(VT.getVectorElementType() ==
4271 N1.getValueType().getVectorElementType() &&
4272 "Extract subvector VTs must have the same element type!");
4273 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4274 "Extract subvector must be from larger vector to smaller vector!");
4277 assert((VT.getVectorNumElements() + N2C->getZExtValue()
4278 <= N1.getValueType().getVectorNumElements())
4279 && "Extract subvector overflow!");
4282 // Trivial extraction.
4283 if (VT.getSimpleVT() == N1.getSimpleValueType())
4286 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4288 return getUNDEF(VT);
4290 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4291 // the concat have the same type as the extract.
4292 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4293 N1.getNumOperands() > 0 &&
4294 VT == N1.getOperand(0).getValueType()) {
4295 unsigned Factor = VT.getVectorNumElements();
4296 return N1.getOperand(N2C->getZExtValue() / Factor);
4299 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4300 // during shuffle legalization.
4301 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4302 VT == N1.getOperand(1).getValueType())
4303 return N1.getOperand(1);
4308 // Perform trivial constant folding.
4310 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4313 // Constant fold FP operations.
4314 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4317 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4318 APFloat::opStatus s;
4321 s = V1.add(V2, APFloat::rmNearestTiesToEven);
4322 if (!HasFPExceptions || s != APFloat::opInvalidOp)
4323 return getConstantFP(V1, DL, VT);
4326 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4327 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4328 return getConstantFP(V1, DL, VT);
4331 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4332 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4333 return getConstantFP(V1, DL, VT);
4336 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4337 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4338 s!=APFloat::opDivByZero)) {
4339 return getConstantFP(V1, DL, VT);
4344 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4345 s!=APFloat::opDivByZero)) {
4346 return getConstantFP(V1, DL, VT);
4349 case ISD::FCOPYSIGN:
4351 return getConstantFP(V1, DL, VT);
4356 if (Opcode == ISD::FP_ROUND) {
4357 APFloat V = N1CFP->getValueAPF(); // make copy
4359 // This can return overflow, underflow, or inexact; we don't care.
4360 // FIXME need to be more flexible about rounding mode.
4361 (void)V.convert(EVTToAPFloatSemantics(VT),
4362 APFloat::rmNearestTiesToEven, &ignored);
4363 return getConstantFP(V, DL, VT);
4367 // Canonicalize an UNDEF to the RHS, even over a constant.
4369 if (isCommutativeBinOp(Opcode)) {
4373 case ISD::FP_ROUND_INREG:
4374 case ISD::SIGN_EXTEND_INREG:
4380 return N1; // fold op(undef, arg2) -> undef
4388 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
4389 // For vectors, we can't easily build an all zero vector, just return
4396 // Fold a bunch of operators when the RHS is undef.
4401 // Handle undef ^ undef -> 0 special case. This is a common
4403 return getConstant(0, DL, VT);
4413 return N2; // fold op(arg1, undef) -> undef
4419 if (getTarget().Options.UnsafeFPMath)
4427 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
4428 // For vectors, we can't easily build an all zero vector, just return
4433 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
4434 // For vectors, we can't easily build an all one vector, just return
4442 // Memoize this node if possible.
4444 SDVTList VTs = getVTList(VT);
4445 if (VT != MVT::Glue) {
4446 SDValue Ops[] = {N1, N2};
4447 FoldingSetNodeID ID;
4448 AddNodeIDNode(ID, Opcode, VTs, Ops);
4450 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4452 E->intersectFlagsWith(Flags);
4453 return SDValue(E, 0);
4456 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
4457 CSEMap.InsertNode(N, IP);
4459 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
4463 return SDValue(N, 0);
4466 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4467 SDValue N1, SDValue N2, SDValue N3) {
4468 // Perform various simplifications.
4471 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4472 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4473 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4474 if (N1CFP && N2CFP && N3CFP) {
4475 APFloat V1 = N1CFP->getValueAPF();
4476 const APFloat &V2 = N2CFP->getValueAPF();
4477 const APFloat &V3 = N3CFP->getValueAPF();
4478 APFloat::opStatus s =
4479 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4480 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4481 return getConstantFP(V1, DL, VT);
4485 case ISD::CONCAT_VECTORS: {
4486 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4487 SDValue Ops[] = {N1, N2, N3};
4488 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4493 // Use FoldSetCC to simplify SETCC's.
4494 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
4496 // Vector constant folding.
4497 SDValue Ops[] = {N1, N2, N3};
4498 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4503 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
4504 if (N1C->getZExtValue())
4505 return N2; // select true, X, Y -> X
4506 return N3; // select false, X, Y -> Y
4509 if (N2 == N3) return N2; // select C, X, X -> X
4511 case ISD::VECTOR_SHUFFLE:
4512 llvm_unreachable("should use getVectorShuffle constructor!");
4513 case ISD::INSERT_VECTOR_ELT: {
4514 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
4515 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
4516 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4517 return getUNDEF(VT);
4520 case ISD::INSERT_SUBVECTOR: {
4522 if (VT.isSimple() && N1.getValueType().isSimple()
4523 && N2.getValueType().isSimple()) {
4524 assert(VT.isVector() && N1.getValueType().isVector() &&
4525 N2.getValueType().isVector() &&
4526 "Insert subvector VTs must be a vectors");
4527 assert(VT == N1.getValueType() &&
4528 "Dest and insert subvector source types must match!");
4529 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4530 "Insert subvector must be from smaller vector to larger vector!");
4531 if (isa<ConstantSDNode>(Index)) {
4532 assert((N2.getValueType().getVectorNumElements() +
4533 cast<ConstantSDNode>(Index)->getZExtValue()
4534 <= VT.getVectorNumElements())
4535 && "Insert subvector overflow!");
4538 // Trivial insertion.
4539 if (VT.getSimpleVT() == N2.getSimpleValueType())
4545 // Fold bit_convert nodes from a type to themselves.
4546 if (N1.getValueType() == VT)
4551 // Memoize node if it doesn't produce a flag.
4553 SDVTList VTs = getVTList(VT);
4554 SDValue Ops[] = {N1, N2, N3};
4555 if (VT != MVT::Glue) {
4556 FoldingSetNodeID ID;
4557 AddNodeIDNode(ID, Opcode, VTs, Ops);
4559 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4560 return SDValue(E, 0);
4562 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4563 createOperands(N, Ops);
4564 CSEMap.InsertNode(N, IP);
4566 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4567 createOperands(N, Ops);
4571 return SDValue(N, 0);
4574 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4575 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4576 SDValue Ops[] = { N1, N2, N3, N4 };
4577 return getNode(Opcode, DL, VT, Ops);
4580 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4581 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4583 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4584 return getNode(Opcode, DL, VT, Ops);
4587 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4588 /// the incoming stack arguments to be loaded from the stack.
4589 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4590 SmallVector<SDValue, 8> ArgChains;
4592 // Include the original chain at the beginning of the list. When this is
4593 // used by target LowerCall hooks, this helps legalize find the
4594 // CALLSEQ_BEGIN node.
4595 ArgChains.push_back(Chain);
4597 // Add a chain value for each stack argument.
4598 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4599 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4600 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4601 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4602 if (FI->getIndex() < 0)
4603 ArgChains.push_back(SDValue(L, 1));
4605 // Build a tokenfactor for all the chains.
4606 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4609 /// getMemsetValue - Vectorized representation of the memset value
4611 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4613 assert(!Value.isUndef());
4615 unsigned NumBits = VT.getScalarSizeInBits();
4616 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4617 assert(C->getAPIntValue().getBitWidth() == 8);
4618 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4620 return DAG.getConstant(Val, dl, VT);
4621 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4625 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4626 EVT IntVT = VT.getScalarType();
4627 if (!IntVT.isInteger())
4628 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4630 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4632 // Use a multiplication with 0x010101... to extend the input to the
4634 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4635 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4636 DAG.getConstant(Magic, dl, IntVT));
4639 if (VT != Value.getValueType() && !VT.isInteger())
4640 Value = DAG.getBitcast(VT.getScalarType(), Value);
4641 if (VT != Value.getValueType())
4642 Value = DAG.getSplatBuildVector(VT, dl, Value);
4647 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4648 /// used when a memcpy is turned into a memset when the source is a constant
4650 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4651 const TargetLowering &TLI, StringRef Str) {
4652 // Handle vector with all elements zero.
4655 return DAG.getConstant(0, dl, VT);
4656 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4657 return DAG.getConstantFP(0.0, dl, VT);
4658 else if (VT.isVector()) {
4659 unsigned NumElts = VT.getVectorNumElements();
4660 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4661 return DAG.getNode(ISD::BITCAST, dl, VT,
4662 DAG.getConstant(0, dl,
4663 EVT::getVectorVT(*DAG.getContext(),
4666 llvm_unreachable("Expected type!");
4669 assert(!VT.isVector() && "Can't handle vector type here!");
4670 unsigned NumVTBits = VT.getSizeInBits();
4671 unsigned NumVTBytes = NumVTBits / 8;
4672 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
4674 APInt Val(NumVTBits, 0);
4675 if (DAG.getDataLayout().isLittleEndian()) {
4676 for (unsigned i = 0; i != NumBytes; ++i)
4677 Val |= (uint64_t)(unsigned char)Str[i] << i*8;
4679 for (unsigned i = 0; i != NumBytes; ++i)
4680 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
4683 // If the "cost" of materializing the integer immediate is less than the cost
4684 // of a load, then it is cost effective to turn the load into the immediate.
4685 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4686 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4687 return DAG.getConstant(Val, dl, VT);
4688 return SDValue(nullptr, 0);
4691 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4693 EVT VT = Base.getValueType();
4694 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4697 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
4699 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
4700 uint64_t SrcDelta = 0;
4701 GlobalAddressSDNode *G = nullptr;
4702 if (Src.getOpcode() == ISD::GlobalAddress)
4703 G = cast<GlobalAddressSDNode>(Src);
4704 else if (Src.getOpcode() == ISD::ADD &&
4705 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4706 Src.getOperand(1).getOpcode() == ISD::Constant) {
4707 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4708 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4713 return getConstantStringInfo(G->getGlobal(), Str,
4714 SrcDelta + G->getOffset(), false);
4717 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4718 /// Return true if the number of memory ops is below the threshold (Limit).
4719 /// It returns the types of the sequence of memory ops to perform
4720 /// memset / memcpy by reference.
4721 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4722 unsigned Limit, uint64_t Size,
4723 unsigned DstAlign, unsigned SrcAlign,
4728 unsigned DstAS, unsigned SrcAS,
4730 const TargetLowering &TLI) {
4731 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4732 "Expecting memcpy / memset source to meet alignment requirement!");
4733 // If 'SrcAlign' is zero, that means the memory operation does not need to
4734 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4735 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4736 // is the specified alignment of the memory operation. If it is zero, that
4737 // means it's possible to change the alignment of the destination.
4738 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4739 // not need to be loaded.
4740 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4741 IsMemset, ZeroMemset, MemcpyStrSrc,
4742 DAG.getMachineFunction());
4744 if (VT == MVT::Other) {
4745 if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) ||
4746 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) {
4747 VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
4749 switch (DstAlign & 7) {
4750 case 0: VT = MVT::i64; break;
4751 case 4: VT = MVT::i32; break;
4752 case 2: VT = MVT::i16; break;
4753 default: VT = MVT::i8; break;
4758 while (!TLI.isTypeLegal(LVT))
4759 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4760 assert(LVT.isInteger());
4766 unsigned NumMemOps = 0;
4768 unsigned VTSize = VT.getSizeInBits() / 8;
4769 while (VTSize > Size) {
4770 // For now, only use non-vector load / store's for the left-over pieces.
4775 if (VT.isVector() || VT.isFloatingPoint()) {
4776 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4777 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4778 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4780 else if (NewVT == MVT::i64 &&
4781 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4782 TLI.isSafeMemOpType(MVT::f64)) {
4783 // i64 is usually not legal on 32-bit targets, but f64 may be.
4791 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4792 if (NewVT == MVT::i8)
4794 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4796 NewVTSize = NewVT.getSizeInBits() / 8;
4798 // If the new VT cannot cover all of the remaining bits, then consider
4799 // issuing a (or a pair of) unaligned and overlapping load / store.
4800 // FIXME: Only does this for 64-bit or more since we don't have proper
4801 // cost model for unaligned load / store.
4803 if (NumMemOps && AllowOverlap &&
4804 VTSize >= 8 && NewVTSize < Size &&
4805 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4813 if (++NumMemOps > Limit)
4816 MemOps.push_back(VT);
4823 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4824 // On Darwin, -Os means optimize for size without hurting performance, so
4825 // only really optimize for size when -Oz (MinSize) is used.
4826 if (MF.getTarget().getTargetTriple().isOSDarwin())
4827 return MF.getFunction()->optForMinSize();
4828 return MF.getFunction()->optForSize();
4831 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4832 SDValue Chain, SDValue Dst, SDValue Src,
4833 uint64_t Size, unsigned Align,
4834 bool isVol, bool AlwaysInline,
4835 MachinePointerInfo DstPtrInfo,
4836 MachinePointerInfo SrcPtrInfo) {
4837 // Turn a memcpy of undef to nop.
4841 // Expand memcpy to a series of load and store ops if the size operand falls
4842 // below a certain threshold.
4843 // TODO: In the AlwaysInline case, if the size is big then generate a loop
4844 // rather than maybe a humongous number of loads and stores.
4845 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4846 std::vector<EVT> MemOps;
4847 bool DstAlignCanChange = false;
4848 MachineFunction &MF = DAG.getMachineFunction();
4849 MachineFrameInfo &MFI = MF.getFrameInfo();
4850 bool OptSize = shouldLowerMemFuncForSize(MF);
4851 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4852 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4853 DstAlignCanChange = true;
4854 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4855 if (Align > SrcAlign)
4858 bool CopyFromStr = isMemSrcFromString(Src, Str);
4859 bool isZeroStr = CopyFromStr && Str.empty();
4860 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4862 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4863 (DstAlignCanChange ? 0 : Align),
4864 (isZeroStr ? 0 : SrcAlign),
4865 false, false, CopyFromStr, true,
4866 DstPtrInfo.getAddrSpace(),
4867 SrcPtrInfo.getAddrSpace(),
4871 if (DstAlignCanChange) {
4872 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4873 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4875 // Don't promote to an alignment that would require dynamic stack
4877 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4878 if (!TRI->needsStackRealignment(MF))
4879 while (NewAlign > Align &&
4880 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign))
4883 if (NewAlign > Align) {
4884 // Give the stack frame object a larger alignment if needed.
4885 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4886 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4891 MachineMemOperand::Flags MMOFlags =
4892 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4893 SmallVector<SDValue, 8> OutChains;
4894 unsigned NumMemOps = MemOps.size();
4895 uint64_t SrcOff = 0, DstOff = 0;
4896 for (unsigned i = 0; i != NumMemOps; ++i) {
4898 unsigned VTSize = VT.getSizeInBits() / 8;
4899 SDValue Value, Store;
4901 if (VTSize > Size) {
4902 // Issuing an unaligned load / store pair that overlaps with the previous
4903 // pair. Adjust the offset accordingly.
4904 assert(i == NumMemOps-1 && i != 0);
4905 SrcOff -= VTSize - Size;
4906 DstOff -= VTSize - Size;
4910 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
4911 // It's unlikely a store of a vector immediate can be done in a single
4912 // instruction. It would require a load from a constantpool first.
4913 // We only handle zero vectors here.
4914 // FIXME: Handle other cases where store of vector immediate is done in
4915 // a single instruction.
4916 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
4917 if (Value.getNode())
4918 Store = DAG.getStore(Chain, dl, Value,
4919 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4920 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
4923 if (!Store.getNode()) {
4924 // The type might not be legal for the target. This should only happen
4925 // if the type is smaller than a legal type, as on PPC, so the right
4926 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
4927 // to Load/Store if NVT==VT.
4928 // FIXME does the case above also need this?
4929 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4930 assert(NVT.bitsGE(VT));
4931 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4932 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4933 SrcPtrInfo.getWithOffset(SrcOff), VT,
4934 MinAlign(SrcAlign, SrcOff), MMOFlags);
4935 OutChains.push_back(Value.getValue(1));
4936 Store = DAG.getTruncStore(
4937 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4938 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
4940 OutChains.push_back(Store);
4946 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4949 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4950 SDValue Chain, SDValue Dst, SDValue Src,
4951 uint64_t Size, unsigned Align,
4952 bool isVol, bool AlwaysInline,
4953 MachinePointerInfo DstPtrInfo,
4954 MachinePointerInfo SrcPtrInfo) {
4955 // Turn a memmove of undef to nop.
4959 // Expand memmove to a series of load and store ops if the size operand falls
4960 // below a certain threshold.
4961 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4962 std::vector<EVT> MemOps;
4963 bool DstAlignCanChange = false;
4964 MachineFunction &MF = DAG.getMachineFunction();
4965 MachineFrameInfo &MFI = MF.getFrameInfo();
4966 bool OptSize = shouldLowerMemFuncForSize(MF);
4967 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4968 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4969 DstAlignCanChange = true;
4970 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4971 if (Align > SrcAlign)
4973 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
4975 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4976 (DstAlignCanChange ? 0 : Align), SrcAlign,
4977 false, false, false, false,
4978 DstPtrInfo.getAddrSpace(),
4979 SrcPtrInfo.getAddrSpace(),
4983 if (DstAlignCanChange) {
4984 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4985 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4986 if (NewAlign > Align) {
4987 // Give the stack frame object a larger alignment if needed.
4988 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4989 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4994 MachineMemOperand::Flags MMOFlags =
4995 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4996 uint64_t SrcOff = 0, DstOff = 0;
4997 SmallVector<SDValue, 8> LoadValues;
4998 SmallVector<SDValue, 8> LoadChains;
4999 SmallVector<SDValue, 8> OutChains;
5000 unsigned NumMemOps = MemOps.size();
5001 for (unsigned i = 0; i < NumMemOps; i++) {
5003 unsigned VTSize = VT.getSizeInBits() / 8;
5007 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5008 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags);
5009 LoadValues.push_back(Value);
5010 LoadChains.push_back(Value.getValue(1));
5013 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5015 for (unsigned i = 0; i < NumMemOps; i++) {
5017 unsigned VTSize = VT.getSizeInBits() / 8;
5020 Store = DAG.getStore(Chain, dl, LoadValues[i],
5021 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5022 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5023 OutChains.push_back(Store);
5027 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5030 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5033 /// \param DAG Selection DAG where lowered code is placed.
5034 /// \param dl Link to corresponding IR location.
5035 /// \param Chain Control flow dependency.
5036 /// \param Dst Pointer to destination memory location.
5037 /// \param Src Value of byte to write into the memory.
5038 /// \param Size Number of bytes to write.
5039 /// \param Align Alignment of the destination in bytes.
5040 /// \param isVol True if destination is volatile.
5041 /// \param DstPtrInfo IR information on the memory pointer.
5042 /// \returns New head in the control flow, if lowering was successful, empty
5043 /// SDValue otherwise.
5045 /// The function tries to replace 'llvm.memset' intrinsic with several store
5046 /// operations and value calculation code. This is usually profitable for small
5048 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5049 SDValue Chain, SDValue Dst, SDValue Src,
5050 uint64_t Size, unsigned Align, bool isVol,
5051 MachinePointerInfo DstPtrInfo) {
5052 // Turn a memset of undef to nop.
5056 // Expand memset to a series of load/store ops if the size operand
5057 // falls below a certain threshold.
5058 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5059 std::vector<EVT> MemOps;
5060 bool DstAlignCanChange = false;
5061 MachineFunction &MF = DAG.getMachineFunction();
5062 MachineFrameInfo &MFI = MF.getFrameInfo();
5063 bool OptSize = shouldLowerMemFuncForSize(MF);
5064 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5065 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5066 DstAlignCanChange = true;
5068 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5069 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5070 Size, (DstAlignCanChange ? 0 : Align), 0,
5071 true, IsZeroVal, false, true,
5072 DstPtrInfo.getAddrSpace(), ~0u,
5076 if (DstAlignCanChange) {
5077 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5078 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5079 if (NewAlign > Align) {
5080 // Give the stack frame object a larger alignment if needed.
5081 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5082 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5087 SmallVector<SDValue, 8> OutChains;
5088 uint64_t DstOff = 0;
5089 unsigned NumMemOps = MemOps.size();
5091 // Find the largest store and generate the bit pattern for it.
5092 EVT LargestVT = MemOps[0];
5093 for (unsigned i = 1; i < NumMemOps; i++)
5094 if (MemOps[i].bitsGT(LargestVT))
5095 LargestVT = MemOps[i];
5096 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5098 for (unsigned i = 0; i < NumMemOps; i++) {
5100 unsigned VTSize = VT.getSizeInBits() / 8;
5101 if (VTSize > Size) {
5102 // Issuing an unaligned load / store pair that overlaps with the previous
5103 // pair. Adjust the offset accordingly.
5104 assert(i == NumMemOps-1 && i != 0);
5105 DstOff -= VTSize - Size;
5108 // If this store is smaller than the largest store see whether we can get
5109 // the smaller value for free with a truncate.
5110 SDValue Value = MemSetValue;
5111 if (VT.bitsLT(LargestVT)) {
5112 if (!LargestVT.isVector() && !VT.isVector() &&
5113 TLI.isTruncateFree(LargestVT, VT))
5114 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5116 Value = getMemsetValue(Src, VT, DAG, dl);
5118 assert(Value.getValueType() == VT && "Value with wrong type.");
5119 SDValue Store = DAG.getStore(
5120 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5121 DstPtrInfo.getWithOffset(DstOff), Align,
5122 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5123 OutChains.push_back(Store);
5124 DstOff += VT.getSizeInBits() / 8;
5128 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5131 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5133 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5134 // pointer operands can be losslessly bitcasted to pointers of address space 0
5135 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5136 report_fatal_error("cannot lower memory intrinsic in address space " +
5141 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5142 SDValue Src, SDValue Size, unsigned Align,
5143 bool isVol, bool AlwaysInline, bool isTailCall,
5144 MachinePointerInfo DstPtrInfo,
5145 MachinePointerInfo SrcPtrInfo) {
5146 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5148 // Check to see if we should lower the memcpy to loads and stores first.
5149 // For cases within the target-specified limits, this is the best choice.
5150 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5152 // Memcpy with size zero? Just return the original chain.
5153 if (ConstantSize->isNullValue())
5156 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5157 ConstantSize->getZExtValue(),Align,
5158 isVol, false, DstPtrInfo, SrcPtrInfo);
5159 if (Result.getNode())
5163 // Then check to see if we should lower the memcpy with target-specific
5164 // code. If the target chooses to do this, this is the next best.
5166 SDValue Result = TSI->EmitTargetCodeForMemcpy(
5167 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5168 DstPtrInfo, SrcPtrInfo);
5169 if (Result.getNode())
5173 // If we really need inline code and the target declined to provide it,
5174 // use a (potentially long) sequence of loads and stores.
5176 assert(ConstantSize && "AlwaysInline requires a constant size!");
5177 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5178 ConstantSize->getZExtValue(), Align, isVol,
5179 true, DstPtrInfo, SrcPtrInfo);
5182 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5183 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5185 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5186 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5187 // respect volatile, so they may do things like read or write memory
5188 // beyond the given memory regions. But fixing this isn't easy, and most
5189 // people don't care.
5191 // Emit a library call.
5192 TargetLowering::ArgListTy Args;
5193 TargetLowering::ArgListEntry Entry;
5194 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5195 Entry.Node = Dst; Args.push_back(Entry);
5196 Entry.Node = Src; Args.push_back(Entry);
5197 Entry.Node = Size; Args.push_back(Entry);
5198 // FIXME: pass in SDLoc
5199 TargetLowering::CallLoweringInfo CLI(*this);
5202 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5203 Dst.getValueType().getTypeForEVT(*getContext()),
5204 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5205 TLI->getPointerTy(getDataLayout())),
5208 .setTailCall(isTailCall);
5210 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5211 return CallResult.second;
5214 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5215 SDValue Src, SDValue Size, unsigned Align,
5216 bool isVol, bool isTailCall,
5217 MachinePointerInfo DstPtrInfo,
5218 MachinePointerInfo SrcPtrInfo) {
5219 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5221 // Check to see if we should lower the memmove to loads and stores first.
5222 // For cases within the target-specified limits, this is the best choice.
5223 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5225 // Memmove with size zero? Just return the original chain.
5226 if (ConstantSize->isNullValue())
5230 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5231 ConstantSize->getZExtValue(), Align, isVol,
5232 false, DstPtrInfo, SrcPtrInfo);
5233 if (Result.getNode())
5237 // Then check to see if we should lower the memmove with target-specific
5238 // code. If the target chooses to do this, this is the next best.
5240 SDValue Result = TSI->EmitTargetCodeForMemmove(
5241 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5242 if (Result.getNode())
5246 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5247 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5249 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5250 // not be safe. See memcpy above for more details.
5252 // Emit a library call.
5253 TargetLowering::ArgListTy Args;
5254 TargetLowering::ArgListEntry Entry;
5255 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5256 Entry.Node = Dst; Args.push_back(Entry);
5257 Entry.Node = Src; Args.push_back(Entry);
5258 Entry.Node = Size; Args.push_back(Entry);
5259 // FIXME: pass in SDLoc
5260 TargetLowering::CallLoweringInfo CLI(*this);
5263 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5264 Dst.getValueType().getTypeForEVT(*getContext()),
5265 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5266 TLI->getPointerTy(getDataLayout())),
5269 .setTailCall(isTailCall);
5271 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5272 return CallResult.second;
5275 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5276 SDValue Src, SDValue Size, unsigned Align,
5277 bool isVol, bool isTailCall,
5278 MachinePointerInfo DstPtrInfo) {
5279 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5281 // Check to see if we should lower the memset to stores first.
5282 // For cases within the target-specified limits, this is the best choice.
5283 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5285 // Memset with size zero? Just return the original chain.
5286 if (ConstantSize->isNullValue())
5290 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5291 Align, isVol, DstPtrInfo);
5293 if (Result.getNode())
5297 // Then check to see if we should lower the memset with target-specific
5298 // code. If the target chooses to do this, this is the next best.
5300 SDValue Result = TSI->EmitTargetCodeForMemset(
5301 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5302 if (Result.getNode())
5306 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5308 // Emit a library call.
5309 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5310 TargetLowering::ArgListTy Args;
5311 TargetLowering::ArgListEntry Entry;
5312 Entry.Node = Dst; Entry.Ty = IntPtrTy;
5313 Args.push_back(Entry);
5315 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5316 Args.push_back(Entry);
5318 Entry.Ty = IntPtrTy;
5319 Args.push_back(Entry);
5321 // FIXME: pass in SDLoc
5322 TargetLowering::CallLoweringInfo CLI(*this);
5325 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5326 Dst.getValueType().getTypeForEVT(*getContext()),
5327 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5328 TLI->getPointerTy(getDataLayout())),
5331 .setTailCall(isTailCall);
5333 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5334 return CallResult.second;
5337 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5338 SDVTList VTList, ArrayRef<SDValue> Ops,
5339 MachineMemOperand *MMO) {
5340 FoldingSetNodeID ID;
5341 ID.AddInteger(MemVT.getRawBits());
5342 AddNodeIDNode(ID, Opcode, VTList, Ops);
5343 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5345 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5346 cast<AtomicSDNode>(E)->refineAlignment(MMO);
5347 return SDValue(E, 0);
5350 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5351 VTList, MemVT, MMO);
5352 createOperands(N, Ops);
5354 CSEMap.InsertNode(N, IP);
5356 return SDValue(N, 0);
5359 SDValue SelectionDAG::getAtomicCmpSwap(
5360 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5361 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5362 unsigned Alignment, AtomicOrdering SuccessOrdering,
5363 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
5364 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5365 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5366 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5368 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5369 Alignment = getEVTAlignment(MemVT);
5371 MachineFunction &MF = getMachineFunction();
5373 // FIXME: Volatile isn't really correct; we should keep track of atomic
5374 // orderings in the memoperand.
5375 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5376 MachineMemOperand::MOStore;
5377 MachineMemOperand *MMO =
5378 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5379 AAMDNodes(), nullptr, SynchScope, SuccessOrdering,
5382 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5385 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5386 EVT MemVT, SDVTList VTs, SDValue Chain,
5387 SDValue Ptr, SDValue Cmp, SDValue Swp,
5388 MachineMemOperand *MMO) {
5389 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5390 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5391 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5393 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5394 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5397 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5398 SDValue Chain, SDValue Ptr, SDValue Val,
5399 const Value *PtrVal, unsigned Alignment,
5400 AtomicOrdering Ordering,
5401 SynchronizationScope SynchScope) {
5402 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5403 Alignment = getEVTAlignment(MemVT);
5405 MachineFunction &MF = getMachineFunction();
5406 // An atomic store does not load. An atomic load does not store.
5407 // (An atomicrmw obviously both loads and stores.)
5408 // For now, atomics are considered to be volatile always, and they are
5410 // FIXME: Volatile isn't really correct; we should keep track of atomic
5411 // orderings in the memoperand.
5412 auto Flags = MachineMemOperand::MOVolatile;
5413 if (Opcode != ISD::ATOMIC_STORE)
5414 Flags |= MachineMemOperand::MOLoad;
5415 if (Opcode != ISD::ATOMIC_LOAD)
5416 Flags |= MachineMemOperand::MOStore;
5418 MachineMemOperand *MMO =
5419 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5420 MemVT.getStoreSize(), Alignment, AAMDNodes(),
5421 nullptr, SynchScope, Ordering);
5423 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5426 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5427 SDValue Chain, SDValue Ptr, SDValue Val,
5428 MachineMemOperand *MMO) {
5429 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5430 Opcode == ISD::ATOMIC_LOAD_SUB ||
5431 Opcode == ISD::ATOMIC_LOAD_AND ||
5432 Opcode == ISD::ATOMIC_LOAD_OR ||
5433 Opcode == ISD::ATOMIC_LOAD_XOR ||
5434 Opcode == ISD::ATOMIC_LOAD_NAND ||
5435 Opcode == ISD::ATOMIC_LOAD_MIN ||
5436 Opcode == ISD::ATOMIC_LOAD_MAX ||
5437 Opcode == ISD::ATOMIC_LOAD_UMIN ||
5438 Opcode == ISD::ATOMIC_LOAD_UMAX ||
5439 Opcode == ISD::ATOMIC_SWAP ||
5440 Opcode == ISD::ATOMIC_STORE) &&
5441 "Invalid Atomic Op");
5443 EVT VT = Val.getValueType();
5445 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5446 getVTList(VT, MVT::Other);
5447 SDValue Ops[] = {Chain, Ptr, Val};
5448 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5451 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5452 EVT VT, SDValue Chain, SDValue Ptr,
5453 MachineMemOperand *MMO) {
5454 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5456 SDVTList VTs = getVTList(VT, MVT::Other);
5457 SDValue Ops[] = {Chain, Ptr};
5458 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5461 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5462 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5463 if (Ops.size() == 1)
5466 SmallVector<EVT, 4> VTs;
5467 VTs.reserve(Ops.size());
5468 for (unsigned i = 0; i < Ops.size(); ++i)
5469 VTs.push_back(Ops[i].getValueType());
5470 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5473 SDValue SelectionDAG::getMemIntrinsicNode(
5474 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5475 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5476 bool ReadMem, bool WriteMem, unsigned Size) {
5477 if (Align == 0) // Ensure that codegen never sees alignment 0
5478 Align = getEVTAlignment(MemVT);
5480 MachineFunction &MF = getMachineFunction();
5481 auto Flags = MachineMemOperand::MONone;
5483 Flags |= MachineMemOperand::MOStore;
5485 Flags |= MachineMemOperand::MOLoad;
5487 Flags |= MachineMemOperand::MOVolatile;
5489 Size = MemVT.getStoreSize();
5490 MachineMemOperand *MMO =
5491 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5493 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5496 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5498 ArrayRef<SDValue> Ops, EVT MemVT,
5499 MachineMemOperand *MMO) {
5500 assert((Opcode == ISD::INTRINSIC_VOID ||
5501 Opcode == ISD::INTRINSIC_W_CHAIN ||
5502 Opcode == ISD::PREFETCH ||
5503 Opcode == ISD::LIFETIME_START ||
5504 Opcode == ISD::LIFETIME_END ||
5505 (Opcode <= INT_MAX &&
5506 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5507 "Opcode is not a memory-accessing opcode!");
5509 // Memoize the node unless it returns a flag.
5510 MemIntrinsicSDNode *N;
5511 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5512 FoldingSetNodeID ID;
5513 AddNodeIDNode(ID, Opcode, VTList, Ops);
5514 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5516 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5517 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5518 return SDValue(E, 0);
5521 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5522 VTList, MemVT, MMO);
5523 createOperands(N, Ops);
5525 CSEMap.InsertNode(N, IP);
5527 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5528 VTList, MemVT, MMO);
5529 createOperands(N, Ops);
5532 return SDValue(N, 0);
5535 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5536 /// MachinePointerInfo record from it. This is particularly useful because the
5537 /// code generator has many cases where it doesn't bother passing in a
5538 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5539 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5540 int64_t Offset = 0) {
5541 // If this is FI+Offset, we can model it.
5542 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5543 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5544 FI->getIndex(), Offset);
5546 // If this is (FI+Offset1)+Offset2, we can model it.
5547 if (Ptr.getOpcode() != ISD::ADD ||
5548 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5549 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5550 return MachinePointerInfo();
5552 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5553 return MachinePointerInfo::getFixedStack(
5554 DAG.getMachineFunction(), FI,
5555 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5558 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5559 /// MachinePointerInfo record from it. This is particularly useful because the
5560 /// code generator has many cases where it doesn't bother passing in a
5561 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5562 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5564 // If the 'Offset' value isn't a constant, we can't handle this.
5565 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5566 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5567 if (OffsetOp.isUndef())
5568 return InferPointerInfo(DAG, Ptr);
5569 return MachinePointerInfo();
5572 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5573 EVT VT, const SDLoc &dl, SDValue Chain,
5574 SDValue Ptr, SDValue Offset,
5575 MachinePointerInfo PtrInfo, EVT MemVT,
5577 MachineMemOperand::Flags MMOFlags,
5578 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5579 assert(Chain.getValueType() == MVT::Other &&
5580 "Invalid chain type");
5581 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5582 Alignment = getEVTAlignment(MemVT);
5584 MMOFlags |= MachineMemOperand::MOLoad;
5585 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5586 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5588 if (PtrInfo.V.isNull())
5589 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5591 MachineFunction &MF = getMachineFunction();
5592 MachineMemOperand *MMO = MF.getMachineMemOperand(
5593 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5594 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5597 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5598 EVT VT, const SDLoc &dl, SDValue Chain,
5599 SDValue Ptr, SDValue Offset, EVT MemVT,
5600 MachineMemOperand *MMO) {
5602 ExtType = ISD::NON_EXTLOAD;
5603 } else if (ExtType == ISD::NON_EXTLOAD) {
5604 assert(VT == MemVT && "Non-extending load from different memory type!");
5607 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5608 "Should only be an extending load, not truncating!");
5609 assert(VT.isInteger() == MemVT.isInteger() &&
5610 "Cannot convert from FP to Int or Int -> FP!");
5611 assert(VT.isVector() == MemVT.isVector() &&
5612 "Cannot use an ext load to convert to or from a vector!");
5613 assert((!VT.isVector() ||
5614 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5615 "Cannot use an ext load to change the number of vector elements!");
5618 bool Indexed = AM != ISD::UNINDEXED;
5619 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5621 SDVTList VTs = Indexed ?
5622 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5623 SDValue Ops[] = { Chain, Ptr, Offset };
5624 FoldingSetNodeID ID;
5625 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5626 ID.AddInteger(MemVT.getRawBits());
5627 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5628 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5629 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5631 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5632 cast<LoadSDNode>(E)->refineAlignment(MMO);
5633 return SDValue(E, 0);
5635 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5636 ExtType, MemVT, MMO);
5637 createOperands(N, Ops);
5639 CSEMap.InsertNode(N, IP);
5641 return SDValue(N, 0);
5644 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5645 SDValue Ptr, MachinePointerInfo PtrInfo,
5647 MachineMemOperand::Flags MMOFlags,
5648 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5649 SDValue Undef = getUNDEF(Ptr.getValueType());
5650 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5651 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5654 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5655 SDValue Ptr, MachineMemOperand *MMO) {
5656 SDValue Undef = getUNDEF(Ptr.getValueType());
5657 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5661 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5662 EVT VT, SDValue Chain, SDValue Ptr,
5663 MachinePointerInfo PtrInfo, EVT MemVT,
5665 MachineMemOperand::Flags MMOFlags,
5666 const AAMDNodes &AAInfo) {
5667 SDValue Undef = getUNDEF(Ptr.getValueType());
5668 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5669 MemVT, Alignment, MMOFlags, AAInfo);
5672 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5673 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5674 MachineMemOperand *MMO) {
5675 SDValue Undef = getUNDEF(Ptr.getValueType());
5676 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5680 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5681 SDValue Base, SDValue Offset,
5682 ISD::MemIndexedMode AM) {
5683 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5684 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5685 // Don't propagate the invariant or dereferenceable flags.
5687 LD->getMemOperand()->getFlags() &
5688 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5689 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5690 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5691 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5695 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5696 SDValue Ptr, MachinePointerInfo PtrInfo,
5698 MachineMemOperand::Flags MMOFlags,
5699 const AAMDNodes &AAInfo) {
5700 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5701 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5702 Alignment = getEVTAlignment(Val.getValueType());
5704 MMOFlags |= MachineMemOperand::MOStore;
5705 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5707 if (PtrInfo.V.isNull())
5708 PtrInfo = InferPointerInfo(*this, Ptr);
5710 MachineFunction &MF = getMachineFunction();
5711 MachineMemOperand *MMO = MF.getMachineMemOperand(
5712 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5713 return getStore(Chain, dl, Val, Ptr, MMO);
5716 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5717 SDValue Ptr, MachineMemOperand *MMO) {
5718 assert(Chain.getValueType() == MVT::Other &&
5719 "Invalid chain type");
5720 EVT VT = Val.getValueType();
5721 SDVTList VTs = getVTList(MVT::Other);
5722 SDValue Undef = getUNDEF(Ptr.getValueType());
5723 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5724 FoldingSetNodeID ID;
5725 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5726 ID.AddInteger(VT.getRawBits());
5727 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5728 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5729 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5731 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5732 cast<StoreSDNode>(E)->refineAlignment(MMO);
5733 return SDValue(E, 0);
5735 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5736 ISD::UNINDEXED, false, VT, MMO);
5737 createOperands(N, Ops);
5739 CSEMap.InsertNode(N, IP);
5741 return SDValue(N, 0);
5744 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5745 SDValue Ptr, MachinePointerInfo PtrInfo,
5746 EVT SVT, unsigned Alignment,
5747 MachineMemOperand::Flags MMOFlags,
5748 const AAMDNodes &AAInfo) {
5749 assert(Chain.getValueType() == MVT::Other &&
5750 "Invalid chain type");
5751 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5752 Alignment = getEVTAlignment(SVT);
5754 MMOFlags |= MachineMemOperand::MOStore;
5755 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5757 if (PtrInfo.V.isNull())
5758 PtrInfo = InferPointerInfo(*this, Ptr);
5760 MachineFunction &MF = getMachineFunction();
5761 MachineMemOperand *MMO = MF.getMachineMemOperand(
5762 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5763 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5766 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5767 SDValue Ptr, EVT SVT,
5768 MachineMemOperand *MMO) {
5769 EVT VT = Val.getValueType();
5771 assert(Chain.getValueType() == MVT::Other &&
5772 "Invalid chain type");
5774 return getStore(Chain, dl, Val, Ptr, MMO);
5776 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5777 "Should only be a truncating store, not extending!");
5778 assert(VT.isInteger() == SVT.isInteger() &&
5779 "Can't do FP-INT conversion!");
5780 assert(VT.isVector() == SVT.isVector() &&
5781 "Cannot use trunc store to convert to or from a vector!");
5782 assert((!VT.isVector() ||
5783 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5784 "Cannot use trunc store to change the number of vector elements!");
5786 SDVTList VTs = getVTList(MVT::Other);
5787 SDValue Undef = getUNDEF(Ptr.getValueType());
5788 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5789 FoldingSetNodeID ID;
5790 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5791 ID.AddInteger(SVT.getRawBits());
5792 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5793 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5794 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5796 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5797 cast<StoreSDNode>(E)->refineAlignment(MMO);
5798 return SDValue(E, 0);
5800 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5801 ISD::UNINDEXED, true, SVT, MMO);
5802 createOperands(N, Ops);
5804 CSEMap.InsertNode(N, IP);
5806 return SDValue(N, 0);
5809 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5810 SDValue Base, SDValue Offset,
5811 ISD::MemIndexedMode AM) {
5812 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5813 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5814 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5815 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5816 FoldingSetNodeID ID;
5817 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5818 ID.AddInteger(ST->getMemoryVT().getRawBits());
5819 ID.AddInteger(ST->getRawSubclassData());
5820 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5822 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5823 return SDValue(E, 0);
5825 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5826 ST->isTruncatingStore(), ST->getMemoryVT(),
5827 ST->getMemOperand());
5828 createOperands(N, Ops);
5830 CSEMap.InsertNode(N, IP);
5832 return SDValue(N, 0);
5835 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5836 SDValue Ptr, SDValue Mask, SDValue Src0,
5837 EVT MemVT, MachineMemOperand *MMO,
5838 ISD::LoadExtType ExtTy, bool isExpanding) {
5840 SDVTList VTs = getVTList(VT, MVT::Other);
5841 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5842 FoldingSetNodeID ID;
5843 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5844 ID.AddInteger(VT.getRawBits());
5845 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5846 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5847 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5849 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5850 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5851 return SDValue(E, 0);
5853 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5854 ExtTy, isExpanding, MemVT, MMO);
5855 createOperands(N, Ops);
5857 CSEMap.InsertNode(N, IP);
5859 return SDValue(N, 0);
5862 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5863 SDValue Val, SDValue Ptr, SDValue Mask,
5864 EVT MemVT, MachineMemOperand *MMO,
5865 bool IsTruncating, bool IsCompressing) {
5866 assert(Chain.getValueType() == MVT::Other &&
5867 "Invalid chain type");
5868 EVT VT = Val.getValueType();
5869 SDVTList VTs = getVTList(MVT::Other);
5870 SDValue Ops[] = { Chain, Ptr, Mask, Val };
5871 FoldingSetNodeID ID;
5872 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5873 ID.AddInteger(VT.getRawBits());
5874 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5875 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5876 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5878 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5879 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5880 return SDValue(E, 0);
5882 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5883 IsTruncating, IsCompressing, MemVT, MMO);
5884 createOperands(N, Ops);
5886 CSEMap.InsertNode(N, IP);
5888 return SDValue(N, 0);
5891 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5892 ArrayRef<SDValue> Ops,
5893 MachineMemOperand *MMO) {
5894 assert(Ops.size() == 5 && "Incompatible number of operands");
5896 FoldingSetNodeID ID;
5897 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5898 ID.AddInteger(VT.getRawBits());
5899 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5900 dl.getIROrder(), VTs, VT, MMO));
5901 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5903 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5904 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5905 return SDValue(E, 0);
5908 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5910 createOperands(N, Ops);
5912 assert(N->getValue().getValueType() == N->getValueType(0) &&
5913 "Incompatible type of the PassThru value in MaskedGatherSDNode");
5914 assert(N->getMask().getValueType().getVectorNumElements() ==
5915 N->getValueType(0).getVectorNumElements() &&
5916 "Vector width mismatch between mask and data");
5917 assert(N->getIndex().getValueType().getVectorNumElements() ==
5918 N->getValueType(0).getVectorNumElements() &&
5919 "Vector width mismatch between index and data");
5921 CSEMap.InsertNode(N, IP);
5923 return SDValue(N, 0);
5926 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
5927 ArrayRef<SDValue> Ops,
5928 MachineMemOperand *MMO) {
5929 assert(Ops.size() == 5 && "Incompatible number of operands");
5931 FoldingSetNodeID ID;
5932 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5933 ID.AddInteger(VT.getRawBits());
5934 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
5935 dl.getIROrder(), VTs, VT, MMO));
5936 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5938 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5939 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
5940 return SDValue(E, 0);
5942 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5944 createOperands(N, Ops);
5946 assert(N->getMask().getValueType().getVectorNumElements() ==
5947 N->getValue().getValueType().getVectorNumElements() &&
5948 "Vector width mismatch between mask and data");
5949 assert(N->getIndex().getValueType().getVectorNumElements() ==
5950 N->getValue().getValueType().getVectorNumElements() &&
5951 "Vector width mismatch between index and data");
5953 CSEMap.InsertNode(N, IP);
5955 return SDValue(N, 0);
5958 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
5959 SDValue Ptr, SDValue SV, unsigned Align) {
5960 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
5961 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
5964 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5965 ArrayRef<SDUse> Ops) {
5966 switch (Ops.size()) {
5967 case 0: return getNode(Opcode, DL, VT);
5968 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
5969 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5970 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5974 // Copy from an SDUse array into an SDValue array for use with
5975 // the regular getNode logic.
5976 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
5977 return getNode(Opcode, DL, VT, NewOps);
5980 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5981 ArrayRef<SDValue> Ops, const SDNodeFlags *Flags) {
5982 unsigned NumOps = Ops.size();
5984 case 0: return getNode(Opcode, DL, VT);
5985 case 1: return getNode(Opcode, DL, VT, Ops[0]);
5986 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
5987 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5993 case ISD::CONCAT_VECTORS: {
5994 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
5995 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
5999 case ISD::SELECT_CC: {
6000 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6001 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6002 "LHS and RHS of condition must have same type!");
6003 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6004 "True and False arms of SelectCC must have same type!");
6005 assert(Ops[2].getValueType() == VT &&
6006 "select_cc node must be of same type as true and false value!");
6010 assert(NumOps == 5 && "BR_CC takes 5 operands!");
6011 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6012 "LHS/RHS of comparison should match types!");
6019 SDVTList VTs = getVTList(VT);
6021 if (VT != MVT::Glue) {
6022 FoldingSetNodeID ID;
6023 AddNodeIDNode(ID, Opcode, VTs, Ops);
6026 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6027 return SDValue(E, 0);
6029 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6030 createOperands(N, Ops);
6032 CSEMap.InsertNode(N, IP);
6034 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6035 createOperands(N, Ops);
6039 return SDValue(N, 0);
6042 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6043 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6044 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6047 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6048 ArrayRef<SDValue> Ops) {
6049 if (VTList.NumVTs == 1)
6050 return getNode(Opcode, DL, VTList.VTs[0], Ops);
6054 // FIXME: figure out how to safely handle things like
6055 // int foo(int x) { return 1 << (x & 255); }
6056 // int bar() { return foo(256); }
6057 case ISD::SRA_PARTS:
6058 case ISD::SRL_PARTS:
6059 case ISD::SHL_PARTS:
6060 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6061 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6062 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6063 else if (N3.getOpcode() == ISD::AND)
6064 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6065 // If the and is only masking out bits that cannot effect the shift,
6066 // eliminate the and.
6067 unsigned NumBits = VT.getScalarSizeInBits()*2;
6068 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6069 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6075 // Memoize the node unless it returns a flag.
6077 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6078 FoldingSetNodeID ID;
6079 AddNodeIDNode(ID, Opcode, VTList, Ops);
6081 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6082 return SDValue(E, 0);
6084 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6085 createOperands(N, Ops);
6086 CSEMap.InsertNode(N, IP);
6088 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6089 createOperands(N, Ops);
6092 return SDValue(N, 0);
6095 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6097 return getNode(Opcode, DL, VTList, None);
6100 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6102 SDValue Ops[] = { N1 };
6103 return getNode(Opcode, DL, VTList, Ops);
6106 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6107 SDValue N1, SDValue N2) {
6108 SDValue Ops[] = { N1, N2 };
6109 return getNode(Opcode, DL, VTList, Ops);
6112 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6113 SDValue N1, SDValue N2, SDValue N3) {
6114 SDValue Ops[] = { N1, N2, N3 };
6115 return getNode(Opcode, DL, VTList, Ops);
6118 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6119 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6120 SDValue Ops[] = { N1, N2, N3, N4 };
6121 return getNode(Opcode, DL, VTList, Ops);
6124 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6125 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6127 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6128 return getNode(Opcode, DL, VTList, Ops);
6131 SDVTList SelectionDAG::getVTList(EVT VT) {
6132 return makeVTList(SDNode::getValueTypeList(VT), 1);
6135 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6136 FoldingSetNodeID ID;
6138 ID.AddInteger(VT1.getRawBits());
6139 ID.AddInteger(VT2.getRawBits());
6142 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6144 EVT *Array = Allocator.Allocate<EVT>(2);
6147 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6148 VTListMap.InsertNode(Result, IP);
6150 return Result->getSDVTList();
6153 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6154 FoldingSetNodeID ID;
6156 ID.AddInteger(VT1.getRawBits());
6157 ID.AddInteger(VT2.getRawBits());
6158 ID.AddInteger(VT3.getRawBits());
6161 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6163 EVT *Array = Allocator.Allocate<EVT>(3);
6167 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6168 VTListMap.InsertNode(Result, IP);
6170 return Result->getSDVTList();
6173 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6174 FoldingSetNodeID ID;
6176 ID.AddInteger(VT1.getRawBits());
6177 ID.AddInteger(VT2.getRawBits());
6178 ID.AddInteger(VT3.getRawBits());
6179 ID.AddInteger(VT4.getRawBits());
6182 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6184 EVT *Array = Allocator.Allocate<EVT>(4);
6189 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6190 VTListMap.InsertNode(Result, IP);
6192 return Result->getSDVTList();
6195 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6196 unsigned NumVTs = VTs.size();
6197 FoldingSetNodeID ID;
6198 ID.AddInteger(NumVTs);
6199 for (unsigned index = 0; index < NumVTs; index++) {
6200 ID.AddInteger(VTs[index].getRawBits());
6204 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6206 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6207 std::copy(VTs.begin(), VTs.end(), Array);
6208 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6209 VTListMap.InsertNode(Result, IP);
6211 return Result->getSDVTList();
6215 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6216 /// specified operands. If the resultant node already exists in the DAG,
6217 /// this does not modify the specified node, instead it returns the node that
6218 /// already exists. If the resultant node does not exist in the DAG, the
6219 /// input node is returned. As a degenerate case, if you specify the same
6220 /// input operands as the node already has, the input node is returned.
6221 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6222 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6224 // Check to see if there is no change.
6225 if (Op == N->getOperand(0)) return N;
6227 // See if the modified node already exists.
6228 void *InsertPos = nullptr;
6229 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6232 // Nope it doesn't. Remove the node from its current place in the maps.
6234 if (!RemoveNodeFromCSEMaps(N))
6235 InsertPos = nullptr;
6237 // Now we update the operands.
6238 N->OperandList[0].set(Op);
6240 // If this gets put into a CSE map, add it.
6241 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6245 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6246 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6248 // Check to see if there is no change.
6249 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6250 return N; // No operands changed, just return the input node.
6252 // See if the modified node already exists.
6253 void *InsertPos = nullptr;
6254 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6257 // Nope it doesn't. Remove the node from its current place in the maps.
6259 if (!RemoveNodeFromCSEMaps(N))
6260 InsertPos = nullptr;
6262 // Now we update the operands.
6263 if (N->OperandList[0] != Op1)
6264 N->OperandList[0].set(Op1);
6265 if (N->OperandList[1] != Op2)
6266 N->OperandList[1].set(Op2);
6268 // If this gets put into a CSE map, add it.
6269 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6273 SDNode *SelectionDAG::
6274 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6275 SDValue Ops[] = { Op1, Op2, Op3 };
6276 return UpdateNodeOperands(N, Ops);
6279 SDNode *SelectionDAG::
6280 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6281 SDValue Op3, SDValue Op4) {
6282 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6283 return UpdateNodeOperands(N, Ops);
6286 SDNode *SelectionDAG::
6287 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6288 SDValue Op3, SDValue Op4, SDValue Op5) {
6289 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6290 return UpdateNodeOperands(N, Ops);
6293 SDNode *SelectionDAG::
6294 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6295 unsigned NumOps = Ops.size();
6296 assert(N->getNumOperands() == NumOps &&
6297 "Update with wrong number of operands");
6299 // If no operands changed just return the input node.
6300 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6303 // See if the modified node already exists.
6304 void *InsertPos = nullptr;
6305 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6308 // Nope it doesn't. Remove the node from its current place in the maps.
6310 if (!RemoveNodeFromCSEMaps(N))
6311 InsertPos = nullptr;
6313 // Now we update the operands.
6314 for (unsigned i = 0; i != NumOps; ++i)
6315 if (N->OperandList[i] != Ops[i])
6316 N->OperandList[i].set(Ops[i]);
6318 // If this gets put into a CSE map, add it.
6319 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6323 /// DropOperands - Release the operands and set this node to have
6325 void SDNode::DropOperands() {
6326 // Unlike the code in MorphNodeTo that does this, we don't need to
6327 // watch for dead nodes here.
6328 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6334 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6337 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6339 SDVTList VTs = getVTList(VT);
6340 return SelectNodeTo(N, MachineOpc, VTs, None);
6343 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6344 EVT VT, SDValue Op1) {
6345 SDVTList VTs = getVTList(VT);
6346 SDValue Ops[] = { Op1 };
6347 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6350 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6351 EVT VT, SDValue Op1,
6353 SDVTList VTs = getVTList(VT);
6354 SDValue Ops[] = { Op1, Op2 };
6355 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6358 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6359 EVT VT, SDValue Op1,
6360 SDValue Op2, SDValue Op3) {
6361 SDVTList VTs = getVTList(VT);
6362 SDValue Ops[] = { Op1, Op2, Op3 };
6363 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6366 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6367 EVT VT, ArrayRef<SDValue> Ops) {
6368 SDVTList VTs = getVTList(VT);
6369 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6372 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6373 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6374 SDVTList VTs = getVTList(VT1, VT2);
6375 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6378 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6380 SDVTList VTs = getVTList(VT1, VT2);
6381 return SelectNodeTo(N, MachineOpc, VTs, None);
6384 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6385 EVT VT1, EVT VT2, EVT VT3,
6386 ArrayRef<SDValue> Ops) {
6387 SDVTList VTs = getVTList(VT1, VT2, VT3);
6388 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6391 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6393 SDValue Op1, SDValue Op2) {
6394 SDVTList VTs = getVTList(VT1, VT2);
6395 SDValue Ops[] = { Op1, Op2 };
6396 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6399 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6400 SDVTList VTs,ArrayRef<SDValue> Ops) {
6401 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6402 // Reset the NodeID to -1.
6405 ReplaceAllUsesWith(N, New);
6411 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6412 /// the line number information on the merged node since it is not possible to
6413 /// preserve the information that operation is associated with multiple lines.
6414 /// This will make the debugger working better at -O0, were there is a higher
6415 /// probability having other instructions associated with that line.
6417 /// For IROrder, we keep the smaller of the two
6418 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6419 DebugLoc NLoc = N->getDebugLoc();
6420 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6421 N->setDebugLoc(DebugLoc());
6423 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6424 N->setIROrder(Order);
6428 /// MorphNodeTo - This *mutates* the specified node to have the specified
6429 /// return type, opcode, and operands.
6431 /// Note that MorphNodeTo returns the resultant node. If there is already a
6432 /// node of the specified opcode and operands, it returns that node instead of
6433 /// the current one. Note that the SDLoc need not be the same.
6435 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6436 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6437 /// node, and because it doesn't require CSE recalculation for any of
6438 /// the node's users.
6440 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6441 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6442 /// the legalizer which maintain worklists that would need to be updated when
6443 /// deleting things.
6444 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6445 SDVTList VTs, ArrayRef<SDValue> Ops) {
6446 // If an identical node already exists, use it.
6448 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6449 FoldingSetNodeID ID;
6450 AddNodeIDNode(ID, Opc, VTs, Ops);
6451 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6452 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6455 if (!RemoveNodeFromCSEMaps(N))
6458 // Start the morphing.
6460 N->ValueList = VTs.VTs;
6461 N->NumValues = VTs.NumVTs;
6463 // Clear the operands list, updating used nodes to remove this from their
6464 // use list. Keep track of any operands that become dead as a result.
6465 SmallPtrSet<SDNode*, 16> DeadNodeSet;
6466 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6468 SDNode *Used = Use.getNode();
6470 if (Used->use_empty())
6471 DeadNodeSet.insert(Used);
6474 // For MachineNode, initialize the memory references information.
6475 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6476 MN->setMemRefs(nullptr, nullptr);
6478 // Swap for an appropriately sized array from the recycler.
6480 createOperands(N, Ops);
6482 // Delete any nodes that are still dead after adding the uses for the
6484 if (!DeadNodeSet.empty()) {
6485 SmallVector<SDNode *, 16> DeadNodes;
6486 for (SDNode *N : DeadNodeSet)
6488 DeadNodes.push_back(N);
6489 RemoveDeadNodes(DeadNodes);
6493 CSEMap.InsertNode(N, IP); // Memoize the new node.
6498 /// getMachineNode - These are used for target selectors to create a new node
6499 /// with specified return type(s), MachineInstr opcode, and operands.
6501 /// Note that getMachineNode returns the resultant node. If there is already a
6502 /// node of the specified opcode and operands, it returns that node instead of
6503 /// the current one.
6504 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6506 SDVTList VTs = getVTList(VT);
6507 return getMachineNode(Opcode, dl, VTs, None);
6510 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6511 EVT VT, SDValue Op1) {
6512 SDVTList VTs = getVTList(VT);
6513 SDValue Ops[] = { Op1 };
6514 return getMachineNode(Opcode, dl, VTs, Ops);
6517 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6518 EVT VT, SDValue Op1, SDValue Op2) {
6519 SDVTList VTs = getVTList(VT);
6520 SDValue Ops[] = { Op1, Op2 };
6521 return getMachineNode(Opcode, dl, VTs, Ops);
6524 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6525 EVT VT, SDValue Op1, SDValue Op2,
6527 SDVTList VTs = getVTList(VT);
6528 SDValue Ops[] = { Op1, Op2, Op3 };
6529 return getMachineNode(Opcode, dl, VTs, Ops);
6532 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6533 EVT VT, ArrayRef<SDValue> Ops) {
6534 SDVTList VTs = getVTList(VT);
6535 return getMachineNode(Opcode, dl, VTs, Ops);
6538 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6539 EVT VT1, EVT VT2, SDValue Op1,
6541 SDVTList VTs = getVTList(VT1, VT2);
6542 SDValue Ops[] = { Op1, Op2 };
6543 return getMachineNode(Opcode, dl, VTs, Ops);
6546 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6547 EVT VT1, EVT VT2, SDValue Op1,
6548 SDValue Op2, SDValue Op3) {
6549 SDVTList VTs = getVTList(VT1, VT2);
6550 SDValue Ops[] = { Op1, Op2, Op3 };
6551 return getMachineNode(Opcode, dl, VTs, Ops);
6554 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6556 ArrayRef<SDValue> Ops) {
6557 SDVTList VTs = getVTList(VT1, VT2);
6558 return getMachineNode(Opcode, dl, VTs, Ops);
6561 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6562 EVT VT1, EVT VT2, EVT VT3,
6563 SDValue Op1, SDValue Op2) {
6564 SDVTList VTs = getVTList(VT1, VT2, VT3);
6565 SDValue Ops[] = { Op1, Op2 };
6566 return getMachineNode(Opcode, dl, VTs, Ops);
6569 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6570 EVT VT1, EVT VT2, EVT VT3,
6571 SDValue Op1, SDValue Op2,
6573 SDVTList VTs = getVTList(VT1, VT2, VT3);
6574 SDValue Ops[] = { Op1, Op2, Op3 };
6575 return getMachineNode(Opcode, dl, VTs, Ops);
6578 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6579 EVT VT1, EVT VT2, EVT VT3,
6580 ArrayRef<SDValue> Ops) {
6581 SDVTList VTs = getVTList(VT1, VT2, VT3);
6582 return getMachineNode(Opcode, dl, VTs, Ops);
6585 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6586 ArrayRef<EVT> ResultTys,
6587 ArrayRef<SDValue> Ops) {
6588 SDVTList VTs = getVTList(ResultTys);
6589 return getMachineNode(Opcode, dl, VTs, Ops);
6592 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6594 ArrayRef<SDValue> Ops) {
6595 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6600 FoldingSetNodeID ID;
6601 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6603 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6604 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6608 // Allocate a new MachineSDNode.
6609 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6610 createOperands(N, Ops);
6613 CSEMap.InsertNode(N, IP);
6619 /// getTargetExtractSubreg - A convenience function for creating
6620 /// TargetOpcode::EXTRACT_SUBREG nodes.
6621 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6623 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6624 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6625 VT, Operand, SRIdxVal);
6626 return SDValue(Subreg, 0);
6629 /// getTargetInsertSubreg - A convenience function for creating
6630 /// TargetOpcode::INSERT_SUBREG nodes.
6631 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6632 SDValue Operand, SDValue Subreg) {
6633 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6634 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6635 VT, Operand, Subreg, SRIdxVal);
6636 return SDValue(Result, 0);
6639 /// getNodeIfExists - Get the specified node if it's already available, or
6640 /// else return NULL.
6641 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6642 ArrayRef<SDValue> Ops,
6643 const SDNodeFlags *Flags) {
6644 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6645 FoldingSetNodeID ID;
6646 AddNodeIDNode(ID, Opcode, VTList, Ops);
6648 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6650 E->intersectFlagsWith(Flags);
6657 /// getDbgValue - Creates a SDDbgValue node.
6660 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6661 unsigned R, bool IsIndirect, uint64_t Off,
6662 const DebugLoc &DL, unsigned O) {
6663 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6664 "Expected inlined-at fields to agree");
6665 return new (DbgInfo->getAlloc())
6666 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6670 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6671 const Value *C, uint64_t Off,
6672 const DebugLoc &DL, unsigned O) {
6673 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6674 "Expected inlined-at fields to agree");
6675 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6679 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6680 unsigned FI, uint64_t Off,
6683 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6684 "Expected inlined-at fields to agree");
6685 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6690 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6691 /// pointed to by a use iterator is deleted, increment the use iterator
6692 /// so that it doesn't dangle.
6694 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6695 SDNode::use_iterator &UI;
6696 SDNode::use_iterator &UE;
6698 void NodeDeleted(SDNode *N, SDNode *E) override {
6699 // Increment the iterator as needed.
6700 while (UI != UE && N == *UI)
6705 RAUWUpdateListener(SelectionDAG &d,
6706 SDNode::use_iterator &ui,
6707 SDNode::use_iterator &ue)
6708 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6713 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6714 /// This can cause recursive merging of nodes in the DAG.
6716 /// This version assumes From has a single result value.
6718 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6719 SDNode *From = FromN.getNode();
6720 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6721 "Cannot replace with this method!");
6722 assert(From != To.getNode() && "Cannot replace uses of with self");
6724 // Preserve Debug Values
6725 TransferDbgValues(FromN, To);
6727 // Iterate over all the existing uses of From. New uses will be added
6728 // to the beginning of the use list, which we avoid visiting.
6729 // This specifically avoids visiting uses of From that arise while the
6730 // replacement is happening, because any such uses would be the result
6731 // of CSE: If an existing node looks like From after one of its operands
6732 // is replaced by To, we don't want to replace of all its users with To
6733 // too. See PR3018 for more info.
6734 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6735 RAUWUpdateListener Listener(*this, UI, UE);
6739 // This node is about to morph, remove its old self from the CSE maps.
6740 RemoveNodeFromCSEMaps(User);
6742 // A user can appear in a use list multiple times, and when this
6743 // happens the uses are usually next to each other in the list.
6744 // To help reduce the number of CSE recomputations, process all
6745 // the uses of this user that we can find this way.
6747 SDUse &Use = UI.getUse();
6750 } while (UI != UE && *UI == User);
6752 // Now that we have modified User, add it back to the CSE maps. If it
6753 // already exists there, recursively merge the results together.
6754 AddModifiedNodeToCSEMaps(User);
6758 // If we just RAUW'd the root, take note.
6759 if (FromN == getRoot())
6763 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6764 /// This can cause recursive merging of nodes in the DAG.
6766 /// This version assumes that for each value of From, there is a
6767 /// corresponding value in To in the same position with the same type.
6769 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6771 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6772 assert((!From->hasAnyUseOfValue(i) ||
6773 From->getValueType(i) == To->getValueType(i)) &&
6774 "Cannot use this version of ReplaceAllUsesWith!");
6777 // Handle the trivial case.
6781 // Preserve Debug Info. Only do this if there's a use.
6782 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6783 if (From->hasAnyUseOfValue(i)) {
6784 assert((i < To->getNumValues()) && "Invalid To location");
6785 TransferDbgValues(SDValue(From, i), SDValue(To, i));
6788 // Iterate over just the existing users of From. See the comments in
6789 // the ReplaceAllUsesWith above.
6790 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6791 RAUWUpdateListener Listener(*this, UI, UE);
6795 // This node is about to morph, remove its old self from the CSE maps.
6796 RemoveNodeFromCSEMaps(User);
6798 // A user can appear in a use list multiple times, and when this
6799 // happens the uses are usually next to each other in the list.
6800 // To help reduce the number of CSE recomputations, process all
6801 // the uses of this user that we can find this way.
6803 SDUse &Use = UI.getUse();
6806 } while (UI != UE && *UI == User);
6808 // Now that we have modified User, add it back to the CSE maps. If it
6809 // already exists there, recursively merge the results together.
6810 AddModifiedNodeToCSEMaps(User);
6813 // If we just RAUW'd the root, take note.
6814 if (From == getRoot().getNode())
6815 setRoot(SDValue(To, getRoot().getResNo()));
6818 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6819 /// This can cause recursive merging of nodes in the DAG.
6821 /// This version can replace From with any result values. To must match the
6822 /// number and types of values returned by From.
6823 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6824 if (From->getNumValues() == 1) // Handle the simple case efficiently.
6825 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6827 // Preserve Debug Info.
6828 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6829 TransferDbgValues(SDValue(From, i), *To);
6831 // Iterate over just the existing users of From. See the comments in
6832 // the ReplaceAllUsesWith above.
6833 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6834 RAUWUpdateListener Listener(*this, UI, UE);
6838 // This node is about to morph, remove its old self from the CSE maps.
6839 RemoveNodeFromCSEMaps(User);
6841 // A user can appear in a use list multiple times, and when this
6842 // happens the uses are usually next to each other in the list.
6843 // To help reduce the number of CSE recomputations, process all
6844 // the uses of this user that we can find this way.
6846 SDUse &Use = UI.getUse();
6847 const SDValue &ToOp = To[Use.getResNo()];
6850 } while (UI != UE && *UI == User);
6852 // Now that we have modified User, add it back to the CSE maps. If it
6853 // already exists there, recursively merge the results together.
6854 AddModifiedNodeToCSEMaps(User);
6857 // If we just RAUW'd the root, take note.
6858 if (From == getRoot().getNode())
6859 setRoot(SDValue(To[getRoot().getResNo()]));
6862 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6863 /// uses of other values produced by From.getNode() alone. The Deleted
6864 /// vector is handled the same way as for ReplaceAllUsesWith.
6865 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6866 // Handle the really simple, really trivial case efficiently.
6867 if (From == To) return;
6869 // Handle the simple, trivial, case efficiently.
6870 if (From.getNode()->getNumValues() == 1) {
6871 ReplaceAllUsesWith(From, To);
6875 // Preserve Debug Info.
6876 TransferDbgValues(From, To);
6878 // Iterate over just the existing users of From. See the comments in
6879 // the ReplaceAllUsesWith above.
6880 SDNode::use_iterator UI = From.getNode()->use_begin(),
6881 UE = From.getNode()->use_end();
6882 RAUWUpdateListener Listener(*this, UI, UE);
6885 bool UserRemovedFromCSEMaps = false;
6887 // A user can appear in a use list multiple times, and when this
6888 // happens the uses are usually next to each other in the list.
6889 // To help reduce the number of CSE recomputations, process all
6890 // the uses of this user that we can find this way.
6892 SDUse &Use = UI.getUse();
6894 // Skip uses of different values from the same node.
6895 if (Use.getResNo() != From.getResNo()) {
6900 // If this node hasn't been modified yet, it's still in the CSE maps,
6901 // so remove its old self from the CSE maps.
6902 if (!UserRemovedFromCSEMaps) {
6903 RemoveNodeFromCSEMaps(User);
6904 UserRemovedFromCSEMaps = true;
6909 } while (UI != UE && *UI == User);
6911 // We are iterating over all uses of the From node, so if a use
6912 // doesn't use the specific value, no changes are made.
6913 if (!UserRemovedFromCSEMaps)
6916 // Now that we have modified User, add it back to the CSE maps. If it
6917 // already exists there, recursively merge the results together.
6918 AddModifiedNodeToCSEMaps(User);
6921 // If we just RAUW'd the root, take note.
6922 if (From == getRoot())
6927 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
6928 /// to record information about a use.
6935 /// operator< - Sort Memos by User.
6936 bool operator<(const UseMemo &L, const UseMemo &R) {
6937 return (intptr_t)L.User < (intptr_t)R.User;
6941 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
6942 /// uses of other values produced by From.getNode() alone. The same value
6943 /// may appear in both the From and To list. The Deleted vector is
6944 /// handled the same way as for ReplaceAllUsesWith.
6945 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
6948 // Handle the simple, trivial case efficiently.
6950 return ReplaceAllUsesOfValueWith(*From, *To);
6952 TransferDbgValues(*From, *To);
6954 // Read up all the uses and make records of them. This helps
6955 // processing new uses that are introduced during the
6956 // replacement process.
6957 SmallVector<UseMemo, 4> Uses;
6958 for (unsigned i = 0; i != Num; ++i) {
6959 unsigned FromResNo = From[i].getResNo();
6960 SDNode *FromNode = From[i].getNode();
6961 for (SDNode::use_iterator UI = FromNode->use_begin(),
6962 E = FromNode->use_end(); UI != E; ++UI) {
6963 SDUse &Use = UI.getUse();
6964 if (Use.getResNo() == FromResNo) {
6965 UseMemo Memo = { *UI, i, &Use };
6966 Uses.push_back(Memo);
6971 // Sort the uses, so that all the uses from a given User are together.
6972 std::sort(Uses.begin(), Uses.end());
6974 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
6975 UseIndex != UseIndexEnd; ) {
6976 // We know that this user uses some value of From. If it is the right
6977 // value, update it.
6978 SDNode *User = Uses[UseIndex].User;
6980 // This node is about to morph, remove its old self from the CSE maps.
6981 RemoveNodeFromCSEMaps(User);
6983 // The Uses array is sorted, so all the uses for a given User
6984 // are next to each other in the list.
6985 // To help reduce the number of CSE recomputations, process all
6986 // the uses of this user that we can find this way.
6988 unsigned i = Uses[UseIndex].Index;
6989 SDUse &Use = *Uses[UseIndex].Use;
6993 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
6995 // Now that we have modified User, add it back to the CSE maps. If it
6996 // already exists there, recursively merge the results together.
6997 AddModifiedNodeToCSEMaps(User);
7001 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
7002 /// based on their topological order. It returns the maximum id and a vector
7003 /// of the SDNodes* in assigned order by reference.
7004 unsigned SelectionDAG::AssignTopologicalOrder() {
7006 unsigned DAGSize = 0;
7008 // SortedPos tracks the progress of the algorithm. Nodes before it are
7009 // sorted, nodes after it are unsorted. When the algorithm completes
7010 // it is at the end of the list.
7011 allnodes_iterator SortedPos = allnodes_begin();
7013 // Visit all the nodes. Move nodes with no operands to the front of
7014 // the list immediately. Annotate nodes that do have operands with their
7015 // operand count. Before we do this, the Node Id fields of the nodes
7016 // may contain arbitrary values. After, the Node Id fields for nodes
7017 // before SortedPos will contain the topological sort index, and the
7018 // Node Id fields for nodes At SortedPos and after will contain the
7019 // count of outstanding operands.
7020 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7022 checkForCycles(N, this);
7023 unsigned Degree = N->getNumOperands();
7025 // A node with no uses, add it to the result array immediately.
7026 N->setNodeId(DAGSize++);
7027 allnodes_iterator Q(N);
7029 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7030 assert(SortedPos != AllNodes.end() && "Overran node list");
7033 // Temporarily use the Node Id as scratch space for the degree count.
7034 N->setNodeId(Degree);
7038 // Visit all the nodes. As we iterate, move nodes into sorted order,
7039 // such that by the time the end is reached all nodes will be sorted.
7040 for (SDNode &Node : allnodes()) {
7042 checkForCycles(N, this);
7043 // N is in sorted position, so all its uses have one less operand
7044 // that needs to be sorted.
7045 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7048 unsigned Degree = P->getNodeId();
7049 assert(Degree != 0 && "Invalid node degree");
7052 // All of P's operands are sorted, so P may sorted now.
7053 P->setNodeId(DAGSize++);
7054 if (P->getIterator() != SortedPos)
7055 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7056 assert(SortedPos != AllNodes.end() && "Overran node list");
7059 // Update P's outstanding operand count.
7060 P->setNodeId(Degree);
7063 if (Node.getIterator() == SortedPos) {
7065 allnodes_iterator I(N);
7067 dbgs() << "Overran sorted position:\n";
7068 S->dumprFull(this); dbgs() << "\n";
7069 dbgs() << "Checking if this is due to cycles\n";
7070 checkForCycles(this, true);
7072 llvm_unreachable(nullptr);
7076 assert(SortedPos == AllNodes.end() &&
7077 "Topological sort incomplete!");
7078 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7079 "First node in topological sort is not the entry token!");
7080 assert(AllNodes.front().getNodeId() == 0 &&
7081 "First node in topological sort has non-zero id!");
7082 assert(AllNodes.front().getNumOperands() == 0 &&
7083 "First node in topological sort has operands!");
7084 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7085 "Last node in topologic sort has unexpected id!");
7086 assert(AllNodes.back().use_empty() &&
7087 "Last node in topologic sort has users!");
7088 assert(DAGSize == allnodes_size() && "Node count mismatch!");
7092 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7093 /// value is produced by SD.
7094 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7096 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7097 SD->setHasDebugValue(true);
7099 DbgInfo->add(DB, SD, isParameter);
7102 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
7103 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
7104 if (From == To || !From.getNode()->getHasDebugValue())
7106 SDNode *FromNode = From.getNode();
7107 SDNode *ToNode = To.getNode();
7108 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
7109 SmallVector<SDDbgValue *, 2> ClonedDVs;
7110 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
7112 SDDbgValue *Dbg = *I;
7113 // Only add Dbgvalues attached to same ResNo.
7114 if (Dbg->getKind() == SDDbgValue::SDNODE &&
7115 Dbg->getSDNode() == From.getNode() &&
7116 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
7117 assert(FromNode != ToNode &&
7118 "Should not transfer Debug Values intranode");
7120 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
7121 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
7122 Dbg->getDebugLoc(), Dbg->getOrder());
7123 ClonedDVs.push_back(Clone);
7124 Dbg->setIsInvalidated();
7127 for (SDDbgValue *I : ClonedDVs)
7128 AddDbgValue(I, ToNode, false);
7131 //===----------------------------------------------------------------------===//
7133 //===----------------------------------------------------------------------===//
7135 bool llvm::isNullConstant(SDValue V) {
7136 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7137 return Const != nullptr && Const->isNullValue();
7140 bool llvm::isNullFPConstant(SDValue V) {
7141 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7142 return Const != nullptr && Const->isZero() && !Const->isNegative();
7145 bool llvm::isAllOnesConstant(SDValue V) {
7146 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7147 return Const != nullptr && Const->isAllOnesValue();
7150 bool llvm::isOneConstant(SDValue V) {
7151 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7152 return Const != nullptr && Const->isOne();
7155 bool llvm::isBitwiseNot(SDValue V) {
7156 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7159 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7160 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7163 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7164 BitVector UndefElements;
7165 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7167 // BuildVectors can truncate their operands. Ignore that case here.
7168 // FIXME: We blindly ignore splats which include undef which is overly
7170 if (CN && UndefElements.none() &&
7171 CN->getValueType(0) == N.getValueType().getScalarType())
7178 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7179 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7182 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7183 BitVector UndefElements;
7184 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7186 if (CN && UndefElements.none())
7193 HandleSDNode::~HandleSDNode() {
7197 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7199 const GlobalValue *GA, EVT VT,
7200 int64_t o, unsigned char TF)
7201 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7205 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7206 EVT VT, unsigned SrcAS,
7208 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7209 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7211 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7212 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7213 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7214 MemSDNodeBits.IsVolatile = MMO->isVolatile();
7215 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7216 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7217 MemSDNodeBits.IsInvariant = MMO->isInvariant();
7219 // We check here that the size of the memory operand fits within the size of
7220 // the MMO. This is because the MMO might indicate only a possible address
7221 // range instead of specifying the affected memory addresses precisely.
7222 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7225 /// Profile - Gather unique data for the node.
7227 void SDNode::Profile(FoldingSetNodeID &ID) const {
7228 AddNodeIDNode(ID, this);
7233 std::vector<EVT> VTs;
7236 VTs.reserve(MVT::LAST_VALUETYPE);
7237 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7238 VTs.push_back(MVT((MVT::SimpleValueType)i));
7243 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
7244 static ManagedStatic<EVTArray> SimpleVTArray;
7245 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
7247 /// getValueTypeList - Return a pointer to the specified value type.
7249 const EVT *SDNode::getValueTypeList(EVT VT) {
7250 if (VT.isExtended()) {
7251 sys::SmartScopedLock<true> Lock(*VTMutex);
7252 return &(*EVTs->insert(VT).first);
7254 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7255 "Value type out of range!");
7256 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7260 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7261 /// indicated value. This method ignores uses of other values defined by this
7263 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7264 assert(Value < getNumValues() && "Bad value!");
7266 // TODO: Only iterate over uses of a given value of the node
7267 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7268 if (UI.getUse().getResNo() == Value) {
7275 // Found exactly the right number of uses?
7280 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7281 /// value. This method ignores uses of other values defined by this operation.
7282 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7283 assert(Value < getNumValues() && "Bad value!");
7285 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7286 if (UI.getUse().getResNo() == Value)
7293 /// isOnlyUserOf - Return true if this node is the only use of N.
7295 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7297 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7308 /// Return true if the only users of N are contained in Nodes.
7309 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7311 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7313 if (llvm::any_of(Nodes,
7314 [&User](const SDNode *Node) { return User == Node; }))
7323 /// isOperand - Return true if this node is an operand of N.
7325 bool SDValue::isOperandOf(const SDNode *N) const {
7326 for (const SDValue &Op : N->op_values())
7332 bool SDNode::isOperandOf(const SDNode *N) const {
7333 for (const SDValue &Op : N->op_values())
7334 if (this == Op.getNode())
7339 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7340 /// be a chain) reaches the specified operand without crossing any
7341 /// side-effecting instructions on any chain path. In practice, this looks
7342 /// through token factors and non-volatile loads. In order to remain efficient,
7343 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7345 /// Note that we only need to examine chains when we're searching for
7346 /// side-effects; SelectionDAG requires that all side-effects are represented
7347 /// by chains, even if another operand would force a specific ordering. This
7348 /// constraint is necessary to allow transformations like splitting loads.
7349 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7350 unsigned Depth) const {
7351 if (*this == Dest) return true;
7353 // Don't search too deeply, we just want to be able to see through
7354 // TokenFactor's etc.
7355 if (Depth == 0) return false;
7357 // If this is a token factor, all inputs to the TF happen in parallel.
7358 if (getOpcode() == ISD::TokenFactor) {
7359 // First, try a shallow search.
7360 if (is_contained((*this)->ops(), Dest)) {
7361 // We found the chain we want as an operand of this TokenFactor.
7362 // Essentially, we reach the chain without side-effects if we could
7363 // serialize the TokenFactor into a simple chain of operations with
7364 // Dest as the last operation. This is automatically true if the
7365 // chain has one use: there are no other ordering constraints.
7366 // If the chain has more than one use, we give up: some other
7367 // use of Dest might force a side-effect between Dest and the current
7369 if (Dest.hasOneUse())
7372 // Next, try a deep search: check whether every operand of the TokenFactor
7374 return all_of((*this)->ops(), [=](SDValue Op) {
7375 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7379 // Loads don't have side effects, look through them.
7380 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7381 if (!Ld->isVolatile())
7382 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7387 bool SDNode::hasPredecessor(const SDNode *N) const {
7388 SmallPtrSet<const SDNode *, 32> Visited;
7389 SmallVector<const SDNode *, 16> Worklist;
7390 Worklist.push_back(this);
7391 return hasPredecessorHelper(N, Visited, Worklist);
7394 const SDNodeFlags *SDNode::getFlags() const {
7395 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
7396 return &FlagsNode->Flags;
7400 void SDNode::intersectFlagsWith(const SDNodeFlags *Flags) {
7401 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
7402 FlagsNode->Flags.intersectWith(Flags);
7405 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7406 assert(N->getNumValues() == 1 &&
7407 "Can't unroll a vector with multiple results!");
7409 EVT VT = N->getValueType(0);
7410 unsigned NE = VT.getVectorNumElements();
7411 EVT EltVT = VT.getVectorElementType();
7414 SmallVector<SDValue, 8> Scalars;
7415 SmallVector<SDValue, 4> Operands(N->getNumOperands());
7417 // If ResNE is 0, fully unroll the vector op.
7420 else if (NE > ResNE)
7424 for (i= 0; i != NE; ++i) {
7425 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7426 SDValue Operand = N->getOperand(j);
7427 EVT OperandVT = Operand.getValueType();
7428 if (OperandVT.isVector()) {
7429 // A vector operand; extract a single element.
7430 EVT OperandEltVT = OperandVT.getVectorElementType();
7432 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7433 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7435 // A scalar operand; just use it as is.
7436 Operands[j] = Operand;
7440 switch (N->getOpcode()) {
7442 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7447 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7454 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7455 getShiftAmountOperand(Operands[0].getValueType(),
7458 case ISD::SIGN_EXTEND_INREG:
7459 case ISD::FP_ROUND_INREG: {
7460 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7461 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7463 getValueType(ExtVT)));
7468 for (; i < ResNE; ++i)
7469 Scalars.push_back(getUNDEF(EltVT));
7471 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7472 return getBuildVector(VecVT, dl, Scalars);
7475 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7479 if (LD->isVolatile() || Base->isVolatile())
7481 if (LD->isIndexed() || Base->isIndexed())
7483 if (LD->getChain() != Base->getChain())
7485 EVT VT = LD->getValueType(0);
7486 if (VT.getSizeInBits() / 8 != Bytes)
7489 SDValue Loc = LD->getOperand(1);
7490 SDValue BaseLoc = Base->getOperand(1);
7491 if (Loc.getOpcode() == ISD::FrameIndex) {
7492 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7494 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7495 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7496 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7497 int FS = MFI.getObjectSize(FI);
7498 int BFS = MFI.getObjectSize(BFI);
7499 if (FS != BFS || FS != (int)Bytes) return false;
7500 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
7504 if (isBaseWithConstantOffset(Loc)) {
7505 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
7506 if (Loc.getOperand(0) == BaseLoc) {
7507 // If the base location is a simple address with no offset itself, then
7508 // the second load's first add operand should be the base address.
7509 if (LocOffset == Dist * (int)Bytes)
7511 } else if (isBaseWithConstantOffset(BaseLoc)) {
7512 // The base location itself has an offset, so subtract that value from the
7513 // second load's offset before comparing to distance * size.
7515 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
7516 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
7517 if ((LocOffset - BOffset) == Dist * (int)Bytes)
7522 const GlobalValue *GV1 = nullptr;
7523 const GlobalValue *GV2 = nullptr;
7524 int64_t Offset1 = 0;
7525 int64_t Offset2 = 0;
7526 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7527 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7528 if (isGA1 && isGA2 && GV1 == GV2)
7529 return Offset1 == (Offset2 + Dist*Bytes);
7534 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7535 /// it cannot be inferred.
7536 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7537 // If this is a GlobalAddress + cst, return the alignment.
7538 const GlobalValue *GV;
7539 int64_t GVOffset = 0;
7540 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7541 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7542 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
7543 llvm::computeKnownBits(const_cast<GlobalValue *>(GV), KnownZero, KnownOne,
7545 unsigned AlignBits = KnownZero.countTrailingOnes();
7546 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7548 return MinAlign(Align, GVOffset);
7551 // If this is a direct reference to a stack slot, use information about the
7552 // stack slot's alignment.
7553 int FrameIdx = 1 << 31;
7554 int64_t FrameOffset = 0;
7555 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7556 FrameIdx = FI->getIndex();
7557 } else if (isBaseWithConstantOffset(Ptr) &&
7558 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7560 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7561 FrameOffset = Ptr.getConstantOperandVal(1);
7564 if (FrameIdx != (1 << 31)) {
7565 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7566 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7574 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7575 /// which is split (or expanded) into two not necessarily identical pieces.
7576 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7577 // Currently all types are split in half.
7580 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7582 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
7584 return std::make_pair(LoVT, HiVT);
7587 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7589 std::pair<SDValue, SDValue>
7590 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7592 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7593 N.getValueType().getVectorNumElements() &&
7594 "More vector elements requested than available!");
7596 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7597 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7598 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7599 getConstant(LoVT.getVectorNumElements(), DL,
7600 TLI->getVectorIdxTy(getDataLayout())));
7601 return std::make_pair(Lo, Hi);
7604 void SelectionDAG::ExtractVectorElements(SDValue Op,
7605 SmallVectorImpl<SDValue> &Args,
7606 unsigned Start, unsigned Count) {
7607 EVT VT = Op.getValueType();
7609 Count = VT.getVectorNumElements();
7611 EVT EltVT = VT.getVectorElementType();
7612 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7614 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7615 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7616 Op, getConstant(i, SL, IdxTy)));
7620 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7621 unsigned GlobalAddressSDNode::getAddressSpace() const {
7622 return getGlobal()->getType()->getAddressSpace();
7626 Type *ConstantPoolSDNode::getType() const {
7627 if (isMachineConstantPoolEntry())
7628 return Val.MachineCPVal->getType();
7629 return Val.ConstVal->getType();
7632 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
7634 unsigned &SplatBitSize,
7636 unsigned MinSplatBits,
7637 bool isBigEndian) const {
7638 EVT VT = getValueType(0);
7639 assert(VT.isVector() && "Expected a vector type");
7640 unsigned sz = VT.getSizeInBits();
7641 if (MinSplatBits > sz)
7644 SplatValue = APInt(sz, 0);
7645 SplatUndef = APInt(sz, 0);
7647 // Get the bits. Bits with undefined values (when the corresponding element
7648 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7649 // in SplatValue. If any of the values are not constant, give up and return
7651 unsigned int nOps = getNumOperands();
7652 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
7653 unsigned EltBitSize = VT.getScalarSizeInBits();
7655 for (unsigned j = 0; j < nOps; ++j) {
7656 unsigned i = isBigEndian ? nOps-1-j : j;
7657 SDValue OpVal = getOperand(i);
7658 unsigned BitPos = j * EltBitSize;
7660 if (OpVal.isUndef())
7661 SplatUndef.setBits(BitPos, BitPos + EltBitSize);
7662 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
7663 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltBitSize),
7665 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7666 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
7671 // The build_vector is all constants or undefs. Find the smallest element
7672 // size that splats the vector.
7674 HasAnyUndefs = (SplatUndef != 0);
7677 unsigned HalfSize = sz / 2;
7678 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7679 APInt LowValue = SplatValue.trunc(HalfSize);
7680 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7681 APInt LowUndef = SplatUndef.trunc(HalfSize);
7683 // If the two halves do not match (ignoring undef bits), stop here.
7684 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7685 MinSplatBits > HalfSize)
7688 SplatValue = HighValue | LowValue;
7689 SplatUndef = HighUndef & LowUndef;
7698 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7699 if (UndefElements) {
7700 UndefElements->clear();
7701 UndefElements->resize(getNumOperands());
7704 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7705 SDValue Op = getOperand(i);
7708 (*UndefElements)[i] = true;
7709 } else if (!Splatted) {
7711 } else if (Splatted != Op) {
7717 assert(getOperand(0).isUndef() &&
7718 "Can only have a splat without a constant for all undefs.");
7719 return getOperand(0);
7726 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7727 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7731 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7732 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7736 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7737 uint32_t BitWidth) const {
7738 if (ConstantFPSDNode *CN =
7739 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7741 APSInt IntVal(BitWidth);
7742 const APFloat &APF = CN->getValueAPF();
7743 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7748 return IntVal.exactLogBase2();
7753 bool BuildVectorSDNode::isConstant() const {
7754 for (const SDValue &Op : op_values()) {
7755 unsigned Opc = Op.getOpcode();
7756 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7762 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7763 // Find the first non-undef value in the shuffle mask.
7765 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7768 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7770 // Make sure all remaining elements are either undef or the same as the first
7772 for (int Idx = Mask[i]; i != e; ++i)
7773 if (Mask[i] >= 0 && Mask[i] != Idx)
7778 // \brief Returns the SDNode if it is a constant integer BuildVector
7779 // or constant integer.
7780 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7781 if (isa<ConstantSDNode>(N))
7783 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7785 // Treat a GlobalAddress supporting constant offset folding as a
7786 // constant integer.
7787 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7788 if (GA->getOpcode() == ISD::GlobalAddress &&
7789 TLI->isOffsetFoldingLegal(GA))
7794 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
7795 if (isa<ConstantFPSDNode>(N))
7798 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
7805 static void checkForCyclesHelper(const SDNode *N,
7806 SmallPtrSetImpl<const SDNode*> &Visited,
7807 SmallPtrSetImpl<const SDNode*> &Checked,
7808 const llvm::SelectionDAG *DAG) {
7809 // If this node has already been checked, don't check it again.
7810 if (Checked.count(N))
7813 // If a node has already been visited on this depth-first walk, reject it as
7815 if (!Visited.insert(N).second) {
7816 errs() << "Detected cycle in SelectionDAG\n";
7817 dbgs() << "Offending node:\n";
7818 N->dumprFull(DAG); dbgs() << "\n";
7822 for (const SDValue &Op : N->op_values())
7823 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7830 void llvm::checkForCycles(const llvm::SDNode *N,
7831 const llvm::SelectionDAG *DAG,
7835 #ifdef EXPENSIVE_CHECKS
7837 #endif // EXPENSIVE_CHECKS
7839 assert(N && "Checking nonexistent SDNode");
7840 SmallPtrSet<const SDNode*, 32> visited;
7841 SmallPtrSet<const SDNode*, 32> checked;
7842 checkForCyclesHelper(N, visited, checked, DAG);
7847 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7848 checkForCycles(DAG->getRoot().getNode(), DAG, force);