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/KnownBits.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Mutex.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetIntrinsicInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 #include "llvm/Target/TargetSubtargetInfo.h"
57 /// makeVTList - Return an instance of the SDVTList struct initialized with the
58 /// specified members.
59 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
60 SDVTList Res = {VTs, NumVTs};
64 // Default null implementations of the callbacks.
65 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
66 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
68 //===----------------------------------------------------------------------===//
69 // ConstantFPSDNode Class
70 //===----------------------------------------------------------------------===//
72 /// isExactlyValue - We don't rely on operator== working on double values, as
73 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
74 /// As such, this method can be used to do an exact bit-for-bit comparison of
75 /// two floating point values.
76 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
77 return getValueAPF().bitwiseIsEqual(V);
80 bool ConstantFPSDNode::isValueValidForType(EVT VT,
82 assert(VT.isFloatingPoint() && "Can only convert between FP types");
84 // convert modifies in place, so make a copy.
85 APFloat Val2 = APFloat(Val);
87 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
88 APFloat::rmNearestTiesToEven,
93 //===----------------------------------------------------------------------===//
95 //===----------------------------------------------------------------------===//
97 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
98 auto *BV = dyn_cast<BuildVectorSDNode>(N);
103 unsigned SplatBitSize;
105 EVT EltVT = N->getValueType(0).getVectorElementType();
106 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs) &&
107 EltVT.getSizeInBits() >= SplatBitSize;
110 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
111 // specializations of the more general isConstantSplatVector()?
113 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
114 // Look through a bit convert.
115 while (N->getOpcode() == ISD::BITCAST)
116 N = N->getOperand(0).getNode();
118 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
120 unsigned i = 0, e = N->getNumOperands();
122 // Skip over all of the undef values.
123 while (i != e && N->getOperand(i).isUndef())
126 // Do not accept an all-undef vector.
127 if (i == e) return false;
129 // Do not accept build_vectors that aren't all constants or which have non-~0
130 // elements. We have to be a bit careful here, as the type of the constant
131 // may not be the same as the type of the vector elements due to type
132 // legalization (the elements are promoted to a legal type for the target and
133 // a vector of a type may be legal when the base element type is not).
134 // We only want to check enough bits to cover the vector elements, because
135 // we care if the resultant vector is all ones, not whether the individual
137 SDValue NotZero = N->getOperand(i);
138 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
139 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
140 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
142 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
143 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
148 // Okay, we have at least one ~0 value, check to see if the rest match or are
149 // undefs. Even with the above element type twiddling, this should be OK, as
150 // the same type legalization should have applied to all the elements.
151 for (++i; i != e; ++i)
152 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
157 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
158 // Look through a bit convert.
159 while (N->getOpcode() == ISD::BITCAST)
160 N = N->getOperand(0).getNode();
162 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
164 bool IsAllUndef = true;
165 for (const SDValue &Op : N->op_values()) {
169 // Do not accept build_vectors that aren't all constants or which have non-0
170 // elements. We have to be a bit careful here, as the type of the constant
171 // may not be the same as the type of the vector elements due to type
172 // legalization (the elements are promoted to a legal type for the target
173 // and a vector of a type may be legal when the base element type is not).
174 // We only want to check enough bits to cover the vector elements, because
175 // we care if the resultant vector is all zeros, not whether the individual
177 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
178 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
179 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
181 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
182 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
188 // Do not accept an all-undef vector.
194 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
195 if (N->getOpcode() != ISD::BUILD_VECTOR)
198 for (const SDValue &Op : N->op_values()) {
201 if (!isa<ConstantSDNode>(Op))
207 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
208 if (N->getOpcode() != ISD::BUILD_VECTOR)
211 for (const SDValue &Op : N->op_values()) {
214 if (!isa<ConstantFPSDNode>(Op))
220 bool ISD::allOperandsUndef(const SDNode *N) {
221 // Return false if the node has no operands.
222 // This is "logically inconsistent" with the definition of "all" but
223 // is probably the desired behavior.
224 if (N->getNumOperands() == 0)
227 for (const SDValue &Op : N->op_values())
234 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
237 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
239 return ISD::SIGN_EXTEND;
241 return ISD::ZERO_EXTEND;
246 llvm_unreachable("Invalid LoadExtType");
249 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
250 // To perform this operation, we just need to swap the L and G bits of the
252 unsigned OldL = (Operation >> 2) & 1;
253 unsigned OldG = (Operation >> 1) & 1;
254 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
255 (OldL << 1) | // New G bit
256 (OldG << 2)); // New L bit.
259 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
260 unsigned Operation = Op;
262 Operation ^= 7; // Flip L, G, E bits, but not U.
264 Operation ^= 15; // Flip all of the condition bits.
266 if (Operation > ISD::SETTRUE2)
267 Operation &= ~8; // Don't let N and U bits get set.
269 return ISD::CondCode(Operation);
273 /// For an integer comparison, return 1 if the comparison is a signed operation
274 /// and 2 if the result is an unsigned comparison. Return zero if the operation
275 /// does not depend on the sign of the input (setne and seteq).
276 static int isSignedOp(ISD::CondCode Opcode) {
278 default: llvm_unreachable("Illegal integer setcc operation!");
280 case ISD::SETNE: return 0;
284 case ISD::SETGE: return 1;
288 case ISD::SETUGE: return 2;
292 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
294 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
295 // Cannot fold a signed integer setcc with an unsigned integer setcc.
296 return ISD::SETCC_INVALID;
298 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
300 // If the N and U bits get set, then the resultant comparison DOES suddenly
301 // care about orderedness, and it is true when ordered.
302 if (Op > ISD::SETTRUE2)
303 Op &= ~16; // Clear the U bit if the N bit is set.
305 // Canonicalize illegal integer setcc's.
306 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
309 return ISD::CondCode(Op);
312 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
314 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
315 // Cannot fold a signed setcc with an unsigned setcc.
316 return ISD::SETCC_INVALID;
318 // Combine all of the condition bits.
319 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
321 // Canonicalize illegal integer setcc's.
325 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
326 case ISD::SETOEQ: // SETEQ & SETU[LG]E
327 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
328 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
329 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
336 //===----------------------------------------------------------------------===//
337 // SDNode Profile Support
338 //===----------------------------------------------------------------------===//
340 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
342 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
346 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
347 /// solely with their pointer.
348 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
349 ID.AddPointer(VTList.VTs);
352 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
354 static void AddNodeIDOperands(FoldingSetNodeID &ID,
355 ArrayRef<SDValue> Ops) {
356 for (auto& Op : Ops) {
357 ID.AddPointer(Op.getNode());
358 ID.AddInteger(Op.getResNo());
362 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
364 static void AddNodeIDOperands(FoldingSetNodeID &ID,
365 ArrayRef<SDUse> Ops) {
366 for (auto& Op : Ops) {
367 ID.AddPointer(Op.getNode());
368 ID.AddInteger(Op.getResNo());
372 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
373 SDVTList VTList, ArrayRef<SDValue> OpList) {
374 AddNodeIDOpcode(ID, OpC);
375 AddNodeIDValueTypes(ID, VTList);
376 AddNodeIDOperands(ID, OpList);
379 /// If this is an SDNode with special info, add this info to the NodeID data.
380 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
381 switch (N->getOpcode()) {
382 case ISD::TargetExternalSymbol:
383 case ISD::ExternalSymbol:
385 llvm_unreachable("Should only be used on nodes with operands");
386 default: break; // Normal nodes don't need extra info.
387 case ISD::TargetConstant:
388 case ISD::Constant: {
389 const ConstantSDNode *C = cast<ConstantSDNode>(N);
390 ID.AddPointer(C->getConstantIntValue());
391 ID.AddBoolean(C->isOpaque());
394 case ISD::TargetConstantFP:
395 case ISD::ConstantFP: {
396 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
399 case ISD::TargetGlobalAddress:
400 case ISD::GlobalAddress:
401 case ISD::TargetGlobalTLSAddress:
402 case ISD::GlobalTLSAddress: {
403 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
404 ID.AddPointer(GA->getGlobal());
405 ID.AddInteger(GA->getOffset());
406 ID.AddInteger(GA->getTargetFlags());
409 case ISD::BasicBlock:
410 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
413 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
415 case ISD::RegisterMask:
416 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
419 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
421 case ISD::FrameIndex:
422 case ISD::TargetFrameIndex:
423 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
426 case ISD::TargetJumpTable:
427 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
428 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
430 case ISD::ConstantPool:
431 case ISD::TargetConstantPool: {
432 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
433 ID.AddInteger(CP->getAlignment());
434 ID.AddInteger(CP->getOffset());
435 if (CP->isMachineConstantPoolEntry())
436 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
438 ID.AddPointer(CP->getConstVal());
439 ID.AddInteger(CP->getTargetFlags());
442 case ISD::TargetIndex: {
443 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
444 ID.AddInteger(TI->getIndex());
445 ID.AddInteger(TI->getOffset());
446 ID.AddInteger(TI->getTargetFlags());
450 const LoadSDNode *LD = cast<LoadSDNode>(N);
451 ID.AddInteger(LD->getMemoryVT().getRawBits());
452 ID.AddInteger(LD->getRawSubclassData());
453 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
457 const StoreSDNode *ST = cast<StoreSDNode>(N);
458 ID.AddInteger(ST->getMemoryVT().getRawBits());
459 ID.AddInteger(ST->getRawSubclassData());
460 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
463 case ISD::ATOMIC_CMP_SWAP:
464 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
465 case ISD::ATOMIC_SWAP:
466 case ISD::ATOMIC_LOAD_ADD:
467 case ISD::ATOMIC_LOAD_SUB:
468 case ISD::ATOMIC_LOAD_AND:
469 case ISD::ATOMIC_LOAD_OR:
470 case ISD::ATOMIC_LOAD_XOR:
471 case ISD::ATOMIC_LOAD_NAND:
472 case ISD::ATOMIC_LOAD_MIN:
473 case ISD::ATOMIC_LOAD_MAX:
474 case ISD::ATOMIC_LOAD_UMIN:
475 case ISD::ATOMIC_LOAD_UMAX:
476 case ISD::ATOMIC_LOAD:
477 case ISD::ATOMIC_STORE: {
478 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
479 ID.AddInteger(AT->getMemoryVT().getRawBits());
480 ID.AddInteger(AT->getRawSubclassData());
481 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
484 case ISD::PREFETCH: {
485 const MemSDNode *PF = cast<MemSDNode>(N);
486 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
489 case ISD::VECTOR_SHUFFLE: {
490 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
491 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
493 ID.AddInteger(SVN->getMaskElt(i));
496 case ISD::TargetBlockAddress:
497 case ISD::BlockAddress: {
498 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
499 ID.AddPointer(BA->getBlockAddress());
500 ID.AddInteger(BA->getOffset());
501 ID.AddInteger(BA->getTargetFlags());
504 } // end switch (N->getOpcode())
506 // Target specific memory nodes could also have address spaces to check.
507 if (N->isTargetMemoryOpcode())
508 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
511 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
513 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
514 AddNodeIDOpcode(ID, N->getOpcode());
515 // Add the return value info.
516 AddNodeIDValueTypes(ID, N->getVTList());
517 // Add the operand info.
518 AddNodeIDOperands(ID, N->ops());
520 // Handle SDNode leafs with special info.
521 AddNodeIDCustom(ID, N);
524 //===----------------------------------------------------------------------===//
525 // SelectionDAG Class
526 //===----------------------------------------------------------------------===//
528 /// doNotCSE - Return true if CSE should not be performed for this node.
529 static bool doNotCSE(SDNode *N) {
530 if (N->getValueType(0) == MVT::Glue)
531 return true; // Never CSE anything that produces a flag.
533 switch (N->getOpcode()) {
535 case ISD::HANDLENODE:
537 return true; // Never CSE these nodes.
540 // Check that remaining values produced are not flags.
541 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
542 if (N->getValueType(i) == MVT::Glue)
543 return true; // Never CSE anything that produces a flag.
548 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
550 void SelectionDAG::RemoveDeadNodes() {
551 // Create a dummy node (which is not added to allnodes), that adds a reference
552 // to the root node, preventing it from being deleted.
553 HandleSDNode Dummy(getRoot());
555 SmallVector<SDNode*, 128> DeadNodes;
557 // Add all obviously-dead nodes to the DeadNodes worklist.
558 for (SDNode &Node : allnodes())
559 if (Node.use_empty())
560 DeadNodes.push_back(&Node);
562 RemoveDeadNodes(DeadNodes);
564 // If the root changed (e.g. it was a dead load, update the root).
565 setRoot(Dummy.getValue());
568 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
569 /// given list, and any nodes that become unreachable as a result.
570 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
572 // Process the worklist, deleting the nodes and adding their uses to the
574 while (!DeadNodes.empty()) {
575 SDNode *N = DeadNodes.pop_back_val();
577 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
578 DUL->NodeDeleted(N, nullptr);
580 // Take the node out of the appropriate CSE map.
581 RemoveNodeFromCSEMaps(N);
583 // Next, brutally remove the operand list. This is safe to do, as there are
584 // no cycles in the graph.
585 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
587 SDNode *Operand = Use.getNode();
590 // Now that we removed this operand, see if there are no uses of it left.
591 if (Operand->use_empty())
592 DeadNodes.push_back(Operand);
599 void SelectionDAG::RemoveDeadNode(SDNode *N){
600 SmallVector<SDNode*, 16> DeadNodes(1, N);
602 // Create a dummy node that adds a reference to the root node, preventing
603 // it from being deleted. (This matters if the root is an operand of the
605 HandleSDNode Dummy(getRoot());
607 RemoveDeadNodes(DeadNodes);
610 void SelectionDAG::DeleteNode(SDNode *N) {
611 // First take this out of the appropriate CSE map.
612 RemoveNodeFromCSEMaps(N);
614 // Finally, remove uses due to operands of this node, remove from the
615 // AllNodes list, and delete the node.
616 DeleteNodeNotInCSEMaps(N);
619 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
620 assert(N->getIterator() != AllNodes.begin() &&
621 "Cannot delete the entry node!");
622 assert(N->use_empty() && "Cannot delete a node that is not dead!");
624 // Drop all of the operands and decrement used node's use counts.
630 void SDDbgInfo::erase(const SDNode *Node) {
631 DbgValMapType::iterator I = DbgValMap.find(Node);
632 if (I == DbgValMap.end())
634 for (auto &Val: I->second)
635 Val->setIsInvalidated();
639 void SelectionDAG::DeallocateNode(SDNode *N) {
640 // If we have operands, deallocate them.
643 NodeAllocator.Deallocate(AllNodes.remove(N));
645 // Set the opcode to DELETED_NODE to help catch bugs when node
646 // memory is reallocated.
647 // FIXME: There are places in SDag that have grown a dependency on the opcode
648 // value in the released node.
649 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
650 N->NodeType = ISD::DELETED_NODE;
652 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
653 // them and forget about that node.
658 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
659 static void VerifySDNode(SDNode *N) {
660 switch (N->getOpcode()) {
663 case ISD::BUILD_PAIR: {
664 EVT VT = N->getValueType(0);
665 assert(N->getNumValues() == 1 && "Too many results!");
666 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
667 "Wrong return type!");
668 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
669 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
670 "Mismatched operand types!");
671 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
672 "Wrong operand type!");
673 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
674 "Wrong return type size");
677 case ISD::BUILD_VECTOR: {
678 assert(N->getNumValues() == 1 && "Too many results!");
679 assert(N->getValueType(0).isVector() && "Wrong return type!");
680 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
681 "Wrong number of operands!");
682 EVT EltVT = N->getValueType(0).getVectorElementType();
683 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
684 assert((I->getValueType() == EltVT ||
685 (EltVT.isInteger() && I->getValueType().isInteger() &&
686 EltVT.bitsLE(I->getValueType()))) &&
687 "Wrong operand type!");
688 assert(I->getValueType() == N->getOperand(0).getValueType() &&
689 "Operands must all have the same type");
697 /// \brief Insert a newly allocated node into the DAG.
699 /// Handles insertion into the all nodes list and CSE map, as well as
700 /// verification and other common operations when a new node is allocated.
701 void SelectionDAG::InsertNode(SDNode *N) {
702 AllNodes.push_back(N);
704 N->PersistentId = NextPersistentId++;
709 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
710 /// correspond to it. This is useful when we're about to delete or repurpose
711 /// the node. We don't want future request for structurally identical nodes
712 /// to return N anymore.
713 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
715 switch (N->getOpcode()) {
716 case ISD::HANDLENODE: return false; // noop.
718 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
719 "Cond code doesn't exist!");
720 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
721 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
723 case ISD::ExternalSymbol:
724 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
726 case ISD::TargetExternalSymbol: {
727 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
728 Erased = TargetExternalSymbols.erase(
729 std::pair<std::string,unsigned char>(ESN->getSymbol(),
730 ESN->getTargetFlags()));
733 case ISD::MCSymbol: {
734 auto *MCSN = cast<MCSymbolSDNode>(N);
735 Erased = MCSymbols.erase(MCSN->getMCSymbol());
738 case ISD::VALUETYPE: {
739 EVT VT = cast<VTSDNode>(N)->getVT();
740 if (VT.isExtended()) {
741 Erased = ExtendedValueTypeNodes.erase(VT);
743 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
744 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
749 // Remove it from the CSE Map.
750 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
751 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
752 Erased = CSEMap.RemoveNode(N);
756 // Verify that the node was actually in one of the CSE maps, unless it has a
757 // flag result (which cannot be CSE'd) or is one of the special cases that are
758 // not subject to CSE.
759 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
760 !N->isMachineOpcode() && !doNotCSE(N)) {
763 llvm_unreachable("Node is not in map!");
769 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
770 /// maps and modified in place. Add it back to the CSE maps, unless an identical
771 /// node already exists, in which case transfer all its users to the existing
772 /// node. This transfer can potentially trigger recursive merging.
775 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
776 // For node types that aren't CSE'd, just act as if no identical node
779 SDNode *Existing = CSEMap.GetOrInsertNode(N);
781 // If there was already an existing matching node, use ReplaceAllUsesWith
782 // to replace the dead one with the existing one. This can cause
783 // recursive merging of other unrelated nodes down the line.
784 ReplaceAllUsesWith(N, Existing);
786 // N is now dead. Inform the listeners and delete it.
787 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
788 DUL->NodeDeleted(N, Existing);
789 DeleteNodeNotInCSEMaps(N);
794 // If the node doesn't already exist, we updated it. Inform listeners.
795 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
799 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
800 /// were replaced with those specified. If this node is never memoized,
801 /// return null, otherwise return a pointer to the slot it would take. If a
802 /// node already exists with these operands, the slot will be non-null.
803 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
808 SDValue Ops[] = { Op };
810 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
811 AddNodeIDCustom(ID, N);
812 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
814 if (const SDNodeFlags *Flags = N->getFlags())
815 Node->intersectFlagsWith(Flags);
819 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
820 /// were replaced with those specified. If this node is never memoized,
821 /// return null, otherwise return a pointer to the slot it would take. If a
822 /// node already exists with these operands, the slot will be non-null.
823 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
824 SDValue Op1, SDValue Op2,
829 SDValue Ops[] = { Op1, Op2 };
831 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
832 AddNodeIDCustom(ID, N);
833 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
835 if (const SDNodeFlags *Flags = N->getFlags())
836 Node->intersectFlagsWith(Flags);
841 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
842 /// were replaced with those specified. If this node is never memoized,
843 /// return null, otherwise return a pointer to the slot it would take. If a
844 /// node already exists with these operands, the slot will be non-null.
845 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
851 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
852 AddNodeIDCustom(ID, N);
853 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
855 if (const SDNodeFlags *Flags = N->getFlags())
856 Node->intersectFlagsWith(Flags);
860 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
861 Type *Ty = VT == MVT::iPTR ?
862 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
863 VT.getTypeForEVT(*getContext());
865 return getDataLayout().getABITypeAlignment(Ty);
868 // EntryNode could meaningfully have debug info if we can find it...
869 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
870 : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL),
871 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
872 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false),
873 UpdateListeners(nullptr) {
874 InsertNode(&EntryNode);
875 DbgInfo = new SDDbgInfo();
878 void SelectionDAG::init(MachineFunction &NewMF,
879 OptimizationRemarkEmitter &NewORE) {
882 TLI = getSubtarget().getTargetLowering();
883 TSI = getSubtarget().getSelectionDAGInfo();
884 Context = &MF->getFunction()->getContext();
887 SelectionDAG::~SelectionDAG() {
888 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
890 OperandRecycler.clear(OperandAllocator);
894 void SelectionDAG::allnodes_clear() {
895 assert(&*AllNodes.begin() == &EntryNode);
896 AllNodes.remove(AllNodes.begin());
897 while (!AllNodes.empty())
898 DeallocateNode(&AllNodes.front());
900 NextPersistentId = 0;
904 SDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, const SDLoc &DL,
905 SDVTList VTs, SDValue N1, SDValue N2,
906 const SDNodeFlags *Flags) {
907 SDValue Ops[] = {N1, N2};
909 if (isBinOpWithFlags(Opcode)) {
910 // If no flags were passed in, use a default flags object.
912 if (Flags == nullptr)
915 auto *FN = newSDNode<BinaryWithFlagsSDNode>(Opcode, DL.getIROrder(),
916 DL.getDebugLoc(), VTs, *Flags);
917 createOperands(FN, Ops);
922 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
923 createOperands(N, Ops);
927 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
929 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
931 switch (N->getOpcode()) {
934 case ISD::ConstantFP:
935 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
936 "debug location. Use another overload.");
942 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
943 const SDLoc &DL, void *&InsertPos) {
944 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
946 switch (N->getOpcode()) {
948 case ISD::ConstantFP:
949 // Erase debug location from the node if the node is used at several
950 // different places. Do not propagate one location to all uses as it
951 // will cause a worse single stepping debugging experience.
952 if (N->getDebugLoc() != DL.getDebugLoc())
953 N->setDebugLoc(DebugLoc());
956 // When the node's point of use is located earlier in the instruction
957 // sequence than its prior point of use, update its debug info to the
959 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
960 N->setDebugLoc(DL.getDebugLoc());
967 void SelectionDAG::clear() {
969 OperandRecycler.clear(OperandAllocator);
970 OperandAllocator.Reset();
973 ExtendedValueTypeNodes.clear();
974 ExternalSymbols.clear();
975 TargetExternalSymbols.clear();
977 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
978 static_cast<CondCodeSDNode*>(nullptr));
979 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
980 static_cast<SDNode*>(nullptr));
982 EntryNode.UseList = nullptr;
983 InsertNode(&EntryNode);
984 Root = getEntryNode();
988 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
989 return VT.bitsGT(Op.getValueType()) ?
990 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
991 getNode(ISD::TRUNCATE, DL, VT, Op);
994 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
995 return VT.bitsGT(Op.getValueType()) ?
996 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
997 getNode(ISD::TRUNCATE, DL, VT, Op);
1000 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1001 return VT.bitsGT(Op.getValueType()) ?
1002 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1003 getNode(ISD::TRUNCATE, DL, VT, Op);
1006 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1008 if (VT.bitsLE(Op.getValueType()))
1009 return getNode(ISD::TRUNCATE, SL, VT, Op);
1011 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1012 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1015 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1016 assert(!VT.isVector() &&
1017 "getZeroExtendInReg should use the vector element type instead of "
1018 "the vector type!");
1019 if (Op.getValueType() == VT) return Op;
1020 unsigned BitWidth = Op.getScalarValueSizeInBits();
1021 APInt Imm = APInt::getLowBitsSet(BitWidth,
1022 VT.getSizeInBits());
1023 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1024 getConstant(Imm, DL, Op.getValueType()));
1027 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1029 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1030 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1031 "The sizes of the input and result must match in order to perform the "
1032 "extend in-register.");
1033 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1034 "The destination vector type must have fewer lanes than the input.");
1035 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1038 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1040 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1041 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1042 "The sizes of the input and result must match in order to perform the "
1043 "extend in-register.");
1044 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1045 "The destination vector type must have fewer lanes than the input.");
1046 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1049 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1051 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1052 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1053 "The sizes of the input and result must match in order to perform the "
1054 "extend in-register.");
1055 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1056 "The destination vector type must have fewer lanes than the input.");
1057 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1060 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1062 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1063 EVT EltVT = VT.getScalarType();
1065 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1066 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1069 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1070 EVT EltVT = VT.getScalarType();
1072 switch (TLI->getBooleanContents(VT)) {
1073 case TargetLowering::ZeroOrOneBooleanContent:
1074 case TargetLowering::UndefinedBooleanContent:
1075 TrueValue = getConstant(1, DL, VT);
1077 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1078 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1082 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1085 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1086 bool isT, bool isO) {
1087 EVT EltVT = VT.getScalarType();
1088 assert((EltVT.getSizeInBits() >= 64 ||
1089 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1090 "getConstant with a uint64_t value that doesn't fit in the type!");
1091 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1094 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1095 bool isT, bool isO) {
1096 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1099 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1100 EVT VT, bool isT, bool isO) {
1101 assert(VT.isInteger() && "Cannot create FP integer constant!");
1103 EVT EltVT = VT.getScalarType();
1104 const ConstantInt *Elt = &Val;
1106 // In some cases the vector type is legal but the element type is illegal and
1107 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1108 // inserted value (the type does not need to match the vector element type).
1109 // Any extra bits introduced will be truncated away.
1110 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1111 TargetLowering::TypePromoteInteger) {
1112 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1113 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1114 Elt = ConstantInt::get(*getContext(), NewVal);
1116 // In other cases the element type is illegal and needs to be expanded, for
1117 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1118 // the value into n parts and use a vector type with n-times the elements.
1119 // Then bitcast to the type requested.
1120 // Legalizing constants too early makes the DAGCombiner's job harder so we
1121 // only legalize if the DAG tells us we must produce legal types.
1122 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1123 TLI->getTypeAction(*getContext(), EltVT) ==
1124 TargetLowering::TypeExpandInteger) {
1125 const APInt &NewVal = Elt->getValue();
1126 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1127 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1128 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1129 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1131 // Check the temporary vector is the correct size. If this fails then
1132 // getTypeToTransformTo() probably returned a type whose size (in bits)
1133 // isn't a power-of-2 factor of the requested type size.
1134 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1136 SmallVector<SDValue, 2> EltParts;
1137 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1138 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1139 .zextOrTrunc(ViaEltSizeInBits), DL,
1140 ViaEltVT, isT, isO));
1143 // EltParts is currently in little endian order. If we actually want
1144 // big-endian order then reverse it now.
1145 if (getDataLayout().isBigEndian())
1146 std::reverse(EltParts.begin(), EltParts.end());
1148 // The elements must be reversed when the element order is different
1149 // to the endianness of the elements (because the BITCAST is itself a
1150 // vector shuffle in this situation). However, we do not need any code to
1151 // perform this reversal because getConstant() is producing a vector
1153 // This situation occurs in MIPS MSA.
1155 SmallVector<SDValue, 8> Ops;
1156 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1157 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1158 return getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1161 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1162 "APInt size does not match type size!");
1163 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1164 FoldingSetNodeID ID;
1165 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1169 SDNode *N = nullptr;
1170 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1172 return SDValue(N, 0);
1175 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1176 CSEMap.InsertNode(N, IP);
1180 SDValue Result(N, 0);
1182 Result = getSplatBuildVector(VT, DL, Result);
1186 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1188 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1191 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1193 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1196 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1197 EVT VT, bool isTarget) {
1198 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1200 EVT EltVT = VT.getScalarType();
1202 // Do the map lookup using the actual bit pattern for the floating point
1203 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1204 // we don't have issues with SNANs.
1205 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1206 FoldingSetNodeID ID;
1207 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1210 SDNode *N = nullptr;
1211 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1213 return SDValue(N, 0);
1216 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1217 CSEMap.InsertNode(N, IP);
1221 SDValue Result(N, 0);
1223 Result = getSplatBuildVector(VT, DL, Result);
1227 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1229 EVT EltVT = VT.getScalarType();
1230 if (EltVT == MVT::f32)
1231 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1232 else if (EltVT == MVT::f64)
1233 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1234 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1235 EltVT == MVT::f16) {
1237 APFloat APF = APFloat(Val);
1238 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1240 return getConstantFP(APF, DL, VT, isTarget);
1242 llvm_unreachable("Unsupported type in getConstantFP");
1245 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1246 EVT VT, int64_t Offset, bool isTargetGA,
1247 unsigned char TargetFlags) {
1248 assert((TargetFlags == 0 || isTargetGA) &&
1249 "Cannot set target flags on target-independent globals");
1251 // Truncate (with sign-extension) the offset value to the pointer size.
1252 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1254 Offset = SignExtend64(Offset, BitWidth);
1257 if (GV->isThreadLocal())
1258 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1260 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1262 FoldingSetNodeID ID;
1263 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1265 ID.AddInteger(Offset);
1266 ID.AddInteger(TargetFlags);
1268 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1269 return SDValue(E, 0);
1271 auto *N = newSDNode<GlobalAddressSDNode>(
1272 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1273 CSEMap.InsertNode(N, IP);
1275 return SDValue(N, 0);
1278 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1279 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1280 FoldingSetNodeID ID;
1281 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1284 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1285 return SDValue(E, 0);
1287 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1288 CSEMap.InsertNode(N, IP);
1290 return SDValue(N, 0);
1293 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1294 unsigned char TargetFlags) {
1295 assert((TargetFlags == 0 || isTarget) &&
1296 "Cannot set target flags on target-independent jump tables");
1297 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1298 FoldingSetNodeID ID;
1299 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1301 ID.AddInteger(TargetFlags);
1303 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1304 return SDValue(E, 0);
1306 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1307 CSEMap.InsertNode(N, IP);
1309 return SDValue(N, 0);
1312 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1313 unsigned Alignment, int Offset,
1315 unsigned char TargetFlags) {
1316 assert((TargetFlags == 0 || isTarget) &&
1317 "Cannot set target flags on target-independent globals");
1319 Alignment = MF->getFunction()->optForSize()
1320 ? getDataLayout().getABITypeAlignment(C->getType())
1321 : getDataLayout().getPrefTypeAlignment(C->getType());
1322 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1323 FoldingSetNodeID ID;
1324 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1325 ID.AddInteger(Alignment);
1326 ID.AddInteger(Offset);
1328 ID.AddInteger(TargetFlags);
1330 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1331 return SDValue(E, 0);
1333 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1335 CSEMap.InsertNode(N, IP);
1337 return SDValue(N, 0);
1341 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1342 unsigned Alignment, int Offset,
1344 unsigned char TargetFlags) {
1345 assert((TargetFlags == 0 || isTarget) &&
1346 "Cannot set target flags on target-independent globals");
1348 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1349 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1350 FoldingSetNodeID ID;
1351 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1352 ID.AddInteger(Alignment);
1353 ID.AddInteger(Offset);
1354 C->addSelectionDAGCSEId(ID);
1355 ID.AddInteger(TargetFlags);
1357 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1358 return SDValue(E, 0);
1360 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1362 CSEMap.InsertNode(N, IP);
1364 return SDValue(N, 0);
1367 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1368 unsigned char TargetFlags) {
1369 FoldingSetNodeID ID;
1370 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1371 ID.AddInteger(Index);
1372 ID.AddInteger(Offset);
1373 ID.AddInteger(TargetFlags);
1375 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1376 return SDValue(E, 0);
1378 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1379 CSEMap.InsertNode(N, IP);
1381 return SDValue(N, 0);
1384 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1385 FoldingSetNodeID ID;
1386 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1389 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1390 return SDValue(E, 0);
1392 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1393 CSEMap.InsertNode(N, IP);
1395 return SDValue(N, 0);
1398 SDValue SelectionDAG::getValueType(EVT VT) {
1399 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1400 ValueTypeNodes.size())
1401 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1403 SDNode *&N = VT.isExtended() ?
1404 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1406 if (N) return SDValue(N, 0);
1407 N = newSDNode<VTSDNode>(VT);
1409 return SDValue(N, 0);
1412 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1413 SDNode *&N = ExternalSymbols[Sym];
1414 if (N) return SDValue(N, 0);
1415 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1417 return SDValue(N, 0);
1420 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1421 SDNode *&N = MCSymbols[Sym];
1423 return SDValue(N, 0);
1424 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1426 return SDValue(N, 0);
1429 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1430 unsigned char TargetFlags) {
1432 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1434 if (N) return SDValue(N, 0);
1435 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1437 return SDValue(N, 0);
1440 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1441 if ((unsigned)Cond >= CondCodeNodes.size())
1442 CondCodeNodes.resize(Cond+1);
1444 if (!CondCodeNodes[Cond]) {
1445 auto *N = newSDNode<CondCodeSDNode>(Cond);
1446 CondCodeNodes[Cond] = N;
1450 return SDValue(CondCodeNodes[Cond], 0);
1453 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1454 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1455 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1457 ShuffleVectorSDNode::commuteMask(M);
1460 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1461 SDValue N2, ArrayRef<int> Mask) {
1462 assert(VT.getVectorNumElements() == Mask.size() &&
1463 "Must have the same number of vector elements as mask elements!");
1464 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1465 "Invalid VECTOR_SHUFFLE");
1467 // Canonicalize shuffle undef, undef -> undef
1468 if (N1.isUndef() && N2.isUndef())
1469 return getUNDEF(VT);
1471 // Validate that all indices in Mask are within the range of the elements
1472 // input to the shuffle.
1473 int NElts = Mask.size();
1474 assert(all_of(Mask, [&](int M) { return M < (NElts * 2); }) &&
1475 "Index out of range");
1477 // Copy the mask so we can do any needed cleanup.
1478 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1480 // Canonicalize shuffle v, v -> v, undef
1483 for (int i = 0; i != NElts; ++i)
1484 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1487 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1489 commuteShuffle(N1, N2, MaskVec);
1491 // If shuffling a splat, try to blend the splat instead. We do this here so
1492 // that even when this arises during lowering we don't have to re-handle it.
1493 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1494 BitVector UndefElements;
1495 SDValue Splat = BV->getSplatValue(&UndefElements);
1499 for (int i = 0; i < NElts; ++i) {
1500 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1503 // If this input comes from undef, mark it as such.
1504 if (UndefElements[MaskVec[i] - Offset]) {
1509 // If we can blend a non-undef lane, use that instead.
1510 if (!UndefElements[i])
1511 MaskVec[i] = i + Offset;
1514 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1515 BlendSplat(N1BV, 0);
1516 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1517 BlendSplat(N2BV, NElts);
1519 // Canonicalize all index into lhs, -> shuffle lhs, undef
1520 // Canonicalize all index into rhs, -> shuffle rhs, undef
1521 bool AllLHS = true, AllRHS = true;
1522 bool N2Undef = N2.isUndef();
1523 for (int i = 0; i != NElts; ++i) {
1524 if (MaskVec[i] >= NElts) {
1529 } else if (MaskVec[i] >= 0) {
1533 if (AllLHS && AllRHS)
1534 return getUNDEF(VT);
1535 if (AllLHS && !N2Undef)
1539 commuteShuffle(N1, N2, MaskVec);
1541 // Reset our undef status after accounting for the mask.
1542 N2Undef = N2.isUndef();
1543 // Re-check whether both sides ended up undef.
1544 if (N1.isUndef() && N2Undef)
1545 return getUNDEF(VT);
1547 // If Identity shuffle return that node.
1548 bool Identity = true, AllSame = true;
1549 for (int i = 0; i != NElts; ++i) {
1550 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1551 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1553 if (Identity && NElts)
1556 // Shuffling a constant splat doesn't change the result.
1560 // Look through any bitcasts. We check that these don't change the number
1561 // (and size) of elements and just changes their types.
1562 while (V.getOpcode() == ISD::BITCAST)
1563 V = V->getOperand(0);
1565 // A splat should always show up as a build vector node.
1566 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1567 BitVector UndefElements;
1568 SDValue Splat = BV->getSplatValue(&UndefElements);
1569 // If this is a splat of an undef, shuffling it is also undef.
1570 if (Splat && Splat.isUndef())
1571 return getUNDEF(VT);
1574 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1576 // We only have a splat which can skip shuffles if there is a splatted
1577 // value and no undef lanes rearranged by the shuffle.
1578 if (Splat && UndefElements.none()) {
1579 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1580 // number of elements match or the value splatted is a zero constant.
1583 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1584 if (C->isNullValue())
1588 // If the shuffle itself creates a splat, build the vector directly.
1589 if (AllSame && SameNumElts) {
1590 EVT BuildVT = BV->getValueType(0);
1591 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1592 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1594 // We may have jumped through bitcasts, so the type of the
1595 // BUILD_VECTOR may not match the type of the shuffle.
1597 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1603 FoldingSetNodeID ID;
1604 SDValue Ops[2] = { N1, N2 };
1605 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1606 for (int i = 0; i != NElts; ++i)
1607 ID.AddInteger(MaskVec[i]);
1610 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1611 return SDValue(E, 0);
1613 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1614 // SDNode doesn't have access to it. This memory will be "leaked" when
1615 // the node is deallocated, but recovered when the NodeAllocator is released.
1616 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1617 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1619 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1620 dl.getDebugLoc(), MaskAlloc);
1621 createOperands(N, Ops);
1623 CSEMap.InsertNode(N, IP);
1625 return SDValue(N, 0);
1628 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1629 MVT VT = SV.getSimpleValueType(0);
1630 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1631 ShuffleVectorSDNode::commuteMask(MaskVec);
1633 SDValue Op0 = SV.getOperand(0);
1634 SDValue Op1 = SV.getOperand(1);
1635 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1638 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1639 FoldingSetNodeID ID;
1640 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1641 ID.AddInteger(RegNo);
1643 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1644 return SDValue(E, 0);
1646 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1647 CSEMap.InsertNode(N, IP);
1649 return SDValue(N, 0);
1652 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1653 FoldingSetNodeID ID;
1654 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1655 ID.AddPointer(RegMask);
1657 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1658 return SDValue(E, 0);
1660 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1661 CSEMap.InsertNode(N, IP);
1663 return SDValue(N, 0);
1666 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1668 FoldingSetNodeID ID;
1669 SDValue Ops[] = { Root };
1670 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1671 ID.AddPointer(Label);
1673 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1674 return SDValue(E, 0);
1676 auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1677 createOperands(N, Ops);
1679 CSEMap.InsertNode(N, IP);
1681 return SDValue(N, 0);
1684 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1687 unsigned char TargetFlags) {
1688 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1690 FoldingSetNodeID ID;
1691 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1693 ID.AddInteger(Offset);
1694 ID.AddInteger(TargetFlags);
1696 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1697 return SDValue(E, 0);
1699 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1700 CSEMap.InsertNode(N, IP);
1702 return SDValue(N, 0);
1705 SDValue SelectionDAG::getSrcValue(const Value *V) {
1706 assert((!V || V->getType()->isPointerTy()) &&
1707 "SrcValue is not a pointer?");
1709 FoldingSetNodeID ID;
1710 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1714 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1715 return SDValue(E, 0);
1717 auto *N = newSDNode<SrcValueSDNode>(V);
1718 CSEMap.InsertNode(N, IP);
1720 return SDValue(N, 0);
1723 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1724 FoldingSetNodeID ID;
1725 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1729 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1730 return SDValue(E, 0);
1732 auto *N = newSDNode<MDNodeSDNode>(MD);
1733 CSEMap.InsertNode(N, IP);
1735 return SDValue(N, 0);
1738 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1739 if (VT == V.getValueType())
1742 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1745 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1746 unsigned SrcAS, unsigned DestAS) {
1747 SDValue Ops[] = {Ptr};
1748 FoldingSetNodeID ID;
1749 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1750 ID.AddInteger(SrcAS);
1751 ID.AddInteger(DestAS);
1754 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1755 return SDValue(E, 0);
1757 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1759 createOperands(N, Ops);
1761 CSEMap.InsertNode(N, IP);
1763 return SDValue(N, 0);
1766 /// getShiftAmountOperand - Return the specified value casted to
1767 /// the target's desired shift amount type.
1768 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1769 EVT OpTy = Op.getValueType();
1770 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1771 if (OpTy == ShTy || OpTy.isVector()) return Op;
1773 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1776 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1778 const TargetLowering &TLI = getTargetLoweringInfo();
1779 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1780 EVT VT = Node->getValueType(0);
1781 SDValue Tmp1 = Node->getOperand(0);
1782 SDValue Tmp2 = Node->getOperand(1);
1783 unsigned Align = Node->getConstantOperandVal(3);
1785 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1786 Tmp2, MachinePointerInfo(V));
1787 SDValue VAList = VAListLoad;
1789 if (Align > TLI.getMinStackArgumentAlignment()) {
1790 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1792 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1793 getConstant(Align - 1, dl, VAList.getValueType()));
1795 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1796 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1799 // Increment the pointer, VAList, to the next vaarg
1800 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1801 getConstant(getDataLayout().getTypeAllocSize(
1802 VT.getTypeForEVT(*getContext())),
1803 dl, VAList.getValueType()));
1804 // Store the incremented VAList to the legalized pointer
1806 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1807 // Load the actual argument out of the pointer VAList
1808 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1811 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1813 const TargetLowering &TLI = getTargetLoweringInfo();
1814 // This defaults to loading a pointer from the input and storing it to the
1815 // output, returning the chain.
1816 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1817 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1819 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1820 Node->getOperand(2), MachinePointerInfo(VS));
1821 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1822 MachinePointerInfo(VD));
1825 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1826 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1827 unsigned ByteSize = VT.getStoreSize();
1828 Type *Ty = VT.getTypeForEVT(*getContext());
1829 unsigned StackAlign =
1830 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1832 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1833 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1836 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1837 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1838 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1839 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1840 const DataLayout &DL = getDataLayout();
1842 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1844 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1845 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1846 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1849 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1850 ISD::CondCode Cond, const SDLoc &dl) {
1851 // These setcc operations always fold.
1855 case ISD::SETFALSE2: return getConstant(0, dl, VT);
1857 case ISD::SETTRUE2: {
1858 TargetLowering::BooleanContent Cnt =
1859 TLI->getBooleanContents(N1->getValueType(0));
1861 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1875 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1879 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1880 const APInt &C2 = N2C->getAPIntValue();
1881 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1882 const APInt &C1 = N1C->getAPIntValue();
1885 default: llvm_unreachable("Unknown integer setcc!");
1886 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT);
1887 case ISD::SETNE: return getConstant(C1 != C2, dl, VT);
1888 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1889 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1890 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1891 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1892 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT);
1893 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT);
1894 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT);
1895 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT);
1899 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1900 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1901 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1904 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1905 return getUNDEF(VT);
1907 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1908 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1909 return getUNDEF(VT);
1911 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1912 R==APFloat::cmpLessThan, dl, VT);
1913 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1914 return getUNDEF(VT);
1916 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1917 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1918 return getUNDEF(VT);
1920 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1921 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1922 return getUNDEF(VT);
1924 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1925 R==APFloat::cmpEqual, dl, VT);
1926 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1927 return getUNDEF(VT);
1929 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1930 R==APFloat::cmpEqual, dl, VT);
1931 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1932 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT);
1933 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1934 R==APFloat::cmpEqual, dl, VT);
1935 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1936 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1937 R==APFloat::cmpLessThan, dl, VT);
1938 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1939 R==APFloat::cmpUnordered, dl, VT);
1940 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1941 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1944 // Ensure that the constant occurs on the RHS.
1945 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1946 MVT CompVT = N1.getValueType().getSimpleVT();
1947 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1950 return getSetCC(dl, VT, N2, N1, SwappedCond);
1954 // Could not fold it.
1958 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1959 /// use this predicate to simplify operations downstream.
1960 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1961 unsigned BitWidth = Op.getScalarValueSizeInBits();
1962 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
1965 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1966 /// this predicate to simplify operations downstream. Mask is known to be zero
1967 /// for bits that V cannot have.
1968 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1969 unsigned Depth) const {
1970 APInt KnownZero, KnownOne;
1971 computeKnownBits(Op, KnownZero, KnownOne, Depth);
1972 return (KnownZero & Mask) == Mask;
1975 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
1976 /// is less than the element bit-width of the shift node, return it.
1977 static const APInt *getValidShiftAmountConstant(SDValue V) {
1978 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
1979 // Shifting more than the bitwidth is not valid.
1980 const APInt &ShAmt = SA->getAPIntValue();
1981 if (ShAmt.ult(V.getScalarValueSizeInBits()))
1987 /// Determine which bits of Op are known to be either zero or one and return
1988 /// them in the KnownZero/KnownOne bitsets. For vectors, the known bits are
1989 /// those that are shared by every vector element.
1990 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
1991 APInt &KnownOne, unsigned Depth) const {
1992 EVT VT = Op.getValueType();
1993 APInt DemandedElts = VT.isVector()
1994 ? APInt::getAllOnesValue(VT.getVectorNumElements())
1996 computeKnownBits(Op, KnownZero, KnownOne, DemandedElts, Depth);
1999 /// Determine which bits of Op are known to be either zero or one and return
2000 /// them in the KnownZero/KnownOne bitsets. The DemandedElts argument allows
2001 /// us to only collect the known bits that are shared by the requested vector
2003 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
2004 APInt &KnownOne, const APInt &DemandedElts,
2005 unsigned Depth) const {
2006 unsigned BitWidth = Op.getScalarValueSizeInBits();
2008 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
2010 return; // Limit search depth.
2012 APInt KnownZero2, KnownOne2;
2013 unsigned NumElts = DemandedElts.getBitWidth();
2016 return; // No demanded elts, better to assume we don't know anything.
2018 unsigned Opcode = Op.getOpcode();
2021 // We know all of the bits for a constant!
2022 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
2023 KnownZero = ~KnownOne;
2025 case ISD::BUILD_VECTOR:
2026 // Collect the known bits that are shared by every demanded vector element.
2027 assert(NumElts == Op.getValueType().getVectorNumElements() &&
2028 "Unexpected vector size");
2029 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2030 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2031 if (!DemandedElts[i])
2034 SDValue SrcOp = Op.getOperand(i);
2035 computeKnownBits(SrcOp, KnownZero2, KnownOne2, Depth + 1);
2037 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2038 if (SrcOp.getValueSizeInBits() != BitWidth) {
2039 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2040 "Expected BUILD_VECTOR implicit truncation");
2041 KnownOne2 = KnownOne2.trunc(BitWidth);
2042 KnownZero2 = KnownZero2.trunc(BitWidth);
2045 // Known bits are the values that are shared by every demanded element.
2046 KnownOne &= KnownOne2;
2047 KnownZero &= KnownZero2;
2049 // If we don't know any bits, early out.
2050 if (!KnownOne && !KnownZero)
2054 case ISD::VECTOR_SHUFFLE: {
2055 // Collect the known bits that are shared by every vector element referenced
2057 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2058 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2059 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2060 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2061 for (unsigned i = 0; i != NumElts; ++i) {
2062 if (!DemandedElts[i])
2065 int M = SVN->getMaskElt(i);
2067 // For UNDEF elements, we don't know anything about the common state of
2068 // the shuffle result.
2069 KnownOne.clearAllBits();
2070 KnownZero.clearAllBits();
2071 DemandedLHS.clearAllBits();
2072 DemandedRHS.clearAllBits();
2076 if ((unsigned)M < NumElts)
2077 DemandedLHS.setBit((unsigned)M % NumElts);
2079 DemandedRHS.setBit((unsigned)M % NumElts);
2081 // Known bits are the values that are shared by every demanded element.
2082 if (!!DemandedLHS) {
2083 SDValue LHS = Op.getOperand(0);
2084 computeKnownBits(LHS, KnownZero2, KnownOne2, DemandedLHS, Depth + 1);
2085 KnownOne &= KnownOne2;
2086 KnownZero &= KnownZero2;
2088 // If we don't know any bits, early out.
2089 if (!KnownOne && !KnownZero)
2091 if (!!DemandedRHS) {
2092 SDValue RHS = Op.getOperand(1);
2093 computeKnownBits(RHS, KnownZero2, KnownOne2, DemandedRHS, Depth + 1);
2094 KnownOne &= KnownOne2;
2095 KnownZero &= KnownZero2;
2099 case ISD::CONCAT_VECTORS: {
2100 // Split DemandedElts and test each of the demanded subvectors.
2101 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2102 EVT SubVectorVT = Op.getOperand(0).getValueType();
2103 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2104 unsigned NumSubVectors = Op.getNumOperands();
2105 for (unsigned i = 0; i != NumSubVectors; ++i) {
2106 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2107 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2108 if (!!DemandedSub) {
2109 SDValue Sub = Op.getOperand(i);
2110 computeKnownBits(Sub, KnownZero2, KnownOne2, DemandedSub, Depth + 1);
2111 KnownOne &= KnownOne2;
2112 KnownZero &= KnownZero2;
2114 // If we don't know any bits, early out.
2115 if (!KnownOne && !KnownZero)
2120 case ISD::EXTRACT_SUBVECTOR: {
2121 // If we know the element index, just demand that subvector elements,
2122 // otherwise demand them all.
2123 SDValue Src = Op.getOperand(0);
2124 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2125 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2126 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2127 // Offset the demanded elts by the subvector index.
2128 uint64_t Idx = SubIdx->getZExtValue();
2129 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
2130 computeKnownBits(Src, KnownZero, KnownOne, DemandedSrc, Depth + 1);
2132 computeKnownBits(Src, KnownZero, KnownOne, Depth + 1);
2136 case ISD::BITCAST: {
2137 SDValue N0 = Op.getOperand(0);
2138 unsigned SubBitWidth = N0.getScalarValueSizeInBits();
2140 // Ignore bitcasts from floating point.
2141 if (!N0.getValueType().isInteger())
2144 // Fast handling of 'identity' bitcasts.
2145 if (BitWidth == SubBitWidth) {
2146 computeKnownBits(N0, KnownZero, KnownOne, DemandedElts, Depth + 1);
2150 // Support big-endian targets when it becomes useful.
2151 bool IsLE = getDataLayout().isLittleEndian();
2155 // Bitcast 'small element' vector to 'large element' scalar/vector.
2156 if ((BitWidth % SubBitWidth) == 0) {
2157 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2159 // Collect known bits for the (larger) output by collecting the known
2160 // bits from each set of sub elements and shift these into place.
2161 // We need to separately call computeKnownBits for each set of
2162 // sub elements as the knownbits for each is likely to be different.
2163 unsigned SubScale = BitWidth / SubBitWidth;
2164 APInt SubDemandedElts(NumElts * SubScale, 0);
2165 for (unsigned i = 0; i != NumElts; ++i)
2166 if (DemandedElts[i])
2167 SubDemandedElts.setBit(i * SubScale);
2169 for (unsigned i = 0; i != SubScale; ++i) {
2170 computeKnownBits(N0, KnownZero2, KnownOne2, SubDemandedElts.shl(i),
2172 KnownOne |= KnownOne2.zext(BitWidth).shl(SubBitWidth * i);
2173 KnownZero |= KnownZero2.zext(BitWidth).shl(SubBitWidth * i);
2177 // Bitcast 'large element' scalar/vector to 'small element' vector.
2178 if ((SubBitWidth % BitWidth) == 0) {
2179 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2181 // Collect known bits for the (smaller) output by collecting the known
2182 // bits from the overlapping larger input elements and extracting the
2183 // sub sections we actually care about.
2184 unsigned SubScale = SubBitWidth / BitWidth;
2185 APInt SubDemandedElts(NumElts / SubScale, 0);
2186 for (unsigned i = 0; i != NumElts; ++i)
2187 if (DemandedElts[i])
2188 SubDemandedElts.setBit(i / SubScale);
2190 computeKnownBits(N0, KnownZero2, KnownOne2, SubDemandedElts, Depth + 1);
2192 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2193 for (unsigned i = 0; i != NumElts; ++i)
2194 if (DemandedElts[i]) {
2195 unsigned Offset = (i % SubScale) * BitWidth;
2196 KnownOne &= KnownOne2.lshr(Offset).trunc(BitWidth);
2197 KnownZero &= KnownZero2.lshr(Offset).trunc(BitWidth);
2198 // If we don't know any bits, early out.
2199 if (!KnownOne && !KnownZero)
2206 // If either the LHS or the RHS are Zero, the result is zero.
2207 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2209 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2212 // Output known-1 bits are only known if set in both the LHS & RHS.
2213 KnownOne &= KnownOne2;
2214 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2215 KnownZero |= KnownZero2;
2218 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2220 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2223 // Output known-0 bits are only known if clear in both the LHS & RHS.
2224 KnownZero &= KnownZero2;
2225 // Output known-1 are known to be set if set in either the LHS | RHS.
2226 KnownOne |= KnownOne2;
2229 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2231 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2234 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2235 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
2236 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2237 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
2238 KnownZero = KnownZeroOut;
2242 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2244 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2247 // If low bits are zero in either operand, output low known-0 bits.
2248 // Also compute a conservative estimate for high known-0 bits.
2249 // More trickiness is possible, but this is sufficient for the
2250 // interesting case of alignment computation.
2251 KnownOne.clearAllBits();
2252 unsigned TrailZ = KnownZero.countTrailingOnes() +
2253 KnownZero2.countTrailingOnes();
2254 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
2255 KnownZero2.countLeadingOnes(),
2256 BitWidth) - BitWidth;
2258 KnownZero.clearAllBits();
2259 KnownZero.setLowBits(std::min(TrailZ, BitWidth));
2260 KnownZero.setHighBits(std::min(LeadZ, BitWidth));
2264 // For the purposes of computing leading zeros we can conservatively
2265 // treat a udiv as a logical right shift by the power of 2 known to
2266 // be less than the denominator.
2267 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2269 unsigned LeadZ = KnownZero2.countLeadingOnes();
2271 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2273 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
2274 if (RHSUnknownLeadingOnes != BitWidth)
2275 LeadZ = std::min(BitWidth,
2276 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
2278 KnownZero.setHighBits(LeadZ);
2282 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
2283 // If we don't know any bits, early out.
2284 if (!KnownOne && !KnownZero)
2286 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2288 // Only known if known in both the LHS and RHS.
2289 KnownOne &= KnownOne2;
2290 KnownZero &= KnownZero2;
2292 case ISD::SELECT_CC:
2293 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
2294 // If we don't know any bits, early out.
2295 if (!KnownOne && !KnownZero)
2297 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
2299 // Only known if known in both the LHS and RHS.
2300 KnownOne &= KnownOne2;
2301 KnownZero &= KnownZero2;
2305 if (Op.getResNo() != 1)
2307 // The boolean result conforms to getBooleanContents.
2308 // If we know the result of a setcc has the top bits zero, use this info.
2309 // We know that we have an integer-based boolean since these operations
2310 // are only available for integer.
2311 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2312 TargetLowering::ZeroOrOneBooleanContent &&
2314 KnownZero.setBitsFrom(1);
2317 // If we know the result of a setcc has the top bits zero, use this info.
2318 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2319 TargetLowering::ZeroOrOneBooleanContent &&
2321 KnownZero.setBitsFrom(1);
2324 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2325 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2327 KnownZero = KnownZero << *ShAmt;
2328 KnownOne = KnownOne << *ShAmt;
2329 // Low bits are known zero.
2330 KnownZero.setLowBits(ShAmt->getZExtValue());
2334 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2335 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2337 KnownZero.lshrInPlace(*ShAmt);
2338 KnownOne.lshrInPlace(*ShAmt);
2339 // High bits are known zero.
2340 KnownZero.setHighBits(ShAmt->getZExtValue());
2344 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2345 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2347 KnownZero.lshrInPlace(*ShAmt);
2348 KnownOne.lshrInPlace(*ShAmt);
2349 // If we know the value of the sign bit, then we know it is copied across
2350 // the high bits by the shift amount.
2351 APInt SignMask = APInt::getSignMask(BitWidth);
2352 SignMask.lshrInPlace(*ShAmt); // Adjust to where it is now in the mask.
2353 if (KnownZero.intersects(SignMask)) {
2354 KnownZero.setHighBits(ShAmt->getZExtValue());// New bits are known zero.
2355 } else if (KnownOne.intersects(SignMask)) {
2356 KnownOne.setHighBits(ShAmt->getZExtValue()); // New bits are known one.
2360 case ISD::SIGN_EXTEND_INREG: {
2361 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2362 unsigned EBits = EVT.getScalarSizeInBits();
2364 // Sign extension. Compute the demanded bits in the result that are not
2365 // present in the input.
2366 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2368 APInt InSignMask = APInt::getSignMask(EBits);
2369 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2371 // If the sign extended bits are demanded, we know that the sign
2373 InSignMask = InSignMask.zext(BitWidth);
2374 if (NewBits.getBoolValue())
2375 InputDemandedBits |= InSignMask;
2377 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2379 KnownOne &= InputDemandedBits;
2380 KnownZero &= InputDemandedBits;
2382 // If the sign bit of the input is known set or clear, then we know the
2383 // top bits of the result.
2384 if (KnownZero.intersects(InSignMask)) { // Input sign bit known clear
2385 KnownZero |= NewBits;
2386 KnownOne &= ~NewBits;
2387 } else if (KnownOne.intersects(InSignMask)) { // Input sign bit known set
2388 KnownOne |= NewBits;
2389 KnownZero &= ~NewBits;
2390 } else { // Input sign bit unknown
2391 KnownZero &= ~NewBits;
2392 KnownOne &= ~NewBits;
2397 case ISD::CTTZ_ZERO_UNDEF:
2399 case ISD::CTLZ_ZERO_UNDEF:
2401 KnownZero.setBitsFrom(Log2_32(BitWidth)+1);
2405 LoadSDNode *LD = cast<LoadSDNode>(Op);
2406 // If this is a ZEXTLoad and we are looking at the loaded value.
2407 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2408 EVT VT = LD->getMemoryVT();
2409 unsigned MemBits = VT.getScalarSizeInBits();
2410 KnownZero.setBitsFrom(MemBits);
2411 } else if (const MDNode *Ranges = LD->getRanges()) {
2412 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2413 computeKnownBitsFromRangeMetadata(*Ranges, KnownZero, KnownOne);
2417 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2418 EVT InVT = Op.getOperand(0).getValueType();
2419 unsigned InBits = InVT.getScalarSizeInBits();
2420 KnownZero = KnownZero.trunc(InBits);
2421 KnownOne = KnownOne.trunc(InBits);
2422 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne,
2423 DemandedElts.zext(InVT.getVectorNumElements()),
2425 KnownZero = KnownZero.zext(BitWidth);
2426 KnownOne = KnownOne.zext(BitWidth);
2427 KnownZero.setBitsFrom(InBits);
2430 case ISD::ZERO_EXTEND: {
2431 EVT InVT = Op.getOperand(0).getValueType();
2432 unsigned InBits = InVT.getScalarSizeInBits();
2433 KnownZero = KnownZero.trunc(InBits);
2434 KnownOne = KnownOne.trunc(InBits);
2435 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2437 KnownZero = KnownZero.zext(BitWidth);
2438 KnownOne = KnownOne.zext(BitWidth);
2439 KnownZero.setBitsFrom(InBits);
2442 // TODO ISD::SIGN_EXTEND_VECTOR_INREG
2443 case ISD::SIGN_EXTEND: {
2444 EVT InVT = Op.getOperand(0).getValueType();
2445 unsigned InBits = InVT.getScalarSizeInBits();
2447 KnownZero = KnownZero.trunc(InBits);
2448 KnownOne = KnownOne.trunc(InBits);
2449 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2452 // If the sign bit is known to be zero or one, then sext will extend
2453 // it to the top bits, else it will just zext.
2454 KnownZero = KnownZero.sext(BitWidth);
2455 KnownOne = KnownOne.sext(BitWidth);
2458 case ISD::ANY_EXTEND: {
2459 EVT InVT = Op.getOperand(0).getValueType();
2460 unsigned InBits = InVT.getScalarSizeInBits();
2461 KnownZero = KnownZero.trunc(InBits);
2462 KnownOne = KnownOne.trunc(InBits);
2463 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2464 KnownZero = KnownZero.zext(BitWidth);
2465 KnownOne = KnownOne.zext(BitWidth);
2468 case ISD::TRUNCATE: {
2469 EVT InVT = Op.getOperand(0).getValueType();
2470 unsigned InBits = InVT.getScalarSizeInBits();
2471 KnownZero = KnownZero.zext(InBits);
2472 KnownOne = KnownOne.zext(InBits);
2473 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2475 KnownZero = KnownZero.trunc(BitWidth);
2476 KnownOne = KnownOne.trunc(BitWidth);
2479 case ISD::AssertZext: {
2480 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2481 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2482 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2483 KnownZero |= (~InMask);
2484 KnownOne &= (~KnownZero);
2488 // All bits are zero except the low bit.
2489 KnownZero.setBitsFrom(1);
2493 if (Op.getResNo() == 1) {
2494 // If we know the result of a setcc has the top bits zero, use this info.
2495 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2496 TargetLowering::ZeroOrOneBooleanContent &&
2498 KnownZero.setBitsFrom(1);
2504 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2505 // We know that the top bits of C-X are clear if X contains less bits
2506 // than C (i.e. no wrap-around can happen). For example, 20-X is
2507 // positive if we can prove that X is >= 0 and < 16.
2508 if (CLHS->getAPIntValue().isNonNegative()) {
2509 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2510 // NLZ can't be BitWidth with no sign bit
2511 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2512 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2515 // If all of the MaskV bits are known to be zero, then we know the
2516 // output top bits are zero, because we now know that the output is
2518 if ((KnownZero2 & MaskV) == MaskV) {
2519 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2520 // Top bits known zero.
2521 KnownZero.setHighBits(NLZ2);
2526 // If low bits are know to be zero in both operands, then we know they are
2527 // going to be 0 in the result. Both addition and complement operations
2528 // preserve the low zero bits.
2529 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2531 unsigned KnownZeroLow = KnownZero2.countTrailingOnes();
2532 if (KnownZeroLow == 0)
2535 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2537 KnownZeroLow = std::min(KnownZeroLow,
2538 KnownZero2.countTrailingOnes());
2539 KnownZero.setBits(0, KnownZeroLow);
2544 if (Op.getResNo() == 1) {
2545 // If we know the result of a setcc has the top bits zero, use this info.
2546 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2547 TargetLowering::ZeroOrOneBooleanContent &&
2549 KnownZero.setBitsFrom(1);
2556 // Output known-0 bits are known if clear or set in both the low clear bits
2557 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2558 // low 3 bits clear.
2559 // Output known-0 bits are also known if the top bits of each input are
2560 // known to be clear. For example, if one input has the top 10 bits clear
2561 // and the other has the top 8 bits clear, we know the top 7 bits of the
2562 // output must be clear.
2563 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2565 unsigned KnownZeroHigh = KnownZero2.countLeadingOnes();
2566 unsigned KnownZeroLow = KnownZero2.countTrailingOnes();
2568 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2570 KnownZeroHigh = std::min(KnownZeroHigh,
2571 KnownZero2.countLeadingOnes());
2572 KnownZeroLow = std::min(KnownZeroLow,
2573 KnownZero2.countTrailingOnes());
2575 if (Opcode == ISD::ADDE) {
2576 // With ADDE, a carry bit may be added in, so we can only use this
2577 // information if we know (at least) that the low two bits are clear.
2578 // We then return to the caller that the low bit is unknown but that
2579 // other bits are known zero.
2580 if (KnownZeroLow >= 2)
2581 KnownZero.setBits(1, KnownZeroLow);
2585 KnownZero.setLowBits(KnownZeroLow);
2586 if (KnownZeroHigh > 1)
2587 KnownZero.setHighBits(KnownZeroHigh - 1);
2591 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2592 const APInt &RA = Rem->getAPIntValue().abs();
2593 if (RA.isPowerOf2()) {
2594 APInt LowBits = RA - 1;
2595 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2598 // The low bits of the first operand are unchanged by the srem.
2599 KnownZero = KnownZero2 & LowBits;
2600 KnownOne = KnownOne2 & LowBits;
2602 // If the first operand is non-negative or has all low bits zero, then
2603 // the upper bits are all zero.
2604 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2605 KnownZero |= ~LowBits;
2607 // If the first operand is negative and not all low bits are zero, then
2608 // the upper bits are all one.
2609 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2610 KnownOne |= ~LowBits;
2611 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2616 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2617 const APInt &RA = Rem->getAPIntValue();
2618 if (RA.isPowerOf2()) {
2619 APInt LowBits = (RA - 1);
2620 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2623 // The upper bits are all zero, the lower ones are unchanged.
2624 KnownZero = KnownZero2 | ~LowBits;
2625 KnownOne = KnownOne2 & LowBits;
2630 // Since the result is less than or equal to either operand, any leading
2631 // zero bits in either operand must also exist in the result.
2632 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2634 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2637 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2638 KnownZero2.countLeadingOnes());
2639 KnownOne.clearAllBits();
2640 KnownZero.clearAllBits();
2641 KnownZero.setHighBits(Leaders);
2644 case ISD::EXTRACT_ELEMENT: {
2645 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2646 const unsigned Index = Op.getConstantOperandVal(1);
2647 const unsigned BitWidth = Op.getValueSizeInBits();
2649 // Remove low part of known bits mask
2650 KnownZero = KnownZero.getHiBits(KnownZero.getBitWidth() - Index * BitWidth);
2651 KnownOne = KnownOne.getHiBits(KnownOne.getBitWidth() - Index * BitWidth);
2653 // Remove high part of known bit mask
2654 KnownZero = KnownZero.trunc(BitWidth);
2655 KnownOne = KnownOne.trunc(BitWidth);
2658 case ISD::EXTRACT_VECTOR_ELT: {
2659 SDValue InVec = Op.getOperand(0);
2660 SDValue EltNo = Op.getOperand(1);
2661 EVT VecVT = InVec.getValueType();
2662 const unsigned BitWidth = Op.getValueSizeInBits();
2663 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
2664 const unsigned NumSrcElts = VecVT.getVectorNumElements();
2665 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2666 // anything about the extended bits.
2667 if (BitWidth > EltBitWidth) {
2668 KnownZero = KnownZero.trunc(EltBitWidth);
2669 KnownOne = KnownOne.trunc(EltBitWidth);
2671 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
2672 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
2673 // If we know the element index, just demand that vector element.
2674 unsigned Idx = ConstEltNo->getZExtValue();
2675 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
2676 computeKnownBits(InVec, KnownZero, KnownOne, DemandedElt, Depth + 1);
2678 // Unknown element index, so ignore DemandedElts and demand them all.
2679 computeKnownBits(InVec, KnownZero, KnownOne, Depth + 1);
2681 if (BitWidth > EltBitWidth) {
2682 KnownZero = KnownZero.zext(BitWidth);
2683 KnownOne = KnownOne.zext(BitWidth);
2687 case ISD::INSERT_VECTOR_ELT: {
2688 SDValue InVec = Op.getOperand(0);
2689 SDValue InVal = Op.getOperand(1);
2690 SDValue EltNo = Op.getOperand(2);
2692 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
2693 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
2694 // If we know the element index, split the demand between the
2695 // source vector and the inserted element.
2696 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2697 unsigned EltIdx = CEltNo->getZExtValue();
2699 // If we demand the inserted element then add its common known bits.
2700 if (DemandedElts[EltIdx]) {
2701 computeKnownBits(InVal, KnownZero2, KnownOne2, Depth + 1);
2702 KnownOne &= KnownOne2.zextOrTrunc(KnownOne.getBitWidth());
2703 KnownZero &= KnownZero2.zextOrTrunc(KnownZero.getBitWidth());;
2706 // If we demand the source vector then add its common known bits, ensuring
2707 // that we don't demand the inserted element.
2708 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
2710 computeKnownBits(InVec, KnownZero2, KnownOne2, VectorElts, Depth + 1);
2711 KnownOne &= KnownOne2;
2712 KnownZero &= KnownZero2;
2715 // Unknown element index, so ignore DemandedElts and demand them all.
2716 computeKnownBits(InVec, KnownZero, KnownOne, Depth + 1);
2717 computeKnownBits(InVal, KnownZero2, KnownOne2, Depth + 1);
2718 KnownOne &= KnownOne2.zextOrTrunc(KnownOne.getBitWidth());
2719 KnownZero &= KnownZero2.zextOrTrunc(KnownZero.getBitWidth());;
2723 case ISD::BITREVERSE: {
2724 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2726 KnownZero = KnownZero2.reverseBits();
2727 KnownOne = KnownOne2.reverseBits();
2731 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2733 KnownZero = KnownZero2.byteSwap();
2734 KnownOne = KnownOne2.byteSwap();
2738 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2741 // If the source's MSB is zero then we know the rest of the bits already.
2742 if (KnownZero2[BitWidth - 1]) {
2743 KnownZero = KnownZero2;
2744 KnownOne = KnownOne2;
2748 // We only know that the absolute values's MSB will be zero iff there is
2749 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
2750 KnownOne2.clearBit(BitWidth - 1);
2751 if (KnownOne2.getBoolValue()) {
2752 KnownZero = APInt::getSignMask(BitWidth);
2758 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2760 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2763 // UMIN - we know that the result will have the maximum of the
2764 // known zero leading bits of the inputs.
2765 unsigned LeadZero = KnownZero.countLeadingOnes();
2766 LeadZero = std::max(LeadZero, KnownZero2.countLeadingOnes());
2768 KnownZero &= KnownZero2;
2769 KnownOne &= KnownOne2;
2770 KnownZero.setHighBits(LeadZero);
2774 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2776 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2779 // UMAX - we know that the result will have the maximum of the
2780 // known one leading bits of the inputs.
2781 unsigned LeadOne = KnownOne.countLeadingOnes();
2782 LeadOne = std::max(LeadOne, KnownOne2.countLeadingOnes());
2784 KnownZero &= KnownZero2;
2785 KnownOne &= KnownOne2;
2786 KnownOne.setHighBits(LeadOne);
2791 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2793 // If we don't know any bits, early out.
2794 if (!KnownOne && !KnownZero)
2796 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2798 KnownZero &= KnownZero2;
2799 KnownOne &= KnownOne2;
2802 case ISD::FrameIndex:
2803 case ISD::TargetFrameIndex:
2804 if (unsigned Align = InferPtrAlignment(Op)) {
2805 // The low bits are known zero if the pointer is aligned.
2806 KnownZero.setLowBits(Log2_32(Align));
2812 if (Opcode < ISD::BUILTIN_OP_END)
2815 case ISD::INTRINSIC_WO_CHAIN:
2816 case ISD::INTRINSIC_W_CHAIN:
2817 case ISD::INTRINSIC_VOID:
2818 // Allow the target to implement this method for its nodes.
2819 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, DemandedElts,
2824 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2827 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
2829 // X + 0 never overflow
2830 if (isNullConstant(N1))
2833 APInt N1Zero, N1One;
2834 computeKnownBits(N1, N1Zero, N1One);
2835 if (N1Zero.getBoolValue()) {
2836 APInt N0Zero, N0One;
2837 computeKnownBits(N0, N0Zero, N0One);
2840 (void)(~N0Zero).uadd_ov(~N1Zero, overflow);
2845 // mulhi + 1 never overflow
2846 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
2847 (~N1Zero & 0x01) == ~N1Zero)
2850 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
2851 APInt N0Zero, N0One;
2852 computeKnownBits(N0, N0Zero, N0One);
2854 if ((~N0Zero & 0x01) == ~N0Zero)
2858 return OFK_Sometime;
2861 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2862 EVT OpVT = Val.getValueType();
2863 unsigned BitWidth = OpVT.getScalarSizeInBits();
2865 // Is the constant a known power of 2?
2866 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
2867 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2869 // A left-shift of a constant one will have exactly one bit set because
2870 // shifting the bit off the end is undefined.
2871 if (Val.getOpcode() == ISD::SHL) {
2872 auto *C = isConstOrConstSplat(Val.getOperand(0));
2873 if (C && C->getAPIntValue() == 1)
2877 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2879 if (Val.getOpcode() == ISD::SRL) {
2880 auto *C = isConstOrConstSplat(Val.getOperand(0));
2881 if (C && C->getAPIntValue().isSignMask())
2885 // Are all operands of a build vector constant powers of two?
2886 if (Val.getOpcode() == ISD::BUILD_VECTOR)
2887 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
2888 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
2889 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2894 // More could be done here, though the above checks are enough
2895 // to handle some common cases.
2897 // Fall back to computeKnownBits to catch other known cases.
2898 APInt KnownZero, KnownOne;
2899 computeKnownBits(Val, KnownZero, KnownOne);
2900 return (KnownZero.countPopulation() == BitWidth - 1) &&
2901 (KnownOne.countPopulation() == 1);
2904 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2905 EVT VT = Op.getValueType();
2906 APInt DemandedElts = VT.isVector()
2907 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2909 return ComputeNumSignBits(Op, DemandedElts, Depth);
2912 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2913 unsigned Depth) const {
2914 EVT VT = Op.getValueType();
2915 assert(VT.isInteger() && "Invalid VT!");
2916 unsigned VTBits = VT.getScalarSizeInBits();
2918 unsigned FirstAnswer = 1;
2921 return 1; // Limit search depth.
2924 return 1; // No demanded elts, better to assume we don't know anything.
2926 switch (Op.getOpcode()) {
2928 case ISD::AssertSext:
2929 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2930 return VTBits-Tmp+1;
2931 case ISD::AssertZext:
2932 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2935 case ISD::Constant: {
2936 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2937 return Val.getNumSignBits();
2940 case ISD::BUILD_VECTOR:
2942 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
2943 if (!DemandedElts[i])
2946 SDValue SrcOp = Op.getOperand(i);
2947 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
2949 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2950 if (SrcOp.getValueSizeInBits() != VTBits) {
2951 assert(SrcOp.getValueSizeInBits() > VTBits &&
2952 "Expected BUILD_VECTOR implicit truncation");
2953 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
2954 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
2956 Tmp = std::min(Tmp, Tmp2);
2960 case ISD::SIGN_EXTEND:
2961 case ISD::SIGN_EXTEND_VECTOR_INREG:
2962 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
2963 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2965 case ISD::SIGN_EXTEND_INREG:
2966 // Max of the input and what this extends.
2967 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
2970 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2971 return std::max(Tmp, Tmp2);
2974 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2975 // SRA X, C -> adds C sign bits.
2976 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2977 APInt ShiftVal = C->getAPIntValue();
2979 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
2983 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2984 // shl destroys sign bits.
2985 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2986 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
2987 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
2988 return Tmp - C->getZExtValue();
2993 case ISD::XOR: // NOT is handled here.
2994 // Logical binary ops preserve the number of sign bits at the worst.
2995 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2997 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2998 FirstAnswer = std::min(Tmp, Tmp2);
2999 // We computed what we know about the sign bits as our first
3000 // answer. Now proceed to the generic code that uses
3001 // computeKnownBits, and pick whichever answer is better.
3006 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3007 if (Tmp == 1) return 1; // Early out.
3008 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3009 return std::min(Tmp, Tmp2);
3010 case ISD::SELECT_CC:
3011 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3012 if (Tmp == 1) return 1; // Early out.
3013 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
3014 return std::min(Tmp, Tmp2);
3019 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3021 return 1; // Early out.
3022 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3023 return std::min(Tmp, Tmp2);
3030 if (Op.getResNo() != 1)
3032 // The boolean result conforms to getBooleanContents. Fall through.
3033 // If setcc returns 0/-1, all bits are sign bits.
3034 // We know that we have an integer-based boolean since these operations
3035 // are only available for integer.
3036 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3037 TargetLowering::ZeroOrNegativeOneBooleanContent)
3041 // If setcc returns 0/-1, all bits are sign bits.
3042 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3043 TargetLowering::ZeroOrNegativeOneBooleanContent)
3048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3049 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
3051 // Handle rotate right by N like a rotate left by 32-N.
3052 if (Op.getOpcode() == ISD::ROTR)
3053 RotAmt = (VTBits-RotAmt) & (VTBits-1);
3055 // If we aren't rotating out all of the known-in sign bits, return the
3056 // number that are left. This handles rotl(sext(x), 1) for example.
3057 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3058 if (Tmp > RotAmt+1) return Tmp-RotAmt;
3063 // Add can have at most one carry bit. Thus we know that the output
3064 // is, at worst, one more bit than the inputs.
3065 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3066 if (Tmp == 1) return 1; // Early out.
3068 // Special case decrementing a value (ADD X, -1):
3069 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3070 if (CRHS->isAllOnesValue()) {
3071 APInt KnownZero, KnownOne;
3072 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
3074 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3076 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
3079 // If we are subtracting one from a positive number, there is no carry
3080 // out of the result.
3081 if (KnownZero.isNegative())
3085 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3086 if (Tmp2 == 1) return 1;
3087 return std::min(Tmp, Tmp2)-1;
3090 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3091 if (Tmp2 == 1) return 1;
3094 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3095 if (CLHS->isNullValue()) {
3096 APInt KnownZero, KnownOne;
3097 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
3098 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3100 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
3103 // If the input is known to be positive (the sign bit is known clear),
3104 // the output of the NEG has the same number of sign bits as the input.
3105 if (KnownZero.isNegative())
3108 // Otherwise, we treat this like a SUB.
3111 // Sub can have at most one carry bit. Thus we know that the output
3112 // is, at worst, one more bit than the inputs.
3113 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3114 if (Tmp == 1) return 1; // Early out.
3115 return std::min(Tmp, Tmp2)-1;
3116 case ISD::TRUNCATE: {
3117 // Check if the sign bits of source go down as far as the truncated value.
3118 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3119 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3120 if (NumSrcSignBits > (NumSrcBits - VTBits))
3121 return NumSrcSignBits - (NumSrcBits - VTBits);
3124 case ISD::EXTRACT_ELEMENT: {
3125 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3126 const int BitWidth = Op.getValueSizeInBits();
3127 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3129 // Get reverse index (starting from 1), Op1 value indexes elements from
3130 // little end. Sign starts at big end.
3131 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3133 // If the sign portion ends in our element the subtraction gives correct
3134 // result. Otherwise it gives either negative or > bitwidth result
3135 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3137 case ISD::EXTRACT_VECTOR_ELT: {
3138 SDValue InVec = Op.getOperand(0);
3139 SDValue EltNo = Op.getOperand(1);
3140 EVT VecVT = InVec.getValueType();
3141 const unsigned BitWidth = Op.getValueSizeInBits();
3142 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3143 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3145 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3146 // anything about sign bits. But if the sizes match we can derive knowledge
3147 // about sign bits from the vector operand.
3148 if (BitWidth != EltBitWidth)
3151 // If we know the element index, just demand that vector element, else for
3152 // an unknown element index, ignore DemandedElts and demand them all.
3153 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3154 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3155 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3157 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3159 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3161 case ISD::EXTRACT_SUBVECTOR:
3162 return ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3163 case ISD::CONCAT_VECTORS:
3164 // Determine the minimum number of sign bits across all input vectors.
3165 // Early out if the result is already 1.
3166 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3167 for (unsigned i = 1, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i)
3168 Tmp = std::min(Tmp, ComputeNumSignBits(Op.getOperand(i), Depth + 1));
3172 // If we are looking at the loaded value of the SDNode.
3173 if (Op.getResNo() == 0) {
3174 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3175 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3176 unsigned ExtType = LD->getExtensionType();
3179 case ISD::SEXTLOAD: // '17' bits known
3180 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3181 return VTBits-Tmp+1;
3182 case ISD::ZEXTLOAD: // '16' bits known
3183 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3189 // Allow the target to implement this method for its nodes.
3190 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3191 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3192 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3193 Op.getOpcode() == ISD::INTRINSIC_VOID) {
3195 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3197 FirstAnswer = std::max(FirstAnswer, NumBits);
3200 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3201 // use this information.
3202 APInt KnownZero, KnownOne;
3203 computeKnownBits(Op, KnownZero, KnownOne, DemandedElts, Depth);
3206 if (KnownZero.isNegative()) { // sign bit is 0
3208 } else if (KnownOne.isNegative()) { // sign bit is 1;
3215 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3216 // the number of identical bits in the top of the input value.
3218 Mask <<= Mask.getBitWidth()-VTBits;
3219 // Return # leading zeros. We use 'min' here in case Val was zero before
3220 // shifting. We don't want to return '64' as for an i32 "0".
3221 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3224 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3225 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3226 !isa<ConstantSDNode>(Op.getOperand(1)))
3229 if (Op.getOpcode() == ISD::OR &&
3230 !MaskedValueIsZero(Op.getOperand(0),
3231 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3237 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
3238 // If we're told that NaNs won't happen, assume they won't.
3239 if (getTarget().Options.NoNaNsFPMath)
3242 if (const BinaryWithFlagsSDNode *BF = dyn_cast<BinaryWithFlagsSDNode>(Op))
3243 return BF->Flags.hasNoNaNs();
3245 // If the value is a constant, we can obviously see if it is a NaN or not.
3246 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3247 return !C->getValueAPF().isNaN();
3249 // TODO: Recognize more cases here.
3254 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3255 // If the value is a constant, we can obviously see if it is a zero or not.
3256 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3257 return !C->isZero();
3259 // TODO: Recognize more cases here.
3260 switch (Op.getOpcode()) {
3263 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3264 return !C->isNullValue();
3271 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3272 // Check the obvious case.
3273 if (A == B) return true;
3275 // For for negative and positive zero.
3276 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3277 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3278 if (CA->isZero() && CB->isZero()) return true;
3280 // Otherwise they may not be equal.
3284 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3285 assert(A.getValueType() == B.getValueType() &&
3286 "Values must have the same type");
3289 computeKnownBits(A, AZero, AOne);
3290 computeKnownBits(B, BZero, BOne);
3291 return (AZero | BZero).isAllOnesValue();
3294 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3295 ArrayRef<SDValue> Ops,
3296 llvm::SelectionDAG &DAG) {
3297 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3298 assert(llvm::all_of(Ops,
3300 return Ops[0].getValueType() == Op.getValueType();
3302 "Concatenation of vectors with inconsistent value types!");
3303 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3304 VT.getVectorNumElements() &&
3305 "Incorrect element count in vector concatenation!");
3307 if (Ops.size() == 1)
3310 // Concat of UNDEFs is UNDEF.
3311 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3312 return DAG.getUNDEF(VT);
3314 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3315 // simplified to one big BUILD_VECTOR.
3316 // FIXME: Add support for SCALAR_TO_VECTOR as well.
3317 EVT SVT = VT.getScalarType();
3318 SmallVector<SDValue, 16> Elts;
3319 for (SDValue Op : Ops) {
3320 EVT OpVT = Op.getValueType();
3322 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3323 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3324 Elts.append(Op->op_begin(), Op->op_end());
3329 // BUILD_VECTOR requires all inputs to be of the same type, find the
3330 // maximum type and extend them all.
3331 for (SDValue Op : Elts)
3332 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3334 if (SVT.bitsGT(VT.getScalarType()))
3335 for (SDValue &Op : Elts)
3336 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3337 ? DAG.getZExtOrTrunc(Op, DL, SVT)
3338 : DAG.getSExtOrTrunc(Op, DL, SVT);
3340 return DAG.getBuildVector(VT, DL, Elts);
3343 /// Gets or creates the specified node.
3344 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3345 FoldingSetNodeID ID;
3346 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3348 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3349 return SDValue(E, 0);
3351 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3353 CSEMap.InsertNode(N, IP);
3356 return SDValue(N, 0);
3359 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3361 // Constant fold unary operations with an integer constant operand. Even
3362 // opaque constant will be folded, because the folding of unary operations
3363 // doesn't create new constants with different values. Nevertheless, the
3364 // opaque flag is preserved during folding to prevent future folding with
3366 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3367 const APInt &Val = C->getAPIntValue();
3370 case ISD::SIGN_EXTEND:
3371 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3372 C->isTargetOpcode(), C->isOpaque());
3373 case ISD::ANY_EXTEND:
3374 case ISD::ZERO_EXTEND:
3376 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3377 C->isTargetOpcode(), C->isOpaque());
3378 case ISD::UINT_TO_FP:
3379 case ISD::SINT_TO_FP: {
3380 APFloat apf(EVTToAPFloatSemantics(VT),
3381 APInt::getNullValue(VT.getSizeInBits()));
3382 (void)apf.convertFromAPInt(Val,
3383 Opcode==ISD::SINT_TO_FP,
3384 APFloat::rmNearestTiesToEven);
3385 return getConstantFP(apf, DL, VT);
3388 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3389 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3390 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3391 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3392 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3393 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3394 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3395 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3398 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3400 case ISD::BITREVERSE:
3401 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3404 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3407 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3410 case ISD::CTLZ_ZERO_UNDEF:
3411 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3414 case ISD::CTTZ_ZERO_UNDEF:
3415 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3417 case ISD::FP16_TO_FP: {
3419 APFloat FPV(APFloat::IEEEhalf(),
3420 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3422 // This can return overflow, underflow, or inexact; we don't care.
3423 // FIXME need to be more flexible about rounding mode.
3424 (void)FPV.convert(EVTToAPFloatSemantics(VT),
3425 APFloat::rmNearestTiesToEven, &Ignored);
3426 return getConstantFP(FPV, DL, VT);
3431 // Constant fold unary operations with a floating point constant operand.
3432 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3433 APFloat V = C->getValueAPF(); // make copy
3437 return getConstantFP(V, DL, VT);
3440 return getConstantFP(V, DL, VT);
3442 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3443 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3444 return getConstantFP(V, DL, VT);
3448 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3449 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3450 return getConstantFP(V, DL, VT);
3454 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3455 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3456 return getConstantFP(V, DL, VT);
3459 case ISD::FP_EXTEND: {
3461 // This can return overflow, underflow, or inexact; we don't care.
3462 // FIXME need to be more flexible about rounding mode.
3463 (void)V.convert(EVTToAPFloatSemantics(VT),
3464 APFloat::rmNearestTiesToEven, &ignored);
3465 return getConstantFP(V, DL, VT);
3467 case ISD::FP_TO_SINT:
3468 case ISD::FP_TO_UINT: {
3470 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3471 // FIXME need to be more flexible about rounding mode.
3472 APFloat::opStatus s =
3473 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3474 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3476 return getConstant(IntVal, DL, VT);
3479 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3480 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3481 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3482 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3483 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3484 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3486 case ISD::FP_TO_FP16: {
3488 // This can return overflow, underflow, or inexact; we don't care.
3489 // FIXME need to be more flexible about rounding mode.
3490 (void)V.convert(APFloat::IEEEhalf(),
3491 APFloat::rmNearestTiesToEven, &Ignored);
3492 return getConstant(V.bitcastToAPInt(), DL, VT);
3497 // Constant fold unary operations with a vector integer or float operand.
3498 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3499 if (BV->isConstant()) {
3502 // FIXME: Entirely reasonable to perform folding of other unary
3503 // operations here as the need arises.
3510 case ISD::FP_EXTEND:
3511 case ISD::FP_TO_SINT:
3512 case ISD::FP_TO_UINT:
3514 case ISD::UINT_TO_FP:
3515 case ISD::SINT_TO_FP:
3517 case ISD::BITREVERSE:
3520 case ISD::CTLZ_ZERO_UNDEF:
3522 case ISD::CTTZ_ZERO_UNDEF:
3524 SDValue Ops = { Operand };
3525 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3532 unsigned OpOpcode = Operand.getNode()->getOpcode();
3534 case ISD::TokenFactor:
3535 case ISD::MERGE_VALUES:
3536 case ISD::CONCAT_VECTORS:
3537 return Operand; // Factor, merge or concat of one node? No need.
3538 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3539 case ISD::FP_EXTEND:
3540 assert(VT.isFloatingPoint() &&
3541 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3542 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3543 assert((!VT.isVector() ||
3544 VT.getVectorNumElements() ==
3545 Operand.getValueType().getVectorNumElements()) &&
3546 "Vector element count mismatch!");
3547 assert(Operand.getValueType().bitsLT(VT) &&
3548 "Invalid fpext node, dst < src!");
3549 if (Operand.isUndef())
3550 return getUNDEF(VT);
3552 case ISD::SIGN_EXTEND:
3553 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3554 "Invalid SIGN_EXTEND!");
3555 if (Operand.getValueType() == VT) return Operand; // noop extension
3556 assert((!VT.isVector() ||
3557 VT.getVectorNumElements() ==
3558 Operand.getValueType().getVectorNumElements()) &&
3559 "Vector element count mismatch!");
3560 assert(Operand.getValueType().bitsLT(VT) &&
3561 "Invalid sext node, dst < src!");
3562 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3563 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3564 else if (OpOpcode == ISD::UNDEF)
3565 // sext(undef) = 0, because the top bits will all be the same.
3566 return getConstant(0, DL, VT);
3568 case ISD::ZERO_EXTEND:
3569 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3570 "Invalid ZERO_EXTEND!");
3571 if (Operand.getValueType() == VT) return Operand; // noop extension
3572 assert((!VT.isVector() ||
3573 VT.getVectorNumElements() ==
3574 Operand.getValueType().getVectorNumElements()) &&
3575 "Vector element count mismatch!");
3576 assert(Operand.getValueType().bitsLT(VT) &&
3577 "Invalid zext node, dst < src!");
3578 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3579 return getNode(ISD::ZERO_EXTEND, DL, VT,
3580 Operand.getNode()->getOperand(0));
3581 else if (OpOpcode == ISD::UNDEF)
3582 // zext(undef) = 0, because the top bits will be zero.
3583 return getConstant(0, DL, VT);
3585 case ISD::ANY_EXTEND:
3586 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3587 "Invalid ANY_EXTEND!");
3588 if (Operand.getValueType() == VT) return Operand; // noop extension
3589 assert((!VT.isVector() ||
3590 VT.getVectorNumElements() ==
3591 Operand.getValueType().getVectorNumElements()) &&
3592 "Vector element count mismatch!");
3593 assert(Operand.getValueType().bitsLT(VT) &&
3594 "Invalid anyext node, dst < src!");
3596 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3597 OpOpcode == ISD::ANY_EXTEND)
3598 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3599 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3600 else if (OpOpcode == ISD::UNDEF)
3601 return getUNDEF(VT);
3603 // (ext (trunx x)) -> x
3604 if (OpOpcode == ISD::TRUNCATE) {
3605 SDValue OpOp = Operand.getNode()->getOperand(0);
3606 if (OpOp.getValueType() == VT)
3611 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3612 "Invalid TRUNCATE!");
3613 if (Operand.getValueType() == VT) return Operand; // noop truncate
3614 assert((!VT.isVector() ||
3615 VT.getVectorNumElements() ==
3616 Operand.getValueType().getVectorNumElements()) &&
3617 "Vector element count mismatch!");
3618 assert(Operand.getValueType().bitsGT(VT) &&
3619 "Invalid truncate node, src < dst!");
3620 if (OpOpcode == ISD::TRUNCATE)
3621 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3622 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3623 OpOpcode == ISD::ANY_EXTEND) {
3624 // If the source is smaller than the dest, we still need an extend.
3625 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
3626 .bitsLT(VT.getScalarType()))
3627 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3628 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
3629 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3630 return Operand.getNode()->getOperand(0);
3632 if (OpOpcode == ISD::UNDEF)
3633 return getUNDEF(VT);
3636 assert(VT.isInteger() && VT == Operand.getValueType() &&
3638 if (OpOpcode == ISD::UNDEF)
3639 return getUNDEF(VT);
3642 assert(VT.isInteger() && VT == Operand.getValueType() &&
3644 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3645 "BSWAP types must be a multiple of 16 bits!");
3646 if (OpOpcode == ISD::UNDEF)
3647 return getUNDEF(VT);
3649 case ISD::BITREVERSE:
3650 assert(VT.isInteger() && VT == Operand.getValueType() &&
3651 "Invalid BITREVERSE!");
3652 if (OpOpcode == ISD::UNDEF)
3653 return getUNDEF(VT);
3656 // Basic sanity checking.
3657 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3658 "Cannot BITCAST between types of different sizes!");
3659 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3660 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3661 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3662 if (OpOpcode == ISD::UNDEF)
3663 return getUNDEF(VT);
3665 case ISD::SCALAR_TO_VECTOR:
3666 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3667 (VT.getVectorElementType() == Operand.getValueType() ||
3668 (VT.getVectorElementType().isInteger() &&
3669 Operand.getValueType().isInteger() &&
3670 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3671 "Illegal SCALAR_TO_VECTOR node!");
3672 if (OpOpcode == ISD::UNDEF)
3673 return getUNDEF(VT);
3674 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3675 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3676 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3677 Operand.getConstantOperandVal(1) == 0 &&
3678 Operand.getOperand(0).getValueType() == VT)
3679 return Operand.getOperand(0);
3682 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3683 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3684 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3685 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
3686 Operand.getNode()->getOperand(0),
3687 &cast<BinaryWithFlagsSDNode>(Operand.getNode())->Flags);
3688 if (OpOpcode == ISD::FNEG) // --X -> X
3689 return Operand.getNode()->getOperand(0);
3692 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3693 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
3698 SDVTList VTs = getVTList(VT);
3699 SDValue Ops[] = {Operand};
3700 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3701 FoldingSetNodeID ID;
3702 AddNodeIDNode(ID, Opcode, VTs, Ops);
3704 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3705 return SDValue(E, 0);
3707 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3708 createOperands(N, Ops);
3709 CSEMap.InsertNode(N, IP);
3711 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3712 createOperands(N, Ops);
3716 return SDValue(N, 0);
3719 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3722 case ISD::ADD: return std::make_pair(C1 + C2, true);
3723 case ISD::SUB: return std::make_pair(C1 - C2, true);
3724 case ISD::MUL: return std::make_pair(C1 * C2, true);
3725 case ISD::AND: return std::make_pair(C1 & C2, true);
3726 case ISD::OR: return std::make_pair(C1 | C2, true);
3727 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3728 case ISD::SHL: return std::make_pair(C1 << C2, true);
3729 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3730 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3731 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3732 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3733 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3734 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3735 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3736 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3738 if (!C2.getBoolValue())
3740 return std::make_pair(C1.udiv(C2), true);
3742 if (!C2.getBoolValue())
3744 return std::make_pair(C1.urem(C2), true);
3746 if (!C2.getBoolValue())
3748 return std::make_pair(C1.sdiv(C2), true);
3750 if (!C2.getBoolValue())
3752 return std::make_pair(C1.srem(C2), true);
3754 return std::make_pair(APInt(1, 0), false);
3757 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3758 EVT VT, const ConstantSDNode *Cst1,
3759 const ConstantSDNode *Cst2) {
3760 if (Cst1->isOpaque() || Cst2->isOpaque())
3763 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3764 Cst2->getAPIntValue());
3767 return getConstant(Folded.first, DL, VT);
3770 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3771 const GlobalAddressSDNode *GA,
3773 if (GA->getOpcode() != ISD::GlobalAddress)
3775 if (!TLI->isOffsetFoldingLegal(GA))
3777 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3780 int64_t Offset = Cst2->getSExtValue();
3782 case ISD::ADD: break;
3783 case ISD::SUB: Offset = -uint64_t(Offset); break;
3784 default: return SDValue();
3786 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3787 GA->getOffset() + uint64_t(Offset));
3790 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
3796 // If a divisor is zero/undef or any element of a divisor vector is
3797 // zero/undef, the whole op is undef.
3798 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
3799 SDValue Divisor = Ops[1];
3800 if (Divisor.isUndef() || isNullConstant(Divisor))
3803 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
3804 any_of(Divisor->op_values(),
3805 [](SDValue V) { return V.isUndef() || isNullConstant(V); });
3806 // TODO: Handle signed overflow.
3808 // TODO: Handle oversized shifts.
3814 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3815 EVT VT, SDNode *Cst1,
3817 // If the opcode is a target-specific ISD node, there's nothing we can
3818 // do here and the operand rules may not line up with the below, so
3820 if (Opcode >= ISD::BUILTIN_OP_END)
3823 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
3824 return getUNDEF(VT);
3826 // Handle the case of two scalars.
3827 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3828 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3829 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3830 assert((!Folded || !VT.isVector()) &&
3831 "Can't fold vectors ops with scalar operands");
3836 // fold (add Sym, c) -> Sym+c
3837 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3838 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3839 if (isCommutativeBinOp(Opcode))
3840 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3841 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3843 // For vectors extract each constant element into Inputs so we can constant
3844 // fold them individually.
3845 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3846 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3850 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3852 EVT SVT = VT.getScalarType();
3853 SmallVector<SDValue, 4> Outputs;
3854 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3855 SDValue V1 = BV1->getOperand(I);
3856 SDValue V2 = BV2->getOperand(I);
3858 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3859 // FIXME: This is valid and could be handled by truncation.
3860 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3863 // Fold one vector element.
3864 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
3866 // Scalar folding only succeeded if the result is a constant or UNDEF.
3867 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3868 ScalarResult.getOpcode() != ISD::ConstantFP)
3870 Outputs.push_back(ScalarResult);
3873 assert(VT.getVectorNumElements() == Outputs.size() &&
3874 "Vector size mismatch!");
3876 // We may have a vector type but a scalar result. Create a splat.
3877 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3879 // Build a big vector out of the scalar elements we generated.
3880 return getBuildVector(VT, SDLoc(), Outputs);
3883 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3884 const SDLoc &DL, EVT VT,
3885 ArrayRef<SDValue> Ops,
3886 const SDNodeFlags *Flags) {
3887 // If the opcode is a target-specific ISD node, there's nothing we can
3888 // do here and the operand rules may not line up with the below, so
3890 if (Opcode >= ISD::BUILTIN_OP_END)
3893 if (isUndef(Opcode, Ops))
3894 return getUNDEF(VT);
3896 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3900 unsigned NumElts = VT.getVectorNumElements();
3902 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3903 return !Op.getValueType().isVector() ||
3904 Op.getValueType().getVectorNumElements() == NumElts;
3907 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3908 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3909 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3910 (BV && BV->isConstant());
3913 // All operands must be vector types with the same number of elements as
3914 // the result type and must be either UNDEF or a build vector of constant
3915 // or UNDEF scalars.
3916 if (!all_of(Ops, IsConstantBuildVectorOrUndef) ||
3917 !all_of(Ops, IsScalarOrSameVectorSize))
3920 // If we are comparing vectors, then the result needs to be a i1 boolean
3921 // that is then sign-extended back to the legal result type.
3922 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3924 // Find legal integer scalar type for constant promotion and
3925 // ensure that its scalar size is at least as large as source.
3926 EVT LegalSVT = VT.getScalarType();
3927 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
3928 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3929 if (LegalSVT.bitsLT(VT.getScalarType()))
3933 // Constant fold each scalar lane separately.
3934 SmallVector<SDValue, 4> ScalarResults;
3935 for (unsigned i = 0; i != NumElts; i++) {
3936 SmallVector<SDValue, 4> ScalarOps;
3937 for (SDValue Op : Ops) {
3938 EVT InSVT = Op.getValueType().getScalarType();
3939 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3941 // We've checked that this is UNDEF or a constant of some kind.
3943 ScalarOps.push_back(getUNDEF(InSVT));
3945 ScalarOps.push_back(Op);
3949 SDValue ScalarOp = InBV->getOperand(i);
3950 EVT ScalarVT = ScalarOp.getValueType();
3952 // Build vector (integer) scalar operands may need implicit
3953 // truncation - do this before constant folding.
3954 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
3955 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
3957 ScalarOps.push_back(ScalarOp);
3960 // Constant fold the scalar operands.
3961 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
3963 // Legalize the (integer) scalar constant if necessary.
3964 if (LegalSVT != SVT)
3965 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
3967 // Scalar folding only succeeded if the result is a constant or UNDEF.
3968 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3969 ScalarResult.getOpcode() != ISD::ConstantFP)
3971 ScalarResults.push_back(ScalarResult);
3974 return getBuildVector(VT, DL, ScalarResults);
3977 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3978 SDValue N1, SDValue N2,
3979 const SDNodeFlags *Flags) {
3980 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3981 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3982 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3983 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3985 // Canonicalize constant to RHS if commutative.
3986 if (isCommutativeBinOp(Opcode)) {
3988 std::swap(N1C, N2C);
3990 } else if (N1CFP && !N2CFP) {
3991 std::swap(N1CFP, N2CFP);
3998 case ISD::TokenFactor:
3999 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4000 N2.getValueType() == MVT::Other && "Invalid token factor!");
4001 // Fold trivial token factors.
4002 if (N1.getOpcode() == ISD::EntryToken) return N2;
4003 if (N2.getOpcode() == ISD::EntryToken) return N1;
4004 if (N1 == N2) return N1;
4006 case ISD::CONCAT_VECTORS: {
4007 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4008 SDValue Ops[] = {N1, N2};
4009 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4014 assert(VT.isInteger() && "This operator does not apply to FP types!");
4015 assert(N1.getValueType() == N2.getValueType() &&
4016 N1.getValueType() == VT && "Binary operator types must match!");
4017 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4018 // worth handling here.
4019 if (N2C && N2C->isNullValue())
4021 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4028 assert(VT.isInteger() && "This operator does not apply to FP types!");
4029 assert(N1.getValueType() == N2.getValueType() &&
4030 N1.getValueType() == VT && "Binary operator types must match!");
4031 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4032 // it's worth handling here.
4033 if (N2C && N2C->isNullValue())
4047 assert(VT.isInteger() && "This operator does not apply to FP types!");
4048 assert(N1.getValueType() == N2.getValueType() &&
4049 N1.getValueType() == VT && "Binary operator types must match!");
4056 if (getTarget().Options.UnsafeFPMath) {
4057 if (Opcode == ISD::FADD) {
4059 if (N2CFP && N2CFP->getValueAPF().isZero())
4061 } else if (Opcode == ISD::FSUB) {
4063 if (N2CFP && N2CFP->getValueAPF().isZero())
4065 } else if (Opcode == ISD::FMUL) {
4067 if (N2CFP && N2CFP->isZero())
4070 if (N2CFP && N2CFP->isExactlyValue(1.0))
4074 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4075 assert(N1.getValueType() == N2.getValueType() &&
4076 N1.getValueType() == VT && "Binary operator types must match!");
4078 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4079 assert(N1.getValueType() == VT &&
4080 N1.getValueType().isFloatingPoint() &&
4081 N2.getValueType().isFloatingPoint() &&
4082 "Invalid FCOPYSIGN!");
4089 assert(VT == N1.getValueType() &&
4090 "Shift operators return type must be the same as their first arg");
4091 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4092 "Shifts only work on integers");
4093 assert((!VT.isVector() || VT == N2.getValueType()) &&
4094 "Vector shift amounts must be in the same as their first arg");
4095 // Verify that the shift amount VT is bit enough to hold valid shift
4096 // amounts. This catches things like trying to shift an i1024 value by an
4097 // i8, which is easy to fall into in generic code that uses
4098 // TLI.getShiftAmount().
4099 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4100 "Invalid use of small shift amount with oversized value!");
4102 // Always fold shifts of i1 values so the code generator doesn't need to
4103 // handle them. Since we know the size of the shift has to be less than the
4104 // size of the value, the shift/rotate count is guaranteed to be zero.
4107 if (N2C && N2C->isNullValue())
4110 case ISD::FP_ROUND_INREG: {
4111 EVT EVT = cast<VTSDNode>(N2)->getVT();
4112 assert(VT == N1.getValueType() && "Not an inreg round!");
4113 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4114 "Cannot FP_ROUND_INREG integer types");
4115 assert(EVT.isVector() == VT.isVector() &&
4116 "FP_ROUND_INREG type should be vector iff the operand "
4118 assert((!EVT.isVector() ||
4119 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4120 "Vector element counts must match in FP_ROUND_INREG");
4121 assert(EVT.bitsLE(VT) && "Not rounding down!");
4123 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4127 assert(VT.isFloatingPoint() &&
4128 N1.getValueType().isFloatingPoint() &&
4129 VT.bitsLE(N1.getValueType()) &&
4130 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4131 "Invalid FP_ROUND!");
4132 if (N1.getValueType() == VT) return N1; // noop conversion.
4134 case ISD::AssertSext:
4135 case ISD::AssertZext: {
4136 EVT EVT = cast<VTSDNode>(N2)->getVT();
4137 assert(VT == N1.getValueType() && "Not an inreg extend!");
4138 assert(VT.isInteger() && EVT.isInteger() &&
4139 "Cannot *_EXTEND_INREG FP types");
4140 assert(!EVT.isVector() &&
4141 "AssertSExt/AssertZExt type should be the vector element type "
4142 "rather than the vector type!");
4143 assert(EVT.bitsLE(VT) && "Not extending!");
4144 if (VT == EVT) return N1; // noop assertion.
4147 case ISD::SIGN_EXTEND_INREG: {
4148 EVT EVT = cast<VTSDNode>(N2)->getVT();
4149 assert(VT == N1.getValueType() && "Not an inreg extend!");
4150 assert(VT.isInteger() && EVT.isInteger() &&
4151 "Cannot *_EXTEND_INREG FP types");
4152 assert(EVT.isVector() == VT.isVector() &&
4153 "SIGN_EXTEND_INREG type should be vector iff the operand "
4155 assert((!EVT.isVector() ||
4156 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4157 "Vector element counts must match in SIGN_EXTEND_INREG");
4158 assert(EVT.bitsLE(VT) && "Not extending!");
4159 if (EVT == VT) return N1; // Not actually extending
4161 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4162 unsigned FromBits = EVT.getScalarSizeInBits();
4163 Val <<= Val.getBitWidth() - FromBits;
4164 Val = Val.ashr(Val.getBitWidth() - FromBits);
4165 return getConstant(Val, DL, ConstantVT);
4169 const APInt &Val = N1C->getAPIntValue();
4170 return SignExtendInReg(Val, VT);
4172 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4173 SmallVector<SDValue, 8> Ops;
4174 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4175 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4176 SDValue Op = N1.getOperand(i);
4178 Ops.push_back(getUNDEF(OpVT));
4181 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4182 APInt Val = C->getAPIntValue();
4183 Ops.push_back(SignExtendInReg(Val, OpVT));
4185 return getBuildVector(VT, DL, Ops);
4189 case ISD::EXTRACT_VECTOR_ELT:
4190 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4192 return getUNDEF(VT);
4194 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4195 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4196 return getUNDEF(VT);
4198 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4199 // expanding copies of large vectors from registers.
4201 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4202 N1.getNumOperands() > 0) {
4204 N1.getOperand(0).getValueType().getVectorNumElements();
4205 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4206 N1.getOperand(N2C->getZExtValue() / Factor),
4207 getConstant(N2C->getZExtValue() % Factor, DL,
4208 N2.getValueType()));
4211 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4212 // expanding large vector constants.
4213 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4214 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4216 if (VT != Elt.getValueType())
4217 // If the vector element type is not legal, the BUILD_VECTOR operands
4218 // are promoted and implicitly truncated, and the result implicitly
4219 // extended. Make that explicit here.
4220 Elt = getAnyExtOrTrunc(Elt, DL, VT);
4225 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4226 // operations are lowered to scalars.
4227 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4228 // If the indices are the same, return the inserted element else
4229 // if the indices are known different, extract the element from
4230 // the original vector.
4231 SDValue N1Op2 = N1.getOperand(2);
4232 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4234 if (N1Op2C && N2C) {
4235 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4236 if (VT == N1.getOperand(1).getValueType())
4237 return N1.getOperand(1);
4239 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4242 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4246 case ISD::EXTRACT_ELEMENT:
4247 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4248 assert(!N1.getValueType().isVector() && !VT.isVector() &&
4249 (N1.getValueType().isInteger() == VT.isInteger()) &&
4250 N1.getValueType() != VT &&
4251 "Wrong types for EXTRACT_ELEMENT!");
4253 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4254 // 64-bit integers into 32-bit parts. Instead of building the extract of
4255 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4256 if (N1.getOpcode() == ISD::BUILD_PAIR)
4257 return N1.getOperand(N2C->getZExtValue());
4259 // EXTRACT_ELEMENT of a constant int is also very common.
4261 unsigned ElementSize = VT.getSizeInBits();
4262 unsigned Shift = ElementSize * N2C->getZExtValue();
4263 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4264 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4267 case ISD::EXTRACT_SUBVECTOR:
4268 if (VT.isSimple() && N1.getValueType().isSimple()) {
4269 assert(VT.isVector() && N1.getValueType().isVector() &&
4270 "Extract subvector VTs must be a vectors!");
4271 assert(VT.getVectorElementType() ==
4272 N1.getValueType().getVectorElementType() &&
4273 "Extract subvector VTs must have the same element type!");
4274 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4275 "Extract subvector must be from larger vector to smaller vector!");
4278 assert((VT.getVectorNumElements() + N2C->getZExtValue()
4279 <= N1.getValueType().getVectorNumElements())
4280 && "Extract subvector overflow!");
4283 // Trivial extraction.
4284 if (VT.getSimpleVT() == N1.getSimpleValueType())
4287 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4289 return getUNDEF(VT);
4291 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4292 // the concat have the same type as the extract.
4293 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4294 N1.getNumOperands() > 0 &&
4295 VT == N1.getOperand(0).getValueType()) {
4296 unsigned Factor = VT.getVectorNumElements();
4297 return N1.getOperand(N2C->getZExtValue() / Factor);
4300 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4301 // during shuffle legalization.
4302 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4303 VT == N1.getOperand(1).getValueType())
4304 return N1.getOperand(1);
4309 // Perform trivial constant folding.
4311 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4314 // Constant fold FP operations.
4315 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4318 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4319 APFloat::opStatus s;
4322 s = V1.add(V2, APFloat::rmNearestTiesToEven);
4323 if (!HasFPExceptions || s != APFloat::opInvalidOp)
4324 return getConstantFP(V1, DL, VT);
4327 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4328 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4329 return getConstantFP(V1, DL, VT);
4332 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4333 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4334 return getConstantFP(V1, DL, VT);
4337 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4338 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4339 s!=APFloat::opDivByZero)) {
4340 return getConstantFP(V1, DL, VT);
4345 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4346 s!=APFloat::opDivByZero)) {
4347 return getConstantFP(V1, DL, VT);
4350 case ISD::FCOPYSIGN:
4352 return getConstantFP(V1, DL, VT);
4357 if (Opcode == ISD::FP_ROUND) {
4358 APFloat V = N1CFP->getValueAPF(); // make copy
4360 // This can return overflow, underflow, or inexact; we don't care.
4361 // FIXME need to be more flexible about rounding mode.
4362 (void)V.convert(EVTToAPFloatSemantics(VT),
4363 APFloat::rmNearestTiesToEven, &ignored);
4364 return getConstantFP(V, DL, VT);
4368 // Canonicalize an UNDEF to the RHS, even over a constant.
4370 if (isCommutativeBinOp(Opcode)) {
4374 case ISD::FP_ROUND_INREG:
4375 case ISD::SIGN_EXTEND_INREG:
4381 return N1; // fold op(undef, arg2) -> undef
4389 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
4390 // For vectors, we can't easily build an all zero vector, just return
4397 // Fold a bunch of operators when the RHS is undef.
4402 // Handle undef ^ undef -> 0 special case. This is a common
4404 return getConstant(0, DL, VT);
4414 return N2; // fold op(arg1, undef) -> undef
4420 if (getTarget().Options.UnsafeFPMath)
4428 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
4429 // For vectors, we can't easily build an all zero vector, just return
4434 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
4435 // For vectors, we can't easily build an all one vector, just return
4443 // Memoize this node if possible.
4445 SDVTList VTs = getVTList(VT);
4446 if (VT != MVT::Glue) {
4447 SDValue Ops[] = {N1, N2};
4448 FoldingSetNodeID ID;
4449 AddNodeIDNode(ID, Opcode, VTs, Ops);
4451 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4453 E->intersectFlagsWith(Flags);
4454 return SDValue(E, 0);
4457 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
4458 CSEMap.InsertNode(N, IP);
4460 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
4464 return SDValue(N, 0);
4467 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4468 SDValue N1, SDValue N2, SDValue N3) {
4469 // Perform various simplifications.
4472 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4473 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4474 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4475 if (N1CFP && N2CFP && N3CFP) {
4476 APFloat V1 = N1CFP->getValueAPF();
4477 const APFloat &V2 = N2CFP->getValueAPF();
4478 const APFloat &V3 = N3CFP->getValueAPF();
4479 APFloat::opStatus s =
4480 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4481 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4482 return getConstantFP(V1, DL, VT);
4486 case ISD::CONCAT_VECTORS: {
4487 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4488 SDValue Ops[] = {N1, N2, N3};
4489 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4494 // Use FoldSetCC to simplify SETCC's.
4495 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
4497 // Vector constant folding.
4498 SDValue Ops[] = {N1, N2, N3};
4499 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4504 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
4505 if (N1C->getZExtValue())
4506 return N2; // select true, X, Y -> X
4507 return N3; // select false, X, Y -> Y
4510 if (N2 == N3) return N2; // select C, X, X -> X
4512 case ISD::VECTOR_SHUFFLE:
4513 llvm_unreachable("should use getVectorShuffle constructor!");
4514 case ISD::INSERT_VECTOR_ELT: {
4515 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
4516 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
4517 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4518 return getUNDEF(VT);
4521 case ISD::INSERT_SUBVECTOR: {
4523 if (VT.isSimple() && N1.getValueType().isSimple()
4524 && N2.getValueType().isSimple()) {
4525 assert(VT.isVector() && N1.getValueType().isVector() &&
4526 N2.getValueType().isVector() &&
4527 "Insert subvector VTs must be a vectors");
4528 assert(VT == N1.getValueType() &&
4529 "Dest and insert subvector source types must match!");
4530 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4531 "Insert subvector must be from smaller vector to larger vector!");
4532 if (isa<ConstantSDNode>(Index)) {
4533 assert((N2.getValueType().getVectorNumElements() +
4534 cast<ConstantSDNode>(Index)->getZExtValue()
4535 <= VT.getVectorNumElements())
4536 && "Insert subvector overflow!");
4539 // Trivial insertion.
4540 if (VT.getSimpleVT() == N2.getSimpleValueType())
4546 // Fold bit_convert nodes from a type to themselves.
4547 if (N1.getValueType() == VT)
4552 // Memoize node if it doesn't produce a flag.
4554 SDVTList VTs = getVTList(VT);
4555 SDValue Ops[] = {N1, N2, N3};
4556 if (VT != MVT::Glue) {
4557 FoldingSetNodeID ID;
4558 AddNodeIDNode(ID, Opcode, VTs, Ops);
4560 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4561 return SDValue(E, 0);
4563 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4564 createOperands(N, Ops);
4565 CSEMap.InsertNode(N, IP);
4567 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4568 createOperands(N, Ops);
4572 return SDValue(N, 0);
4575 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4576 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4577 SDValue Ops[] = { N1, N2, N3, N4 };
4578 return getNode(Opcode, DL, VT, Ops);
4581 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4582 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4584 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4585 return getNode(Opcode, DL, VT, Ops);
4588 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4589 /// the incoming stack arguments to be loaded from the stack.
4590 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4591 SmallVector<SDValue, 8> ArgChains;
4593 // Include the original chain at the beginning of the list. When this is
4594 // used by target LowerCall hooks, this helps legalize find the
4595 // CALLSEQ_BEGIN node.
4596 ArgChains.push_back(Chain);
4598 // Add a chain value for each stack argument.
4599 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4600 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4601 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4602 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4603 if (FI->getIndex() < 0)
4604 ArgChains.push_back(SDValue(L, 1));
4606 // Build a tokenfactor for all the chains.
4607 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4610 /// getMemsetValue - Vectorized representation of the memset value
4612 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4614 assert(!Value.isUndef());
4616 unsigned NumBits = VT.getScalarSizeInBits();
4617 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4618 assert(C->getAPIntValue().getBitWidth() == 8);
4619 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4621 return DAG.getConstant(Val, dl, VT);
4622 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4626 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4627 EVT IntVT = VT.getScalarType();
4628 if (!IntVT.isInteger())
4629 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4631 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4633 // Use a multiplication with 0x010101... to extend the input to the
4635 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4636 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4637 DAG.getConstant(Magic, dl, IntVT));
4640 if (VT != Value.getValueType() && !VT.isInteger())
4641 Value = DAG.getBitcast(VT.getScalarType(), Value);
4642 if (VT != Value.getValueType())
4643 Value = DAG.getSplatBuildVector(VT, dl, Value);
4648 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4649 /// used when a memcpy is turned into a memset when the source is a constant
4651 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4652 const TargetLowering &TLI, StringRef Str) {
4653 // Handle vector with all elements zero.
4656 return DAG.getConstant(0, dl, VT);
4657 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4658 return DAG.getConstantFP(0.0, dl, VT);
4659 else if (VT.isVector()) {
4660 unsigned NumElts = VT.getVectorNumElements();
4661 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4662 return DAG.getNode(ISD::BITCAST, dl, VT,
4663 DAG.getConstant(0, dl,
4664 EVT::getVectorVT(*DAG.getContext(),
4667 llvm_unreachable("Expected type!");
4670 assert(!VT.isVector() && "Can't handle vector type here!");
4671 unsigned NumVTBits = VT.getSizeInBits();
4672 unsigned NumVTBytes = NumVTBits / 8;
4673 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
4675 APInt Val(NumVTBits, 0);
4676 if (DAG.getDataLayout().isLittleEndian()) {
4677 for (unsigned i = 0; i != NumBytes; ++i)
4678 Val |= (uint64_t)(unsigned char)Str[i] << i*8;
4680 for (unsigned i = 0; i != NumBytes; ++i)
4681 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
4684 // If the "cost" of materializing the integer immediate is less than the cost
4685 // of a load, then it is cost effective to turn the load into the immediate.
4686 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4687 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4688 return DAG.getConstant(Val, dl, VT);
4689 return SDValue(nullptr, 0);
4692 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4694 EVT VT = Base.getValueType();
4695 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4698 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
4700 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
4701 uint64_t SrcDelta = 0;
4702 GlobalAddressSDNode *G = nullptr;
4703 if (Src.getOpcode() == ISD::GlobalAddress)
4704 G = cast<GlobalAddressSDNode>(Src);
4705 else if (Src.getOpcode() == ISD::ADD &&
4706 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4707 Src.getOperand(1).getOpcode() == ISD::Constant) {
4708 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4709 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4714 return getConstantStringInfo(G->getGlobal(), Str,
4715 SrcDelta + G->getOffset(), false);
4718 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4719 /// Return true if the number of memory ops is below the threshold (Limit).
4720 /// It returns the types of the sequence of memory ops to perform
4721 /// memset / memcpy by reference.
4722 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4723 unsigned Limit, uint64_t Size,
4724 unsigned DstAlign, unsigned SrcAlign,
4729 unsigned DstAS, unsigned SrcAS,
4731 const TargetLowering &TLI) {
4732 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4733 "Expecting memcpy / memset source to meet alignment requirement!");
4734 // If 'SrcAlign' is zero, that means the memory operation does not need to
4735 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4736 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4737 // is the specified alignment of the memory operation. If it is zero, that
4738 // means it's possible to change the alignment of the destination.
4739 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4740 // not need to be loaded.
4741 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4742 IsMemset, ZeroMemset, MemcpyStrSrc,
4743 DAG.getMachineFunction());
4745 if (VT == MVT::Other) {
4746 if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) ||
4747 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) {
4748 VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
4750 switch (DstAlign & 7) {
4751 case 0: VT = MVT::i64; break;
4752 case 4: VT = MVT::i32; break;
4753 case 2: VT = MVT::i16; break;
4754 default: VT = MVT::i8; break;
4759 while (!TLI.isTypeLegal(LVT))
4760 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4761 assert(LVT.isInteger());
4767 unsigned NumMemOps = 0;
4769 unsigned VTSize = VT.getSizeInBits() / 8;
4770 while (VTSize > Size) {
4771 // For now, only use non-vector load / store's for the left-over pieces.
4776 if (VT.isVector() || VT.isFloatingPoint()) {
4777 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4778 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4779 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4781 else if (NewVT == MVT::i64 &&
4782 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4783 TLI.isSafeMemOpType(MVT::f64)) {
4784 // i64 is usually not legal on 32-bit targets, but f64 may be.
4792 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4793 if (NewVT == MVT::i8)
4795 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4797 NewVTSize = NewVT.getSizeInBits() / 8;
4799 // If the new VT cannot cover all of the remaining bits, then consider
4800 // issuing a (or a pair of) unaligned and overlapping load / store.
4801 // FIXME: Only does this for 64-bit or more since we don't have proper
4802 // cost model for unaligned load / store.
4804 if (NumMemOps && AllowOverlap &&
4805 VTSize >= 8 && NewVTSize < Size &&
4806 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4814 if (++NumMemOps > Limit)
4817 MemOps.push_back(VT);
4824 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4825 // On Darwin, -Os means optimize for size without hurting performance, so
4826 // only really optimize for size when -Oz (MinSize) is used.
4827 if (MF.getTarget().getTargetTriple().isOSDarwin())
4828 return MF.getFunction()->optForMinSize();
4829 return MF.getFunction()->optForSize();
4832 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4833 SDValue Chain, SDValue Dst, SDValue Src,
4834 uint64_t Size, unsigned Align,
4835 bool isVol, bool AlwaysInline,
4836 MachinePointerInfo DstPtrInfo,
4837 MachinePointerInfo SrcPtrInfo) {
4838 // Turn a memcpy of undef to nop.
4842 // Expand memcpy to a series of load and store ops if the size operand falls
4843 // below a certain threshold.
4844 // TODO: In the AlwaysInline case, if the size is big then generate a loop
4845 // rather than maybe a humongous number of loads and stores.
4846 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4847 std::vector<EVT> MemOps;
4848 bool DstAlignCanChange = false;
4849 MachineFunction &MF = DAG.getMachineFunction();
4850 MachineFrameInfo &MFI = MF.getFrameInfo();
4851 bool OptSize = shouldLowerMemFuncForSize(MF);
4852 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4853 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4854 DstAlignCanChange = true;
4855 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4856 if (Align > SrcAlign)
4859 bool CopyFromStr = isMemSrcFromString(Src, Str);
4860 bool isZeroStr = CopyFromStr && Str.empty();
4861 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4863 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4864 (DstAlignCanChange ? 0 : Align),
4865 (isZeroStr ? 0 : SrcAlign),
4866 false, false, CopyFromStr, true,
4867 DstPtrInfo.getAddrSpace(),
4868 SrcPtrInfo.getAddrSpace(),
4872 if (DstAlignCanChange) {
4873 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4874 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4876 // Don't promote to an alignment that would require dynamic stack
4878 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4879 if (!TRI->needsStackRealignment(MF))
4880 while (NewAlign > Align &&
4881 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign))
4884 if (NewAlign > Align) {
4885 // Give the stack frame object a larger alignment if needed.
4886 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4887 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4892 MachineMemOperand::Flags MMOFlags =
4893 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4894 SmallVector<SDValue, 8> OutChains;
4895 unsigned NumMemOps = MemOps.size();
4896 uint64_t SrcOff = 0, DstOff = 0;
4897 for (unsigned i = 0; i != NumMemOps; ++i) {
4899 unsigned VTSize = VT.getSizeInBits() / 8;
4900 SDValue Value, Store;
4902 if (VTSize > Size) {
4903 // Issuing an unaligned load / store pair that overlaps with the previous
4904 // pair. Adjust the offset accordingly.
4905 assert(i == NumMemOps-1 && i != 0);
4906 SrcOff -= VTSize - Size;
4907 DstOff -= VTSize - Size;
4911 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
4912 // It's unlikely a store of a vector immediate can be done in a single
4913 // instruction. It would require a load from a constantpool first.
4914 // We only handle zero vectors here.
4915 // FIXME: Handle other cases where store of vector immediate is done in
4916 // a single instruction.
4917 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
4918 if (Value.getNode())
4919 Store = DAG.getStore(Chain, dl, Value,
4920 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4921 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
4924 if (!Store.getNode()) {
4925 // The type might not be legal for the target. This should only happen
4926 // if the type is smaller than a legal type, as on PPC, so the right
4927 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
4928 // to Load/Store if NVT==VT.
4929 // FIXME does the case above also need this?
4930 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4931 assert(NVT.bitsGE(VT));
4932 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4933 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4934 SrcPtrInfo.getWithOffset(SrcOff), VT,
4935 MinAlign(SrcAlign, SrcOff), MMOFlags);
4936 OutChains.push_back(Value.getValue(1));
4937 Store = DAG.getTruncStore(
4938 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4939 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
4941 OutChains.push_back(Store);
4947 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4950 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4951 SDValue Chain, SDValue Dst, SDValue Src,
4952 uint64_t Size, unsigned Align,
4953 bool isVol, bool AlwaysInline,
4954 MachinePointerInfo DstPtrInfo,
4955 MachinePointerInfo SrcPtrInfo) {
4956 // Turn a memmove of undef to nop.
4960 // Expand memmove to a series of load and store ops if the size operand falls
4961 // below a certain threshold.
4962 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4963 std::vector<EVT> MemOps;
4964 bool DstAlignCanChange = false;
4965 MachineFunction &MF = DAG.getMachineFunction();
4966 MachineFrameInfo &MFI = MF.getFrameInfo();
4967 bool OptSize = shouldLowerMemFuncForSize(MF);
4968 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4969 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4970 DstAlignCanChange = true;
4971 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4972 if (Align > SrcAlign)
4974 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
4976 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4977 (DstAlignCanChange ? 0 : Align), SrcAlign,
4978 false, false, false, false,
4979 DstPtrInfo.getAddrSpace(),
4980 SrcPtrInfo.getAddrSpace(),
4984 if (DstAlignCanChange) {
4985 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4986 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4987 if (NewAlign > Align) {
4988 // Give the stack frame object a larger alignment if needed.
4989 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4990 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4995 MachineMemOperand::Flags MMOFlags =
4996 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4997 uint64_t SrcOff = 0, DstOff = 0;
4998 SmallVector<SDValue, 8> LoadValues;
4999 SmallVector<SDValue, 8> LoadChains;
5000 SmallVector<SDValue, 8> OutChains;
5001 unsigned NumMemOps = MemOps.size();
5002 for (unsigned i = 0; i < NumMemOps; i++) {
5004 unsigned VTSize = VT.getSizeInBits() / 8;
5008 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5009 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags);
5010 LoadValues.push_back(Value);
5011 LoadChains.push_back(Value.getValue(1));
5014 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5016 for (unsigned i = 0; i < NumMemOps; i++) {
5018 unsigned VTSize = VT.getSizeInBits() / 8;
5021 Store = DAG.getStore(Chain, dl, LoadValues[i],
5022 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5023 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5024 OutChains.push_back(Store);
5028 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5031 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5034 /// \param DAG Selection DAG where lowered code is placed.
5035 /// \param dl Link to corresponding IR location.
5036 /// \param Chain Control flow dependency.
5037 /// \param Dst Pointer to destination memory location.
5038 /// \param Src Value of byte to write into the memory.
5039 /// \param Size Number of bytes to write.
5040 /// \param Align Alignment of the destination in bytes.
5041 /// \param isVol True if destination is volatile.
5042 /// \param DstPtrInfo IR information on the memory pointer.
5043 /// \returns New head in the control flow, if lowering was successful, empty
5044 /// SDValue otherwise.
5046 /// The function tries to replace 'llvm.memset' intrinsic with several store
5047 /// operations and value calculation code. This is usually profitable for small
5049 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5050 SDValue Chain, SDValue Dst, SDValue Src,
5051 uint64_t Size, unsigned Align, bool isVol,
5052 MachinePointerInfo DstPtrInfo) {
5053 // Turn a memset of undef to nop.
5057 // Expand memset to a series of load/store ops if the size operand
5058 // falls below a certain threshold.
5059 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5060 std::vector<EVT> MemOps;
5061 bool DstAlignCanChange = false;
5062 MachineFunction &MF = DAG.getMachineFunction();
5063 MachineFrameInfo &MFI = MF.getFrameInfo();
5064 bool OptSize = shouldLowerMemFuncForSize(MF);
5065 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5066 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5067 DstAlignCanChange = true;
5069 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5070 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5071 Size, (DstAlignCanChange ? 0 : Align), 0,
5072 true, IsZeroVal, false, true,
5073 DstPtrInfo.getAddrSpace(), ~0u,
5077 if (DstAlignCanChange) {
5078 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5079 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5080 if (NewAlign > Align) {
5081 // Give the stack frame object a larger alignment if needed.
5082 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5083 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5088 SmallVector<SDValue, 8> OutChains;
5089 uint64_t DstOff = 0;
5090 unsigned NumMemOps = MemOps.size();
5092 // Find the largest store and generate the bit pattern for it.
5093 EVT LargestVT = MemOps[0];
5094 for (unsigned i = 1; i < NumMemOps; i++)
5095 if (MemOps[i].bitsGT(LargestVT))
5096 LargestVT = MemOps[i];
5097 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5099 for (unsigned i = 0; i < NumMemOps; i++) {
5101 unsigned VTSize = VT.getSizeInBits() / 8;
5102 if (VTSize > Size) {
5103 // Issuing an unaligned load / store pair that overlaps with the previous
5104 // pair. Adjust the offset accordingly.
5105 assert(i == NumMemOps-1 && i != 0);
5106 DstOff -= VTSize - Size;
5109 // If this store is smaller than the largest store see whether we can get
5110 // the smaller value for free with a truncate.
5111 SDValue Value = MemSetValue;
5112 if (VT.bitsLT(LargestVT)) {
5113 if (!LargestVT.isVector() && !VT.isVector() &&
5114 TLI.isTruncateFree(LargestVT, VT))
5115 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5117 Value = getMemsetValue(Src, VT, DAG, dl);
5119 assert(Value.getValueType() == VT && "Value with wrong type.");
5120 SDValue Store = DAG.getStore(
5121 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5122 DstPtrInfo.getWithOffset(DstOff), Align,
5123 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5124 OutChains.push_back(Store);
5125 DstOff += VT.getSizeInBits() / 8;
5129 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5132 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5134 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5135 // pointer operands can be losslessly bitcasted to pointers of address space 0
5136 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5137 report_fatal_error("cannot lower memory intrinsic in address space " +
5142 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5143 SDValue Src, SDValue Size, unsigned Align,
5144 bool isVol, bool AlwaysInline, bool isTailCall,
5145 MachinePointerInfo DstPtrInfo,
5146 MachinePointerInfo SrcPtrInfo) {
5147 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5149 // Check to see if we should lower the memcpy to loads and stores first.
5150 // For cases within the target-specified limits, this is the best choice.
5151 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5153 // Memcpy with size zero? Just return the original chain.
5154 if (ConstantSize->isNullValue())
5157 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5158 ConstantSize->getZExtValue(),Align,
5159 isVol, false, DstPtrInfo, SrcPtrInfo);
5160 if (Result.getNode())
5164 // Then check to see if we should lower the memcpy with target-specific
5165 // code. If the target chooses to do this, this is the next best.
5167 SDValue Result = TSI->EmitTargetCodeForMemcpy(
5168 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5169 DstPtrInfo, SrcPtrInfo);
5170 if (Result.getNode())
5174 // If we really need inline code and the target declined to provide it,
5175 // use a (potentially long) sequence of loads and stores.
5177 assert(ConstantSize && "AlwaysInline requires a constant size!");
5178 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5179 ConstantSize->getZExtValue(), Align, isVol,
5180 true, DstPtrInfo, SrcPtrInfo);
5183 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5184 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5186 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5187 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5188 // respect volatile, so they may do things like read or write memory
5189 // beyond the given memory regions. But fixing this isn't easy, and most
5190 // people don't care.
5192 // Emit a library call.
5193 TargetLowering::ArgListTy Args;
5194 TargetLowering::ArgListEntry Entry;
5195 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5196 Entry.Node = Dst; Args.push_back(Entry);
5197 Entry.Node = Src; Args.push_back(Entry);
5198 Entry.Node = Size; Args.push_back(Entry);
5199 // FIXME: pass in SDLoc
5200 TargetLowering::CallLoweringInfo CLI(*this);
5203 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5204 Dst.getValueType().getTypeForEVT(*getContext()),
5205 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5206 TLI->getPointerTy(getDataLayout())),
5209 .setTailCall(isTailCall);
5211 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5212 return CallResult.second;
5215 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5216 SDValue Src, SDValue Size, unsigned Align,
5217 bool isVol, bool isTailCall,
5218 MachinePointerInfo DstPtrInfo,
5219 MachinePointerInfo SrcPtrInfo) {
5220 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5222 // Check to see if we should lower the memmove to loads and stores first.
5223 // For cases within the target-specified limits, this is the best choice.
5224 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5226 // Memmove with size zero? Just return the original chain.
5227 if (ConstantSize->isNullValue())
5231 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5232 ConstantSize->getZExtValue(), Align, isVol,
5233 false, DstPtrInfo, SrcPtrInfo);
5234 if (Result.getNode())
5238 // Then check to see if we should lower the memmove with target-specific
5239 // code. If the target chooses to do this, this is the next best.
5241 SDValue Result = TSI->EmitTargetCodeForMemmove(
5242 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5243 if (Result.getNode())
5247 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5248 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5250 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5251 // not be safe. See memcpy above for more details.
5253 // Emit a library call.
5254 TargetLowering::ArgListTy Args;
5255 TargetLowering::ArgListEntry Entry;
5256 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5257 Entry.Node = Dst; Args.push_back(Entry);
5258 Entry.Node = Src; Args.push_back(Entry);
5259 Entry.Node = Size; Args.push_back(Entry);
5260 // FIXME: pass in SDLoc
5261 TargetLowering::CallLoweringInfo CLI(*this);
5264 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5265 Dst.getValueType().getTypeForEVT(*getContext()),
5266 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5267 TLI->getPointerTy(getDataLayout())),
5270 .setTailCall(isTailCall);
5272 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5273 return CallResult.second;
5276 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5277 SDValue Src, SDValue Size, unsigned Align,
5278 bool isVol, bool isTailCall,
5279 MachinePointerInfo DstPtrInfo) {
5280 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5282 // Check to see if we should lower the memset to stores first.
5283 // For cases within the target-specified limits, this is the best choice.
5284 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5286 // Memset with size zero? Just return the original chain.
5287 if (ConstantSize->isNullValue())
5291 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5292 Align, isVol, DstPtrInfo);
5294 if (Result.getNode())
5298 // Then check to see if we should lower the memset with target-specific
5299 // code. If the target chooses to do this, this is the next best.
5301 SDValue Result = TSI->EmitTargetCodeForMemset(
5302 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5303 if (Result.getNode())
5307 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5309 // Emit a library call.
5310 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5311 TargetLowering::ArgListTy Args;
5312 TargetLowering::ArgListEntry Entry;
5313 Entry.Node = Dst; Entry.Ty = IntPtrTy;
5314 Args.push_back(Entry);
5316 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5317 Args.push_back(Entry);
5319 Entry.Ty = IntPtrTy;
5320 Args.push_back(Entry);
5322 // FIXME: pass in SDLoc
5323 TargetLowering::CallLoweringInfo CLI(*this);
5326 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5327 Dst.getValueType().getTypeForEVT(*getContext()),
5328 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5329 TLI->getPointerTy(getDataLayout())),
5332 .setTailCall(isTailCall);
5334 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5335 return CallResult.second;
5338 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5339 SDVTList VTList, ArrayRef<SDValue> Ops,
5340 MachineMemOperand *MMO) {
5341 FoldingSetNodeID ID;
5342 ID.AddInteger(MemVT.getRawBits());
5343 AddNodeIDNode(ID, Opcode, VTList, Ops);
5344 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5346 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5347 cast<AtomicSDNode>(E)->refineAlignment(MMO);
5348 return SDValue(E, 0);
5351 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5352 VTList, MemVT, MMO);
5353 createOperands(N, Ops);
5355 CSEMap.InsertNode(N, IP);
5357 return SDValue(N, 0);
5360 SDValue SelectionDAG::getAtomicCmpSwap(
5361 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5362 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5363 unsigned Alignment, AtomicOrdering SuccessOrdering,
5364 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
5365 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5366 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5367 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5369 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5370 Alignment = getEVTAlignment(MemVT);
5372 MachineFunction &MF = getMachineFunction();
5374 // FIXME: Volatile isn't really correct; we should keep track of atomic
5375 // orderings in the memoperand.
5376 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5377 MachineMemOperand::MOStore;
5378 MachineMemOperand *MMO =
5379 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5380 AAMDNodes(), nullptr, SynchScope, SuccessOrdering,
5383 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5386 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5387 EVT MemVT, SDVTList VTs, SDValue Chain,
5388 SDValue Ptr, SDValue Cmp, SDValue Swp,
5389 MachineMemOperand *MMO) {
5390 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5391 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5392 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5394 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5395 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5398 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5399 SDValue Chain, SDValue Ptr, SDValue Val,
5400 const Value *PtrVal, unsigned Alignment,
5401 AtomicOrdering Ordering,
5402 SynchronizationScope SynchScope) {
5403 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5404 Alignment = getEVTAlignment(MemVT);
5406 MachineFunction &MF = getMachineFunction();
5407 // An atomic store does not load. An atomic load does not store.
5408 // (An atomicrmw obviously both loads and stores.)
5409 // For now, atomics are considered to be volatile always, and they are
5411 // FIXME: Volatile isn't really correct; we should keep track of atomic
5412 // orderings in the memoperand.
5413 auto Flags = MachineMemOperand::MOVolatile;
5414 if (Opcode != ISD::ATOMIC_STORE)
5415 Flags |= MachineMemOperand::MOLoad;
5416 if (Opcode != ISD::ATOMIC_LOAD)
5417 Flags |= MachineMemOperand::MOStore;
5419 MachineMemOperand *MMO =
5420 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5421 MemVT.getStoreSize(), Alignment, AAMDNodes(),
5422 nullptr, SynchScope, Ordering);
5424 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5427 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5428 SDValue Chain, SDValue Ptr, SDValue Val,
5429 MachineMemOperand *MMO) {
5430 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5431 Opcode == ISD::ATOMIC_LOAD_SUB ||
5432 Opcode == ISD::ATOMIC_LOAD_AND ||
5433 Opcode == ISD::ATOMIC_LOAD_OR ||
5434 Opcode == ISD::ATOMIC_LOAD_XOR ||
5435 Opcode == ISD::ATOMIC_LOAD_NAND ||
5436 Opcode == ISD::ATOMIC_LOAD_MIN ||
5437 Opcode == ISD::ATOMIC_LOAD_MAX ||
5438 Opcode == ISD::ATOMIC_LOAD_UMIN ||
5439 Opcode == ISD::ATOMIC_LOAD_UMAX ||
5440 Opcode == ISD::ATOMIC_SWAP ||
5441 Opcode == ISD::ATOMIC_STORE) &&
5442 "Invalid Atomic Op");
5444 EVT VT = Val.getValueType();
5446 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5447 getVTList(VT, MVT::Other);
5448 SDValue Ops[] = {Chain, Ptr, Val};
5449 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5452 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5453 EVT VT, SDValue Chain, SDValue Ptr,
5454 MachineMemOperand *MMO) {
5455 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5457 SDVTList VTs = getVTList(VT, MVT::Other);
5458 SDValue Ops[] = {Chain, Ptr};
5459 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5462 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5463 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5464 if (Ops.size() == 1)
5467 SmallVector<EVT, 4> VTs;
5468 VTs.reserve(Ops.size());
5469 for (unsigned i = 0; i < Ops.size(); ++i)
5470 VTs.push_back(Ops[i].getValueType());
5471 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5474 SDValue SelectionDAG::getMemIntrinsicNode(
5475 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5476 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5477 bool ReadMem, bool WriteMem, unsigned Size) {
5478 if (Align == 0) // Ensure that codegen never sees alignment 0
5479 Align = getEVTAlignment(MemVT);
5481 MachineFunction &MF = getMachineFunction();
5482 auto Flags = MachineMemOperand::MONone;
5484 Flags |= MachineMemOperand::MOStore;
5486 Flags |= MachineMemOperand::MOLoad;
5488 Flags |= MachineMemOperand::MOVolatile;
5490 Size = MemVT.getStoreSize();
5491 MachineMemOperand *MMO =
5492 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5494 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5497 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5499 ArrayRef<SDValue> Ops, EVT MemVT,
5500 MachineMemOperand *MMO) {
5501 assert((Opcode == ISD::INTRINSIC_VOID ||
5502 Opcode == ISD::INTRINSIC_W_CHAIN ||
5503 Opcode == ISD::PREFETCH ||
5504 Opcode == ISD::LIFETIME_START ||
5505 Opcode == ISD::LIFETIME_END ||
5506 (Opcode <= INT_MAX &&
5507 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5508 "Opcode is not a memory-accessing opcode!");
5510 // Memoize the node unless it returns a flag.
5511 MemIntrinsicSDNode *N;
5512 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5513 FoldingSetNodeID ID;
5514 AddNodeIDNode(ID, Opcode, VTList, Ops);
5515 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5517 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5518 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5519 return SDValue(E, 0);
5522 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5523 VTList, MemVT, MMO);
5524 createOperands(N, Ops);
5526 CSEMap.InsertNode(N, IP);
5528 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5529 VTList, MemVT, MMO);
5530 createOperands(N, Ops);
5533 return SDValue(N, 0);
5536 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5537 /// MachinePointerInfo record from it. This is particularly useful because the
5538 /// code generator has many cases where it doesn't bother passing in a
5539 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5540 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5541 int64_t Offset = 0) {
5542 // If this is FI+Offset, we can model it.
5543 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5544 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5545 FI->getIndex(), Offset);
5547 // If this is (FI+Offset1)+Offset2, we can model it.
5548 if (Ptr.getOpcode() != ISD::ADD ||
5549 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5550 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5551 return MachinePointerInfo();
5553 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5554 return MachinePointerInfo::getFixedStack(
5555 DAG.getMachineFunction(), FI,
5556 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5559 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5560 /// MachinePointerInfo record from it. This is particularly useful because the
5561 /// code generator has many cases where it doesn't bother passing in a
5562 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5563 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5565 // If the 'Offset' value isn't a constant, we can't handle this.
5566 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5567 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5568 if (OffsetOp.isUndef())
5569 return InferPointerInfo(DAG, Ptr);
5570 return MachinePointerInfo();
5573 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5574 EVT VT, const SDLoc &dl, SDValue Chain,
5575 SDValue Ptr, SDValue Offset,
5576 MachinePointerInfo PtrInfo, EVT MemVT,
5578 MachineMemOperand::Flags MMOFlags,
5579 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5580 assert(Chain.getValueType() == MVT::Other &&
5581 "Invalid chain type");
5582 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5583 Alignment = getEVTAlignment(MemVT);
5585 MMOFlags |= MachineMemOperand::MOLoad;
5586 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5587 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5589 if (PtrInfo.V.isNull())
5590 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5592 MachineFunction &MF = getMachineFunction();
5593 MachineMemOperand *MMO = MF.getMachineMemOperand(
5594 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5595 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5598 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5599 EVT VT, const SDLoc &dl, SDValue Chain,
5600 SDValue Ptr, SDValue Offset, EVT MemVT,
5601 MachineMemOperand *MMO) {
5603 ExtType = ISD::NON_EXTLOAD;
5604 } else if (ExtType == ISD::NON_EXTLOAD) {
5605 assert(VT == MemVT && "Non-extending load from different memory type!");
5608 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5609 "Should only be an extending load, not truncating!");
5610 assert(VT.isInteger() == MemVT.isInteger() &&
5611 "Cannot convert from FP to Int or Int -> FP!");
5612 assert(VT.isVector() == MemVT.isVector() &&
5613 "Cannot use an ext load to convert to or from a vector!");
5614 assert((!VT.isVector() ||
5615 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5616 "Cannot use an ext load to change the number of vector elements!");
5619 bool Indexed = AM != ISD::UNINDEXED;
5620 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5622 SDVTList VTs = Indexed ?
5623 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5624 SDValue Ops[] = { Chain, Ptr, Offset };
5625 FoldingSetNodeID ID;
5626 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5627 ID.AddInteger(MemVT.getRawBits());
5628 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5629 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5630 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5632 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5633 cast<LoadSDNode>(E)->refineAlignment(MMO);
5634 return SDValue(E, 0);
5636 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5637 ExtType, MemVT, MMO);
5638 createOperands(N, Ops);
5640 CSEMap.InsertNode(N, IP);
5642 return SDValue(N, 0);
5645 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5646 SDValue Ptr, MachinePointerInfo PtrInfo,
5648 MachineMemOperand::Flags MMOFlags,
5649 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5650 SDValue Undef = getUNDEF(Ptr.getValueType());
5651 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5652 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5655 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5656 SDValue Ptr, MachineMemOperand *MMO) {
5657 SDValue Undef = getUNDEF(Ptr.getValueType());
5658 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5662 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5663 EVT VT, SDValue Chain, SDValue Ptr,
5664 MachinePointerInfo PtrInfo, EVT MemVT,
5666 MachineMemOperand::Flags MMOFlags,
5667 const AAMDNodes &AAInfo) {
5668 SDValue Undef = getUNDEF(Ptr.getValueType());
5669 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5670 MemVT, Alignment, MMOFlags, AAInfo);
5673 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5674 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5675 MachineMemOperand *MMO) {
5676 SDValue Undef = getUNDEF(Ptr.getValueType());
5677 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5681 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5682 SDValue Base, SDValue Offset,
5683 ISD::MemIndexedMode AM) {
5684 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5685 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5686 // Don't propagate the invariant or dereferenceable flags.
5688 LD->getMemOperand()->getFlags() &
5689 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5690 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5691 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5692 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5696 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5697 SDValue Ptr, MachinePointerInfo PtrInfo,
5699 MachineMemOperand::Flags MMOFlags,
5700 const AAMDNodes &AAInfo) {
5701 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5702 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5703 Alignment = getEVTAlignment(Val.getValueType());
5705 MMOFlags |= MachineMemOperand::MOStore;
5706 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5708 if (PtrInfo.V.isNull())
5709 PtrInfo = InferPointerInfo(*this, Ptr);
5711 MachineFunction &MF = getMachineFunction();
5712 MachineMemOperand *MMO = MF.getMachineMemOperand(
5713 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5714 return getStore(Chain, dl, Val, Ptr, MMO);
5717 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5718 SDValue Ptr, MachineMemOperand *MMO) {
5719 assert(Chain.getValueType() == MVT::Other &&
5720 "Invalid chain type");
5721 EVT VT = Val.getValueType();
5722 SDVTList VTs = getVTList(MVT::Other);
5723 SDValue Undef = getUNDEF(Ptr.getValueType());
5724 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5725 FoldingSetNodeID ID;
5726 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5727 ID.AddInteger(VT.getRawBits());
5728 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5729 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5730 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5732 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5733 cast<StoreSDNode>(E)->refineAlignment(MMO);
5734 return SDValue(E, 0);
5736 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5737 ISD::UNINDEXED, false, VT, MMO);
5738 createOperands(N, Ops);
5740 CSEMap.InsertNode(N, IP);
5742 return SDValue(N, 0);
5745 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5746 SDValue Ptr, MachinePointerInfo PtrInfo,
5747 EVT SVT, unsigned Alignment,
5748 MachineMemOperand::Flags MMOFlags,
5749 const AAMDNodes &AAInfo) {
5750 assert(Chain.getValueType() == MVT::Other &&
5751 "Invalid chain type");
5752 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5753 Alignment = getEVTAlignment(SVT);
5755 MMOFlags |= MachineMemOperand::MOStore;
5756 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5758 if (PtrInfo.V.isNull())
5759 PtrInfo = InferPointerInfo(*this, Ptr);
5761 MachineFunction &MF = getMachineFunction();
5762 MachineMemOperand *MMO = MF.getMachineMemOperand(
5763 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5764 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5767 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5768 SDValue Ptr, EVT SVT,
5769 MachineMemOperand *MMO) {
5770 EVT VT = Val.getValueType();
5772 assert(Chain.getValueType() == MVT::Other &&
5773 "Invalid chain type");
5775 return getStore(Chain, dl, Val, Ptr, MMO);
5777 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5778 "Should only be a truncating store, not extending!");
5779 assert(VT.isInteger() == SVT.isInteger() &&
5780 "Can't do FP-INT conversion!");
5781 assert(VT.isVector() == SVT.isVector() &&
5782 "Cannot use trunc store to convert to or from a vector!");
5783 assert((!VT.isVector() ||
5784 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5785 "Cannot use trunc store to change the number of vector elements!");
5787 SDVTList VTs = getVTList(MVT::Other);
5788 SDValue Undef = getUNDEF(Ptr.getValueType());
5789 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5790 FoldingSetNodeID ID;
5791 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5792 ID.AddInteger(SVT.getRawBits());
5793 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5794 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5795 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5797 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5798 cast<StoreSDNode>(E)->refineAlignment(MMO);
5799 return SDValue(E, 0);
5801 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5802 ISD::UNINDEXED, true, SVT, MMO);
5803 createOperands(N, Ops);
5805 CSEMap.InsertNode(N, IP);
5807 return SDValue(N, 0);
5810 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5811 SDValue Base, SDValue Offset,
5812 ISD::MemIndexedMode AM) {
5813 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5814 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5815 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5816 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5817 FoldingSetNodeID ID;
5818 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5819 ID.AddInteger(ST->getMemoryVT().getRawBits());
5820 ID.AddInteger(ST->getRawSubclassData());
5821 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5823 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5824 return SDValue(E, 0);
5826 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5827 ST->isTruncatingStore(), ST->getMemoryVT(),
5828 ST->getMemOperand());
5829 createOperands(N, Ops);
5831 CSEMap.InsertNode(N, IP);
5833 return SDValue(N, 0);
5836 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5837 SDValue Ptr, SDValue Mask, SDValue Src0,
5838 EVT MemVT, MachineMemOperand *MMO,
5839 ISD::LoadExtType ExtTy, bool isExpanding) {
5841 SDVTList VTs = getVTList(VT, MVT::Other);
5842 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5843 FoldingSetNodeID ID;
5844 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5845 ID.AddInteger(VT.getRawBits());
5846 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5847 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5848 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5850 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5851 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5852 return SDValue(E, 0);
5854 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5855 ExtTy, isExpanding, MemVT, MMO);
5856 createOperands(N, Ops);
5858 CSEMap.InsertNode(N, IP);
5860 return SDValue(N, 0);
5863 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5864 SDValue Val, SDValue Ptr, SDValue Mask,
5865 EVT MemVT, MachineMemOperand *MMO,
5866 bool IsTruncating, bool IsCompressing) {
5867 assert(Chain.getValueType() == MVT::Other &&
5868 "Invalid chain type");
5869 EVT VT = Val.getValueType();
5870 SDVTList VTs = getVTList(MVT::Other);
5871 SDValue Ops[] = { Chain, Ptr, Mask, Val };
5872 FoldingSetNodeID ID;
5873 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5874 ID.AddInteger(VT.getRawBits());
5875 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5876 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5877 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5879 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5880 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5881 return SDValue(E, 0);
5883 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5884 IsTruncating, IsCompressing, MemVT, MMO);
5885 createOperands(N, Ops);
5887 CSEMap.InsertNode(N, IP);
5889 return SDValue(N, 0);
5892 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5893 ArrayRef<SDValue> Ops,
5894 MachineMemOperand *MMO) {
5895 assert(Ops.size() == 5 && "Incompatible number of operands");
5897 FoldingSetNodeID ID;
5898 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5899 ID.AddInteger(VT.getRawBits());
5900 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5901 dl.getIROrder(), VTs, VT, MMO));
5902 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5904 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5905 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5906 return SDValue(E, 0);
5909 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5911 createOperands(N, Ops);
5913 assert(N->getValue().getValueType() == N->getValueType(0) &&
5914 "Incompatible type of the PassThru value in MaskedGatherSDNode");
5915 assert(N->getMask().getValueType().getVectorNumElements() ==
5916 N->getValueType(0).getVectorNumElements() &&
5917 "Vector width mismatch between mask and data");
5918 assert(N->getIndex().getValueType().getVectorNumElements() ==
5919 N->getValueType(0).getVectorNumElements() &&
5920 "Vector width mismatch between index and data");
5922 CSEMap.InsertNode(N, IP);
5924 return SDValue(N, 0);
5927 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
5928 ArrayRef<SDValue> Ops,
5929 MachineMemOperand *MMO) {
5930 assert(Ops.size() == 5 && "Incompatible number of operands");
5932 FoldingSetNodeID ID;
5933 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5934 ID.AddInteger(VT.getRawBits());
5935 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
5936 dl.getIROrder(), VTs, VT, MMO));
5937 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5939 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5940 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
5941 return SDValue(E, 0);
5943 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5945 createOperands(N, Ops);
5947 assert(N->getMask().getValueType().getVectorNumElements() ==
5948 N->getValue().getValueType().getVectorNumElements() &&
5949 "Vector width mismatch between mask and data");
5950 assert(N->getIndex().getValueType().getVectorNumElements() ==
5951 N->getValue().getValueType().getVectorNumElements() &&
5952 "Vector width mismatch between index and data");
5954 CSEMap.InsertNode(N, IP);
5956 return SDValue(N, 0);
5959 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
5960 SDValue Ptr, SDValue SV, unsigned Align) {
5961 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
5962 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
5965 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5966 ArrayRef<SDUse> Ops) {
5967 switch (Ops.size()) {
5968 case 0: return getNode(Opcode, DL, VT);
5969 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
5970 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5971 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5975 // Copy from an SDUse array into an SDValue array for use with
5976 // the regular getNode logic.
5977 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
5978 return getNode(Opcode, DL, VT, NewOps);
5981 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5982 ArrayRef<SDValue> Ops, const SDNodeFlags *Flags) {
5983 unsigned NumOps = Ops.size();
5985 case 0: return getNode(Opcode, DL, VT);
5986 case 1: return getNode(Opcode, DL, VT, Ops[0]);
5987 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
5988 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5994 case ISD::CONCAT_VECTORS: {
5995 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
5996 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
6000 case ISD::SELECT_CC: {
6001 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6002 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6003 "LHS and RHS of condition must have same type!");
6004 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6005 "True and False arms of SelectCC must have same type!");
6006 assert(Ops[2].getValueType() == VT &&
6007 "select_cc node must be of same type as true and false value!");
6011 assert(NumOps == 5 && "BR_CC takes 5 operands!");
6012 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6013 "LHS/RHS of comparison should match types!");
6020 SDVTList VTs = getVTList(VT);
6022 if (VT != MVT::Glue) {
6023 FoldingSetNodeID ID;
6024 AddNodeIDNode(ID, Opcode, VTs, Ops);
6027 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6028 return SDValue(E, 0);
6030 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6031 createOperands(N, Ops);
6033 CSEMap.InsertNode(N, IP);
6035 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6036 createOperands(N, Ops);
6040 return SDValue(N, 0);
6043 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6044 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6045 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6048 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6049 ArrayRef<SDValue> Ops) {
6050 if (VTList.NumVTs == 1)
6051 return getNode(Opcode, DL, VTList.VTs[0], Ops);
6055 // FIXME: figure out how to safely handle things like
6056 // int foo(int x) { return 1 << (x & 255); }
6057 // int bar() { return foo(256); }
6058 case ISD::SRA_PARTS:
6059 case ISD::SRL_PARTS:
6060 case ISD::SHL_PARTS:
6061 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6062 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6063 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6064 else if (N3.getOpcode() == ISD::AND)
6065 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6066 // If the and is only masking out bits that cannot effect the shift,
6067 // eliminate the and.
6068 unsigned NumBits = VT.getScalarSizeInBits()*2;
6069 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6070 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6076 // Memoize the node unless it returns a flag.
6078 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6079 FoldingSetNodeID ID;
6080 AddNodeIDNode(ID, Opcode, VTList, Ops);
6082 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6083 return SDValue(E, 0);
6085 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6086 createOperands(N, Ops);
6087 CSEMap.InsertNode(N, IP);
6089 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6090 createOperands(N, Ops);
6093 return SDValue(N, 0);
6096 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6098 return getNode(Opcode, DL, VTList, None);
6101 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6103 SDValue Ops[] = { N1 };
6104 return getNode(Opcode, DL, VTList, Ops);
6107 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6108 SDValue N1, SDValue N2) {
6109 SDValue Ops[] = { N1, N2 };
6110 return getNode(Opcode, DL, VTList, Ops);
6113 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6114 SDValue N1, SDValue N2, SDValue N3) {
6115 SDValue Ops[] = { N1, N2, N3 };
6116 return getNode(Opcode, DL, VTList, Ops);
6119 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6120 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6121 SDValue Ops[] = { N1, N2, N3, N4 };
6122 return getNode(Opcode, DL, VTList, Ops);
6125 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6126 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6128 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6129 return getNode(Opcode, DL, VTList, Ops);
6132 SDVTList SelectionDAG::getVTList(EVT VT) {
6133 return makeVTList(SDNode::getValueTypeList(VT), 1);
6136 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6137 FoldingSetNodeID ID;
6139 ID.AddInteger(VT1.getRawBits());
6140 ID.AddInteger(VT2.getRawBits());
6143 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6145 EVT *Array = Allocator.Allocate<EVT>(2);
6148 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6149 VTListMap.InsertNode(Result, IP);
6151 return Result->getSDVTList();
6154 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6155 FoldingSetNodeID ID;
6157 ID.AddInteger(VT1.getRawBits());
6158 ID.AddInteger(VT2.getRawBits());
6159 ID.AddInteger(VT3.getRawBits());
6162 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6164 EVT *Array = Allocator.Allocate<EVT>(3);
6168 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6169 VTListMap.InsertNode(Result, IP);
6171 return Result->getSDVTList();
6174 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6175 FoldingSetNodeID ID;
6177 ID.AddInteger(VT1.getRawBits());
6178 ID.AddInteger(VT2.getRawBits());
6179 ID.AddInteger(VT3.getRawBits());
6180 ID.AddInteger(VT4.getRawBits());
6183 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6185 EVT *Array = Allocator.Allocate<EVT>(4);
6190 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6191 VTListMap.InsertNode(Result, IP);
6193 return Result->getSDVTList();
6196 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6197 unsigned NumVTs = VTs.size();
6198 FoldingSetNodeID ID;
6199 ID.AddInteger(NumVTs);
6200 for (unsigned index = 0; index < NumVTs; index++) {
6201 ID.AddInteger(VTs[index].getRawBits());
6205 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6207 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6208 std::copy(VTs.begin(), VTs.end(), Array);
6209 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6210 VTListMap.InsertNode(Result, IP);
6212 return Result->getSDVTList();
6216 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6217 /// specified operands. If the resultant node already exists in the DAG,
6218 /// this does not modify the specified node, instead it returns the node that
6219 /// already exists. If the resultant node does not exist in the DAG, the
6220 /// input node is returned. As a degenerate case, if you specify the same
6221 /// input operands as the node already has, the input node is returned.
6222 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6223 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6225 // Check to see if there is no change.
6226 if (Op == N->getOperand(0)) return N;
6228 // See if the modified node already exists.
6229 void *InsertPos = nullptr;
6230 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6233 // Nope it doesn't. Remove the node from its current place in the maps.
6235 if (!RemoveNodeFromCSEMaps(N))
6236 InsertPos = nullptr;
6238 // Now we update the operands.
6239 N->OperandList[0].set(Op);
6241 // If this gets put into a CSE map, add it.
6242 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6246 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6247 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6249 // Check to see if there is no change.
6250 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6251 return N; // No operands changed, just return the input node.
6253 // See if the modified node already exists.
6254 void *InsertPos = nullptr;
6255 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6258 // Nope it doesn't. Remove the node from its current place in the maps.
6260 if (!RemoveNodeFromCSEMaps(N))
6261 InsertPos = nullptr;
6263 // Now we update the operands.
6264 if (N->OperandList[0] != Op1)
6265 N->OperandList[0].set(Op1);
6266 if (N->OperandList[1] != Op2)
6267 N->OperandList[1].set(Op2);
6269 // If this gets put into a CSE map, add it.
6270 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6274 SDNode *SelectionDAG::
6275 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6276 SDValue Ops[] = { Op1, Op2, Op3 };
6277 return UpdateNodeOperands(N, Ops);
6280 SDNode *SelectionDAG::
6281 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6282 SDValue Op3, SDValue Op4) {
6283 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6284 return UpdateNodeOperands(N, Ops);
6287 SDNode *SelectionDAG::
6288 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6289 SDValue Op3, SDValue Op4, SDValue Op5) {
6290 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6291 return UpdateNodeOperands(N, Ops);
6294 SDNode *SelectionDAG::
6295 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6296 unsigned NumOps = Ops.size();
6297 assert(N->getNumOperands() == NumOps &&
6298 "Update with wrong number of operands");
6300 // If no operands changed just return the input node.
6301 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6304 // See if the modified node already exists.
6305 void *InsertPos = nullptr;
6306 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6309 // Nope it doesn't. Remove the node from its current place in the maps.
6311 if (!RemoveNodeFromCSEMaps(N))
6312 InsertPos = nullptr;
6314 // Now we update the operands.
6315 for (unsigned i = 0; i != NumOps; ++i)
6316 if (N->OperandList[i] != Ops[i])
6317 N->OperandList[i].set(Ops[i]);
6319 // If this gets put into a CSE map, add it.
6320 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6324 /// DropOperands - Release the operands and set this node to have
6326 void SDNode::DropOperands() {
6327 // Unlike the code in MorphNodeTo that does this, we don't need to
6328 // watch for dead nodes here.
6329 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6335 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6338 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6340 SDVTList VTs = getVTList(VT);
6341 return SelectNodeTo(N, MachineOpc, VTs, None);
6344 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6345 EVT VT, SDValue Op1) {
6346 SDVTList VTs = getVTList(VT);
6347 SDValue Ops[] = { Op1 };
6348 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6351 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6352 EVT VT, SDValue Op1,
6354 SDVTList VTs = getVTList(VT);
6355 SDValue Ops[] = { Op1, Op2 };
6356 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6359 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6360 EVT VT, SDValue Op1,
6361 SDValue Op2, SDValue Op3) {
6362 SDVTList VTs = getVTList(VT);
6363 SDValue Ops[] = { Op1, Op2, Op3 };
6364 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6367 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6368 EVT VT, ArrayRef<SDValue> Ops) {
6369 SDVTList VTs = getVTList(VT);
6370 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6373 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6374 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6375 SDVTList VTs = getVTList(VT1, VT2);
6376 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6379 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6381 SDVTList VTs = getVTList(VT1, VT2);
6382 return SelectNodeTo(N, MachineOpc, VTs, None);
6385 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6386 EVT VT1, EVT VT2, EVT VT3,
6387 ArrayRef<SDValue> Ops) {
6388 SDVTList VTs = getVTList(VT1, VT2, VT3);
6389 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6392 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6394 SDValue Op1, SDValue Op2) {
6395 SDVTList VTs = getVTList(VT1, VT2);
6396 SDValue Ops[] = { Op1, Op2 };
6397 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6401 SDVTList VTs,ArrayRef<SDValue> Ops) {
6402 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6403 // Reset the NodeID to -1.
6406 ReplaceAllUsesWith(N, New);
6412 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6413 /// the line number information on the merged node since it is not possible to
6414 /// preserve the information that operation is associated with multiple lines.
6415 /// This will make the debugger working better at -O0, were there is a higher
6416 /// probability having other instructions associated with that line.
6418 /// For IROrder, we keep the smaller of the two
6419 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6420 DebugLoc NLoc = N->getDebugLoc();
6421 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6422 N->setDebugLoc(DebugLoc());
6424 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6425 N->setIROrder(Order);
6429 /// MorphNodeTo - This *mutates* the specified node to have the specified
6430 /// return type, opcode, and operands.
6432 /// Note that MorphNodeTo returns the resultant node. If there is already a
6433 /// node of the specified opcode and operands, it returns that node instead of
6434 /// the current one. Note that the SDLoc need not be the same.
6436 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6437 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6438 /// node, and because it doesn't require CSE recalculation for any of
6439 /// the node's users.
6441 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6442 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6443 /// the legalizer which maintain worklists that would need to be updated when
6444 /// deleting things.
6445 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6446 SDVTList VTs, ArrayRef<SDValue> Ops) {
6447 // If an identical node already exists, use it.
6449 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6450 FoldingSetNodeID ID;
6451 AddNodeIDNode(ID, Opc, VTs, Ops);
6452 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6453 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6456 if (!RemoveNodeFromCSEMaps(N))
6459 // Start the morphing.
6461 N->ValueList = VTs.VTs;
6462 N->NumValues = VTs.NumVTs;
6464 // Clear the operands list, updating used nodes to remove this from their
6465 // use list. Keep track of any operands that become dead as a result.
6466 SmallPtrSet<SDNode*, 16> DeadNodeSet;
6467 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6469 SDNode *Used = Use.getNode();
6471 if (Used->use_empty())
6472 DeadNodeSet.insert(Used);
6475 // For MachineNode, initialize the memory references information.
6476 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6477 MN->setMemRefs(nullptr, nullptr);
6479 // Swap for an appropriately sized array from the recycler.
6481 createOperands(N, Ops);
6483 // Delete any nodes that are still dead after adding the uses for the
6485 if (!DeadNodeSet.empty()) {
6486 SmallVector<SDNode *, 16> DeadNodes;
6487 for (SDNode *N : DeadNodeSet)
6489 DeadNodes.push_back(N);
6490 RemoveDeadNodes(DeadNodes);
6494 CSEMap.InsertNode(N, IP); // Memoize the new node.
6499 /// getMachineNode - These are used for target selectors to create a new node
6500 /// with specified return type(s), MachineInstr opcode, and operands.
6502 /// Note that getMachineNode returns the resultant node. If there is already a
6503 /// node of the specified opcode and operands, it returns that node instead of
6504 /// the current one.
6505 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6507 SDVTList VTs = getVTList(VT);
6508 return getMachineNode(Opcode, dl, VTs, None);
6511 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6512 EVT VT, SDValue Op1) {
6513 SDVTList VTs = getVTList(VT);
6514 SDValue Ops[] = { Op1 };
6515 return getMachineNode(Opcode, dl, VTs, Ops);
6518 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6519 EVT VT, SDValue Op1, SDValue Op2) {
6520 SDVTList VTs = getVTList(VT);
6521 SDValue Ops[] = { Op1, Op2 };
6522 return getMachineNode(Opcode, dl, VTs, Ops);
6525 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6526 EVT VT, SDValue Op1, SDValue Op2,
6528 SDVTList VTs = getVTList(VT);
6529 SDValue Ops[] = { Op1, Op2, Op3 };
6530 return getMachineNode(Opcode, dl, VTs, Ops);
6533 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6534 EVT VT, ArrayRef<SDValue> Ops) {
6535 SDVTList VTs = getVTList(VT);
6536 return getMachineNode(Opcode, dl, VTs, Ops);
6539 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6540 EVT VT1, EVT VT2, SDValue Op1,
6542 SDVTList VTs = getVTList(VT1, VT2);
6543 SDValue Ops[] = { Op1, Op2 };
6544 return getMachineNode(Opcode, dl, VTs, Ops);
6547 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6548 EVT VT1, EVT VT2, SDValue Op1,
6549 SDValue Op2, SDValue Op3) {
6550 SDVTList VTs = getVTList(VT1, VT2);
6551 SDValue Ops[] = { Op1, Op2, Op3 };
6552 return getMachineNode(Opcode, dl, VTs, Ops);
6555 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6557 ArrayRef<SDValue> Ops) {
6558 SDVTList VTs = getVTList(VT1, VT2);
6559 return getMachineNode(Opcode, dl, VTs, Ops);
6562 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6563 EVT VT1, EVT VT2, EVT VT3,
6564 SDValue Op1, SDValue Op2) {
6565 SDVTList VTs = getVTList(VT1, VT2, VT3);
6566 SDValue Ops[] = { Op1, Op2 };
6567 return getMachineNode(Opcode, dl, VTs, Ops);
6570 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6571 EVT VT1, EVT VT2, EVT VT3,
6572 SDValue Op1, SDValue Op2,
6574 SDVTList VTs = getVTList(VT1, VT2, VT3);
6575 SDValue Ops[] = { Op1, Op2, Op3 };
6576 return getMachineNode(Opcode, dl, VTs, Ops);
6579 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6580 EVT VT1, EVT VT2, EVT VT3,
6581 ArrayRef<SDValue> Ops) {
6582 SDVTList VTs = getVTList(VT1, VT2, VT3);
6583 return getMachineNode(Opcode, dl, VTs, Ops);
6586 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6587 ArrayRef<EVT> ResultTys,
6588 ArrayRef<SDValue> Ops) {
6589 SDVTList VTs = getVTList(ResultTys);
6590 return getMachineNode(Opcode, dl, VTs, Ops);
6593 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6595 ArrayRef<SDValue> Ops) {
6596 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6601 FoldingSetNodeID ID;
6602 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6604 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6605 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6609 // Allocate a new MachineSDNode.
6610 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6611 createOperands(N, Ops);
6614 CSEMap.InsertNode(N, IP);
6620 /// getTargetExtractSubreg - A convenience function for creating
6621 /// TargetOpcode::EXTRACT_SUBREG nodes.
6622 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6624 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6625 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6626 VT, Operand, SRIdxVal);
6627 return SDValue(Subreg, 0);
6630 /// getTargetInsertSubreg - A convenience function for creating
6631 /// TargetOpcode::INSERT_SUBREG nodes.
6632 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6633 SDValue Operand, SDValue Subreg) {
6634 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6635 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6636 VT, Operand, Subreg, SRIdxVal);
6637 return SDValue(Result, 0);
6640 /// getNodeIfExists - Get the specified node if it's already available, or
6641 /// else return NULL.
6642 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6643 ArrayRef<SDValue> Ops,
6644 const SDNodeFlags *Flags) {
6645 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6646 FoldingSetNodeID ID;
6647 AddNodeIDNode(ID, Opcode, VTList, Ops);
6649 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6651 E->intersectFlagsWith(Flags);
6658 /// getDbgValue - Creates a SDDbgValue node.
6661 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6662 unsigned R, bool IsIndirect, uint64_t Off,
6663 const DebugLoc &DL, unsigned O) {
6664 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6665 "Expected inlined-at fields to agree");
6666 return new (DbgInfo->getAlloc())
6667 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6671 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6672 const Value *C, uint64_t Off,
6673 const DebugLoc &DL, unsigned O) {
6674 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6675 "Expected inlined-at fields to agree");
6676 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6680 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6681 unsigned FI, uint64_t Off,
6684 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6685 "Expected inlined-at fields to agree");
6686 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6691 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6692 /// pointed to by a use iterator is deleted, increment the use iterator
6693 /// so that it doesn't dangle.
6695 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6696 SDNode::use_iterator &UI;
6697 SDNode::use_iterator &UE;
6699 void NodeDeleted(SDNode *N, SDNode *E) override {
6700 // Increment the iterator as needed.
6701 while (UI != UE && N == *UI)
6706 RAUWUpdateListener(SelectionDAG &d,
6707 SDNode::use_iterator &ui,
6708 SDNode::use_iterator &ue)
6709 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6714 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6715 /// This can cause recursive merging of nodes in the DAG.
6717 /// This version assumes From has a single result value.
6719 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6720 SDNode *From = FromN.getNode();
6721 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6722 "Cannot replace with this method!");
6723 assert(From != To.getNode() && "Cannot replace uses of with self");
6725 // Preserve Debug Values
6726 TransferDbgValues(FromN, To);
6728 // Iterate over all the existing uses of From. New uses will be added
6729 // to the beginning of the use list, which we avoid visiting.
6730 // This specifically avoids visiting uses of From that arise while the
6731 // replacement is happening, because any such uses would be the result
6732 // of CSE: If an existing node looks like From after one of its operands
6733 // is replaced by To, we don't want to replace of all its users with To
6734 // too. See PR3018 for more info.
6735 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6736 RAUWUpdateListener Listener(*this, UI, UE);
6740 // This node is about to morph, remove its old self from the CSE maps.
6741 RemoveNodeFromCSEMaps(User);
6743 // A user can appear in a use list multiple times, and when this
6744 // happens the uses are usually next to each other in the list.
6745 // To help reduce the number of CSE recomputations, process all
6746 // the uses of this user that we can find this way.
6748 SDUse &Use = UI.getUse();
6751 } while (UI != UE && *UI == User);
6753 // Now that we have modified User, add it back to the CSE maps. If it
6754 // already exists there, recursively merge the results together.
6755 AddModifiedNodeToCSEMaps(User);
6759 // If we just RAUW'd the root, take note.
6760 if (FromN == getRoot())
6764 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6765 /// This can cause recursive merging of nodes in the DAG.
6767 /// This version assumes that for each value of From, there is a
6768 /// corresponding value in To in the same position with the same type.
6770 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6772 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6773 assert((!From->hasAnyUseOfValue(i) ||
6774 From->getValueType(i) == To->getValueType(i)) &&
6775 "Cannot use this version of ReplaceAllUsesWith!");
6778 // Handle the trivial case.
6782 // Preserve Debug Info. Only do this if there's a use.
6783 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6784 if (From->hasAnyUseOfValue(i)) {
6785 assert((i < To->getNumValues()) && "Invalid To location");
6786 TransferDbgValues(SDValue(From, i), SDValue(To, i));
6789 // Iterate over just the existing users of From. See the comments in
6790 // the ReplaceAllUsesWith above.
6791 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6792 RAUWUpdateListener Listener(*this, UI, UE);
6796 // This node is about to morph, remove its old self from the CSE maps.
6797 RemoveNodeFromCSEMaps(User);
6799 // A user can appear in a use list multiple times, and when this
6800 // happens the uses are usually next to each other in the list.
6801 // To help reduce the number of CSE recomputations, process all
6802 // the uses of this user that we can find this way.
6804 SDUse &Use = UI.getUse();
6807 } while (UI != UE && *UI == User);
6809 // Now that we have modified User, add it back to the CSE maps. If it
6810 // already exists there, recursively merge the results together.
6811 AddModifiedNodeToCSEMaps(User);
6814 // If we just RAUW'd the root, take note.
6815 if (From == getRoot().getNode())
6816 setRoot(SDValue(To, getRoot().getResNo()));
6819 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6820 /// This can cause recursive merging of nodes in the DAG.
6822 /// This version can replace From with any result values. To must match the
6823 /// number and types of values returned by From.
6824 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6825 if (From->getNumValues() == 1) // Handle the simple case efficiently.
6826 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6828 // Preserve Debug Info.
6829 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6830 TransferDbgValues(SDValue(From, i), *To);
6832 // Iterate over just the existing users of From. See the comments in
6833 // the ReplaceAllUsesWith above.
6834 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6835 RAUWUpdateListener Listener(*this, UI, UE);
6839 // This node is about to morph, remove its old self from the CSE maps.
6840 RemoveNodeFromCSEMaps(User);
6842 // A user can appear in a use list multiple times, and when this
6843 // happens the uses are usually next to each other in the list.
6844 // To help reduce the number of CSE recomputations, process all
6845 // the uses of this user that we can find this way.
6847 SDUse &Use = UI.getUse();
6848 const SDValue &ToOp = To[Use.getResNo()];
6851 } while (UI != UE && *UI == User);
6853 // Now that we have modified User, add it back to the CSE maps. If it
6854 // already exists there, recursively merge the results together.
6855 AddModifiedNodeToCSEMaps(User);
6858 // If we just RAUW'd the root, take note.
6859 if (From == getRoot().getNode())
6860 setRoot(SDValue(To[getRoot().getResNo()]));
6863 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6864 /// uses of other values produced by From.getNode() alone. The Deleted
6865 /// vector is handled the same way as for ReplaceAllUsesWith.
6866 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6867 // Handle the really simple, really trivial case efficiently.
6868 if (From == To) return;
6870 // Handle the simple, trivial, case efficiently.
6871 if (From.getNode()->getNumValues() == 1) {
6872 ReplaceAllUsesWith(From, To);
6876 // Preserve Debug Info.
6877 TransferDbgValues(From, To);
6879 // Iterate over just the existing users of From. See the comments in
6880 // the ReplaceAllUsesWith above.
6881 SDNode::use_iterator UI = From.getNode()->use_begin(),
6882 UE = From.getNode()->use_end();
6883 RAUWUpdateListener Listener(*this, UI, UE);
6886 bool UserRemovedFromCSEMaps = false;
6888 // A user can appear in a use list multiple times, and when this
6889 // happens the uses are usually next to each other in the list.
6890 // To help reduce the number of CSE recomputations, process all
6891 // the uses of this user that we can find this way.
6893 SDUse &Use = UI.getUse();
6895 // Skip uses of different values from the same node.
6896 if (Use.getResNo() != From.getResNo()) {
6901 // If this node hasn't been modified yet, it's still in the CSE maps,
6902 // so remove its old self from the CSE maps.
6903 if (!UserRemovedFromCSEMaps) {
6904 RemoveNodeFromCSEMaps(User);
6905 UserRemovedFromCSEMaps = true;
6910 } while (UI != UE && *UI == User);
6912 // We are iterating over all uses of the From node, so if a use
6913 // doesn't use the specific value, no changes are made.
6914 if (!UserRemovedFromCSEMaps)
6917 // Now that we have modified User, add it back to the CSE maps. If it
6918 // already exists there, recursively merge the results together.
6919 AddModifiedNodeToCSEMaps(User);
6922 // If we just RAUW'd the root, take note.
6923 if (From == getRoot())
6928 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
6929 /// to record information about a use.
6936 /// operator< - Sort Memos by User.
6937 bool operator<(const UseMemo &L, const UseMemo &R) {
6938 return (intptr_t)L.User < (intptr_t)R.User;
6942 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
6943 /// uses of other values produced by From.getNode() alone. The same value
6944 /// may appear in both the From and To list. The Deleted vector is
6945 /// handled the same way as for ReplaceAllUsesWith.
6946 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
6949 // Handle the simple, trivial case efficiently.
6951 return ReplaceAllUsesOfValueWith(*From, *To);
6953 TransferDbgValues(*From, *To);
6955 // Read up all the uses and make records of them. This helps
6956 // processing new uses that are introduced during the
6957 // replacement process.
6958 SmallVector<UseMemo, 4> Uses;
6959 for (unsigned i = 0; i != Num; ++i) {
6960 unsigned FromResNo = From[i].getResNo();
6961 SDNode *FromNode = From[i].getNode();
6962 for (SDNode::use_iterator UI = FromNode->use_begin(),
6963 E = FromNode->use_end(); UI != E; ++UI) {
6964 SDUse &Use = UI.getUse();
6965 if (Use.getResNo() == FromResNo) {
6966 UseMemo Memo = { *UI, i, &Use };
6967 Uses.push_back(Memo);
6972 // Sort the uses, so that all the uses from a given User are together.
6973 std::sort(Uses.begin(), Uses.end());
6975 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
6976 UseIndex != UseIndexEnd; ) {
6977 // We know that this user uses some value of From. If it is the right
6978 // value, update it.
6979 SDNode *User = Uses[UseIndex].User;
6981 // This node is about to morph, remove its old self from the CSE maps.
6982 RemoveNodeFromCSEMaps(User);
6984 // The Uses array is sorted, so all the uses for a given User
6985 // are next to each other in the list.
6986 // To help reduce the number of CSE recomputations, process all
6987 // the uses of this user that we can find this way.
6989 unsigned i = Uses[UseIndex].Index;
6990 SDUse &Use = *Uses[UseIndex].Use;
6994 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
6996 // Now that we have modified User, add it back to the CSE maps. If it
6997 // already exists there, recursively merge the results together.
6998 AddModifiedNodeToCSEMaps(User);
7002 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
7003 /// based on their topological order. It returns the maximum id and a vector
7004 /// of the SDNodes* in assigned order by reference.
7005 unsigned SelectionDAG::AssignTopologicalOrder() {
7007 unsigned DAGSize = 0;
7009 // SortedPos tracks the progress of the algorithm. Nodes before it are
7010 // sorted, nodes after it are unsorted. When the algorithm completes
7011 // it is at the end of the list.
7012 allnodes_iterator SortedPos = allnodes_begin();
7014 // Visit all the nodes. Move nodes with no operands to the front of
7015 // the list immediately. Annotate nodes that do have operands with their
7016 // operand count. Before we do this, the Node Id fields of the nodes
7017 // may contain arbitrary values. After, the Node Id fields for nodes
7018 // before SortedPos will contain the topological sort index, and the
7019 // Node Id fields for nodes At SortedPos and after will contain the
7020 // count of outstanding operands.
7021 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7023 checkForCycles(N, this);
7024 unsigned Degree = N->getNumOperands();
7026 // A node with no uses, add it to the result array immediately.
7027 N->setNodeId(DAGSize++);
7028 allnodes_iterator Q(N);
7030 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7031 assert(SortedPos != AllNodes.end() && "Overran node list");
7034 // Temporarily use the Node Id as scratch space for the degree count.
7035 N->setNodeId(Degree);
7039 // Visit all the nodes. As we iterate, move nodes into sorted order,
7040 // such that by the time the end is reached all nodes will be sorted.
7041 for (SDNode &Node : allnodes()) {
7043 checkForCycles(N, this);
7044 // N is in sorted position, so all its uses have one less operand
7045 // that needs to be sorted.
7046 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7049 unsigned Degree = P->getNodeId();
7050 assert(Degree != 0 && "Invalid node degree");
7053 // All of P's operands are sorted, so P may sorted now.
7054 P->setNodeId(DAGSize++);
7055 if (P->getIterator() != SortedPos)
7056 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7057 assert(SortedPos != AllNodes.end() && "Overran node list");
7060 // Update P's outstanding operand count.
7061 P->setNodeId(Degree);
7064 if (Node.getIterator() == SortedPos) {
7066 allnodes_iterator I(N);
7068 dbgs() << "Overran sorted position:\n";
7069 S->dumprFull(this); dbgs() << "\n";
7070 dbgs() << "Checking if this is due to cycles\n";
7071 checkForCycles(this, true);
7073 llvm_unreachable(nullptr);
7077 assert(SortedPos == AllNodes.end() &&
7078 "Topological sort incomplete!");
7079 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7080 "First node in topological sort is not the entry token!");
7081 assert(AllNodes.front().getNodeId() == 0 &&
7082 "First node in topological sort has non-zero id!");
7083 assert(AllNodes.front().getNumOperands() == 0 &&
7084 "First node in topological sort has operands!");
7085 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7086 "Last node in topologic sort has unexpected id!");
7087 assert(AllNodes.back().use_empty() &&
7088 "Last node in topologic sort has users!");
7089 assert(DAGSize == allnodes_size() && "Node count mismatch!");
7093 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7094 /// value is produced by SD.
7095 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7097 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7098 SD->setHasDebugValue(true);
7100 DbgInfo->add(DB, SD, isParameter);
7103 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
7104 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
7105 if (From == To || !From.getNode()->getHasDebugValue())
7107 SDNode *FromNode = From.getNode();
7108 SDNode *ToNode = To.getNode();
7109 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
7110 SmallVector<SDDbgValue *, 2> ClonedDVs;
7111 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
7113 SDDbgValue *Dbg = *I;
7114 // Only add Dbgvalues attached to same ResNo.
7115 if (Dbg->getKind() == SDDbgValue::SDNODE &&
7116 Dbg->getSDNode() == From.getNode() &&
7117 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
7118 assert(FromNode != ToNode &&
7119 "Should not transfer Debug Values intranode");
7121 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
7122 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
7123 Dbg->getDebugLoc(), Dbg->getOrder());
7124 ClonedDVs.push_back(Clone);
7125 Dbg->setIsInvalidated();
7128 for (SDDbgValue *I : ClonedDVs)
7129 AddDbgValue(I, ToNode, false);
7132 //===----------------------------------------------------------------------===//
7134 //===----------------------------------------------------------------------===//
7136 bool llvm::isNullConstant(SDValue V) {
7137 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7138 return Const != nullptr && Const->isNullValue();
7141 bool llvm::isNullFPConstant(SDValue V) {
7142 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7143 return Const != nullptr && Const->isZero() && !Const->isNegative();
7146 bool llvm::isAllOnesConstant(SDValue V) {
7147 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7148 return Const != nullptr && Const->isAllOnesValue();
7151 bool llvm::isOneConstant(SDValue V) {
7152 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7153 return Const != nullptr && Const->isOne();
7156 bool llvm::isBitwiseNot(SDValue V) {
7157 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7160 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7161 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7164 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7165 BitVector UndefElements;
7166 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7168 // BuildVectors can truncate their operands. Ignore that case here.
7169 // FIXME: We blindly ignore splats which include undef which is overly
7171 if (CN && UndefElements.none() &&
7172 CN->getValueType(0) == N.getValueType().getScalarType())
7179 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7180 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7183 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7184 BitVector UndefElements;
7185 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7187 if (CN && UndefElements.none())
7194 HandleSDNode::~HandleSDNode() {
7198 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7200 const GlobalValue *GA, EVT VT,
7201 int64_t o, unsigned char TF)
7202 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7206 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7207 EVT VT, unsigned SrcAS,
7209 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7210 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7212 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7213 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7214 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7215 MemSDNodeBits.IsVolatile = MMO->isVolatile();
7216 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7217 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7218 MemSDNodeBits.IsInvariant = MMO->isInvariant();
7220 // We check here that the size of the memory operand fits within the size of
7221 // the MMO. This is because the MMO might indicate only a possible address
7222 // range instead of specifying the affected memory addresses precisely.
7223 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7226 /// Profile - Gather unique data for the node.
7228 void SDNode::Profile(FoldingSetNodeID &ID) const {
7229 AddNodeIDNode(ID, this);
7234 std::vector<EVT> VTs;
7237 VTs.reserve(MVT::LAST_VALUETYPE);
7238 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7239 VTs.push_back(MVT((MVT::SimpleValueType)i));
7244 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
7245 static ManagedStatic<EVTArray> SimpleVTArray;
7246 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
7248 /// getValueTypeList - Return a pointer to the specified value type.
7250 const EVT *SDNode::getValueTypeList(EVT VT) {
7251 if (VT.isExtended()) {
7252 sys::SmartScopedLock<true> Lock(*VTMutex);
7253 return &(*EVTs->insert(VT).first);
7255 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7256 "Value type out of range!");
7257 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7261 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7262 /// indicated value. This method ignores uses of other values defined by this
7264 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7265 assert(Value < getNumValues() && "Bad value!");
7267 // TODO: Only iterate over uses of a given value of the node
7268 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7269 if (UI.getUse().getResNo() == Value) {
7276 // Found exactly the right number of uses?
7281 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7282 /// value. This method ignores uses of other values defined by this operation.
7283 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7284 assert(Value < getNumValues() && "Bad value!");
7286 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7287 if (UI.getUse().getResNo() == Value)
7294 /// isOnlyUserOf - Return true if this node is the only use of N.
7296 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7298 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7309 /// Return true if the only users of N are contained in Nodes.
7310 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7312 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7314 if (llvm::any_of(Nodes,
7315 [&User](const SDNode *Node) { return User == Node; }))
7324 /// isOperand - Return true if this node is an operand of N.
7326 bool SDValue::isOperandOf(const SDNode *N) const {
7327 for (const SDValue &Op : N->op_values())
7333 bool SDNode::isOperandOf(const SDNode *N) const {
7334 for (const SDValue &Op : N->op_values())
7335 if (this == Op.getNode())
7340 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7341 /// be a chain) reaches the specified operand without crossing any
7342 /// side-effecting instructions on any chain path. In practice, this looks
7343 /// through token factors and non-volatile loads. In order to remain efficient,
7344 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7346 /// Note that we only need to examine chains when we're searching for
7347 /// side-effects; SelectionDAG requires that all side-effects are represented
7348 /// by chains, even if another operand would force a specific ordering. This
7349 /// constraint is necessary to allow transformations like splitting loads.
7350 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7351 unsigned Depth) const {
7352 if (*this == Dest) return true;
7354 // Don't search too deeply, we just want to be able to see through
7355 // TokenFactor's etc.
7356 if (Depth == 0) return false;
7358 // If this is a token factor, all inputs to the TF happen in parallel.
7359 if (getOpcode() == ISD::TokenFactor) {
7360 // First, try a shallow search.
7361 if (is_contained((*this)->ops(), Dest)) {
7362 // We found the chain we want as an operand of this TokenFactor.
7363 // Essentially, we reach the chain without side-effects if we could
7364 // serialize the TokenFactor into a simple chain of operations with
7365 // Dest as the last operation. This is automatically true if the
7366 // chain has one use: there are no other ordering constraints.
7367 // If the chain has more than one use, we give up: some other
7368 // use of Dest might force a side-effect between Dest and the current
7370 if (Dest.hasOneUse())
7373 // Next, try a deep search: check whether every operand of the TokenFactor
7375 return all_of((*this)->ops(), [=](SDValue Op) {
7376 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7380 // Loads don't have side effects, look through them.
7381 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7382 if (!Ld->isVolatile())
7383 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7388 bool SDNode::hasPredecessor(const SDNode *N) const {
7389 SmallPtrSet<const SDNode *, 32> Visited;
7390 SmallVector<const SDNode *, 16> Worklist;
7391 Worklist.push_back(this);
7392 return hasPredecessorHelper(N, Visited, Worklist);
7395 const SDNodeFlags *SDNode::getFlags() const {
7396 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
7397 return &FlagsNode->Flags;
7401 void SDNode::intersectFlagsWith(const SDNodeFlags *Flags) {
7402 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
7403 FlagsNode->Flags.intersectWith(Flags);
7406 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7407 assert(N->getNumValues() == 1 &&
7408 "Can't unroll a vector with multiple results!");
7410 EVT VT = N->getValueType(0);
7411 unsigned NE = VT.getVectorNumElements();
7412 EVT EltVT = VT.getVectorElementType();
7415 SmallVector<SDValue, 8> Scalars;
7416 SmallVector<SDValue, 4> Operands(N->getNumOperands());
7418 // If ResNE is 0, fully unroll the vector op.
7421 else if (NE > ResNE)
7425 for (i= 0; i != NE; ++i) {
7426 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7427 SDValue Operand = N->getOperand(j);
7428 EVT OperandVT = Operand.getValueType();
7429 if (OperandVT.isVector()) {
7430 // A vector operand; extract a single element.
7431 EVT OperandEltVT = OperandVT.getVectorElementType();
7433 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7434 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7436 // A scalar operand; just use it as is.
7437 Operands[j] = Operand;
7441 switch (N->getOpcode()) {
7443 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7448 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7455 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7456 getShiftAmountOperand(Operands[0].getValueType(),
7459 case ISD::SIGN_EXTEND_INREG:
7460 case ISD::FP_ROUND_INREG: {
7461 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7462 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7464 getValueType(ExtVT)));
7469 for (; i < ResNE; ++i)
7470 Scalars.push_back(getUNDEF(EltVT));
7472 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7473 return getBuildVector(VecVT, dl, Scalars);
7476 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7480 if (LD->isVolatile() || Base->isVolatile())
7482 if (LD->isIndexed() || Base->isIndexed())
7484 if (LD->getChain() != Base->getChain())
7486 EVT VT = LD->getValueType(0);
7487 if (VT.getSizeInBits() / 8 != Bytes)
7490 SDValue Loc = LD->getOperand(1);
7491 SDValue BaseLoc = Base->getOperand(1);
7492 if (Loc.getOpcode() == ISD::FrameIndex) {
7493 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7495 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7496 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7497 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7498 int FS = MFI.getObjectSize(FI);
7499 int BFS = MFI.getObjectSize(BFI);
7500 if (FS != BFS || FS != (int)Bytes) return false;
7501 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
7505 if (isBaseWithConstantOffset(Loc)) {
7506 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
7507 if (Loc.getOperand(0) == BaseLoc) {
7508 // If the base location is a simple address with no offset itself, then
7509 // the second load's first add operand should be the base address.
7510 if (LocOffset == Dist * (int)Bytes)
7512 } else if (isBaseWithConstantOffset(BaseLoc)) {
7513 // The base location itself has an offset, so subtract that value from the
7514 // second load's offset before comparing to distance * size.
7516 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
7517 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
7518 if ((LocOffset - BOffset) == Dist * (int)Bytes)
7523 const GlobalValue *GV1 = nullptr;
7524 const GlobalValue *GV2 = nullptr;
7525 int64_t Offset1 = 0;
7526 int64_t Offset2 = 0;
7527 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7528 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7529 if (isGA1 && isGA2 && GV1 == GV2)
7530 return Offset1 == (Offset2 + Dist*Bytes);
7535 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7536 /// it cannot be inferred.
7537 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7538 // If this is a GlobalAddress + cst, return the alignment.
7539 const GlobalValue *GV;
7540 int64_t GVOffset = 0;
7541 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7542 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7543 KnownBits Known(PtrWidth);
7544 llvm::computeKnownBits(const_cast<GlobalValue *>(GV), Known,
7546 unsigned AlignBits = Known.Zero.countTrailingOnes();
7547 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7549 return MinAlign(Align, GVOffset);
7552 // If this is a direct reference to a stack slot, use information about the
7553 // stack slot's alignment.
7554 int FrameIdx = 1 << 31;
7555 int64_t FrameOffset = 0;
7556 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7557 FrameIdx = FI->getIndex();
7558 } else if (isBaseWithConstantOffset(Ptr) &&
7559 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7561 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7562 FrameOffset = Ptr.getConstantOperandVal(1);
7565 if (FrameIdx != (1 << 31)) {
7566 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7567 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7575 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7576 /// which is split (or expanded) into two not necessarily identical pieces.
7577 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7578 // Currently all types are split in half.
7581 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7583 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
7585 return std::make_pair(LoVT, HiVT);
7588 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7590 std::pair<SDValue, SDValue>
7591 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7593 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7594 N.getValueType().getVectorNumElements() &&
7595 "More vector elements requested than available!");
7597 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7598 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7599 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7600 getConstant(LoVT.getVectorNumElements(), DL,
7601 TLI->getVectorIdxTy(getDataLayout())));
7602 return std::make_pair(Lo, Hi);
7605 void SelectionDAG::ExtractVectorElements(SDValue Op,
7606 SmallVectorImpl<SDValue> &Args,
7607 unsigned Start, unsigned Count) {
7608 EVT VT = Op.getValueType();
7610 Count = VT.getVectorNumElements();
7612 EVT EltVT = VT.getVectorElementType();
7613 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7615 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7616 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7617 Op, getConstant(i, SL, IdxTy)));
7621 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7622 unsigned GlobalAddressSDNode::getAddressSpace() const {
7623 return getGlobal()->getType()->getAddressSpace();
7627 Type *ConstantPoolSDNode::getType() const {
7628 if (isMachineConstantPoolEntry())
7629 return Val.MachineCPVal->getType();
7630 return Val.ConstVal->getType();
7633 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
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 VecWidth = VT.getSizeInBits();
7641 if (MinSplatBits > VecWidth)
7644 // FIXME: The widths are based on this node's type, but build vectors can
7645 // truncate their operands.
7646 SplatValue = APInt(VecWidth, 0);
7647 SplatUndef = APInt(VecWidth, 0);
7649 // Get the bits. Bits with undefined values (when the corresponding element
7650 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7651 // in SplatValue. If any of the values are not constant, give up and return
7653 unsigned int NumOps = getNumOperands();
7654 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
7655 unsigned EltWidth = VT.getScalarSizeInBits();
7657 for (unsigned j = 0; j < NumOps; ++j) {
7658 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
7659 SDValue OpVal = getOperand(i);
7660 unsigned BitPos = j * EltWidth;
7662 if (OpVal.isUndef())
7663 SplatUndef.setBits(BitPos, BitPos + EltWidth);
7664 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
7665 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
7666 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7667 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
7672 // The build_vector is all constants or undefs. Find the smallest element
7673 // size that splats the vector.
7674 HasAnyUndefs = (SplatUndef != 0);
7676 // FIXME: This does not work for vectors with elements less than 8 bits.
7677 while (VecWidth > 8) {
7678 unsigned HalfSize = VecWidth / 2;
7679 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7680 APInt LowValue = SplatValue.trunc(HalfSize);
7681 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7682 APInt LowUndef = SplatUndef.trunc(HalfSize);
7684 // If the two halves do not match (ignoring undef bits), stop here.
7685 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7686 MinSplatBits > HalfSize)
7689 SplatValue = HighValue | LowValue;
7690 SplatUndef = HighUndef & LowUndef;
7692 VecWidth = HalfSize;
7695 SplatBitSize = VecWidth;
7699 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7700 if (UndefElements) {
7701 UndefElements->clear();
7702 UndefElements->resize(getNumOperands());
7705 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7706 SDValue Op = getOperand(i);
7709 (*UndefElements)[i] = true;
7710 } else if (!Splatted) {
7712 } else if (Splatted != Op) {
7718 assert(getOperand(0).isUndef() &&
7719 "Can only have a splat without a constant for all undefs.");
7720 return getOperand(0);
7727 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7728 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7732 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7733 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7737 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7738 uint32_t BitWidth) const {
7739 if (ConstantFPSDNode *CN =
7740 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7742 APSInt IntVal(BitWidth);
7743 const APFloat &APF = CN->getValueAPF();
7744 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7749 return IntVal.exactLogBase2();
7754 bool BuildVectorSDNode::isConstant() const {
7755 for (const SDValue &Op : op_values()) {
7756 unsigned Opc = Op.getOpcode();
7757 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7763 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7764 // Find the first non-undef value in the shuffle mask.
7766 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7769 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7771 // Make sure all remaining elements are either undef or the same as the first
7773 for (int Idx = Mask[i]; i != e; ++i)
7774 if (Mask[i] >= 0 && Mask[i] != Idx)
7779 // \brief Returns the SDNode if it is a constant integer BuildVector
7780 // or constant integer.
7781 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7782 if (isa<ConstantSDNode>(N))
7784 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7786 // Treat a GlobalAddress supporting constant offset folding as a
7787 // constant integer.
7788 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7789 if (GA->getOpcode() == ISD::GlobalAddress &&
7790 TLI->isOffsetFoldingLegal(GA))
7795 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
7796 if (isa<ConstantFPSDNode>(N))
7799 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
7806 static void checkForCyclesHelper(const SDNode *N,
7807 SmallPtrSetImpl<const SDNode*> &Visited,
7808 SmallPtrSetImpl<const SDNode*> &Checked,
7809 const llvm::SelectionDAG *DAG) {
7810 // If this node has already been checked, don't check it again.
7811 if (Checked.count(N))
7814 // If a node has already been visited on this depth-first walk, reject it as
7816 if (!Visited.insert(N).second) {
7817 errs() << "Detected cycle in SelectionDAG\n";
7818 dbgs() << "Offending node:\n";
7819 N->dumprFull(DAG); dbgs() << "\n";
7823 for (const SDValue &Op : N->op_values())
7824 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7831 void llvm::checkForCycles(const llvm::SDNode *N,
7832 const llvm::SelectionDAG *DAG,
7836 #ifdef EXPENSIVE_CHECKS
7838 #endif // EXPENSIVE_CHECKS
7840 assert(N && "Checking nonexistent SDNode");
7841 SmallPtrSet<const SDNode*, 32> visited;
7842 SmallPtrSet<const SDNode*, 32> checked;
7843 checkForCyclesHelper(N, visited, checked, DAG);
7848 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7849 checkForCycles(DAG->getRoot().getNode(), DAG, force);