1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Mutex.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetIntrinsicInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
56 /// makeVTList - Return an instance of the SDVTList struct initialized with the
57 /// specified members.
58 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
59 SDVTList Res = {VTs, NumVTs};
63 // Default null implementations of the callbacks.
64 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
65 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
67 //===----------------------------------------------------------------------===//
68 // ConstantFPSDNode Class
69 //===----------------------------------------------------------------------===//
71 /// isExactlyValue - We don't rely on operator== working on double values, as
72 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
73 /// As such, this method can be used to do an exact bit-for-bit comparison of
74 /// two floating point values.
75 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
76 return getValueAPF().bitwiseIsEqual(V);
79 bool ConstantFPSDNode::isValueValidForType(EVT VT,
81 assert(VT.isFloatingPoint() && "Can only convert between FP types");
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
86 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
87 APFloat::rmNearestTiesToEven,
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
96 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
97 auto *BV = dyn_cast<BuildVectorSDNode>(N);
102 unsigned SplatBitSize;
104 EVT EltVT = N->getValueType(0).getVectorElementType();
105 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs) &&
106 EltVT.getSizeInBits() >= SplatBitSize;
109 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
110 // specializations of the more general isConstantSplatVector()?
112 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
113 // Look through a bit convert.
114 while (N->getOpcode() == ISD::BITCAST)
115 N = N->getOperand(0).getNode();
117 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
119 unsigned i = 0, e = N->getNumOperands();
121 // Skip over all of the undef values.
122 while (i != e && N->getOperand(i).isUndef())
125 // Do not accept an all-undef vector.
126 if (i == e) return false;
128 // Do not accept build_vectors that aren't all constants or which have non-~0
129 // elements. We have to be a bit careful here, as the type of the constant
130 // may not be the same as the type of the vector elements due to type
131 // legalization (the elements are promoted to a legal type for the target and
132 // a vector of a type may be legal when the base element type is not).
133 // We only want to check enough bits to cover the vector elements, because
134 // we care if the resultant vector is all ones, not whether the individual
136 SDValue NotZero = N->getOperand(i);
137 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
138 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
139 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
141 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
142 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
147 // Okay, we have at least one ~0 value, check to see if the rest match or are
148 // undefs. Even with the above element type twiddling, this should be OK, as
149 // the same type legalization should have applied to all the elements.
150 for (++i; i != e; ++i)
151 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
156 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
157 // Look through a bit convert.
158 while (N->getOpcode() == ISD::BITCAST)
159 N = N->getOperand(0).getNode();
161 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
163 bool IsAllUndef = true;
164 for (const SDValue &Op : N->op_values()) {
168 // Do not accept build_vectors that aren't all constants or which have non-0
169 // elements. We have to be a bit careful here, as the type of the constant
170 // may not be the same as the type of the vector elements due to type
171 // legalization (the elements are promoted to a legal type for the target
172 // and a vector of a type may be legal when the base element type is not).
173 // We only want to check enough bits to cover the vector elements, because
174 // we care if the resultant vector is all zeros, not whether the individual
176 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
177 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
178 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
180 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
181 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
187 // Do not accept an all-undef vector.
193 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
194 if (N->getOpcode() != ISD::BUILD_VECTOR)
197 for (const SDValue &Op : N->op_values()) {
200 if (!isa<ConstantSDNode>(Op))
206 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
207 if (N->getOpcode() != ISD::BUILD_VECTOR)
210 for (const SDValue &Op : N->op_values()) {
213 if (!isa<ConstantFPSDNode>(Op))
219 bool ISD::allOperandsUndef(const SDNode *N) {
220 // Return false if the node has no operands.
221 // This is "logically inconsistent" with the definition of "all" but
222 // is probably the desired behavior.
223 if (N->getNumOperands() == 0)
226 for (const SDValue &Op : N->op_values())
233 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
236 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
238 return ISD::SIGN_EXTEND;
240 return ISD::ZERO_EXTEND;
245 llvm_unreachable("Invalid LoadExtType");
248 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
249 // To perform this operation, we just need to swap the L and G bits of the
251 unsigned OldL = (Operation >> 2) & 1;
252 unsigned OldG = (Operation >> 1) & 1;
253 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
254 (OldL << 1) | // New G bit
255 (OldG << 2)); // New L bit.
258 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
259 unsigned Operation = Op;
261 Operation ^= 7; // Flip L, G, E bits, but not U.
263 Operation ^= 15; // Flip all of the condition bits.
265 if (Operation > ISD::SETTRUE2)
266 Operation &= ~8; // Don't let N and U bits get set.
268 return ISD::CondCode(Operation);
272 /// For an integer comparison, return 1 if the comparison is a signed operation
273 /// and 2 if the result is an unsigned comparison. Return zero if the operation
274 /// does not depend on the sign of the input (setne and seteq).
275 static int isSignedOp(ISD::CondCode Opcode) {
277 default: llvm_unreachable("Illegal integer setcc operation!");
279 case ISD::SETNE: return 0;
283 case ISD::SETGE: return 1;
287 case ISD::SETUGE: return 2;
291 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
293 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
294 // Cannot fold a signed integer setcc with an unsigned integer setcc.
295 return ISD::SETCC_INVALID;
297 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
299 // If the N and U bits get set, then the resultant comparison DOES suddenly
300 // care about orderedness, and it is true when ordered.
301 if (Op > ISD::SETTRUE2)
302 Op &= ~16; // Clear the U bit if the N bit is set.
304 // Canonicalize illegal integer setcc's.
305 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
308 return ISD::CondCode(Op);
311 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
313 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
314 // Cannot fold a signed setcc with an unsigned setcc.
315 return ISD::SETCC_INVALID;
317 // Combine all of the condition bits.
318 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
320 // Canonicalize illegal integer setcc's.
324 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
325 case ISD::SETOEQ: // SETEQ & SETU[LG]E
326 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
327 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
328 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
335 //===----------------------------------------------------------------------===//
336 // SDNode Profile Support
337 //===----------------------------------------------------------------------===//
339 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
341 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
345 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
346 /// solely with their pointer.
347 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
348 ID.AddPointer(VTList.VTs);
351 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
353 static void AddNodeIDOperands(FoldingSetNodeID &ID,
354 ArrayRef<SDValue> Ops) {
355 for (auto& Op : Ops) {
356 ID.AddPointer(Op.getNode());
357 ID.AddInteger(Op.getResNo());
361 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
363 static void AddNodeIDOperands(FoldingSetNodeID &ID,
364 ArrayRef<SDUse> Ops) {
365 for (auto& Op : Ops) {
366 ID.AddPointer(Op.getNode());
367 ID.AddInteger(Op.getResNo());
371 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
372 SDVTList VTList, ArrayRef<SDValue> OpList) {
373 AddNodeIDOpcode(ID, OpC);
374 AddNodeIDValueTypes(ID, VTList);
375 AddNodeIDOperands(ID, OpList);
378 /// If this is an SDNode with special info, add this info to the NodeID data.
379 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
380 switch (N->getOpcode()) {
381 case ISD::TargetExternalSymbol:
382 case ISD::ExternalSymbol:
384 llvm_unreachable("Should only be used on nodes with operands");
385 default: break; // Normal nodes don't need extra info.
386 case ISD::TargetConstant:
387 case ISD::Constant: {
388 const ConstantSDNode *C = cast<ConstantSDNode>(N);
389 ID.AddPointer(C->getConstantIntValue());
390 ID.AddBoolean(C->isOpaque());
393 case ISD::TargetConstantFP:
394 case ISD::ConstantFP: {
395 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
398 case ISD::TargetGlobalAddress:
399 case ISD::GlobalAddress:
400 case ISD::TargetGlobalTLSAddress:
401 case ISD::GlobalTLSAddress: {
402 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
403 ID.AddPointer(GA->getGlobal());
404 ID.AddInteger(GA->getOffset());
405 ID.AddInteger(GA->getTargetFlags());
408 case ISD::BasicBlock:
409 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
412 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
414 case ISD::RegisterMask:
415 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
418 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
420 case ISD::FrameIndex:
421 case ISD::TargetFrameIndex:
422 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
425 case ISD::TargetJumpTable:
426 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
427 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
429 case ISD::ConstantPool:
430 case ISD::TargetConstantPool: {
431 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
432 ID.AddInteger(CP->getAlignment());
433 ID.AddInteger(CP->getOffset());
434 if (CP->isMachineConstantPoolEntry())
435 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
437 ID.AddPointer(CP->getConstVal());
438 ID.AddInteger(CP->getTargetFlags());
441 case ISD::TargetIndex: {
442 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
443 ID.AddInteger(TI->getIndex());
444 ID.AddInteger(TI->getOffset());
445 ID.AddInteger(TI->getTargetFlags());
449 const LoadSDNode *LD = cast<LoadSDNode>(N);
450 ID.AddInteger(LD->getMemoryVT().getRawBits());
451 ID.AddInteger(LD->getRawSubclassData());
452 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
456 const StoreSDNode *ST = cast<StoreSDNode>(N);
457 ID.AddInteger(ST->getMemoryVT().getRawBits());
458 ID.AddInteger(ST->getRawSubclassData());
459 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
462 case ISD::ATOMIC_CMP_SWAP:
463 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
464 case ISD::ATOMIC_SWAP:
465 case ISD::ATOMIC_LOAD_ADD:
466 case ISD::ATOMIC_LOAD_SUB:
467 case ISD::ATOMIC_LOAD_AND:
468 case ISD::ATOMIC_LOAD_OR:
469 case ISD::ATOMIC_LOAD_XOR:
470 case ISD::ATOMIC_LOAD_NAND:
471 case ISD::ATOMIC_LOAD_MIN:
472 case ISD::ATOMIC_LOAD_MAX:
473 case ISD::ATOMIC_LOAD_UMIN:
474 case ISD::ATOMIC_LOAD_UMAX:
475 case ISD::ATOMIC_LOAD:
476 case ISD::ATOMIC_STORE: {
477 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
478 ID.AddInteger(AT->getMemoryVT().getRawBits());
479 ID.AddInteger(AT->getRawSubclassData());
480 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
483 case ISD::PREFETCH: {
484 const MemSDNode *PF = cast<MemSDNode>(N);
485 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
488 case ISD::VECTOR_SHUFFLE: {
489 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
490 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
492 ID.AddInteger(SVN->getMaskElt(i));
495 case ISD::TargetBlockAddress:
496 case ISD::BlockAddress: {
497 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
498 ID.AddPointer(BA->getBlockAddress());
499 ID.AddInteger(BA->getOffset());
500 ID.AddInteger(BA->getTargetFlags());
503 } // end switch (N->getOpcode())
505 // Target specific memory nodes could also have address spaces to check.
506 if (N->isTargetMemoryOpcode())
507 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
510 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
512 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
513 AddNodeIDOpcode(ID, N->getOpcode());
514 // Add the return value info.
515 AddNodeIDValueTypes(ID, N->getVTList());
516 // Add the operand info.
517 AddNodeIDOperands(ID, N->ops());
519 // Handle SDNode leafs with special info.
520 AddNodeIDCustom(ID, N);
523 //===----------------------------------------------------------------------===//
524 // SelectionDAG Class
525 //===----------------------------------------------------------------------===//
527 /// doNotCSE - Return true if CSE should not be performed for this node.
528 static bool doNotCSE(SDNode *N) {
529 if (N->getValueType(0) == MVT::Glue)
530 return true; // Never CSE anything that produces a flag.
532 switch (N->getOpcode()) {
534 case ISD::HANDLENODE:
536 return true; // Never CSE these nodes.
539 // Check that remaining values produced are not flags.
540 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
541 if (N->getValueType(i) == MVT::Glue)
542 return true; // Never CSE anything that produces a flag.
547 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
549 void SelectionDAG::RemoveDeadNodes() {
550 // Create a dummy node (which is not added to allnodes), that adds a reference
551 // to the root node, preventing it from being deleted.
552 HandleSDNode Dummy(getRoot());
554 SmallVector<SDNode*, 128> DeadNodes;
556 // Add all obviously-dead nodes to the DeadNodes worklist.
557 for (SDNode &Node : allnodes())
558 if (Node.use_empty())
559 DeadNodes.push_back(&Node);
561 RemoveDeadNodes(DeadNodes);
563 // If the root changed (e.g. it was a dead load, update the root).
564 setRoot(Dummy.getValue());
567 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
568 /// given list, and any nodes that become unreachable as a result.
569 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
571 // Process the worklist, deleting the nodes and adding their uses to the
573 while (!DeadNodes.empty()) {
574 SDNode *N = DeadNodes.pop_back_val();
576 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
577 DUL->NodeDeleted(N, nullptr);
579 // Take the node out of the appropriate CSE map.
580 RemoveNodeFromCSEMaps(N);
582 // Next, brutally remove the operand list. This is safe to do, as there are
583 // no cycles in the graph.
584 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
586 SDNode *Operand = Use.getNode();
589 // Now that we removed this operand, see if there are no uses of it left.
590 if (Operand->use_empty())
591 DeadNodes.push_back(Operand);
598 void SelectionDAG::RemoveDeadNode(SDNode *N){
599 SmallVector<SDNode*, 16> DeadNodes(1, N);
601 // Create a dummy node that adds a reference to the root node, preventing
602 // it from being deleted. (This matters if the root is an operand of the
604 HandleSDNode Dummy(getRoot());
606 RemoveDeadNodes(DeadNodes);
609 void SelectionDAG::DeleteNode(SDNode *N) {
610 // First take this out of the appropriate CSE map.
611 RemoveNodeFromCSEMaps(N);
613 // Finally, remove uses due to operands of this node, remove from the
614 // AllNodes list, and delete the node.
615 DeleteNodeNotInCSEMaps(N);
618 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
619 assert(N->getIterator() != AllNodes.begin() &&
620 "Cannot delete the entry node!");
621 assert(N->use_empty() && "Cannot delete a node that is not dead!");
623 // Drop all of the operands and decrement used node's use counts.
629 void SDDbgInfo::erase(const SDNode *Node) {
630 DbgValMapType::iterator I = DbgValMap.find(Node);
631 if (I == DbgValMap.end())
633 for (auto &Val: I->second)
634 Val->setIsInvalidated();
638 void SelectionDAG::DeallocateNode(SDNode *N) {
639 // If we have operands, deallocate them.
642 // Set the opcode to DELETED_NODE to help catch bugs when node
643 // memory is reallocated.
644 N->NodeType = ISD::DELETED_NODE;
646 NodeAllocator.Deallocate(AllNodes.remove(N));
648 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
649 // them and forget about that node.
654 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
655 static void VerifySDNode(SDNode *N) {
656 switch (N->getOpcode()) {
659 case ISD::BUILD_PAIR: {
660 EVT VT = N->getValueType(0);
661 assert(N->getNumValues() == 1 && "Too many results!");
662 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
663 "Wrong return type!");
664 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
665 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
666 "Mismatched operand types!");
667 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
668 "Wrong operand type!");
669 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
670 "Wrong return type size");
673 case ISD::BUILD_VECTOR: {
674 assert(N->getNumValues() == 1 && "Too many results!");
675 assert(N->getValueType(0).isVector() && "Wrong return type!");
676 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
677 "Wrong number of operands!");
678 EVT EltVT = N->getValueType(0).getVectorElementType();
679 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
680 assert((I->getValueType() == EltVT ||
681 (EltVT.isInteger() && I->getValueType().isInteger() &&
682 EltVT.bitsLE(I->getValueType()))) &&
683 "Wrong operand type!");
684 assert(I->getValueType() == N->getOperand(0).getValueType() &&
685 "Operands must all have the same type");
693 /// \brief Insert a newly allocated node into the DAG.
695 /// Handles insertion into the all nodes list and CSE map, as well as
696 /// verification and other common operations when a new node is allocated.
697 void SelectionDAG::InsertNode(SDNode *N) {
698 AllNodes.push_back(N);
700 N->PersistentId = NextPersistentId++;
705 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
706 /// correspond to it. This is useful when we're about to delete or repurpose
707 /// the node. We don't want future request for structurally identical nodes
708 /// to return N anymore.
709 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
711 switch (N->getOpcode()) {
712 case ISD::HANDLENODE: return false; // noop.
714 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
715 "Cond code doesn't exist!");
716 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
717 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
719 case ISD::ExternalSymbol:
720 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
722 case ISD::TargetExternalSymbol: {
723 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
724 Erased = TargetExternalSymbols.erase(
725 std::pair<std::string,unsigned char>(ESN->getSymbol(),
726 ESN->getTargetFlags()));
729 case ISD::MCSymbol: {
730 auto *MCSN = cast<MCSymbolSDNode>(N);
731 Erased = MCSymbols.erase(MCSN->getMCSymbol());
734 case ISD::VALUETYPE: {
735 EVT VT = cast<VTSDNode>(N)->getVT();
736 if (VT.isExtended()) {
737 Erased = ExtendedValueTypeNodes.erase(VT);
739 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
740 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
745 // Remove it from the CSE Map.
746 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
747 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
748 Erased = CSEMap.RemoveNode(N);
752 // Verify that the node was actually in one of the CSE maps, unless it has a
753 // flag result (which cannot be CSE'd) or is one of the special cases that are
754 // not subject to CSE.
755 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
756 !N->isMachineOpcode() && !doNotCSE(N)) {
759 llvm_unreachable("Node is not in map!");
765 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
766 /// maps and modified in place. Add it back to the CSE maps, unless an identical
767 /// node already exists, in which case transfer all its users to the existing
768 /// node. This transfer can potentially trigger recursive merging.
771 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
772 // For node types that aren't CSE'd, just act as if no identical node
775 SDNode *Existing = CSEMap.GetOrInsertNode(N);
777 // If there was already an existing matching node, use ReplaceAllUsesWith
778 // to replace the dead one with the existing one. This can cause
779 // recursive merging of other unrelated nodes down the line.
780 ReplaceAllUsesWith(N, Existing);
782 // N is now dead. Inform the listeners and delete it.
783 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
784 DUL->NodeDeleted(N, Existing);
785 DeleteNodeNotInCSEMaps(N);
790 // If the node doesn't already exist, we updated it. Inform listeners.
791 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
795 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
796 /// were replaced with those specified. If this node is never memoized,
797 /// return null, otherwise return a pointer to the slot it would take. If a
798 /// node already exists with these operands, the slot will be non-null.
799 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
804 SDValue Ops[] = { Op };
806 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
807 AddNodeIDCustom(ID, N);
808 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
810 if (const SDNodeFlags *Flags = N->getFlags())
811 Node->intersectFlagsWith(Flags);
815 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
816 /// were replaced with those specified. If this node is never memoized,
817 /// return null, otherwise return a pointer to the slot it would take. If a
818 /// node already exists with these operands, the slot will be non-null.
819 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
820 SDValue Op1, SDValue Op2,
825 SDValue Ops[] = { Op1, Op2 };
827 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
828 AddNodeIDCustom(ID, N);
829 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
831 if (const SDNodeFlags *Flags = N->getFlags())
832 Node->intersectFlagsWith(Flags);
837 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
838 /// were replaced with those specified. If this node is never memoized,
839 /// return null, otherwise return a pointer to the slot it would take. If a
840 /// node already exists with these operands, the slot will be non-null.
841 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
847 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
848 AddNodeIDCustom(ID, N);
849 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
851 if (const SDNodeFlags *Flags = N->getFlags())
852 Node->intersectFlagsWith(Flags);
856 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
857 Type *Ty = VT == MVT::iPTR ?
858 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
859 VT.getTypeForEVT(*getContext());
861 return getDataLayout().getABITypeAlignment(Ty);
864 // EntryNode could meaningfully have debug info if we can find it...
865 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
866 : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL),
867 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
868 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false),
869 UpdateListeners(nullptr) {
870 InsertNode(&EntryNode);
871 DbgInfo = new SDDbgInfo();
874 void SelectionDAG::init(MachineFunction &NewMF,
875 OptimizationRemarkEmitter &NewORE) {
878 TLI = getSubtarget().getTargetLowering();
879 TSI = getSubtarget().getSelectionDAGInfo();
880 Context = &MF->getFunction()->getContext();
883 SelectionDAG::~SelectionDAG() {
884 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
886 OperandRecycler.clear(OperandAllocator);
890 void SelectionDAG::allnodes_clear() {
891 assert(&*AllNodes.begin() == &EntryNode);
892 AllNodes.remove(AllNodes.begin());
893 while (!AllNodes.empty())
894 DeallocateNode(&AllNodes.front());
896 NextPersistentId = 0;
900 SDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, const SDLoc &DL,
901 SDVTList VTs, SDValue N1, SDValue N2,
902 const SDNodeFlags *Flags) {
903 SDValue Ops[] = {N1, N2};
905 if (isBinOpWithFlags(Opcode)) {
906 // If no flags were passed in, use a default flags object.
908 if (Flags == nullptr)
911 auto *FN = newSDNode<BinaryWithFlagsSDNode>(Opcode, DL.getIROrder(),
912 DL.getDebugLoc(), VTs, *Flags);
913 createOperands(FN, Ops);
918 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
919 createOperands(N, Ops);
923 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
925 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
927 switch (N->getOpcode()) {
930 case ISD::ConstantFP:
931 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
932 "debug location. Use another overload.");
938 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
939 const SDLoc &DL, void *&InsertPos) {
940 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
942 switch (N->getOpcode()) {
944 case ISD::ConstantFP:
945 // Erase debug location from the node if the node is used at several
946 // different places. Do not propagate one location to all uses as it
947 // will cause a worse single stepping debugging experience.
948 if (N->getDebugLoc() != DL.getDebugLoc())
949 N->setDebugLoc(DebugLoc());
952 // When the node's point of use is located earlier in the instruction
953 // sequence than its prior point of use, update its debug info to the
955 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
956 N->setDebugLoc(DL.getDebugLoc());
963 void SelectionDAG::clear() {
965 OperandRecycler.clear(OperandAllocator);
966 OperandAllocator.Reset();
969 ExtendedValueTypeNodes.clear();
970 ExternalSymbols.clear();
971 TargetExternalSymbols.clear();
973 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
974 static_cast<CondCodeSDNode*>(nullptr));
975 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
976 static_cast<SDNode*>(nullptr));
978 EntryNode.UseList = nullptr;
979 InsertNode(&EntryNode);
980 Root = getEntryNode();
984 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
985 return VT.bitsGT(Op.getValueType()) ?
986 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
987 getNode(ISD::TRUNCATE, DL, VT, Op);
990 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
991 return VT.bitsGT(Op.getValueType()) ?
992 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
993 getNode(ISD::TRUNCATE, DL, VT, Op);
996 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
997 return VT.bitsGT(Op.getValueType()) ?
998 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
999 getNode(ISD::TRUNCATE, DL, VT, Op);
1002 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1004 if (VT.bitsLE(Op.getValueType()))
1005 return getNode(ISD::TRUNCATE, SL, VT, Op);
1007 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1008 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1011 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1012 assert(!VT.isVector() &&
1013 "getZeroExtendInReg should use the vector element type instead of "
1014 "the vector type!");
1015 if (Op.getValueType() == VT) return Op;
1016 unsigned BitWidth = Op.getScalarValueSizeInBits();
1017 APInt Imm = APInt::getLowBitsSet(BitWidth,
1018 VT.getSizeInBits());
1019 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1020 getConstant(Imm, DL, Op.getValueType()));
1023 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1025 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1026 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1027 "The sizes of the input and result must match in order to perform the "
1028 "extend in-register.");
1029 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1030 "The destination vector type must have fewer lanes than the input.");
1031 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1034 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1036 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1037 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1038 "The sizes of the input and result must match in order to perform the "
1039 "extend in-register.");
1040 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1041 "The destination vector type must have fewer lanes than the input.");
1042 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1045 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1047 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1048 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1049 "The sizes of the input and result must match in order to perform the "
1050 "extend in-register.");
1051 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1052 "The destination vector type must have fewer lanes than the input.");
1053 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1056 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1058 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1059 EVT EltVT = VT.getScalarType();
1061 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1062 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1065 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1066 EVT EltVT = VT.getScalarType();
1068 switch (TLI->getBooleanContents(VT)) {
1069 case TargetLowering::ZeroOrOneBooleanContent:
1070 case TargetLowering::UndefinedBooleanContent:
1071 TrueValue = getConstant(1, DL, VT);
1073 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1074 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1078 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1081 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1082 bool isT, bool isO) {
1083 EVT EltVT = VT.getScalarType();
1084 assert((EltVT.getSizeInBits() >= 64 ||
1085 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1086 "getConstant with a uint64_t value that doesn't fit in the type!");
1087 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1090 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1091 bool isT, bool isO) {
1092 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1095 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1096 EVT VT, bool isT, bool isO) {
1097 assert(VT.isInteger() && "Cannot create FP integer constant!");
1099 EVT EltVT = VT.getScalarType();
1100 const ConstantInt *Elt = &Val;
1102 // In some cases the vector type is legal but the element type is illegal and
1103 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1104 // inserted value (the type does not need to match the vector element type).
1105 // Any extra bits introduced will be truncated away.
1106 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1107 TargetLowering::TypePromoteInteger) {
1108 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1109 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1110 Elt = ConstantInt::get(*getContext(), NewVal);
1112 // In other cases the element type is illegal and needs to be expanded, for
1113 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1114 // the value into n parts and use a vector type with n-times the elements.
1115 // Then bitcast to the type requested.
1116 // Legalizing constants too early makes the DAGCombiner's job harder so we
1117 // only legalize if the DAG tells us we must produce legal types.
1118 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1119 TLI->getTypeAction(*getContext(), EltVT) ==
1120 TargetLowering::TypeExpandInteger) {
1121 const APInt &NewVal = Elt->getValue();
1122 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1123 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1124 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1125 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1127 // Check the temporary vector is the correct size. If this fails then
1128 // getTypeToTransformTo() probably returned a type whose size (in bits)
1129 // isn't a power-of-2 factor of the requested type size.
1130 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1132 SmallVector<SDValue, 2> EltParts;
1133 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1134 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1135 .zextOrTrunc(ViaEltSizeInBits), DL,
1136 ViaEltVT, isT, isO));
1139 // EltParts is currently in little endian order. If we actually want
1140 // big-endian order then reverse it now.
1141 if (getDataLayout().isBigEndian())
1142 std::reverse(EltParts.begin(), EltParts.end());
1144 // The elements must be reversed when the element order is different
1145 // to the endianness of the elements (because the BITCAST is itself a
1146 // vector shuffle in this situation). However, we do not need any code to
1147 // perform this reversal because getConstant() is producing a vector
1149 // This situation occurs in MIPS MSA.
1151 SmallVector<SDValue, 8> Ops;
1152 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1153 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1154 return getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1157 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1158 "APInt size does not match type size!");
1159 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1160 FoldingSetNodeID ID;
1161 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1165 SDNode *N = nullptr;
1166 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1168 return SDValue(N, 0);
1171 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1172 CSEMap.InsertNode(N, IP);
1176 SDValue Result(N, 0);
1178 Result = getSplatBuildVector(VT, DL, Result);
1182 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1184 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1187 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1189 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1192 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1193 EVT VT, bool isTarget) {
1194 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1196 EVT EltVT = VT.getScalarType();
1198 // Do the map lookup using the actual bit pattern for the floating point
1199 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1200 // we don't have issues with SNANs.
1201 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1202 FoldingSetNodeID ID;
1203 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1206 SDNode *N = nullptr;
1207 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1209 return SDValue(N, 0);
1212 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1213 CSEMap.InsertNode(N, IP);
1217 SDValue Result(N, 0);
1219 Result = getSplatBuildVector(VT, DL, Result);
1223 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1225 EVT EltVT = VT.getScalarType();
1226 if (EltVT == MVT::f32)
1227 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1228 else if (EltVT == MVT::f64)
1229 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1230 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1231 EltVT == MVT::f16) {
1233 APFloat APF = APFloat(Val);
1234 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1236 return getConstantFP(APF, DL, VT, isTarget);
1238 llvm_unreachable("Unsupported type in getConstantFP");
1241 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1242 EVT VT, int64_t Offset, bool isTargetGA,
1243 unsigned char TargetFlags) {
1244 assert((TargetFlags == 0 || isTargetGA) &&
1245 "Cannot set target flags on target-independent globals");
1247 // Truncate (with sign-extension) the offset value to the pointer size.
1248 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1250 Offset = SignExtend64(Offset, BitWidth);
1253 if (GV->isThreadLocal())
1254 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1256 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1258 FoldingSetNodeID ID;
1259 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1261 ID.AddInteger(Offset);
1262 ID.AddInteger(TargetFlags);
1264 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1265 return SDValue(E, 0);
1267 auto *N = newSDNode<GlobalAddressSDNode>(
1268 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1269 CSEMap.InsertNode(N, IP);
1271 return SDValue(N, 0);
1274 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1275 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1276 FoldingSetNodeID ID;
1277 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1280 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1281 return SDValue(E, 0);
1283 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1284 CSEMap.InsertNode(N, IP);
1286 return SDValue(N, 0);
1289 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1290 unsigned char TargetFlags) {
1291 assert((TargetFlags == 0 || isTarget) &&
1292 "Cannot set target flags on target-independent jump tables");
1293 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1294 FoldingSetNodeID ID;
1295 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1297 ID.AddInteger(TargetFlags);
1299 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1300 return SDValue(E, 0);
1302 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1303 CSEMap.InsertNode(N, IP);
1305 return SDValue(N, 0);
1308 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1309 unsigned Alignment, int Offset,
1311 unsigned char TargetFlags) {
1312 assert((TargetFlags == 0 || isTarget) &&
1313 "Cannot set target flags on target-independent globals");
1315 Alignment = MF->getFunction()->optForSize()
1316 ? getDataLayout().getABITypeAlignment(C->getType())
1317 : getDataLayout().getPrefTypeAlignment(C->getType());
1318 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1319 FoldingSetNodeID ID;
1320 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1321 ID.AddInteger(Alignment);
1322 ID.AddInteger(Offset);
1324 ID.AddInteger(TargetFlags);
1326 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1327 return SDValue(E, 0);
1329 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1331 CSEMap.InsertNode(N, IP);
1333 return SDValue(N, 0);
1337 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1338 unsigned Alignment, int Offset,
1340 unsigned char TargetFlags) {
1341 assert((TargetFlags == 0 || isTarget) &&
1342 "Cannot set target flags on target-independent globals");
1344 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1345 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1346 FoldingSetNodeID ID;
1347 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1348 ID.AddInteger(Alignment);
1349 ID.AddInteger(Offset);
1350 C->addSelectionDAGCSEId(ID);
1351 ID.AddInteger(TargetFlags);
1353 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1354 return SDValue(E, 0);
1356 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1358 CSEMap.InsertNode(N, IP);
1360 return SDValue(N, 0);
1363 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1364 unsigned char TargetFlags) {
1365 FoldingSetNodeID ID;
1366 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1367 ID.AddInteger(Index);
1368 ID.AddInteger(Offset);
1369 ID.AddInteger(TargetFlags);
1371 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1372 return SDValue(E, 0);
1374 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1375 CSEMap.InsertNode(N, IP);
1377 return SDValue(N, 0);
1380 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1381 FoldingSetNodeID ID;
1382 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1385 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1386 return SDValue(E, 0);
1388 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1389 CSEMap.InsertNode(N, IP);
1391 return SDValue(N, 0);
1394 SDValue SelectionDAG::getValueType(EVT VT) {
1395 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1396 ValueTypeNodes.size())
1397 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1399 SDNode *&N = VT.isExtended() ?
1400 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1402 if (N) return SDValue(N, 0);
1403 N = newSDNode<VTSDNode>(VT);
1405 return SDValue(N, 0);
1408 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1409 SDNode *&N = ExternalSymbols[Sym];
1410 if (N) return SDValue(N, 0);
1411 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1413 return SDValue(N, 0);
1416 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1417 SDNode *&N = MCSymbols[Sym];
1419 return SDValue(N, 0);
1420 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1422 return SDValue(N, 0);
1425 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1426 unsigned char TargetFlags) {
1428 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1430 if (N) return SDValue(N, 0);
1431 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1433 return SDValue(N, 0);
1436 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1437 if ((unsigned)Cond >= CondCodeNodes.size())
1438 CondCodeNodes.resize(Cond+1);
1440 if (!CondCodeNodes[Cond]) {
1441 auto *N = newSDNode<CondCodeSDNode>(Cond);
1442 CondCodeNodes[Cond] = N;
1446 return SDValue(CondCodeNodes[Cond], 0);
1449 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1450 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1451 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1453 ShuffleVectorSDNode::commuteMask(M);
1456 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1457 SDValue N2, ArrayRef<int> Mask) {
1458 assert(VT.getVectorNumElements() == Mask.size() &&
1459 "Must have the same number of vector elements as mask elements!");
1460 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1461 "Invalid VECTOR_SHUFFLE");
1463 // Canonicalize shuffle undef, undef -> undef
1464 if (N1.isUndef() && N2.isUndef())
1465 return getUNDEF(VT);
1467 // Validate that all indices in Mask are within the range of the elements
1468 // input to the shuffle.
1469 int NElts = Mask.size();
1470 assert(all_of(Mask, [&](int M) { return M < (NElts * 2); }) &&
1471 "Index out of range");
1473 // Copy the mask so we can do any needed cleanup.
1474 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1476 // Canonicalize shuffle v, v -> v, undef
1479 for (int i = 0; i != NElts; ++i)
1480 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1483 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1485 commuteShuffle(N1, N2, MaskVec);
1487 // If shuffling a splat, try to blend the splat instead. We do this here so
1488 // that even when this arises during lowering we don't have to re-handle it.
1489 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1490 BitVector UndefElements;
1491 SDValue Splat = BV->getSplatValue(&UndefElements);
1495 for (int i = 0; i < NElts; ++i) {
1496 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1499 // If this input comes from undef, mark it as such.
1500 if (UndefElements[MaskVec[i] - Offset]) {
1505 // If we can blend a non-undef lane, use that instead.
1506 if (!UndefElements[i])
1507 MaskVec[i] = i + Offset;
1510 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1511 BlendSplat(N1BV, 0);
1512 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1513 BlendSplat(N2BV, NElts);
1515 // Canonicalize all index into lhs, -> shuffle lhs, undef
1516 // Canonicalize all index into rhs, -> shuffle rhs, undef
1517 bool AllLHS = true, AllRHS = true;
1518 bool N2Undef = N2.isUndef();
1519 for (int i = 0; i != NElts; ++i) {
1520 if (MaskVec[i] >= NElts) {
1525 } else if (MaskVec[i] >= 0) {
1529 if (AllLHS && AllRHS)
1530 return getUNDEF(VT);
1531 if (AllLHS && !N2Undef)
1535 commuteShuffle(N1, N2, MaskVec);
1537 // Reset our undef status after accounting for the mask.
1538 N2Undef = N2.isUndef();
1539 // Re-check whether both sides ended up undef.
1540 if (N1.isUndef() && N2Undef)
1541 return getUNDEF(VT);
1543 // If Identity shuffle return that node.
1544 bool Identity = true, AllSame = true;
1545 for (int i = 0; i != NElts; ++i) {
1546 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1547 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1549 if (Identity && NElts)
1552 // Shuffling a constant splat doesn't change the result.
1556 // Look through any bitcasts. We check that these don't change the number
1557 // (and size) of elements and just changes their types.
1558 while (V.getOpcode() == ISD::BITCAST)
1559 V = V->getOperand(0);
1561 // A splat should always show up as a build vector node.
1562 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1563 BitVector UndefElements;
1564 SDValue Splat = BV->getSplatValue(&UndefElements);
1565 // If this is a splat of an undef, shuffling it is also undef.
1566 if (Splat && Splat.isUndef())
1567 return getUNDEF(VT);
1570 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1572 // We only have a splat which can skip shuffles if there is a splatted
1573 // value and no undef lanes rearranged by the shuffle.
1574 if (Splat && UndefElements.none()) {
1575 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1576 // number of elements match or the value splatted is a zero constant.
1579 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1580 if (C->isNullValue())
1584 // If the shuffle itself creates a splat, build the vector directly.
1585 if (AllSame && SameNumElts) {
1586 EVT BuildVT = BV->getValueType(0);
1587 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1588 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1590 // We may have jumped through bitcasts, so the type of the
1591 // BUILD_VECTOR may not match the type of the shuffle.
1593 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1599 FoldingSetNodeID ID;
1600 SDValue Ops[2] = { N1, N2 };
1601 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1602 for (int i = 0; i != NElts; ++i)
1603 ID.AddInteger(MaskVec[i]);
1606 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1607 return SDValue(E, 0);
1609 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1610 // SDNode doesn't have access to it. This memory will be "leaked" when
1611 // the node is deallocated, but recovered when the NodeAllocator is released.
1612 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1613 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1615 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1616 dl.getDebugLoc(), MaskAlloc);
1617 createOperands(N, Ops);
1619 CSEMap.InsertNode(N, IP);
1621 return SDValue(N, 0);
1624 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1625 MVT VT = SV.getSimpleValueType(0);
1626 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1627 ShuffleVectorSDNode::commuteMask(MaskVec);
1629 SDValue Op0 = SV.getOperand(0);
1630 SDValue Op1 = SV.getOperand(1);
1631 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1634 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1635 FoldingSetNodeID ID;
1636 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1637 ID.AddInteger(RegNo);
1639 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1640 return SDValue(E, 0);
1642 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1643 CSEMap.InsertNode(N, IP);
1645 return SDValue(N, 0);
1648 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1649 FoldingSetNodeID ID;
1650 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1651 ID.AddPointer(RegMask);
1653 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1654 return SDValue(E, 0);
1656 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1657 CSEMap.InsertNode(N, IP);
1659 return SDValue(N, 0);
1662 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1664 FoldingSetNodeID ID;
1665 SDValue Ops[] = { Root };
1666 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1667 ID.AddPointer(Label);
1669 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1670 return SDValue(E, 0);
1672 auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1673 createOperands(N, Ops);
1675 CSEMap.InsertNode(N, IP);
1677 return SDValue(N, 0);
1680 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1683 unsigned char TargetFlags) {
1684 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1686 FoldingSetNodeID ID;
1687 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1689 ID.AddInteger(Offset);
1690 ID.AddInteger(TargetFlags);
1692 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1693 return SDValue(E, 0);
1695 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1696 CSEMap.InsertNode(N, IP);
1698 return SDValue(N, 0);
1701 SDValue SelectionDAG::getSrcValue(const Value *V) {
1702 assert((!V || V->getType()->isPointerTy()) &&
1703 "SrcValue is not a pointer?");
1705 FoldingSetNodeID ID;
1706 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1710 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1711 return SDValue(E, 0);
1713 auto *N = newSDNode<SrcValueSDNode>(V);
1714 CSEMap.InsertNode(N, IP);
1716 return SDValue(N, 0);
1719 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1720 FoldingSetNodeID ID;
1721 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1725 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1726 return SDValue(E, 0);
1728 auto *N = newSDNode<MDNodeSDNode>(MD);
1729 CSEMap.InsertNode(N, IP);
1731 return SDValue(N, 0);
1734 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1735 if (VT == V.getValueType())
1738 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1741 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1742 unsigned SrcAS, unsigned DestAS) {
1743 SDValue Ops[] = {Ptr};
1744 FoldingSetNodeID ID;
1745 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1746 ID.AddInteger(SrcAS);
1747 ID.AddInteger(DestAS);
1750 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1751 return SDValue(E, 0);
1753 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1755 createOperands(N, Ops);
1757 CSEMap.InsertNode(N, IP);
1759 return SDValue(N, 0);
1762 /// getShiftAmountOperand - Return the specified value casted to
1763 /// the target's desired shift amount type.
1764 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1765 EVT OpTy = Op.getValueType();
1766 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1767 if (OpTy == ShTy || OpTy.isVector()) return Op;
1769 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1772 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1774 const TargetLowering &TLI = getTargetLoweringInfo();
1775 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1776 EVT VT = Node->getValueType(0);
1777 SDValue Tmp1 = Node->getOperand(0);
1778 SDValue Tmp2 = Node->getOperand(1);
1779 unsigned Align = Node->getConstantOperandVal(3);
1781 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1782 Tmp2, MachinePointerInfo(V));
1783 SDValue VAList = VAListLoad;
1785 if (Align > TLI.getMinStackArgumentAlignment()) {
1786 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1788 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1789 getConstant(Align - 1, dl, VAList.getValueType()));
1791 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1792 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1795 // Increment the pointer, VAList, to the next vaarg
1796 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1797 getConstant(getDataLayout().getTypeAllocSize(
1798 VT.getTypeForEVT(*getContext())),
1799 dl, VAList.getValueType()));
1800 // Store the incremented VAList to the legalized pointer
1802 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1803 // Load the actual argument out of the pointer VAList
1804 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1807 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1809 const TargetLowering &TLI = getTargetLoweringInfo();
1810 // This defaults to loading a pointer from the input and storing it to the
1811 // output, returning the chain.
1812 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1813 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1815 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1816 Node->getOperand(2), MachinePointerInfo(VS));
1817 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1818 MachinePointerInfo(VD));
1821 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1822 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1823 unsigned ByteSize = VT.getStoreSize();
1824 Type *Ty = VT.getTypeForEVT(*getContext());
1825 unsigned StackAlign =
1826 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1828 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1829 return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout()));
1832 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1833 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1834 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1835 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1836 const DataLayout &DL = getDataLayout();
1838 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1840 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1841 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1842 return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout()));
1845 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1846 ISD::CondCode Cond, const SDLoc &dl) {
1847 // These setcc operations always fold.
1851 case ISD::SETFALSE2: return getConstant(0, dl, VT);
1853 case ISD::SETTRUE2: {
1854 TargetLowering::BooleanContent Cnt =
1855 TLI->getBooleanContents(N1->getValueType(0));
1857 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1871 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1875 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1876 const APInt &C2 = N2C->getAPIntValue();
1877 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1878 const APInt &C1 = N1C->getAPIntValue();
1881 default: llvm_unreachable("Unknown integer setcc!");
1882 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT);
1883 case ISD::SETNE: return getConstant(C1 != C2, dl, VT);
1884 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1885 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1886 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1887 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1888 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT);
1889 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT);
1890 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT);
1891 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT);
1895 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1896 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1897 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1900 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1901 return getUNDEF(VT);
1903 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1904 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1905 return getUNDEF(VT);
1907 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1908 R==APFloat::cmpLessThan, dl, VT);
1909 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1910 return getUNDEF(VT);
1912 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1913 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1914 return getUNDEF(VT);
1916 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1917 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1918 return getUNDEF(VT);
1920 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1921 R==APFloat::cmpEqual, dl, VT);
1922 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1923 return getUNDEF(VT);
1925 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1926 R==APFloat::cmpEqual, dl, VT);
1927 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1928 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT);
1929 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1930 R==APFloat::cmpEqual, dl, VT);
1931 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1932 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1933 R==APFloat::cmpLessThan, dl, VT);
1934 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1935 R==APFloat::cmpUnordered, dl, VT);
1936 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1937 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1940 // Ensure that the constant occurs on the RHS.
1941 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1942 MVT CompVT = N1.getValueType().getSimpleVT();
1943 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1946 return getSetCC(dl, VT, N2, N1, SwappedCond);
1950 // Could not fold it.
1954 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1955 /// use this predicate to simplify operations downstream.
1956 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1957 unsigned BitWidth = Op.getScalarValueSizeInBits();
1958 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1961 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1962 /// this predicate to simplify operations downstream. Mask is known to be zero
1963 /// for bits that V cannot have.
1964 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1965 unsigned Depth) const {
1966 APInt KnownZero, KnownOne;
1967 computeKnownBits(Op, KnownZero, KnownOne, Depth);
1968 return (KnownZero & Mask) == Mask;
1971 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
1972 /// is less than the element bit-width of the shift node, return it.
1973 static const APInt *getValidShiftAmountConstant(SDValue V) {
1974 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
1975 // Shifting more than the bitwidth is not valid.
1976 const APInt &ShAmt = SA->getAPIntValue();
1977 if (ShAmt.ult(V.getScalarValueSizeInBits()))
1983 /// Determine which bits of Op are known to be either zero or one and return
1984 /// them in the KnownZero/KnownOne bitsets. For vectors, the known bits are
1985 /// those that are shared by every vector element.
1986 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
1987 APInt &KnownOne, unsigned Depth) const {
1988 EVT VT = Op.getValueType();
1989 APInt DemandedElts = VT.isVector()
1990 ? APInt::getAllOnesValue(VT.getVectorNumElements())
1992 computeKnownBits(Op, KnownZero, KnownOne, DemandedElts, Depth);
1995 /// Determine which bits of Op are known to be either zero or one and return
1996 /// them in the KnownZero/KnownOne bitsets. The DemandedElts argument allows
1997 /// us to only collect the known bits that are shared by the requested vector
1999 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
2000 APInt &KnownOne, const APInt &DemandedElts,
2001 unsigned Depth) const {
2002 unsigned BitWidth = Op.getScalarValueSizeInBits();
2004 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
2006 return; // Limit search depth.
2008 APInt KnownZero2, KnownOne2;
2009 unsigned NumElts = DemandedElts.getBitWidth();
2012 return; // No demanded elts, better to assume we don't know anything.
2014 unsigned Opcode = Op.getOpcode();
2017 // We know all of the bits for a constant!
2018 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
2019 KnownZero = ~KnownOne;
2021 case ISD::BUILD_VECTOR:
2022 // Collect the known bits that are shared by every demanded vector element.
2023 assert(NumElts == Op.getValueType().getVectorNumElements() &&
2024 "Unexpected vector size");
2025 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2026 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2027 if (!DemandedElts[i])
2030 SDValue SrcOp = Op.getOperand(i);
2031 computeKnownBits(SrcOp, KnownZero2, KnownOne2, Depth + 1);
2033 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2034 if (SrcOp.getValueSizeInBits() != BitWidth) {
2035 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2036 "Expected BUILD_VECTOR implicit truncation");
2037 KnownOne2 = KnownOne2.trunc(BitWidth);
2038 KnownZero2 = KnownZero2.trunc(BitWidth);
2041 // Known bits are the values that are shared by every demanded element.
2042 KnownOne &= KnownOne2;
2043 KnownZero &= KnownZero2;
2045 // If we don't know any bits, early out.
2046 if (!KnownOne && !KnownZero)
2050 case ISD::VECTOR_SHUFFLE: {
2051 // Collect the known bits that are shared by every vector element referenced
2053 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2054 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2055 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2056 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2057 for (unsigned i = 0; i != NumElts; ++i) {
2058 if (!DemandedElts[i])
2061 int M = SVN->getMaskElt(i);
2063 // For UNDEF elements, we don't know anything about the common state of
2064 // the shuffle result.
2065 KnownOne.clearAllBits();
2066 KnownZero.clearAllBits();
2067 DemandedLHS.clearAllBits();
2068 DemandedRHS.clearAllBits();
2072 if ((unsigned)M < NumElts)
2073 DemandedLHS.setBit((unsigned)M % NumElts);
2075 DemandedRHS.setBit((unsigned)M % NumElts);
2077 // Known bits are the values that are shared by every demanded element.
2078 if (!!DemandedLHS) {
2079 SDValue LHS = Op.getOperand(0);
2080 computeKnownBits(LHS, KnownZero2, KnownOne2, DemandedLHS, Depth + 1);
2081 KnownOne &= KnownOne2;
2082 KnownZero &= KnownZero2;
2084 // If we don't know any bits, early out.
2085 if (!KnownOne && !KnownZero)
2087 if (!!DemandedRHS) {
2088 SDValue RHS = Op.getOperand(1);
2089 computeKnownBits(RHS, KnownZero2, KnownOne2, DemandedRHS, Depth + 1);
2090 KnownOne &= KnownOne2;
2091 KnownZero &= KnownZero2;
2095 case ISD::CONCAT_VECTORS: {
2096 // Split DemandedElts and test each of the demanded subvectors.
2097 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2098 EVT SubVectorVT = Op.getOperand(0).getValueType();
2099 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2100 unsigned NumSubVectors = Op.getNumOperands();
2101 for (unsigned i = 0; i != NumSubVectors; ++i) {
2102 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2103 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2104 if (!!DemandedSub) {
2105 SDValue Sub = Op.getOperand(i);
2106 computeKnownBits(Sub, KnownZero2, KnownOne2, DemandedSub, Depth + 1);
2107 KnownOne &= KnownOne2;
2108 KnownZero &= KnownZero2;
2110 // If we don't know any bits, early out.
2111 if (!KnownOne && !KnownZero)
2116 case ISD::EXTRACT_SUBVECTOR: {
2117 // If we know the element index, just demand that subvector elements,
2118 // otherwise demand them all.
2119 SDValue Src = Op.getOperand(0);
2120 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2121 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2122 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2123 // Offset the demanded elts by the subvector index.
2124 uint64_t Idx = SubIdx->getZExtValue();
2125 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
2126 computeKnownBits(Src, KnownZero, KnownOne, DemandedSrc, Depth + 1);
2128 computeKnownBits(Src, KnownZero, KnownOne, Depth + 1);
2132 case ISD::BITCAST: {
2133 SDValue N0 = Op.getOperand(0);
2134 unsigned SubBitWidth = N0.getScalarValueSizeInBits();
2136 // Ignore bitcasts from floating point.
2137 if (!N0.getValueType().isInteger())
2140 // Fast handling of 'identity' bitcasts.
2141 if (BitWidth == SubBitWidth) {
2142 computeKnownBits(N0, KnownZero, KnownOne, DemandedElts, Depth + 1);
2146 // Support big-endian targets when it becomes useful.
2147 bool IsLE = getDataLayout().isLittleEndian();
2151 // Bitcast 'small element' vector to 'large element' scalar/vector.
2152 if ((BitWidth % SubBitWidth) == 0) {
2153 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2155 // Collect known bits for the (larger) output by collecting the known
2156 // bits from each set of sub elements and shift these into place.
2157 // We need to separately call computeKnownBits for each set of
2158 // sub elements as the knownbits for each is likely to be different.
2159 unsigned SubScale = BitWidth / SubBitWidth;
2160 APInt SubDemandedElts(NumElts * SubScale, 0);
2161 for (unsigned i = 0; i != NumElts; ++i)
2162 if (DemandedElts[i])
2163 SubDemandedElts.setBit(i * SubScale);
2165 for (unsigned i = 0; i != SubScale; ++i) {
2166 computeKnownBits(N0, KnownZero2, KnownOne2, SubDemandedElts.shl(i),
2168 KnownOne |= KnownOne2.zext(BitWidth).shl(SubBitWidth * i);
2169 KnownZero |= KnownZero2.zext(BitWidth).shl(SubBitWidth * i);
2173 // Bitcast 'large element' scalar/vector to 'small element' vector.
2174 if ((SubBitWidth % BitWidth) == 0) {
2175 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2177 // Collect known bits for the (smaller) output by collecting the known
2178 // bits from the overlapping larger input elements and extracting the
2179 // sub sections we actually care about.
2180 unsigned SubScale = SubBitWidth / BitWidth;
2181 APInt SubDemandedElts(NumElts / SubScale, 0);
2182 for (unsigned i = 0; i != NumElts; ++i)
2183 if (DemandedElts[i])
2184 SubDemandedElts.setBit(i / SubScale);
2186 computeKnownBits(N0, KnownZero2, KnownOne2, SubDemandedElts, Depth + 1);
2188 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2189 for (unsigned i = 0; i != NumElts; ++i)
2190 if (DemandedElts[i]) {
2191 unsigned Offset = (i % SubScale) * BitWidth;
2192 KnownOne &= KnownOne2.lshr(Offset).trunc(BitWidth);
2193 KnownZero &= KnownZero2.lshr(Offset).trunc(BitWidth);
2194 // If we don't know any bits, early out.
2195 if (!KnownOne && !KnownZero)
2202 // If either the LHS or the RHS are Zero, the result is zero.
2203 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2205 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2208 // Output known-1 bits are only known if set in both the LHS & RHS.
2209 KnownOne &= KnownOne2;
2210 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2211 KnownZero |= KnownZero2;
2214 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2216 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2219 // Output known-0 bits are only known if clear in both the LHS & RHS.
2220 KnownZero &= KnownZero2;
2221 // Output known-1 are known to be set if set in either the LHS | RHS.
2222 KnownOne |= KnownOne2;
2225 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2227 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2230 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2231 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
2232 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2233 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
2234 KnownZero = KnownZeroOut;
2238 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, DemandedElts,
2240 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2243 // If low bits are zero in either operand, output low known-0 bits.
2244 // Also compute a conservative estimate for high known-0 bits.
2245 // More trickiness is possible, but this is sufficient for the
2246 // interesting case of alignment computation.
2247 KnownOne.clearAllBits();
2248 unsigned TrailZ = KnownZero.countTrailingOnes() +
2249 KnownZero2.countTrailingOnes();
2250 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
2251 KnownZero2.countLeadingOnes(),
2252 BitWidth) - BitWidth;
2254 KnownZero.clearAllBits();
2255 KnownZero.setLowBits(std::min(TrailZ, BitWidth));
2256 KnownZero.setHighBits(std::min(LeadZ, BitWidth));
2260 // For the purposes of computing leading zeros we can conservatively
2261 // treat a udiv as a logical right shift by the power of 2 known to
2262 // be less than the denominator.
2263 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2265 unsigned LeadZ = KnownZero2.countLeadingOnes();
2267 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2269 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
2270 if (RHSUnknownLeadingOnes != BitWidth)
2271 LeadZ = std::min(BitWidth,
2272 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
2274 KnownZero.setHighBits(LeadZ);
2278 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
2279 // If we don't know any bits, early out.
2280 if (!KnownOne && !KnownZero)
2282 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2284 // Only known if known in both the LHS and RHS.
2285 KnownOne &= KnownOne2;
2286 KnownZero &= KnownZero2;
2288 case ISD::SELECT_CC:
2289 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
2290 // If we don't know any bits, early out.
2291 if (!KnownOne && !KnownZero)
2293 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
2295 // Only known if known in both the LHS and RHS.
2296 KnownOne &= KnownOne2;
2297 KnownZero &= KnownZero2;
2301 if (Op.getResNo() != 1)
2303 // The boolean result conforms to getBooleanContents.
2304 // If we know the result of a setcc has the top bits zero, use this info.
2305 // We know that we have an integer-based boolean since these operations
2306 // are only available for integer.
2307 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2308 TargetLowering::ZeroOrOneBooleanContent &&
2310 KnownZero.setBitsFrom(1);
2313 // If we know the result of a setcc has the top bits zero, use this info.
2314 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2315 TargetLowering::ZeroOrOneBooleanContent &&
2317 KnownZero.setBitsFrom(1);
2320 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2321 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2323 KnownZero = KnownZero << *ShAmt;
2324 KnownOne = KnownOne << *ShAmt;
2325 // Low bits are known zero.
2326 KnownZero.setLowBits(ShAmt->getZExtValue());
2330 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2331 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2333 KnownZero = KnownZero.lshr(*ShAmt);
2334 KnownOne = KnownOne.lshr(*ShAmt);
2335 // High bits are known zero.
2336 KnownZero.setHighBits(ShAmt->getZExtValue());
2340 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2341 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2343 KnownZero = KnownZero.lshr(*ShAmt);
2344 KnownOne = KnownOne.lshr(*ShAmt);
2345 // If we know the value of the sign bit, then we know it is copied across
2346 // the high bits by the shift amount.
2347 APInt SignBit = APInt::getSignBit(BitWidth);
2348 SignBit = SignBit.lshr(*ShAmt); // Adjust to where it is now in the mask.
2349 if (KnownZero.intersects(SignBit)) {
2350 KnownZero.setHighBits(ShAmt->getZExtValue());// New bits are known zero.
2351 } else if (KnownOne.intersects(SignBit)) {
2352 KnownOne.setHighBits(ShAmt->getZExtValue()); // New bits are known one.
2356 case ISD::SIGN_EXTEND_INREG: {
2357 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2358 unsigned EBits = EVT.getScalarSizeInBits();
2360 // Sign extension. Compute the demanded bits in the result that are not
2361 // present in the input.
2362 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2364 APInt InSignBit = APInt::getSignBit(EBits);
2365 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2367 // If the sign extended bits are demanded, we know that the sign
2369 InSignBit = InSignBit.zext(BitWidth);
2370 if (NewBits.getBoolValue())
2371 InputDemandedBits |= InSignBit;
2373 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2375 KnownOne &= InputDemandedBits;
2376 KnownZero &= InputDemandedBits;
2378 // If the sign bit of the input is known set or clear, then we know the
2379 // top bits of the result.
2380 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
2381 KnownZero |= NewBits;
2382 KnownOne &= ~NewBits;
2383 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
2384 KnownOne |= NewBits;
2385 KnownZero &= ~NewBits;
2386 } else { // Input sign bit unknown
2387 KnownZero &= ~NewBits;
2388 KnownOne &= ~NewBits;
2393 case ISD::CTTZ_ZERO_UNDEF:
2395 case ISD::CTLZ_ZERO_UNDEF:
2397 KnownZero.setBitsFrom(Log2_32(BitWidth)+1);
2401 LoadSDNode *LD = cast<LoadSDNode>(Op);
2402 // If this is a ZEXTLoad and we are looking at the loaded value.
2403 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2404 EVT VT = LD->getMemoryVT();
2405 unsigned MemBits = VT.getScalarSizeInBits();
2406 KnownZero.setBitsFrom(MemBits);
2407 } else if (const MDNode *Ranges = LD->getRanges()) {
2408 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2409 computeKnownBitsFromRangeMetadata(*Ranges, KnownZero, KnownOne);
2413 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2414 EVT InVT = Op.getOperand(0).getValueType();
2415 unsigned InBits = InVT.getScalarSizeInBits();
2416 KnownZero = KnownZero.trunc(InBits);
2417 KnownOne = KnownOne.trunc(InBits);
2418 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne,
2419 DemandedElts.zext(InVT.getVectorNumElements()),
2421 KnownZero = KnownZero.zext(BitWidth);
2422 KnownOne = KnownOne.zext(BitWidth);
2423 KnownZero.setBitsFrom(InBits);
2426 case ISD::ZERO_EXTEND: {
2427 EVT InVT = Op.getOperand(0).getValueType();
2428 unsigned InBits = InVT.getScalarSizeInBits();
2429 KnownZero = KnownZero.trunc(InBits);
2430 KnownOne = KnownOne.trunc(InBits);
2431 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2433 KnownZero = KnownZero.zext(BitWidth);
2434 KnownOne = KnownOne.zext(BitWidth);
2435 KnownZero.setBitsFrom(InBits);
2438 // TODO ISD::SIGN_EXTEND_VECTOR_INREG
2439 case ISD::SIGN_EXTEND: {
2440 EVT InVT = Op.getOperand(0).getValueType();
2441 unsigned InBits = InVT.getScalarSizeInBits();
2443 KnownZero = KnownZero.trunc(InBits);
2444 KnownOne = KnownOne.trunc(InBits);
2445 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2448 // If the sign bit is known to be zero or one, then sext will extend
2449 // it to the top bits, else it will just zext.
2450 KnownZero = KnownZero.sext(BitWidth);
2451 KnownOne = KnownOne.sext(BitWidth);
2454 case ISD::ANY_EXTEND: {
2455 EVT InVT = Op.getOperand(0).getValueType();
2456 unsigned InBits = InVT.getScalarSizeInBits();
2457 KnownZero = KnownZero.trunc(InBits);
2458 KnownOne = KnownOne.trunc(InBits);
2459 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2460 KnownZero = KnownZero.zext(BitWidth);
2461 KnownOne = KnownOne.zext(BitWidth);
2464 case ISD::TRUNCATE: {
2465 EVT InVT = Op.getOperand(0).getValueType();
2466 unsigned InBits = InVT.getScalarSizeInBits();
2467 KnownZero = KnownZero.zext(InBits);
2468 KnownOne = KnownOne.zext(InBits);
2469 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2471 KnownZero = KnownZero.trunc(BitWidth);
2472 KnownOne = KnownOne.trunc(BitWidth);
2475 case ISD::AssertZext: {
2476 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2477 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2478 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2479 KnownZero |= (~InMask);
2480 KnownOne &= (~KnownZero);
2484 // All bits are zero except the low bit.
2485 KnownZero.setBitsFrom(1);
2489 if (Op.getResNo() == 1) {
2490 // If we know the result of a setcc has the top bits zero, use this info.
2491 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2492 TargetLowering::ZeroOrOneBooleanContent &&
2494 KnownZero.setBitsFrom(1);
2500 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2501 // We know that the top bits of C-X are clear if X contains less bits
2502 // than C (i.e. no wrap-around can happen). For example, 20-X is
2503 // positive if we can prove that X is >= 0 and < 16.
2504 if (CLHS->getAPIntValue().isNonNegative()) {
2505 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2506 // NLZ can't be BitWidth with no sign bit
2507 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2508 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2511 // If all of the MaskV bits are known to be zero, then we know the
2512 // output top bits are zero, because we now know that the output is
2514 if ((KnownZero2 & MaskV) == MaskV) {
2515 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2516 // Top bits known zero.
2517 KnownZero.setHighBits(NLZ2);
2522 // If low bits are know to be zero in both operands, then we know they are
2523 // going to be 0 in the result. Both addition and complement operations
2524 // preserve the low zero bits.
2525 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2527 unsigned KnownZeroLow = KnownZero2.countTrailingOnes();
2528 if (KnownZeroLow == 0)
2531 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2533 KnownZeroLow = std::min(KnownZeroLow,
2534 KnownZero2.countTrailingOnes());
2535 KnownZero.setBits(0, KnownZeroLow);
2540 if (Op.getResNo() == 1) {
2541 // If we know the result of a setcc has the top bits zero, use this info.
2542 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2543 TargetLowering::ZeroOrOneBooleanContent &&
2545 KnownZero.setBitsFrom(1);
2552 // Output known-0 bits are known if clear or set in both the low clear bits
2553 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2554 // low 3 bits clear.
2555 // Output known-0 bits are also known if the top bits of each input are
2556 // known to be clear. For example, if one input has the top 10 bits clear
2557 // and the other has the top 8 bits clear, we know the top 7 bits of the
2558 // output must be clear.
2559 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2561 unsigned KnownZeroHigh = KnownZero2.countLeadingOnes();
2562 unsigned KnownZeroLow = KnownZero2.countTrailingOnes();
2564 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2566 KnownZeroHigh = std::min(KnownZeroHigh,
2567 KnownZero2.countLeadingOnes());
2568 KnownZeroLow = std::min(KnownZeroLow,
2569 KnownZero2.countTrailingOnes());
2571 if (Opcode == ISD::ADDE) {
2572 // With ADDE, a carry bit may be added in, so we can only use this
2573 // information if we know (at least) that the low two bits are clear.
2574 // We then return to the caller that the low bit is unknown but that
2575 // other bits are known zero.
2576 if (KnownZeroLow >= 2)
2577 KnownZero.setBits(1, KnownZeroLow);
2581 KnownZero.setLowBits(KnownZeroLow);
2582 if (KnownZeroHigh > 1)
2583 KnownZero.setHighBits(KnownZeroHigh - 1);
2587 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2588 const APInt &RA = Rem->getAPIntValue().abs();
2589 if (RA.isPowerOf2()) {
2590 APInt LowBits = RA - 1;
2591 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2594 // The low bits of the first operand are unchanged by the srem.
2595 KnownZero = KnownZero2 & LowBits;
2596 KnownOne = KnownOne2 & LowBits;
2598 // If the first operand is non-negative or has all low bits zero, then
2599 // the upper bits are all zero.
2600 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2601 KnownZero |= ~LowBits;
2603 // If the first operand is negative and not all low bits are zero, then
2604 // the upper bits are all one.
2605 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2606 KnownOne |= ~LowBits;
2607 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2612 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2613 const APInt &RA = Rem->getAPIntValue();
2614 if (RA.isPowerOf2()) {
2615 APInt LowBits = (RA - 1);
2616 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2619 // The upper bits are all zero, the lower ones are unchanged.
2620 KnownZero = KnownZero2 | ~LowBits;
2621 KnownOne = KnownOne2 & LowBits;
2626 // Since the result is less than or equal to either operand, any leading
2627 // zero bits in either operand must also exist in the result.
2628 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2630 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2633 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2634 KnownZero2.countLeadingOnes());
2635 KnownOne.clearAllBits();
2636 KnownZero.clearAllBits();
2637 KnownZero.setHighBits(Leaders);
2640 case ISD::EXTRACT_ELEMENT: {
2641 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2642 const unsigned Index = Op.getConstantOperandVal(1);
2643 const unsigned BitWidth = Op.getValueSizeInBits();
2645 // Remove low part of known bits mask
2646 KnownZero = KnownZero.getHiBits(KnownZero.getBitWidth() - Index * BitWidth);
2647 KnownOne = KnownOne.getHiBits(KnownOne.getBitWidth() - Index * BitWidth);
2649 // Remove high part of known bit mask
2650 KnownZero = KnownZero.trunc(BitWidth);
2651 KnownOne = KnownOne.trunc(BitWidth);
2654 case ISD::EXTRACT_VECTOR_ELT: {
2655 SDValue InVec = Op.getOperand(0);
2656 SDValue EltNo = Op.getOperand(1);
2657 EVT VecVT = InVec.getValueType();
2658 const unsigned BitWidth = Op.getValueSizeInBits();
2659 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
2660 const unsigned NumSrcElts = VecVT.getVectorNumElements();
2661 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2662 // anything about the extended bits.
2663 if (BitWidth > EltBitWidth) {
2664 KnownZero = KnownZero.trunc(EltBitWidth);
2665 KnownOne = KnownOne.trunc(EltBitWidth);
2667 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
2668 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
2669 // If we know the element index, just demand that vector element.
2670 unsigned Idx = ConstEltNo->getZExtValue();
2671 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
2672 computeKnownBits(InVec, KnownZero, KnownOne, DemandedElt, Depth + 1);
2674 // Unknown element index, so ignore DemandedElts and demand them all.
2675 computeKnownBits(InVec, KnownZero, KnownOne, Depth + 1);
2677 if (BitWidth > EltBitWidth) {
2678 KnownZero = KnownZero.zext(BitWidth);
2679 KnownOne = KnownOne.zext(BitWidth);
2683 case ISD::INSERT_VECTOR_ELT: {
2684 SDValue InVec = Op.getOperand(0);
2685 SDValue InVal = Op.getOperand(1);
2686 SDValue EltNo = Op.getOperand(2);
2688 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
2689 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
2690 // If we know the element index, split the demand between the
2691 // source vector and the inserted element.
2692 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2693 unsigned EltIdx = CEltNo->getZExtValue();
2695 // If we demand the inserted element then add its common known bits.
2696 if (DemandedElts[EltIdx]) {
2697 computeKnownBits(InVal, KnownZero2, KnownOne2, Depth + 1);
2698 KnownOne &= KnownOne2.zextOrTrunc(KnownOne.getBitWidth());
2699 KnownZero &= KnownZero2.zextOrTrunc(KnownZero.getBitWidth());;
2702 // If we demand the source vector then add its common known bits, ensuring
2703 // that we don't demand the inserted element.
2704 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
2706 computeKnownBits(InVec, KnownZero2, KnownOne2, VectorElts, Depth + 1);
2707 KnownOne &= KnownOne2;
2708 KnownZero &= KnownZero2;
2711 // Unknown element index, so ignore DemandedElts and demand them all.
2712 computeKnownBits(InVec, KnownZero, KnownOne, Depth + 1);
2713 computeKnownBits(InVal, KnownZero2, KnownOne2, Depth + 1);
2714 KnownOne &= KnownOne2.zextOrTrunc(KnownOne.getBitWidth());
2715 KnownZero &= KnownZero2.zextOrTrunc(KnownZero.getBitWidth());;
2719 case ISD::BITREVERSE: {
2720 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2722 KnownZero = KnownZero2.reverseBits();
2723 KnownOne = KnownOne2.reverseBits();
2727 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2729 KnownZero = KnownZero2.byteSwap();
2730 KnownOne = KnownOne2.byteSwap();
2734 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, DemandedElts,
2737 // If the source's MSB is zero then we know the rest of the bits already.
2738 if (KnownZero2[BitWidth - 1]) {
2739 KnownZero = KnownZero2;
2740 KnownOne = KnownOne2;
2744 // We only know that the absolute values's MSB will be zero iff there is
2745 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
2746 KnownOne2.clearBit(BitWidth - 1);
2747 if (KnownOne2.getBoolValue()) {
2748 KnownZero = APInt::getSignBit(BitWidth);
2754 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2756 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2759 // UMIN - we know that the result will have the maximum of the
2760 // known zero leading bits of the inputs.
2761 unsigned LeadZero = KnownZero.countLeadingOnes();
2762 LeadZero = std::max(LeadZero, KnownZero2.countLeadingOnes());
2764 KnownZero &= KnownZero2;
2765 KnownOne &= KnownOne2;
2766 KnownZero.setHighBits(LeadZero);
2770 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2772 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2775 // UMAX - we know that the result will have the maximum of the
2776 // known one leading bits of the inputs.
2777 unsigned LeadOne = KnownOne.countLeadingOnes();
2778 LeadOne = std::max(LeadOne, KnownOne2.countLeadingOnes());
2780 KnownZero &= KnownZero2;
2781 KnownOne &= KnownOne2;
2782 KnownOne.setHighBits(LeadOne);
2787 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, DemandedElts,
2789 // If we don't know any bits, early out.
2790 if (!KnownOne && !KnownZero)
2792 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, DemandedElts,
2794 KnownZero &= KnownZero2;
2795 KnownOne &= KnownOne2;
2798 case ISD::FrameIndex:
2799 case ISD::TargetFrameIndex:
2800 if (unsigned Align = InferPtrAlignment(Op)) {
2801 // The low bits are known zero if the pointer is aligned.
2802 KnownZero.setLowBits(Log2_32(Align));
2808 if (Opcode < ISD::BUILTIN_OP_END)
2811 case ISD::INTRINSIC_WO_CHAIN:
2812 case ISD::INTRINSIC_W_CHAIN:
2813 case ISD::INTRINSIC_VOID:
2814 // Allow the target to implement this method for its nodes.
2815 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, DemandedElts,
2820 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2823 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
2825 // X + 0 never overflow
2826 if (isNullConstant(N1))
2829 APInt N1Zero, N1One;
2830 computeKnownBits(N1, N1Zero, N1One);
2831 if (N1Zero.getBoolValue()) {
2832 APInt N0Zero, N0One;
2833 computeKnownBits(N0, N0Zero, N0One);
2836 (~N0Zero).uadd_ov(~N1Zero, overflow);
2841 // mulhi + 1 never overflow
2842 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
2843 (~N1Zero & 0x01) == ~N1Zero)
2846 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
2847 APInt N0Zero, N0One;
2848 computeKnownBits(N0, N0Zero, N0One);
2850 if ((~N0Zero & 0x01) == ~N0Zero)
2854 return OFK_Sometime;
2857 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2858 EVT OpVT = Val.getValueType();
2859 unsigned BitWidth = OpVT.getScalarSizeInBits();
2861 // Is the constant a known power of 2?
2862 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
2863 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2865 // A left-shift of a constant one will have exactly one bit set because
2866 // shifting the bit off the end is undefined.
2867 if (Val.getOpcode() == ISD::SHL) {
2868 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
2869 if (C && C->getAPIntValue() == 1)
2873 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2875 if (Val.getOpcode() == ISD::SRL) {
2876 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
2877 if (C && C->getAPIntValue().isSignBit())
2881 // Are all operands of a build vector constant powers of two?
2882 if (Val.getOpcode() == ISD::BUILD_VECTOR)
2883 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
2884 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
2885 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2890 // More could be done here, though the above checks are enough
2891 // to handle some common cases.
2893 // Fall back to computeKnownBits to catch other known cases.
2894 APInt KnownZero, KnownOne;
2895 computeKnownBits(Val, KnownZero, KnownOne);
2896 return (KnownZero.countPopulation() == BitWidth - 1) &&
2897 (KnownOne.countPopulation() == 1);
2900 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2901 EVT VT = Op.getValueType();
2902 APInt DemandedElts = VT.isVector()
2903 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2905 return ComputeNumSignBits(Op, DemandedElts, Depth);
2908 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2909 unsigned Depth) const {
2910 EVT VT = Op.getValueType();
2911 assert(VT.isInteger() && "Invalid VT!");
2912 unsigned VTBits = VT.getScalarSizeInBits();
2914 unsigned FirstAnswer = 1;
2917 return 1; // Limit search depth.
2920 return 1; // No demanded elts, better to assume we don't know anything.
2922 switch (Op.getOpcode()) {
2924 case ISD::AssertSext:
2925 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2926 return VTBits-Tmp+1;
2927 case ISD::AssertZext:
2928 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2931 case ISD::Constant: {
2932 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2933 return Val.getNumSignBits();
2936 case ISD::BUILD_VECTOR:
2938 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
2939 if (!DemandedElts[i])
2942 SDValue SrcOp = Op.getOperand(i);
2943 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
2945 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2946 if (SrcOp.getValueSizeInBits() != VTBits) {
2947 assert(SrcOp.getValueSizeInBits() > VTBits &&
2948 "Expected BUILD_VECTOR implicit truncation");
2949 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
2950 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
2952 Tmp = std::min(Tmp, Tmp2);
2956 case ISD::SIGN_EXTEND:
2957 case ISD::SIGN_EXTEND_VECTOR_INREG:
2958 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
2959 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2961 case ISD::SIGN_EXTEND_INREG:
2962 // Max of the input and what this extends.
2963 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
2966 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2967 return std::max(Tmp, Tmp2);
2970 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
2971 // SRA X, C -> adds C sign bits.
2972 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2973 APInt ShiftVal = C->getAPIntValue();
2975 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
2979 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2980 // shl destroys sign bits.
2981 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2982 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
2983 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
2984 return Tmp - C->getZExtValue();
2989 case ISD::XOR: // NOT is handled here.
2990 // Logical binary ops preserve the number of sign bits at the worst.
2991 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2993 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2994 FirstAnswer = std::min(Tmp, Tmp2);
2995 // We computed what we know about the sign bits as our first
2996 // answer. Now proceed to the generic code that uses
2997 // computeKnownBits, and pick whichever answer is better.
3002 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3003 if (Tmp == 1) return 1; // Early out.
3004 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3005 return std::min(Tmp, Tmp2);
3006 case ISD::SELECT_CC:
3007 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3008 if (Tmp == 1) return 1; // Early out.
3009 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
3010 return std::min(Tmp, Tmp2);
3015 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3017 return 1; // Early out.
3018 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3019 return std::min(Tmp, Tmp2);
3026 if (Op.getResNo() != 1)
3028 // The boolean result conforms to getBooleanContents. Fall through.
3029 // If setcc returns 0/-1, all bits are sign bits.
3030 // We know that we have an integer-based boolean since these operations
3031 // are only available for integer.
3032 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3033 TargetLowering::ZeroOrNegativeOneBooleanContent)
3037 // If setcc returns 0/-1, all bits are sign bits.
3038 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3039 TargetLowering::ZeroOrNegativeOneBooleanContent)
3044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3045 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
3047 // Handle rotate right by N like a rotate left by 32-N.
3048 if (Op.getOpcode() == ISD::ROTR)
3049 RotAmt = (VTBits-RotAmt) & (VTBits-1);
3051 // If we aren't rotating out all of the known-in sign bits, return the
3052 // number that are left. This handles rotl(sext(x), 1) for example.
3053 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3054 if (Tmp > RotAmt+1) return Tmp-RotAmt;
3059 // Add can have at most one carry bit. Thus we know that the output
3060 // is, at worst, one more bit than the inputs.
3061 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3062 if (Tmp == 1) return 1; // Early out.
3064 // Special case decrementing a value (ADD X, -1):
3065 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3066 if (CRHS->isAllOnesValue()) {
3067 APInt KnownZero, KnownOne;
3068 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
3070 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3072 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
3075 // If we are subtracting one from a positive number, there is no carry
3076 // out of the result.
3077 if (KnownZero.isNegative())
3081 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3082 if (Tmp2 == 1) return 1;
3083 return std::min(Tmp, Tmp2)-1;
3086 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3087 if (Tmp2 == 1) return 1;
3090 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3091 if (CLHS->isNullValue()) {
3092 APInt KnownZero, KnownOne;
3093 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
3094 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3096 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
3099 // If the input is known to be positive (the sign bit is known clear),
3100 // the output of the NEG has the same number of sign bits as the input.
3101 if (KnownZero.isNegative())
3104 // Otherwise, we treat this like a SUB.
3107 // Sub can have at most one carry bit. Thus we know that the output
3108 // is, at worst, one more bit than the inputs.
3109 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3110 if (Tmp == 1) return 1; // Early out.
3111 return std::min(Tmp, Tmp2)-1;
3112 case ISD::TRUNCATE: {
3113 // Check if the sign bits of source go down as far as the truncated value.
3114 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3115 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3116 if (NumSrcSignBits > (NumSrcBits - VTBits))
3117 return NumSrcSignBits - (NumSrcBits - VTBits);
3120 case ISD::EXTRACT_ELEMENT: {
3121 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3122 const int BitWidth = Op.getValueSizeInBits();
3123 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3125 // Get reverse index (starting from 1), Op1 value indexes elements from
3126 // little end. Sign starts at big end.
3127 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3129 // If the sign portion ends in our element the subtraction gives correct
3130 // result. Otherwise it gives either negative or > bitwidth result
3131 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3133 case ISD::INSERT_VECTOR_ELT: {
3134 SDValue InVec = Op.getOperand(0);
3135 SDValue InVal = Op.getOperand(1);
3136 SDValue EltNo = Op.getOperand(2);
3137 unsigned NumElts = InVec.getValueType().getVectorNumElements();
3139 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3140 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3141 // If we know the element index, split the demand between the
3142 // source vector and the inserted element.
3143 unsigned EltIdx = CEltNo->getZExtValue();
3145 // If we demand the inserted element then get its sign bits.
3147 if (DemandedElts[EltIdx])
3148 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3150 // If we demand the source vector then get its sign bits, and determine
3152 APInt VectorElts = DemandedElts;
3153 VectorElts.clearBit(EltIdx);
3155 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3156 Tmp = std::min(Tmp, Tmp2);
3159 // Unknown element index, so ignore DemandedElts and demand them all.
3160 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3161 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3162 Tmp = std::min(Tmp, Tmp2);
3164 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3167 case ISD::EXTRACT_VECTOR_ELT: {
3168 SDValue InVec = Op.getOperand(0);
3169 SDValue EltNo = Op.getOperand(1);
3170 EVT VecVT = InVec.getValueType();
3171 const unsigned BitWidth = Op.getValueSizeInBits();
3172 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3173 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3175 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3176 // anything about sign bits. But if the sizes match we can derive knowledge
3177 // about sign bits from the vector operand.
3178 if (BitWidth != EltBitWidth)
3181 // If we know the element index, just demand that vector element, else for
3182 // an unknown element index, ignore DemandedElts and demand them all.
3183 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3184 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3185 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3187 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3189 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3191 case ISD::EXTRACT_SUBVECTOR:
3192 return ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3193 case ISD::CONCAT_VECTORS:
3194 // Determine the minimum number of sign bits across all input vectors.
3195 // Early out if the result is already 1.
3196 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3197 for (unsigned i = 1, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i)
3198 Tmp = std::min(Tmp, ComputeNumSignBits(Op.getOperand(i), Depth + 1));
3202 // If we are looking at the loaded value of the SDNode.
3203 if (Op.getResNo() == 0) {
3204 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3205 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3206 unsigned ExtType = LD->getExtensionType();
3209 case ISD::SEXTLOAD: // '17' bits known
3210 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3211 return VTBits-Tmp+1;
3212 case ISD::ZEXTLOAD: // '16' bits known
3213 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3219 // Allow the target to implement this method for its nodes.
3220 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3221 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3222 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3223 Op.getOpcode() == ISD::INTRINSIC_VOID) {
3225 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3227 FirstAnswer = std::max(FirstAnswer, NumBits);
3230 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3231 // use this information.
3232 APInt KnownZero, KnownOne;
3233 computeKnownBits(Op, KnownZero, KnownOne, DemandedElts, Depth);
3236 if (KnownZero.isNegative()) { // sign bit is 0
3238 } else if (KnownOne.isNegative()) { // sign bit is 1;
3245 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3246 // the number of identical bits in the top of the input value.
3248 Mask <<= Mask.getBitWidth()-VTBits;
3249 // Return # leading zeros. We use 'min' here in case Val was zero before
3250 // shifting. We don't want to return '64' as for an i32 "0".
3251 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3254 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3255 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3256 !isa<ConstantSDNode>(Op.getOperand(1)))
3259 if (Op.getOpcode() == ISD::OR &&
3260 !MaskedValueIsZero(Op.getOperand(0),
3261 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3267 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
3268 // If we're told that NaNs won't happen, assume they won't.
3269 if (getTarget().Options.NoNaNsFPMath)
3272 if (const BinaryWithFlagsSDNode *BF = dyn_cast<BinaryWithFlagsSDNode>(Op))
3273 return BF->Flags.hasNoNaNs();
3275 // If the value is a constant, we can obviously see if it is a NaN or not.
3276 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3277 return !C->getValueAPF().isNaN();
3279 // TODO: Recognize more cases here.
3284 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3285 // If the value is a constant, we can obviously see if it is a zero or not.
3286 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3287 return !C->isZero();
3289 // TODO: Recognize more cases here.
3290 switch (Op.getOpcode()) {
3293 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3294 return !C->isNullValue();
3301 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3302 // Check the obvious case.
3303 if (A == B) return true;
3305 // For for negative and positive zero.
3306 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3307 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3308 if (CA->isZero() && CB->isZero()) return true;
3310 // Otherwise they may not be equal.
3314 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3315 assert(A.getValueType() == B.getValueType() &&
3316 "Values must have the same type");
3319 computeKnownBits(A, AZero, AOne);
3320 computeKnownBits(B, BZero, BOne);
3321 return (AZero | BZero).isAllOnesValue();
3324 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3325 ArrayRef<SDValue> Ops,
3326 llvm::SelectionDAG &DAG) {
3327 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3328 assert(llvm::all_of(Ops,
3330 return Ops[0].getValueType() == Op.getValueType();
3332 "Concatenation of vectors with inconsistent value types!");
3333 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3334 VT.getVectorNumElements() &&
3335 "Incorrect element count in vector concatenation!");
3337 if (Ops.size() == 1)
3340 // Concat of UNDEFs is UNDEF.
3341 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3342 return DAG.getUNDEF(VT);
3344 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3345 // simplified to one big BUILD_VECTOR.
3346 // FIXME: Add support for SCALAR_TO_VECTOR as well.
3347 EVT SVT = VT.getScalarType();
3348 SmallVector<SDValue, 16> Elts;
3349 for (SDValue Op : Ops) {
3350 EVT OpVT = Op.getValueType();
3352 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3353 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3354 Elts.append(Op->op_begin(), Op->op_end());
3359 // BUILD_VECTOR requires all inputs to be of the same type, find the
3360 // maximum type and extend them all.
3361 for (SDValue Op : Elts)
3362 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3364 if (SVT.bitsGT(VT.getScalarType()))
3365 for (SDValue &Op : Elts)
3366 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3367 ? DAG.getZExtOrTrunc(Op, DL, SVT)
3368 : DAG.getSExtOrTrunc(Op, DL, SVT);
3370 return DAG.getBuildVector(VT, DL, Elts);
3373 /// Gets or creates the specified node.
3374 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3375 FoldingSetNodeID ID;
3376 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3378 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3379 return SDValue(E, 0);
3381 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3383 CSEMap.InsertNode(N, IP);
3386 return SDValue(N, 0);
3389 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3391 // Constant fold unary operations with an integer constant operand. Even
3392 // opaque constant will be folded, because the folding of unary operations
3393 // doesn't create new constants with different values. Nevertheless, the
3394 // opaque flag is preserved during folding to prevent future folding with
3396 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3397 const APInt &Val = C->getAPIntValue();
3400 case ISD::SIGN_EXTEND:
3401 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3402 C->isTargetOpcode(), C->isOpaque());
3403 case ISD::ANY_EXTEND:
3404 case ISD::ZERO_EXTEND:
3406 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3407 C->isTargetOpcode(), C->isOpaque());
3408 case ISD::UINT_TO_FP:
3409 case ISD::SINT_TO_FP: {
3410 APFloat apf(EVTToAPFloatSemantics(VT),
3411 APInt::getNullValue(VT.getSizeInBits()));
3412 (void)apf.convertFromAPInt(Val,
3413 Opcode==ISD::SINT_TO_FP,
3414 APFloat::rmNearestTiesToEven);
3415 return getConstantFP(apf, DL, VT);
3418 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3419 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3420 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3421 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3422 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3423 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3424 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3425 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3428 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3430 case ISD::BITREVERSE:
3431 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3434 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3437 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3440 case ISD::CTLZ_ZERO_UNDEF:
3441 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3444 case ISD::CTTZ_ZERO_UNDEF:
3445 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3447 case ISD::FP16_TO_FP: {
3449 APFloat FPV(APFloat::IEEEhalf(),
3450 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3452 // This can return overflow, underflow, or inexact; we don't care.
3453 // FIXME need to be more flexible about rounding mode.
3454 (void)FPV.convert(EVTToAPFloatSemantics(VT),
3455 APFloat::rmNearestTiesToEven, &Ignored);
3456 return getConstantFP(FPV, DL, VT);
3461 // Constant fold unary operations with a floating point constant operand.
3462 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3463 APFloat V = C->getValueAPF(); // make copy
3467 return getConstantFP(V, DL, VT);
3470 return getConstantFP(V, DL, VT);
3472 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3473 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3474 return getConstantFP(V, DL, VT);
3478 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3479 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3480 return getConstantFP(V, DL, VT);
3484 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3485 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3486 return getConstantFP(V, DL, VT);
3489 case ISD::FP_EXTEND: {
3491 // This can return overflow, underflow, or inexact; we don't care.
3492 // FIXME need to be more flexible about rounding mode.
3493 (void)V.convert(EVTToAPFloatSemantics(VT),
3494 APFloat::rmNearestTiesToEven, &ignored);
3495 return getConstantFP(V, DL, VT);
3497 case ISD::FP_TO_SINT:
3498 case ISD::FP_TO_UINT: {
3500 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3501 // FIXME need to be more flexible about rounding mode.
3502 APFloat::opStatus s =
3503 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3504 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3506 return getConstant(IntVal, DL, VT);
3509 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3510 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3511 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3512 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3513 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3514 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3516 case ISD::FP_TO_FP16: {
3518 // This can return overflow, underflow, or inexact; we don't care.
3519 // FIXME need to be more flexible about rounding mode.
3520 (void)V.convert(APFloat::IEEEhalf(),
3521 APFloat::rmNearestTiesToEven, &Ignored);
3522 return getConstant(V.bitcastToAPInt(), DL, VT);
3527 // Constant fold unary operations with a vector integer or float operand.
3528 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3529 if (BV->isConstant()) {
3532 // FIXME: Entirely reasonable to perform folding of other unary
3533 // operations here as the need arises.
3540 case ISD::FP_EXTEND:
3541 case ISD::FP_TO_SINT:
3542 case ISD::FP_TO_UINT:
3544 case ISD::UINT_TO_FP:
3545 case ISD::SINT_TO_FP:
3547 case ISD::BITREVERSE:
3550 case ISD::CTLZ_ZERO_UNDEF:
3552 case ISD::CTTZ_ZERO_UNDEF:
3554 SDValue Ops = { Operand };
3555 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3562 unsigned OpOpcode = Operand.getNode()->getOpcode();
3564 case ISD::TokenFactor:
3565 case ISD::MERGE_VALUES:
3566 case ISD::CONCAT_VECTORS:
3567 return Operand; // Factor, merge or concat of one node? No need.
3568 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3569 case ISD::FP_EXTEND:
3570 assert(VT.isFloatingPoint() &&
3571 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3572 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3573 assert((!VT.isVector() ||
3574 VT.getVectorNumElements() ==
3575 Operand.getValueType().getVectorNumElements()) &&
3576 "Vector element count mismatch!");
3577 assert(Operand.getValueType().bitsLT(VT) &&
3578 "Invalid fpext node, dst < src!");
3579 if (Operand.isUndef())
3580 return getUNDEF(VT);
3582 case ISD::SIGN_EXTEND:
3583 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3584 "Invalid SIGN_EXTEND!");
3585 if (Operand.getValueType() == VT) return Operand; // noop extension
3586 assert((!VT.isVector() ||
3587 VT.getVectorNumElements() ==
3588 Operand.getValueType().getVectorNumElements()) &&
3589 "Vector element count mismatch!");
3590 assert(Operand.getValueType().bitsLT(VT) &&
3591 "Invalid sext node, dst < src!");
3592 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3593 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3594 else if (OpOpcode == ISD::UNDEF)
3595 // sext(undef) = 0, because the top bits will all be the same.
3596 return getConstant(0, DL, VT);
3598 case ISD::ZERO_EXTEND:
3599 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3600 "Invalid ZERO_EXTEND!");
3601 if (Operand.getValueType() == VT) return Operand; // noop extension
3602 assert((!VT.isVector() ||
3603 VT.getVectorNumElements() ==
3604 Operand.getValueType().getVectorNumElements()) &&
3605 "Vector element count mismatch!");
3606 assert(Operand.getValueType().bitsLT(VT) &&
3607 "Invalid zext node, dst < src!");
3608 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3609 return getNode(ISD::ZERO_EXTEND, DL, VT,
3610 Operand.getNode()->getOperand(0));
3611 else if (OpOpcode == ISD::UNDEF)
3612 // zext(undef) = 0, because the top bits will be zero.
3613 return getConstant(0, DL, VT);
3615 case ISD::ANY_EXTEND:
3616 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3617 "Invalid ANY_EXTEND!");
3618 if (Operand.getValueType() == VT) return Operand; // noop extension
3619 assert((!VT.isVector() ||
3620 VT.getVectorNumElements() ==
3621 Operand.getValueType().getVectorNumElements()) &&
3622 "Vector element count mismatch!");
3623 assert(Operand.getValueType().bitsLT(VT) &&
3624 "Invalid anyext node, dst < src!");
3626 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3627 OpOpcode == ISD::ANY_EXTEND)
3628 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3629 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3630 else if (OpOpcode == ISD::UNDEF)
3631 return getUNDEF(VT);
3633 // (ext (trunx x)) -> x
3634 if (OpOpcode == ISD::TRUNCATE) {
3635 SDValue OpOp = Operand.getNode()->getOperand(0);
3636 if (OpOp.getValueType() == VT)
3641 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3642 "Invalid TRUNCATE!");
3643 if (Operand.getValueType() == VT) return Operand; // noop truncate
3644 assert((!VT.isVector() ||
3645 VT.getVectorNumElements() ==
3646 Operand.getValueType().getVectorNumElements()) &&
3647 "Vector element count mismatch!");
3648 assert(Operand.getValueType().bitsGT(VT) &&
3649 "Invalid truncate node, src < dst!");
3650 if (OpOpcode == ISD::TRUNCATE)
3651 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3652 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3653 OpOpcode == ISD::ANY_EXTEND) {
3654 // If the source is smaller than the dest, we still need an extend.
3655 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
3656 .bitsLT(VT.getScalarType()))
3657 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3658 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
3659 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3660 return Operand.getNode()->getOperand(0);
3662 if (OpOpcode == ISD::UNDEF)
3663 return getUNDEF(VT);
3666 assert(VT.isInteger() && VT == Operand.getValueType() &&
3668 if (OpOpcode == ISD::UNDEF)
3669 return getUNDEF(VT);
3672 assert(VT.isInteger() && VT == Operand.getValueType() &&
3674 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3675 "BSWAP types must be a multiple of 16 bits!");
3676 if (OpOpcode == ISD::UNDEF)
3677 return getUNDEF(VT);
3679 case ISD::BITREVERSE:
3680 assert(VT.isInteger() && VT == Operand.getValueType() &&
3681 "Invalid BITREVERSE!");
3682 if (OpOpcode == ISD::UNDEF)
3683 return getUNDEF(VT);
3686 // Basic sanity checking.
3687 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3688 "Cannot BITCAST between types of different sizes!");
3689 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3690 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3691 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3692 if (OpOpcode == ISD::UNDEF)
3693 return getUNDEF(VT);
3695 case ISD::SCALAR_TO_VECTOR:
3696 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3697 (VT.getVectorElementType() == Operand.getValueType() ||
3698 (VT.getVectorElementType().isInteger() &&
3699 Operand.getValueType().isInteger() &&
3700 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3701 "Illegal SCALAR_TO_VECTOR node!");
3702 if (OpOpcode == ISD::UNDEF)
3703 return getUNDEF(VT);
3704 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3705 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3706 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3707 Operand.getConstantOperandVal(1) == 0 &&
3708 Operand.getOperand(0).getValueType() == VT)
3709 return Operand.getOperand(0);
3712 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3713 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3714 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3715 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
3716 Operand.getNode()->getOperand(0),
3717 &cast<BinaryWithFlagsSDNode>(Operand.getNode())->Flags);
3718 if (OpOpcode == ISD::FNEG) // --X -> X
3719 return Operand.getNode()->getOperand(0);
3722 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3723 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
3728 SDVTList VTs = getVTList(VT);
3729 SDValue Ops[] = {Operand};
3730 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3731 FoldingSetNodeID ID;
3732 AddNodeIDNode(ID, Opcode, VTs, Ops);
3734 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3735 return SDValue(E, 0);
3737 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3738 createOperands(N, Ops);
3739 CSEMap.InsertNode(N, IP);
3741 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3742 createOperands(N, Ops);
3746 return SDValue(N, 0);
3749 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3752 case ISD::ADD: return std::make_pair(C1 + C2, true);
3753 case ISD::SUB: return std::make_pair(C1 - C2, true);
3754 case ISD::MUL: return std::make_pair(C1 * C2, true);
3755 case ISD::AND: return std::make_pair(C1 & C2, true);
3756 case ISD::OR: return std::make_pair(C1 | C2, true);
3757 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3758 case ISD::SHL: return std::make_pair(C1 << C2, true);
3759 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3760 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3761 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3762 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3763 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3764 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3765 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3766 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3768 if (!C2.getBoolValue())
3770 return std::make_pair(C1.udiv(C2), true);
3772 if (!C2.getBoolValue())
3774 return std::make_pair(C1.urem(C2), true);
3776 if (!C2.getBoolValue())
3778 return std::make_pair(C1.sdiv(C2), true);
3780 if (!C2.getBoolValue())
3782 return std::make_pair(C1.srem(C2), true);
3784 return std::make_pair(APInt(1, 0), false);
3787 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3788 EVT VT, const ConstantSDNode *Cst1,
3789 const ConstantSDNode *Cst2) {
3790 if (Cst1->isOpaque() || Cst2->isOpaque())
3793 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3794 Cst2->getAPIntValue());
3797 return getConstant(Folded.first, DL, VT);
3800 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3801 const GlobalAddressSDNode *GA,
3803 if (GA->getOpcode() != ISD::GlobalAddress)
3805 if (!TLI->isOffsetFoldingLegal(GA))
3807 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3810 int64_t Offset = Cst2->getSExtValue();
3812 case ISD::ADD: break;
3813 case ISD::SUB: Offset = -uint64_t(Offset); break;
3814 default: return SDValue();
3816 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3817 GA->getOffset() + uint64_t(Offset));
3820 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
3826 // If a divisor is zero/undef or any element of a divisor vector is
3827 // zero/undef, the whole op is undef.
3828 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
3829 SDValue Divisor = Ops[1];
3830 if (Divisor.isUndef() || isNullConstant(Divisor))
3833 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
3834 any_of(Divisor->op_values(),
3835 [](SDValue V) { return V.isUndef() || isNullConstant(V); });
3836 // TODO: Handle signed overflow.
3838 // TODO: Handle oversized shifts.
3844 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3845 EVT VT, SDNode *Cst1,
3847 // If the opcode is a target-specific ISD node, there's nothing we can
3848 // do here and the operand rules may not line up with the below, so
3850 if (Opcode >= ISD::BUILTIN_OP_END)
3853 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
3854 return getUNDEF(VT);
3856 // Handle the case of two scalars.
3857 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3858 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3859 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3860 assert((!Folded || !VT.isVector()) &&
3861 "Can't fold vectors ops with scalar operands");
3866 // fold (add Sym, c) -> Sym+c
3867 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3868 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3869 if (isCommutativeBinOp(Opcode))
3870 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3871 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3873 // For vectors extract each constant element into Inputs so we can constant
3874 // fold them individually.
3875 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3876 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3880 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3882 EVT SVT = VT.getScalarType();
3883 SmallVector<SDValue, 4> Outputs;
3884 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3885 SDValue V1 = BV1->getOperand(I);
3886 SDValue V2 = BV2->getOperand(I);
3888 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3889 // FIXME: This is valid and could be handled by truncation.
3890 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3893 // Fold one vector element.
3894 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
3896 // Scalar folding only succeeded if the result is a constant or UNDEF.
3897 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3898 ScalarResult.getOpcode() != ISD::ConstantFP)
3900 Outputs.push_back(ScalarResult);
3903 assert(VT.getVectorNumElements() == Outputs.size() &&
3904 "Vector size mismatch!");
3906 // We may have a vector type but a scalar result. Create a splat.
3907 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3909 // Build a big vector out of the scalar elements we generated.
3910 return getBuildVector(VT, SDLoc(), Outputs);
3913 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3914 const SDLoc &DL, EVT VT,
3915 ArrayRef<SDValue> Ops,
3916 const SDNodeFlags *Flags) {
3917 // If the opcode is a target-specific ISD node, there's nothing we can
3918 // do here and the operand rules may not line up with the below, so
3920 if (Opcode >= ISD::BUILTIN_OP_END)
3923 if (isUndef(Opcode, Ops))
3924 return getUNDEF(VT);
3926 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3930 unsigned NumElts = VT.getVectorNumElements();
3932 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3933 return !Op.getValueType().isVector() ||
3934 Op.getValueType().getVectorNumElements() == NumElts;
3937 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3938 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3939 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3940 (BV && BV->isConstant());
3943 // All operands must be vector types with the same number of elements as
3944 // the result type and must be either UNDEF or a build vector of constant
3945 // or UNDEF scalars.
3946 if (!all_of(Ops, IsConstantBuildVectorOrUndef) ||
3947 !all_of(Ops, IsScalarOrSameVectorSize))
3950 // If we are comparing vectors, then the result needs to be a i1 boolean
3951 // that is then sign-extended back to the legal result type.
3952 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3954 // Find legal integer scalar type for constant promotion and
3955 // ensure that its scalar size is at least as large as source.
3956 EVT LegalSVT = VT.getScalarType();
3957 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
3958 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3959 if (LegalSVT.bitsLT(VT.getScalarType()))
3963 // Constant fold each scalar lane separately.
3964 SmallVector<SDValue, 4> ScalarResults;
3965 for (unsigned i = 0; i != NumElts; i++) {
3966 SmallVector<SDValue, 4> ScalarOps;
3967 for (SDValue Op : Ops) {
3968 EVT InSVT = Op.getValueType().getScalarType();
3969 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3971 // We've checked that this is UNDEF or a constant of some kind.
3973 ScalarOps.push_back(getUNDEF(InSVT));
3975 ScalarOps.push_back(Op);
3979 SDValue ScalarOp = InBV->getOperand(i);
3980 EVT ScalarVT = ScalarOp.getValueType();
3982 // Build vector (integer) scalar operands may need implicit
3983 // truncation - do this before constant folding.
3984 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
3985 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
3987 ScalarOps.push_back(ScalarOp);
3990 // Constant fold the scalar operands.
3991 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
3993 // Legalize the (integer) scalar constant if necessary.
3994 if (LegalSVT != SVT)
3995 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
3997 // Scalar folding only succeeded if the result is a constant or UNDEF.
3998 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3999 ScalarResult.getOpcode() != ISD::ConstantFP)
4001 ScalarResults.push_back(ScalarResult);
4004 return getBuildVector(VT, DL, ScalarResults);
4007 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4008 SDValue N1, SDValue N2,
4009 const SDNodeFlags *Flags) {
4010 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4011 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4012 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4013 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4015 // Canonicalize constant to RHS if commutative.
4016 if (isCommutativeBinOp(Opcode)) {
4018 std::swap(N1C, N2C);
4020 } else if (N1CFP && !N2CFP) {
4021 std::swap(N1CFP, N2CFP);
4028 case ISD::TokenFactor:
4029 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4030 N2.getValueType() == MVT::Other && "Invalid token factor!");
4031 // Fold trivial token factors.
4032 if (N1.getOpcode() == ISD::EntryToken) return N2;
4033 if (N2.getOpcode() == ISD::EntryToken) return N1;
4034 if (N1 == N2) return N1;
4036 case ISD::CONCAT_VECTORS: {
4037 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4038 SDValue Ops[] = {N1, N2};
4039 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4044 assert(VT.isInteger() && "This operator does not apply to FP types!");
4045 assert(N1.getValueType() == N2.getValueType() &&
4046 N1.getValueType() == VT && "Binary operator types must match!");
4047 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4048 // worth handling here.
4049 if (N2C && N2C->isNullValue())
4051 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4058 assert(VT.isInteger() && "This operator does not apply to FP types!");
4059 assert(N1.getValueType() == N2.getValueType() &&
4060 N1.getValueType() == VT && "Binary operator types must match!");
4061 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4062 // it's worth handling here.
4063 if (N2C && N2C->isNullValue())
4077 assert(VT.isInteger() && "This operator does not apply to FP types!");
4078 assert(N1.getValueType() == N2.getValueType() &&
4079 N1.getValueType() == VT && "Binary operator types must match!");
4086 if (getTarget().Options.UnsafeFPMath) {
4087 if (Opcode == ISD::FADD) {
4089 if (N2CFP && N2CFP->getValueAPF().isZero())
4091 } else if (Opcode == ISD::FSUB) {
4093 if (N2CFP && N2CFP->getValueAPF().isZero())
4095 } else if (Opcode == ISD::FMUL) {
4097 if (N2CFP && N2CFP->isZero())
4100 if (N2CFP && N2CFP->isExactlyValue(1.0))
4104 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4105 assert(N1.getValueType() == N2.getValueType() &&
4106 N1.getValueType() == VT && "Binary operator types must match!");
4108 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4109 assert(N1.getValueType() == VT &&
4110 N1.getValueType().isFloatingPoint() &&
4111 N2.getValueType().isFloatingPoint() &&
4112 "Invalid FCOPYSIGN!");
4119 assert(VT == N1.getValueType() &&
4120 "Shift operators return type must be the same as their first arg");
4121 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4122 "Shifts only work on integers");
4123 assert((!VT.isVector() || VT == N2.getValueType()) &&
4124 "Vector shift amounts must be in the same as their first arg");
4125 // Verify that the shift amount VT is bit enough to hold valid shift
4126 // amounts. This catches things like trying to shift an i1024 value by an
4127 // i8, which is easy to fall into in generic code that uses
4128 // TLI.getShiftAmount().
4129 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4130 "Invalid use of small shift amount with oversized value!");
4132 // Always fold shifts of i1 values so the code generator doesn't need to
4133 // handle them. Since we know the size of the shift has to be less than the
4134 // size of the value, the shift/rotate count is guaranteed to be zero.
4137 if (N2C && N2C->isNullValue())
4140 case ISD::FP_ROUND_INREG: {
4141 EVT EVT = cast<VTSDNode>(N2)->getVT();
4142 assert(VT == N1.getValueType() && "Not an inreg round!");
4143 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4144 "Cannot FP_ROUND_INREG integer types");
4145 assert(EVT.isVector() == VT.isVector() &&
4146 "FP_ROUND_INREG type should be vector iff the operand "
4148 assert((!EVT.isVector() ||
4149 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4150 "Vector element counts must match in FP_ROUND_INREG");
4151 assert(EVT.bitsLE(VT) && "Not rounding down!");
4153 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4157 assert(VT.isFloatingPoint() &&
4158 N1.getValueType().isFloatingPoint() &&
4159 VT.bitsLE(N1.getValueType()) &&
4160 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4161 "Invalid FP_ROUND!");
4162 if (N1.getValueType() == VT) return N1; // noop conversion.
4164 case ISD::AssertSext:
4165 case ISD::AssertZext: {
4166 EVT EVT = cast<VTSDNode>(N2)->getVT();
4167 assert(VT == N1.getValueType() && "Not an inreg extend!");
4168 assert(VT.isInteger() && EVT.isInteger() &&
4169 "Cannot *_EXTEND_INREG FP types");
4170 assert(!EVT.isVector() &&
4171 "AssertSExt/AssertZExt type should be the vector element type "
4172 "rather than the vector type!");
4173 assert(EVT.bitsLE(VT) && "Not extending!");
4174 if (VT == EVT) return N1; // noop assertion.
4177 case ISD::SIGN_EXTEND_INREG: {
4178 EVT EVT = cast<VTSDNode>(N2)->getVT();
4179 assert(VT == N1.getValueType() && "Not an inreg extend!");
4180 assert(VT.isInteger() && EVT.isInteger() &&
4181 "Cannot *_EXTEND_INREG FP types");
4182 assert(EVT.isVector() == VT.isVector() &&
4183 "SIGN_EXTEND_INREG type should be vector iff the operand "
4185 assert((!EVT.isVector() ||
4186 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4187 "Vector element counts must match in SIGN_EXTEND_INREG");
4188 assert(EVT.bitsLE(VT) && "Not extending!");
4189 if (EVT == VT) return N1; // Not actually extending
4191 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4192 unsigned FromBits = EVT.getScalarSizeInBits();
4193 Val <<= Val.getBitWidth() - FromBits;
4194 Val = Val.ashr(Val.getBitWidth() - FromBits);
4195 return getConstant(Val, DL, ConstantVT);
4199 const APInt &Val = N1C->getAPIntValue();
4200 return SignExtendInReg(Val, VT);
4202 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4203 SmallVector<SDValue, 8> Ops;
4204 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4205 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4206 SDValue Op = N1.getOperand(i);
4208 Ops.push_back(getUNDEF(OpVT));
4211 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4212 APInt Val = C->getAPIntValue();
4213 Ops.push_back(SignExtendInReg(Val, OpVT));
4215 return getBuildVector(VT, DL, Ops);
4219 case ISD::EXTRACT_VECTOR_ELT:
4220 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4222 return getUNDEF(VT);
4224 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4225 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4226 return getUNDEF(VT);
4228 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4229 // expanding copies of large vectors from registers.
4231 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4232 N1.getNumOperands() > 0) {
4234 N1.getOperand(0).getValueType().getVectorNumElements();
4235 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4236 N1.getOperand(N2C->getZExtValue() / Factor),
4237 getConstant(N2C->getZExtValue() % Factor, DL,
4238 N2.getValueType()));
4241 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4242 // expanding large vector constants.
4243 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4244 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4246 if (VT != Elt.getValueType())
4247 // If the vector element type is not legal, the BUILD_VECTOR operands
4248 // are promoted and implicitly truncated, and the result implicitly
4249 // extended. Make that explicit here.
4250 Elt = getAnyExtOrTrunc(Elt, DL, VT);
4255 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4256 // operations are lowered to scalars.
4257 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4258 // If the indices are the same, return the inserted element else
4259 // if the indices are known different, extract the element from
4260 // the original vector.
4261 SDValue N1Op2 = N1.getOperand(2);
4262 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4264 if (N1Op2C && N2C) {
4265 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4266 if (VT == N1.getOperand(1).getValueType())
4267 return N1.getOperand(1);
4269 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4272 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4276 case ISD::EXTRACT_ELEMENT:
4277 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4278 assert(!N1.getValueType().isVector() && !VT.isVector() &&
4279 (N1.getValueType().isInteger() == VT.isInteger()) &&
4280 N1.getValueType() != VT &&
4281 "Wrong types for EXTRACT_ELEMENT!");
4283 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4284 // 64-bit integers into 32-bit parts. Instead of building the extract of
4285 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4286 if (N1.getOpcode() == ISD::BUILD_PAIR)
4287 return N1.getOperand(N2C->getZExtValue());
4289 // EXTRACT_ELEMENT of a constant int is also very common.
4291 unsigned ElementSize = VT.getSizeInBits();
4292 unsigned Shift = ElementSize * N2C->getZExtValue();
4293 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4294 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4297 case ISD::EXTRACT_SUBVECTOR:
4298 if (VT.isSimple() && N1.getValueType().isSimple()) {
4299 assert(VT.isVector() && N1.getValueType().isVector() &&
4300 "Extract subvector VTs must be a vectors!");
4301 assert(VT.getVectorElementType() ==
4302 N1.getValueType().getVectorElementType() &&
4303 "Extract subvector VTs must have the same element type!");
4304 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4305 "Extract subvector must be from larger vector to smaller vector!");
4308 assert((VT.getVectorNumElements() + N2C->getZExtValue()
4309 <= N1.getValueType().getVectorNumElements())
4310 && "Extract subvector overflow!");
4313 // Trivial extraction.
4314 if (VT.getSimpleVT() == N1.getSimpleValueType())
4317 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4319 return getUNDEF(VT);
4321 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4322 // the concat have the same type as the extract.
4323 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4324 N1.getNumOperands() > 0 &&
4325 VT == N1.getOperand(0).getValueType()) {
4326 unsigned Factor = VT.getVectorNumElements();
4327 return N1.getOperand(N2C->getZExtValue() / Factor);
4330 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4331 // during shuffle legalization.
4332 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4333 VT == N1.getOperand(1).getValueType())
4334 return N1.getOperand(1);
4339 // Perform trivial constant folding.
4341 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4344 // Constant fold FP operations.
4345 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4348 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4349 APFloat::opStatus s;
4352 s = V1.add(V2, APFloat::rmNearestTiesToEven);
4353 if (!HasFPExceptions || s != APFloat::opInvalidOp)
4354 return getConstantFP(V1, DL, VT);
4357 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4358 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4359 return getConstantFP(V1, DL, VT);
4362 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4363 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4364 return getConstantFP(V1, DL, VT);
4367 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4368 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4369 s!=APFloat::opDivByZero)) {
4370 return getConstantFP(V1, DL, VT);
4375 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4376 s!=APFloat::opDivByZero)) {
4377 return getConstantFP(V1, DL, VT);
4380 case ISD::FCOPYSIGN:
4382 return getConstantFP(V1, DL, VT);
4387 if (Opcode == ISD::FP_ROUND) {
4388 APFloat V = N1CFP->getValueAPF(); // make copy
4390 // This can return overflow, underflow, or inexact; we don't care.
4391 // FIXME need to be more flexible about rounding mode.
4392 (void)V.convert(EVTToAPFloatSemantics(VT),
4393 APFloat::rmNearestTiesToEven, &ignored);
4394 return getConstantFP(V, DL, VT);
4398 // Canonicalize an UNDEF to the RHS, even over a constant.
4400 if (isCommutativeBinOp(Opcode)) {
4404 case ISD::FP_ROUND_INREG:
4405 case ISD::SIGN_EXTEND_INREG:
4411 return N1; // fold op(undef, arg2) -> undef
4419 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
4420 // For vectors, we can't easily build an all zero vector, just return
4427 // Fold a bunch of operators when the RHS is undef.
4432 // Handle undef ^ undef -> 0 special case. This is a common
4434 return getConstant(0, DL, VT);
4444 return N2; // fold op(arg1, undef) -> undef
4450 if (getTarget().Options.UnsafeFPMath)
4458 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
4459 // For vectors, we can't easily build an all zero vector, just return
4464 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
4465 // For vectors, we can't easily build an all one vector, just return
4473 // Memoize this node if possible.
4475 SDVTList VTs = getVTList(VT);
4476 if (VT != MVT::Glue) {
4477 SDValue Ops[] = {N1, N2};
4478 FoldingSetNodeID ID;
4479 AddNodeIDNode(ID, Opcode, VTs, Ops);
4481 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4483 E->intersectFlagsWith(Flags);
4484 return SDValue(E, 0);
4487 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
4488 CSEMap.InsertNode(N, IP);
4490 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
4494 return SDValue(N, 0);
4497 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4498 SDValue N1, SDValue N2, SDValue N3) {
4499 // Perform various simplifications.
4502 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4503 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4504 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4505 if (N1CFP && N2CFP && N3CFP) {
4506 APFloat V1 = N1CFP->getValueAPF();
4507 const APFloat &V2 = N2CFP->getValueAPF();
4508 const APFloat &V3 = N3CFP->getValueAPF();
4509 APFloat::opStatus s =
4510 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4511 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4512 return getConstantFP(V1, DL, VT);
4516 case ISD::CONCAT_VECTORS: {
4517 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4518 SDValue Ops[] = {N1, N2, N3};
4519 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4524 // Use FoldSetCC to simplify SETCC's.
4525 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
4527 // Vector constant folding.
4528 SDValue Ops[] = {N1, N2, N3};
4529 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4534 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
4535 if (N1C->getZExtValue())
4536 return N2; // select true, X, Y -> X
4537 return N3; // select false, X, Y -> Y
4540 if (N2 == N3) return N2; // select C, X, X -> X
4542 case ISD::VECTOR_SHUFFLE:
4543 llvm_unreachable("should use getVectorShuffle constructor!");
4544 case ISD::INSERT_VECTOR_ELT: {
4545 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
4546 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
4547 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4548 return getUNDEF(VT);
4551 case ISD::INSERT_SUBVECTOR: {
4553 if (VT.isSimple() && N1.getValueType().isSimple()
4554 && N2.getValueType().isSimple()) {
4555 assert(VT.isVector() && N1.getValueType().isVector() &&
4556 N2.getValueType().isVector() &&
4557 "Insert subvector VTs must be a vectors");
4558 assert(VT == N1.getValueType() &&
4559 "Dest and insert subvector source types must match!");
4560 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4561 "Insert subvector must be from smaller vector to larger vector!");
4562 if (isa<ConstantSDNode>(Index)) {
4563 assert((N2.getValueType().getVectorNumElements() +
4564 cast<ConstantSDNode>(Index)->getZExtValue()
4565 <= VT.getVectorNumElements())
4566 && "Insert subvector overflow!");
4569 // Trivial insertion.
4570 if (VT.getSimpleVT() == N2.getSimpleValueType())
4576 // Fold bit_convert nodes from a type to themselves.
4577 if (N1.getValueType() == VT)
4582 // Memoize node if it doesn't produce a flag.
4584 SDVTList VTs = getVTList(VT);
4585 SDValue Ops[] = {N1, N2, N3};
4586 if (VT != MVT::Glue) {
4587 FoldingSetNodeID ID;
4588 AddNodeIDNode(ID, Opcode, VTs, Ops);
4590 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4591 return SDValue(E, 0);
4593 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4594 createOperands(N, Ops);
4595 CSEMap.InsertNode(N, IP);
4597 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4598 createOperands(N, Ops);
4602 return SDValue(N, 0);
4605 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4606 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4607 SDValue Ops[] = { N1, N2, N3, N4 };
4608 return getNode(Opcode, DL, VT, Ops);
4611 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4612 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4614 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4615 return getNode(Opcode, DL, VT, Ops);
4618 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4619 /// the incoming stack arguments to be loaded from the stack.
4620 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4621 SmallVector<SDValue, 8> ArgChains;
4623 // Include the original chain at the beginning of the list. When this is
4624 // used by target LowerCall hooks, this helps legalize find the
4625 // CALLSEQ_BEGIN node.
4626 ArgChains.push_back(Chain);
4628 // Add a chain value for each stack argument.
4629 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4630 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4631 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4632 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4633 if (FI->getIndex() < 0)
4634 ArgChains.push_back(SDValue(L, 1));
4636 // Build a tokenfactor for all the chains.
4637 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4640 /// getMemsetValue - Vectorized representation of the memset value
4642 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4644 assert(!Value.isUndef());
4646 unsigned NumBits = VT.getScalarSizeInBits();
4647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4648 assert(C->getAPIntValue().getBitWidth() == 8);
4649 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4651 return DAG.getConstant(Val, dl, VT);
4652 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4656 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4657 EVT IntVT = VT.getScalarType();
4658 if (!IntVT.isInteger())
4659 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4661 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4663 // Use a multiplication with 0x010101... to extend the input to the
4665 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4666 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4667 DAG.getConstant(Magic, dl, IntVT));
4670 if (VT != Value.getValueType() && !VT.isInteger())
4671 Value = DAG.getBitcast(VT.getScalarType(), Value);
4672 if (VT != Value.getValueType())
4673 Value = DAG.getSplatBuildVector(VT, dl, Value);
4678 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4679 /// used when a memcpy is turned into a memset when the source is a constant
4681 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4682 const TargetLowering &TLI, StringRef Str) {
4683 // Handle vector with all elements zero.
4686 return DAG.getConstant(0, dl, VT);
4687 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4688 return DAG.getConstantFP(0.0, dl, VT);
4689 else if (VT.isVector()) {
4690 unsigned NumElts = VT.getVectorNumElements();
4691 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4692 return DAG.getNode(ISD::BITCAST, dl, VT,
4693 DAG.getConstant(0, dl,
4694 EVT::getVectorVT(*DAG.getContext(),
4697 llvm_unreachable("Expected type!");
4700 assert(!VT.isVector() && "Can't handle vector type here!");
4701 unsigned NumVTBits = VT.getSizeInBits();
4702 unsigned NumVTBytes = NumVTBits / 8;
4703 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
4705 APInt Val(NumVTBits, 0);
4706 if (DAG.getDataLayout().isLittleEndian()) {
4707 for (unsigned i = 0; i != NumBytes; ++i)
4708 Val |= (uint64_t)(unsigned char)Str[i] << i*8;
4710 for (unsigned i = 0; i != NumBytes; ++i)
4711 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
4714 // If the "cost" of materializing the integer immediate is less than the cost
4715 // of a load, then it is cost effective to turn the load into the immediate.
4716 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4717 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4718 return DAG.getConstant(Val, dl, VT);
4719 return SDValue(nullptr, 0);
4722 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4724 EVT VT = Base.getValueType();
4725 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4728 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
4730 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
4731 uint64_t SrcDelta = 0;
4732 GlobalAddressSDNode *G = nullptr;
4733 if (Src.getOpcode() == ISD::GlobalAddress)
4734 G = cast<GlobalAddressSDNode>(Src);
4735 else if (Src.getOpcode() == ISD::ADD &&
4736 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4737 Src.getOperand(1).getOpcode() == ISD::Constant) {
4738 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4739 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4744 return getConstantStringInfo(G->getGlobal(), Str,
4745 SrcDelta + G->getOffset(), false);
4748 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4749 /// Return true if the number of memory ops is below the threshold (Limit).
4750 /// It returns the types of the sequence of memory ops to perform
4751 /// memset / memcpy by reference.
4752 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4753 unsigned Limit, uint64_t Size,
4754 unsigned DstAlign, unsigned SrcAlign,
4759 unsigned DstAS, unsigned SrcAS,
4761 const TargetLowering &TLI) {
4762 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4763 "Expecting memcpy / memset source to meet alignment requirement!");
4764 // If 'SrcAlign' is zero, that means the memory operation does not need to
4765 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4766 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4767 // is the specified alignment of the memory operation. If it is zero, that
4768 // means it's possible to change the alignment of the destination.
4769 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4770 // not need to be loaded.
4771 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4772 IsMemset, ZeroMemset, MemcpyStrSrc,
4773 DAG.getMachineFunction());
4775 if (VT == MVT::Other) {
4776 if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) ||
4777 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) {
4778 VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
4780 switch (DstAlign & 7) {
4781 case 0: VT = MVT::i64; break;
4782 case 4: VT = MVT::i32; break;
4783 case 2: VT = MVT::i16; break;
4784 default: VT = MVT::i8; break;
4789 while (!TLI.isTypeLegal(LVT))
4790 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4791 assert(LVT.isInteger());
4797 unsigned NumMemOps = 0;
4799 unsigned VTSize = VT.getSizeInBits() / 8;
4800 while (VTSize > Size) {
4801 // For now, only use non-vector load / store's for the left-over pieces.
4806 if (VT.isVector() || VT.isFloatingPoint()) {
4807 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4808 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4809 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4811 else if (NewVT == MVT::i64 &&
4812 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4813 TLI.isSafeMemOpType(MVT::f64)) {
4814 // i64 is usually not legal on 32-bit targets, but f64 may be.
4822 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4823 if (NewVT == MVT::i8)
4825 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4827 NewVTSize = NewVT.getSizeInBits() / 8;
4829 // If the new VT cannot cover all of the remaining bits, then consider
4830 // issuing a (or a pair of) unaligned and overlapping load / store.
4831 // FIXME: Only does this for 64-bit or more since we don't have proper
4832 // cost model for unaligned load / store.
4834 if (NumMemOps && AllowOverlap &&
4835 VTSize >= 8 && NewVTSize < Size &&
4836 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4844 if (++NumMemOps > Limit)
4847 MemOps.push_back(VT);
4854 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4855 // On Darwin, -Os means optimize for size without hurting performance, so
4856 // only really optimize for size when -Oz (MinSize) is used.
4857 if (MF.getTarget().getTargetTriple().isOSDarwin())
4858 return MF.getFunction()->optForMinSize();
4859 return MF.getFunction()->optForSize();
4862 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4863 SDValue Chain, SDValue Dst, SDValue Src,
4864 uint64_t Size, unsigned Align,
4865 bool isVol, bool AlwaysInline,
4866 MachinePointerInfo DstPtrInfo,
4867 MachinePointerInfo SrcPtrInfo) {
4868 // Turn a memcpy of undef to nop.
4872 // Expand memcpy to a series of load and store ops if the size operand falls
4873 // below a certain threshold.
4874 // TODO: In the AlwaysInline case, if the size is big then generate a loop
4875 // rather than maybe a humongous number of loads and stores.
4876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4877 std::vector<EVT> MemOps;
4878 bool DstAlignCanChange = false;
4879 MachineFunction &MF = DAG.getMachineFunction();
4880 MachineFrameInfo &MFI = MF.getFrameInfo();
4881 bool OptSize = shouldLowerMemFuncForSize(MF);
4882 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4883 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4884 DstAlignCanChange = true;
4885 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4886 if (Align > SrcAlign)
4889 bool CopyFromStr = isMemSrcFromString(Src, Str);
4890 bool isZeroStr = CopyFromStr && Str.empty();
4891 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4893 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4894 (DstAlignCanChange ? 0 : Align),
4895 (isZeroStr ? 0 : SrcAlign),
4896 false, false, CopyFromStr, true,
4897 DstPtrInfo.getAddrSpace(),
4898 SrcPtrInfo.getAddrSpace(),
4902 if (DstAlignCanChange) {
4903 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4904 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4906 // Don't promote to an alignment that would require dynamic stack
4908 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4909 if (!TRI->needsStackRealignment(MF))
4910 while (NewAlign > Align &&
4911 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign))
4914 if (NewAlign > Align) {
4915 // Give the stack frame object a larger alignment if needed.
4916 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4917 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4922 MachineMemOperand::Flags MMOFlags =
4923 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4924 SmallVector<SDValue, 8> OutChains;
4925 unsigned NumMemOps = MemOps.size();
4926 uint64_t SrcOff = 0, DstOff = 0;
4927 for (unsigned i = 0; i != NumMemOps; ++i) {
4929 unsigned VTSize = VT.getSizeInBits() / 8;
4930 SDValue Value, Store;
4932 if (VTSize > Size) {
4933 // Issuing an unaligned load / store pair that overlaps with the previous
4934 // pair. Adjust the offset accordingly.
4935 assert(i == NumMemOps-1 && i != 0);
4936 SrcOff -= VTSize - Size;
4937 DstOff -= VTSize - Size;
4941 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
4942 // It's unlikely a store of a vector immediate can be done in a single
4943 // instruction. It would require a load from a constantpool first.
4944 // We only handle zero vectors here.
4945 // FIXME: Handle other cases where store of vector immediate is done in
4946 // a single instruction.
4947 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
4948 if (Value.getNode())
4949 Store = DAG.getStore(Chain, dl, Value,
4950 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4951 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
4954 if (!Store.getNode()) {
4955 // The type might not be legal for the target. This should only happen
4956 // if the type is smaller than a legal type, as on PPC, so the right
4957 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
4958 // to Load/Store if NVT==VT.
4959 // FIXME does the case above also need this?
4960 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4961 assert(NVT.bitsGE(VT));
4962 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4963 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4964 SrcPtrInfo.getWithOffset(SrcOff), VT,
4965 MinAlign(SrcAlign, SrcOff), MMOFlags);
4966 OutChains.push_back(Value.getValue(1));
4967 Store = DAG.getTruncStore(
4968 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4969 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
4971 OutChains.push_back(Store);
4977 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4980 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4981 SDValue Chain, SDValue Dst, SDValue Src,
4982 uint64_t Size, unsigned Align,
4983 bool isVol, bool AlwaysInline,
4984 MachinePointerInfo DstPtrInfo,
4985 MachinePointerInfo SrcPtrInfo) {
4986 // Turn a memmove of undef to nop.
4990 // Expand memmove to a series of load and store ops if the size operand falls
4991 // below a certain threshold.
4992 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4993 std::vector<EVT> MemOps;
4994 bool DstAlignCanChange = false;
4995 MachineFunction &MF = DAG.getMachineFunction();
4996 MachineFrameInfo &MFI = MF.getFrameInfo();
4997 bool OptSize = shouldLowerMemFuncForSize(MF);
4998 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4999 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5000 DstAlignCanChange = true;
5001 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5002 if (Align > SrcAlign)
5004 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5006 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5007 (DstAlignCanChange ? 0 : Align), SrcAlign,
5008 false, false, false, false,
5009 DstPtrInfo.getAddrSpace(),
5010 SrcPtrInfo.getAddrSpace(),
5014 if (DstAlignCanChange) {
5015 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5016 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5017 if (NewAlign > Align) {
5018 // Give the stack frame object a larger alignment if needed.
5019 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5020 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5025 MachineMemOperand::Flags MMOFlags =
5026 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5027 uint64_t SrcOff = 0, DstOff = 0;
5028 SmallVector<SDValue, 8> LoadValues;
5029 SmallVector<SDValue, 8> LoadChains;
5030 SmallVector<SDValue, 8> OutChains;
5031 unsigned NumMemOps = MemOps.size();
5032 for (unsigned i = 0; i < NumMemOps; i++) {
5034 unsigned VTSize = VT.getSizeInBits() / 8;
5038 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5039 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags);
5040 LoadValues.push_back(Value);
5041 LoadChains.push_back(Value.getValue(1));
5044 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5046 for (unsigned i = 0; i < NumMemOps; i++) {
5048 unsigned VTSize = VT.getSizeInBits() / 8;
5051 Store = DAG.getStore(Chain, dl, LoadValues[i],
5052 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5053 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5054 OutChains.push_back(Store);
5058 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5061 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5064 /// \param DAG Selection DAG where lowered code is placed.
5065 /// \param dl Link to corresponding IR location.
5066 /// \param Chain Control flow dependency.
5067 /// \param Dst Pointer to destination memory location.
5068 /// \param Src Value of byte to write into the memory.
5069 /// \param Size Number of bytes to write.
5070 /// \param Align Alignment of the destination in bytes.
5071 /// \param isVol True if destination is volatile.
5072 /// \param DstPtrInfo IR information on the memory pointer.
5073 /// \returns New head in the control flow, if lowering was successful, empty
5074 /// SDValue otherwise.
5076 /// The function tries to replace 'llvm.memset' intrinsic with several store
5077 /// operations and value calculation code. This is usually profitable for small
5079 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5080 SDValue Chain, SDValue Dst, SDValue Src,
5081 uint64_t Size, unsigned Align, bool isVol,
5082 MachinePointerInfo DstPtrInfo) {
5083 // Turn a memset of undef to nop.
5087 // Expand memset to a series of load/store ops if the size operand
5088 // falls below a certain threshold.
5089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5090 std::vector<EVT> MemOps;
5091 bool DstAlignCanChange = false;
5092 MachineFunction &MF = DAG.getMachineFunction();
5093 MachineFrameInfo &MFI = MF.getFrameInfo();
5094 bool OptSize = shouldLowerMemFuncForSize(MF);
5095 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5096 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5097 DstAlignCanChange = true;
5099 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5100 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5101 Size, (DstAlignCanChange ? 0 : Align), 0,
5102 true, IsZeroVal, false, true,
5103 DstPtrInfo.getAddrSpace(), ~0u,
5107 if (DstAlignCanChange) {
5108 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5109 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5110 if (NewAlign > Align) {
5111 // Give the stack frame object a larger alignment if needed.
5112 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5113 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5118 SmallVector<SDValue, 8> OutChains;
5119 uint64_t DstOff = 0;
5120 unsigned NumMemOps = MemOps.size();
5122 // Find the largest store and generate the bit pattern for it.
5123 EVT LargestVT = MemOps[0];
5124 for (unsigned i = 1; i < NumMemOps; i++)
5125 if (MemOps[i].bitsGT(LargestVT))
5126 LargestVT = MemOps[i];
5127 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5129 for (unsigned i = 0; i < NumMemOps; i++) {
5131 unsigned VTSize = VT.getSizeInBits() / 8;
5132 if (VTSize > Size) {
5133 // Issuing an unaligned load / store pair that overlaps with the previous
5134 // pair. Adjust the offset accordingly.
5135 assert(i == NumMemOps-1 && i != 0);
5136 DstOff -= VTSize - Size;
5139 // If this store is smaller than the largest store see whether we can get
5140 // the smaller value for free with a truncate.
5141 SDValue Value = MemSetValue;
5142 if (VT.bitsLT(LargestVT)) {
5143 if (!LargestVT.isVector() && !VT.isVector() &&
5144 TLI.isTruncateFree(LargestVT, VT))
5145 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5147 Value = getMemsetValue(Src, VT, DAG, dl);
5149 assert(Value.getValueType() == VT && "Value with wrong type.");
5150 SDValue Store = DAG.getStore(
5151 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5152 DstPtrInfo.getWithOffset(DstOff), Align,
5153 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5154 OutChains.push_back(Store);
5155 DstOff += VT.getSizeInBits() / 8;
5159 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5162 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5164 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5165 // pointer operands can be losslessly bitcasted to pointers of address space 0
5166 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5167 report_fatal_error("cannot lower memory intrinsic in address space " +
5172 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5173 SDValue Src, SDValue Size, unsigned Align,
5174 bool isVol, bool AlwaysInline, bool isTailCall,
5175 MachinePointerInfo DstPtrInfo,
5176 MachinePointerInfo SrcPtrInfo) {
5177 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5179 // Check to see if we should lower the memcpy to loads and stores first.
5180 // For cases within the target-specified limits, this is the best choice.
5181 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5183 // Memcpy with size zero? Just return the original chain.
5184 if (ConstantSize->isNullValue())
5187 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5188 ConstantSize->getZExtValue(),Align,
5189 isVol, false, DstPtrInfo, SrcPtrInfo);
5190 if (Result.getNode())
5194 // Then check to see if we should lower the memcpy with target-specific
5195 // code. If the target chooses to do this, this is the next best.
5197 SDValue Result = TSI->EmitTargetCodeForMemcpy(
5198 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5199 DstPtrInfo, SrcPtrInfo);
5200 if (Result.getNode())
5204 // If we really need inline code and the target declined to provide it,
5205 // use a (potentially long) sequence of loads and stores.
5207 assert(ConstantSize && "AlwaysInline requires a constant size!");
5208 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5209 ConstantSize->getZExtValue(), Align, isVol,
5210 true, DstPtrInfo, SrcPtrInfo);
5213 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5214 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5216 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5217 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5218 // respect volatile, so they may do things like read or write memory
5219 // beyond the given memory regions. But fixing this isn't easy, and most
5220 // people don't care.
5222 // Emit a library call.
5223 TargetLowering::ArgListTy Args;
5224 TargetLowering::ArgListEntry Entry;
5225 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5226 Entry.Node = Dst; Args.push_back(Entry);
5227 Entry.Node = Src; Args.push_back(Entry);
5228 Entry.Node = Size; Args.push_back(Entry);
5229 // FIXME: pass in SDLoc
5230 TargetLowering::CallLoweringInfo CLI(*this);
5233 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5234 Dst.getValueType().getTypeForEVT(*getContext()),
5235 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5236 TLI->getPointerTy(getDataLayout())),
5239 .setTailCall(isTailCall);
5241 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5242 return CallResult.second;
5245 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5246 SDValue Src, SDValue Size, unsigned Align,
5247 bool isVol, bool isTailCall,
5248 MachinePointerInfo DstPtrInfo,
5249 MachinePointerInfo SrcPtrInfo) {
5250 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5252 // Check to see if we should lower the memmove to loads and stores first.
5253 // For cases within the target-specified limits, this is the best choice.
5254 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5256 // Memmove with size zero? Just return the original chain.
5257 if (ConstantSize->isNullValue())
5261 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5262 ConstantSize->getZExtValue(), Align, isVol,
5263 false, DstPtrInfo, SrcPtrInfo);
5264 if (Result.getNode())
5268 // Then check to see if we should lower the memmove with target-specific
5269 // code. If the target chooses to do this, this is the next best.
5271 SDValue Result = TSI->EmitTargetCodeForMemmove(
5272 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5273 if (Result.getNode())
5277 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5278 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5280 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5281 // not be safe. See memcpy above for more details.
5283 // Emit a library call.
5284 TargetLowering::ArgListTy Args;
5285 TargetLowering::ArgListEntry Entry;
5286 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5287 Entry.Node = Dst; Args.push_back(Entry);
5288 Entry.Node = Src; Args.push_back(Entry);
5289 Entry.Node = Size; Args.push_back(Entry);
5290 // FIXME: pass in SDLoc
5291 TargetLowering::CallLoweringInfo CLI(*this);
5294 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5295 Dst.getValueType().getTypeForEVT(*getContext()),
5296 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5297 TLI->getPointerTy(getDataLayout())),
5300 .setTailCall(isTailCall);
5302 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5303 return CallResult.second;
5306 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5307 SDValue Src, SDValue Size, unsigned Align,
5308 bool isVol, bool isTailCall,
5309 MachinePointerInfo DstPtrInfo) {
5310 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5312 // Check to see if we should lower the memset to stores first.
5313 // For cases within the target-specified limits, this is the best choice.
5314 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5316 // Memset with size zero? Just return the original chain.
5317 if (ConstantSize->isNullValue())
5321 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5322 Align, isVol, DstPtrInfo);
5324 if (Result.getNode())
5328 // Then check to see if we should lower the memset with target-specific
5329 // code. If the target chooses to do this, this is the next best.
5331 SDValue Result = TSI->EmitTargetCodeForMemset(
5332 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5333 if (Result.getNode())
5337 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5339 // Emit a library call.
5340 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5341 TargetLowering::ArgListTy Args;
5342 TargetLowering::ArgListEntry Entry;
5343 Entry.Node = Dst; Entry.Ty = IntPtrTy;
5344 Args.push_back(Entry);
5346 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5347 Args.push_back(Entry);
5349 Entry.Ty = IntPtrTy;
5350 Args.push_back(Entry);
5352 // FIXME: pass in SDLoc
5353 TargetLowering::CallLoweringInfo CLI(*this);
5356 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5357 Dst.getValueType().getTypeForEVT(*getContext()),
5358 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5359 TLI->getPointerTy(getDataLayout())),
5362 .setTailCall(isTailCall);
5364 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5365 return CallResult.second;
5368 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5369 SDVTList VTList, ArrayRef<SDValue> Ops,
5370 MachineMemOperand *MMO) {
5371 FoldingSetNodeID ID;
5372 ID.AddInteger(MemVT.getRawBits());
5373 AddNodeIDNode(ID, Opcode, VTList, Ops);
5374 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5376 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5377 cast<AtomicSDNode>(E)->refineAlignment(MMO);
5378 return SDValue(E, 0);
5381 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5382 VTList, MemVT, MMO);
5383 createOperands(N, Ops);
5385 CSEMap.InsertNode(N, IP);
5387 return SDValue(N, 0);
5390 SDValue SelectionDAG::getAtomicCmpSwap(
5391 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5392 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5393 unsigned Alignment, AtomicOrdering SuccessOrdering,
5394 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
5395 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5396 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5397 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5399 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5400 Alignment = getEVTAlignment(MemVT);
5402 MachineFunction &MF = getMachineFunction();
5404 // FIXME: Volatile isn't really correct; we should keep track of atomic
5405 // orderings in the memoperand.
5406 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5407 MachineMemOperand::MOStore;
5408 MachineMemOperand *MMO =
5409 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5410 AAMDNodes(), nullptr, SynchScope, SuccessOrdering,
5413 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5416 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5417 EVT MemVT, SDVTList VTs, SDValue Chain,
5418 SDValue Ptr, SDValue Cmp, SDValue Swp,
5419 MachineMemOperand *MMO) {
5420 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5421 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5422 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5424 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5425 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5428 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5429 SDValue Chain, SDValue Ptr, SDValue Val,
5430 const Value *PtrVal, unsigned Alignment,
5431 AtomicOrdering Ordering,
5432 SynchronizationScope SynchScope) {
5433 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5434 Alignment = getEVTAlignment(MemVT);
5436 MachineFunction &MF = getMachineFunction();
5437 // An atomic store does not load. An atomic load does not store.
5438 // (An atomicrmw obviously both loads and stores.)
5439 // For now, atomics are considered to be volatile always, and they are
5441 // FIXME: Volatile isn't really correct; we should keep track of atomic
5442 // orderings in the memoperand.
5443 auto Flags = MachineMemOperand::MOVolatile;
5444 if (Opcode != ISD::ATOMIC_STORE)
5445 Flags |= MachineMemOperand::MOLoad;
5446 if (Opcode != ISD::ATOMIC_LOAD)
5447 Flags |= MachineMemOperand::MOStore;
5449 MachineMemOperand *MMO =
5450 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5451 MemVT.getStoreSize(), Alignment, AAMDNodes(),
5452 nullptr, SynchScope, Ordering);
5454 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5457 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5458 SDValue Chain, SDValue Ptr, SDValue Val,
5459 MachineMemOperand *MMO) {
5460 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5461 Opcode == ISD::ATOMIC_LOAD_SUB ||
5462 Opcode == ISD::ATOMIC_LOAD_AND ||
5463 Opcode == ISD::ATOMIC_LOAD_OR ||
5464 Opcode == ISD::ATOMIC_LOAD_XOR ||
5465 Opcode == ISD::ATOMIC_LOAD_NAND ||
5466 Opcode == ISD::ATOMIC_LOAD_MIN ||
5467 Opcode == ISD::ATOMIC_LOAD_MAX ||
5468 Opcode == ISD::ATOMIC_LOAD_UMIN ||
5469 Opcode == ISD::ATOMIC_LOAD_UMAX ||
5470 Opcode == ISD::ATOMIC_SWAP ||
5471 Opcode == ISD::ATOMIC_STORE) &&
5472 "Invalid Atomic Op");
5474 EVT VT = Val.getValueType();
5476 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5477 getVTList(VT, MVT::Other);
5478 SDValue Ops[] = {Chain, Ptr, Val};
5479 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5482 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5483 EVT VT, SDValue Chain, SDValue Ptr,
5484 MachineMemOperand *MMO) {
5485 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5487 SDVTList VTs = getVTList(VT, MVT::Other);
5488 SDValue Ops[] = {Chain, Ptr};
5489 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5492 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5493 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5494 if (Ops.size() == 1)
5497 SmallVector<EVT, 4> VTs;
5498 VTs.reserve(Ops.size());
5499 for (unsigned i = 0; i < Ops.size(); ++i)
5500 VTs.push_back(Ops[i].getValueType());
5501 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5504 SDValue SelectionDAG::getMemIntrinsicNode(
5505 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5506 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5507 bool ReadMem, bool WriteMem, unsigned Size) {
5508 if (Align == 0) // Ensure that codegen never sees alignment 0
5509 Align = getEVTAlignment(MemVT);
5511 MachineFunction &MF = getMachineFunction();
5512 auto Flags = MachineMemOperand::MONone;
5514 Flags |= MachineMemOperand::MOStore;
5516 Flags |= MachineMemOperand::MOLoad;
5518 Flags |= MachineMemOperand::MOVolatile;
5520 Size = MemVT.getStoreSize();
5521 MachineMemOperand *MMO =
5522 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5524 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5527 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5529 ArrayRef<SDValue> Ops, EVT MemVT,
5530 MachineMemOperand *MMO) {
5531 assert((Opcode == ISD::INTRINSIC_VOID ||
5532 Opcode == ISD::INTRINSIC_W_CHAIN ||
5533 Opcode == ISD::PREFETCH ||
5534 Opcode == ISD::LIFETIME_START ||
5535 Opcode == ISD::LIFETIME_END ||
5536 (Opcode <= INT_MAX &&
5537 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5538 "Opcode is not a memory-accessing opcode!");
5540 // Memoize the node unless it returns a flag.
5541 MemIntrinsicSDNode *N;
5542 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5543 FoldingSetNodeID ID;
5544 AddNodeIDNode(ID, Opcode, VTList, Ops);
5545 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5547 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5548 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5549 return SDValue(E, 0);
5552 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5553 VTList, MemVT, MMO);
5554 createOperands(N, Ops);
5556 CSEMap.InsertNode(N, IP);
5558 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5559 VTList, MemVT, MMO);
5560 createOperands(N, Ops);
5563 return SDValue(N, 0);
5566 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5567 /// MachinePointerInfo record from it. This is particularly useful because the
5568 /// code generator has many cases where it doesn't bother passing in a
5569 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5570 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5571 int64_t Offset = 0) {
5572 // If this is FI+Offset, we can model it.
5573 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5574 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5575 FI->getIndex(), Offset);
5577 // If this is (FI+Offset1)+Offset2, we can model it.
5578 if (Ptr.getOpcode() != ISD::ADD ||
5579 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5580 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5581 return MachinePointerInfo();
5583 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5584 return MachinePointerInfo::getFixedStack(
5585 DAG.getMachineFunction(), FI,
5586 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5589 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5590 /// MachinePointerInfo record from it. This is particularly useful because the
5591 /// code generator has many cases where it doesn't bother passing in a
5592 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5593 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5595 // If the 'Offset' value isn't a constant, we can't handle this.
5596 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5597 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5598 if (OffsetOp.isUndef())
5599 return InferPointerInfo(DAG, Ptr);
5600 return MachinePointerInfo();
5603 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5604 EVT VT, const SDLoc &dl, SDValue Chain,
5605 SDValue Ptr, SDValue Offset,
5606 MachinePointerInfo PtrInfo, EVT MemVT,
5608 MachineMemOperand::Flags MMOFlags,
5609 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5610 assert(Chain.getValueType() == MVT::Other &&
5611 "Invalid chain type");
5612 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5613 Alignment = getEVTAlignment(MemVT);
5615 MMOFlags |= MachineMemOperand::MOLoad;
5616 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5617 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5619 if (PtrInfo.V.isNull())
5620 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5622 MachineFunction &MF = getMachineFunction();
5623 MachineMemOperand *MMO = MF.getMachineMemOperand(
5624 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5625 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5628 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5629 EVT VT, const SDLoc &dl, SDValue Chain,
5630 SDValue Ptr, SDValue Offset, EVT MemVT,
5631 MachineMemOperand *MMO) {
5633 ExtType = ISD::NON_EXTLOAD;
5634 } else if (ExtType == ISD::NON_EXTLOAD) {
5635 assert(VT == MemVT && "Non-extending load from different memory type!");
5638 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5639 "Should only be an extending load, not truncating!");
5640 assert(VT.isInteger() == MemVT.isInteger() &&
5641 "Cannot convert from FP to Int or Int -> FP!");
5642 assert(VT.isVector() == MemVT.isVector() &&
5643 "Cannot use an ext load to convert to or from a vector!");
5644 assert((!VT.isVector() ||
5645 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5646 "Cannot use an ext load to change the number of vector elements!");
5649 bool Indexed = AM != ISD::UNINDEXED;
5650 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5652 SDVTList VTs = Indexed ?
5653 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5654 SDValue Ops[] = { Chain, Ptr, Offset };
5655 FoldingSetNodeID ID;
5656 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5657 ID.AddInteger(MemVT.getRawBits());
5658 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5659 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5660 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5662 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5663 cast<LoadSDNode>(E)->refineAlignment(MMO);
5664 return SDValue(E, 0);
5666 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5667 ExtType, MemVT, MMO);
5668 createOperands(N, Ops);
5670 CSEMap.InsertNode(N, IP);
5672 return SDValue(N, 0);
5675 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5676 SDValue Ptr, MachinePointerInfo PtrInfo,
5678 MachineMemOperand::Flags MMOFlags,
5679 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5680 SDValue Undef = getUNDEF(Ptr.getValueType());
5681 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5682 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5685 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5686 SDValue Ptr, MachineMemOperand *MMO) {
5687 SDValue Undef = getUNDEF(Ptr.getValueType());
5688 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5692 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5693 EVT VT, SDValue Chain, SDValue Ptr,
5694 MachinePointerInfo PtrInfo, EVT MemVT,
5696 MachineMemOperand::Flags MMOFlags,
5697 const AAMDNodes &AAInfo) {
5698 SDValue Undef = getUNDEF(Ptr.getValueType());
5699 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5700 MemVT, Alignment, MMOFlags, AAInfo);
5703 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5704 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5705 MachineMemOperand *MMO) {
5706 SDValue Undef = getUNDEF(Ptr.getValueType());
5707 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5711 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5712 SDValue Base, SDValue Offset,
5713 ISD::MemIndexedMode AM) {
5714 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5715 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5716 // Don't propagate the invariant or dereferenceable flags.
5718 LD->getMemOperand()->getFlags() &
5719 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5720 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5721 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5722 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5726 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5727 SDValue Ptr, MachinePointerInfo PtrInfo,
5729 MachineMemOperand::Flags MMOFlags,
5730 const AAMDNodes &AAInfo) {
5731 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5732 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5733 Alignment = getEVTAlignment(Val.getValueType());
5735 MMOFlags |= MachineMemOperand::MOStore;
5736 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5738 if (PtrInfo.V.isNull())
5739 PtrInfo = InferPointerInfo(*this, Ptr);
5741 MachineFunction &MF = getMachineFunction();
5742 MachineMemOperand *MMO = MF.getMachineMemOperand(
5743 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5744 return getStore(Chain, dl, Val, Ptr, MMO);
5747 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5748 SDValue Ptr, MachineMemOperand *MMO) {
5749 assert(Chain.getValueType() == MVT::Other &&
5750 "Invalid chain type");
5751 EVT VT = Val.getValueType();
5752 SDVTList VTs = getVTList(MVT::Other);
5753 SDValue Undef = getUNDEF(Ptr.getValueType());
5754 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5755 FoldingSetNodeID ID;
5756 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5757 ID.AddInteger(VT.getRawBits());
5758 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5759 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5760 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5762 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5763 cast<StoreSDNode>(E)->refineAlignment(MMO);
5764 return SDValue(E, 0);
5766 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5767 ISD::UNINDEXED, false, VT, MMO);
5768 createOperands(N, Ops);
5770 CSEMap.InsertNode(N, IP);
5772 return SDValue(N, 0);
5775 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5776 SDValue Ptr, MachinePointerInfo PtrInfo,
5777 EVT SVT, unsigned Alignment,
5778 MachineMemOperand::Flags MMOFlags,
5779 const AAMDNodes &AAInfo) {
5780 assert(Chain.getValueType() == MVT::Other &&
5781 "Invalid chain type");
5782 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5783 Alignment = getEVTAlignment(SVT);
5785 MMOFlags |= MachineMemOperand::MOStore;
5786 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5788 if (PtrInfo.V.isNull())
5789 PtrInfo = InferPointerInfo(*this, Ptr);
5791 MachineFunction &MF = getMachineFunction();
5792 MachineMemOperand *MMO = MF.getMachineMemOperand(
5793 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5794 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5797 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5798 SDValue Ptr, EVT SVT,
5799 MachineMemOperand *MMO) {
5800 EVT VT = Val.getValueType();
5802 assert(Chain.getValueType() == MVT::Other &&
5803 "Invalid chain type");
5805 return getStore(Chain, dl, Val, Ptr, MMO);
5807 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5808 "Should only be a truncating store, not extending!");
5809 assert(VT.isInteger() == SVT.isInteger() &&
5810 "Can't do FP-INT conversion!");
5811 assert(VT.isVector() == SVT.isVector() &&
5812 "Cannot use trunc store to convert to or from a vector!");
5813 assert((!VT.isVector() ||
5814 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5815 "Cannot use trunc store to change the number of vector elements!");
5817 SDVTList VTs = getVTList(MVT::Other);
5818 SDValue Undef = getUNDEF(Ptr.getValueType());
5819 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5820 FoldingSetNodeID ID;
5821 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5822 ID.AddInteger(SVT.getRawBits());
5823 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5824 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5825 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5827 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5828 cast<StoreSDNode>(E)->refineAlignment(MMO);
5829 return SDValue(E, 0);
5831 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5832 ISD::UNINDEXED, true, SVT, MMO);
5833 createOperands(N, Ops);
5835 CSEMap.InsertNode(N, IP);
5837 return SDValue(N, 0);
5840 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5841 SDValue Base, SDValue Offset,
5842 ISD::MemIndexedMode AM) {
5843 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5844 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5845 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5846 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5847 FoldingSetNodeID ID;
5848 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5849 ID.AddInteger(ST->getMemoryVT().getRawBits());
5850 ID.AddInteger(ST->getRawSubclassData());
5851 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5853 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5854 return SDValue(E, 0);
5856 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5857 ST->isTruncatingStore(), ST->getMemoryVT(),
5858 ST->getMemOperand());
5859 createOperands(N, Ops);
5861 CSEMap.InsertNode(N, IP);
5863 return SDValue(N, 0);
5866 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5867 SDValue Ptr, SDValue Mask, SDValue Src0,
5868 EVT MemVT, MachineMemOperand *MMO,
5869 ISD::LoadExtType ExtTy, bool isExpanding) {
5871 SDVTList VTs = getVTList(VT, MVT::Other);
5872 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5873 FoldingSetNodeID ID;
5874 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5875 ID.AddInteger(VT.getRawBits());
5876 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5877 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5878 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5880 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5881 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5882 return SDValue(E, 0);
5884 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5885 ExtTy, isExpanding, MemVT, MMO);
5886 createOperands(N, Ops);
5888 CSEMap.InsertNode(N, IP);
5890 return SDValue(N, 0);
5893 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5894 SDValue Val, SDValue Ptr, SDValue Mask,
5895 EVT MemVT, MachineMemOperand *MMO,
5896 bool IsTruncating, bool IsCompressing) {
5897 assert(Chain.getValueType() == MVT::Other &&
5898 "Invalid chain type");
5899 EVT VT = Val.getValueType();
5900 SDVTList VTs = getVTList(MVT::Other);
5901 SDValue Ops[] = { Chain, Ptr, Mask, Val };
5902 FoldingSetNodeID ID;
5903 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5904 ID.AddInteger(VT.getRawBits());
5905 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5906 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5907 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5909 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5910 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5911 return SDValue(E, 0);
5913 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5914 IsTruncating, IsCompressing, MemVT, MMO);
5915 createOperands(N, Ops);
5917 CSEMap.InsertNode(N, IP);
5919 return SDValue(N, 0);
5922 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5923 ArrayRef<SDValue> Ops,
5924 MachineMemOperand *MMO) {
5925 assert(Ops.size() == 5 && "Incompatible number of operands");
5927 FoldingSetNodeID ID;
5928 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5929 ID.AddInteger(VT.getRawBits());
5930 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5931 dl.getIROrder(), VTs, VT, MMO));
5932 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5934 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5935 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5936 return SDValue(E, 0);
5939 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5941 createOperands(N, Ops);
5943 assert(N->getValue().getValueType() == N->getValueType(0) &&
5944 "Incompatible type of the PassThru value in MaskedGatherSDNode");
5945 assert(N->getMask().getValueType().getVectorNumElements() ==
5946 N->getValueType(0).getVectorNumElements() &&
5947 "Vector width mismatch between mask and data");
5948 assert(N->getIndex().getValueType().getVectorNumElements() ==
5949 N->getValueType(0).getVectorNumElements() &&
5950 "Vector width mismatch between index and data");
5952 CSEMap.InsertNode(N, IP);
5954 return SDValue(N, 0);
5957 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
5958 ArrayRef<SDValue> Ops,
5959 MachineMemOperand *MMO) {
5960 assert(Ops.size() == 5 && "Incompatible number of operands");
5962 FoldingSetNodeID ID;
5963 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5964 ID.AddInteger(VT.getRawBits());
5965 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
5966 dl.getIROrder(), VTs, VT, MMO));
5967 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5969 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5970 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
5971 return SDValue(E, 0);
5973 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5975 createOperands(N, Ops);
5977 assert(N->getMask().getValueType().getVectorNumElements() ==
5978 N->getValue().getValueType().getVectorNumElements() &&
5979 "Vector width mismatch between mask and data");
5980 assert(N->getIndex().getValueType().getVectorNumElements() ==
5981 N->getValue().getValueType().getVectorNumElements() &&
5982 "Vector width mismatch between index and data");
5984 CSEMap.InsertNode(N, IP);
5986 return SDValue(N, 0);
5989 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
5990 SDValue Ptr, SDValue SV, unsigned Align) {
5991 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
5992 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
5995 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5996 ArrayRef<SDUse> Ops) {
5997 switch (Ops.size()) {
5998 case 0: return getNode(Opcode, DL, VT);
5999 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
6000 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
6001 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6005 // Copy from an SDUse array into an SDValue array for use with
6006 // the regular getNode logic.
6007 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
6008 return getNode(Opcode, DL, VT, NewOps);
6011 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6012 ArrayRef<SDValue> Ops, const SDNodeFlags *Flags) {
6013 unsigned NumOps = Ops.size();
6015 case 0: return getNode(Opcode, DL, VT);
6016 case 1: return getNode(Opcode, DL, VT, Ops[0]);
6017 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
6018 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6024 case ISD::CONCAT_VECTORS: {
6025 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
6026 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
6030 case ISD::SELECT_CC: {
6031 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6032 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6033 "LHS and RHS of condition must have same type!");
6034 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6035 "True and False arms of SelectCC must have same type!");
6036 assert(Ops[2].getValueType() == VT &&
6037 "select_cc node must be of same type as true and false value!");
6041 assert(NumOps == 5 && "BR_CC takes 5 operands!");
6042 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6043 "LHS/RHS of comparison should match types!");
6050 SDVTList VTs = getVTList(VT);
6052 if (VT != MVT::Glue) {
6053 FoldingSetNodeID ID;
6054 AddNodeIDNode(ID, Opcode, VTs, Ops);
6057 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6058 return SDValue(E, 0);
6060 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6061 createOperands(N, Ops);
6063 CSEMap.InsertNode(N, IP);
6065 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6066 createOperands(N, Ops);
6070 return SDValue(N, 0);
6073 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6074 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6075 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6078 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6079 ArrayRef<SDValue> Ops) {
6080 if (VTList.NumVTs == 1)
6081 return getNode(Opcode, DL, VTList.VTs[0], Ops);
6085 // FIXME: figure out how to safely handle things like
6086 // int foo(int x) { return 1 << (x & 255); }
6087 // int bar() { return foo(256); }
6088 case ISD::SRA_PARTS:
6089 case ISD::SRL_PARTS:
6090 case ISD::SHL_PARTS:
6091 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6092 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6093 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6094 else if (N3.getOpcode() == ISD::AND)
6095 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6096 // If the and is only masking out bits that cannot effect the shift,
6097 // eliminate the and.
6098 unsigned NumBits = VT.getScalarSizeInBits()*2;
6099 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6100 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6106 // Memoize the node unless it returns a flag.
6108 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6109 FoldingSetNodeID ID;
6110 AddNodeIDNode(ID, Opcode, VTList, Ops);
6112 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6113 return SDValue(E, 0);
6115 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6116 createOperands(N, Ops);
6117 CSEMap.InsertNode(N, IP);
6119 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6120 createOperands(N, Ops);
6123 return SDValue(N, 0);
6126 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6128 return getNode(Opcode, DL, VTList, None);
6131 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6133 SDValue Ops[] = { N1 };
6134 return getNode(Opcode, DL, VTList, Ops);
6137 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6138 SDValue N1, SDValue N2) {
6139 SDValue Ops[] = { N1, N2 };
6140 return getNode(Opcode, DL, VTList, Ops);
6143 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6144 SDValue N1, SDValue N2, SDValue N3) {
6145 SDValue Ops[] = { N1, N2, N3 };
6146 return getNode(Opcode, DL, VTList, Ops);
6149 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6150 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6151 SDValue Ops[] = { N1, N2, N3, N4 };
6152 return getNode(Opcode, DL, VTList, Ops);
6155 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6156 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6158 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6159 return getNode(Opcode, DL, VTList, Ops);
6162 SDVTList SelectionDAG::getVTList(EVT VT) {
6163 return makeVTList(SDNode::getValueTypeList(VT), 1);
6166 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6167 FoldingSetNodeID ID;
6169 ID.AddInteger(VT1.getRawBits());
6170 ID.AddInteger(VT2.getRawBits());
6173 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6175 EVT *Array = Allocator.Allocate<EVT>(2);
6178 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6179 VTListMap.InsertNode(Result, IP);
6181 return Result->getSDVTList();
6184 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6185 FoldingSetNodeID ID;
6187 ID.AddInteger(VT1.getRawBits());
6188 ID.AddInteger(VT2.getRawBits());
6189 ID.AddInteger(VT3.getRawBits());
6192 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6194 EVT *Array = Allocator.Allocate<EVT>(3);
6198 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6199 VTListMap.InsertNode(Result, IP);
6201 return Result->getSDVTList();
6204 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6205 FoldingSetNodeID ID;
6207 ID.AddInteger(VT1.getRawBits());
6208 ID.AddInteger(VT2.getRawBits());
6209 ID.AddInteger(VT3.getRawBits());
6210 ID.AddInteger(VT4.getRawBits());
6213 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6215 EVT *Array = Allocator.Allocate<EVT>(4);
6220 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6221 VTListMap.InsertNode(Result, IP);
6223 return Result->getSDVTList();
6226 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6227 unsigned NumVTs = VTs.size();
6228 FoldingSetNodeID ID;
6229 ID.AddInteger(NumVTs);
6230 for (unsigned index = 0; index < NumVTs; index++) {
6231 ID.AddInteger(VTs[index].getRawBits());
6235 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6237 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6238 std::copy(VTs.begin(), VTs.end(), Array);
6239 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6240 VTListMap.InsertNode(Result, IP);
6242 return Result->getSDVTList();
6246 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6247 /// specified operands. If the resultant node already exists in the DAG,
6248 /// this does not modify the specified node, instead it returns the node that
6249 /// already exists. If the resultant node does not exist in the DAG, the
6250 /// input node is returned. As a degenerate case, if you specify the same
6251 /// input operands as the node already has, the input node is returned.
6252 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6253 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6255 // Check to see if there is no change.
6256 if (Op == N->getOperand(0)) return N;
6258 // See if the modified node already exists.
6259 void *InsertPos = nullptr;
6260 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6263 // Nope it doesn't. Remove the node from its current place in the maps.
6265 if (!RemoveNodeFromCSEMaps(N))
6266 InsertPos = nullptr;
6268 // Now we update the operands.
6269 N->OperandList[0].set(Op);
6271 // If this gets put into a CSE map, add it.
6272 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6276 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6277 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6279 // Check to see if there is no change.
6280 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6281 return N; // No operands changed, just return the input node.
6283 // See if the modified node already exists.
6284 void *InsertPos = nullptr;
6285 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6288 // Nope it doesn't. Remove the node from its current place in the maps.
6290 if (!RemoveNodeFromCSEMaps(N))
6291 InsertPos = nullptr;
6293 // Now we update the operands.
6294 if (N->OperandList[0] != Op1)
6295 N->OperandList[0].set(Op1);
6296 if (N->OperandList[1] != Op2)
6297 N->OperandList[1].set(Op2);
6299 // If this gets put into a CSE map, add it.
6300 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6304 SDNode *SelectionDAG::
6305 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6306 SDValue Ops[] = { Op1, Op2, Op3 };
6307 return UpdateNodeOperands(N, Ops);
6310 SDNode *SelectionDAG::
6311 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6312 SDValue Op3, SDValue Op4) {
6313 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6314 return UpdateNodeOperands(N, Ops);
6317 SDNode *SelectionDAG::
6318 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6319 SDValue Op3, SDValue Op4, SDValue Op5) {
6320 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6321 return UpdateNodeOperands(N, Ops);
6324 SDNode *SelectionDAG::
6325 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6326 unsigned NumOps = Ops.size();
6327 assert(N->getNumOperands() == NumOps &&
6328 "Update with wrong number of operands");
6330 // If no operands changed just return the input node.
6331 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6334 // See if the modified node already exists.
6335 void *InsertPos = nullptr;
6336 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6339 // Nope it doesn't. Remove the node from its current place in the maps.
6341 if (!RemoveNodeFromCSEMaps(N))
6342 InsertPos = nullptr;
6344 // Now we update the operands.
6345 for (unsigned i = 0; i != NumOps; ++i)
6346 if (N->OperandList[i] != Ops[i])
6347 N->OperandList[i].set(Ops[i]);
6349 // If this gets put into a CSE map, add it.
6350 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6354 /// DropOperands - Release the operands and set this node to have
6356 void SDNode::DropOperands() {
6357 // Unlike the code in MorphNodeTo that does this, we don't need to
6358 // watch for dead nodes here.
6359 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6365 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6368 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6370 SDVTList VTs = getVTList(VT);
6371 return SelectNodeTo(N, MachineOpc, VTs, None);
6374 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6375 EVT VT, SDValue Op1) {
6376 SDVTList VTs = getVTList(VT);
6377 SDValue Ops[] = { Op1 };
6378 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6381 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6382 EVT VT, SDValue Op1,
6384 SDVTList VTs = getVTList(VT);
6385 SDValue Ops[] = { Op1, Op2 };
6386 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6389 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6390 EVT VT, SDValue Op1,
6391 SDValue Op2, SDValue Op3) {
6392 SDVTList VTs = getVTList(VT);
6393 SDValue Ops[] = { Op1, Op2, Op3 };
6394 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6397 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6398 EVT VT, ArrayRef<SDValue> Ops) {
6399 SDVTList VTs = getVTList(VT);
6400 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6403 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6404 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6405 SDVTList VTs = getVTList(VT1, VT2);
6406 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6409 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6411 SDVTList VTs = getVTList(VT1, VT2);
6412 return SelectNodeTo(N, MachineOpc, VTs, None);
6415 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6416 EVT VT1, EVT VT2, EVT VT3,
6417 ArrayRef<SDValue> Ops) {
6418 SDVTList VTs = getVTList(VT1, VT2, VT3);
6419 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6422 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6424 SDValue Op1, SDValue Op2) {
6425 SDVTList VTs = getVTList(VT1, VT2);
6426 SDValue Ops[] = { Op1, Op2 };
6427 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6430 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6431 SDVTList VTs,ArrayRef<SDValue> Ops) {
6432 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6433 // Reset the NodeID to -1.
6436 ReplaceAllUsesWith(N, New);
6442 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6443 /// the line number information on the merged node since it is not possible to
6444 /// preserve the information that operation is associated with multiple lines.
6445 /// This will make the debugger working better at -O0, were there is a higher
6446 /// probability having other instructions associated with that line.
6448 /// For IROrder, we keep the smaller of the two
6449 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6450 DebugLoc NLoc = N->getDebugLoc();
6451 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6452 N->setDebugLoc(DebugLoc());
6454 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6455 N->setIROrder(Order);
6459 /// MorphNodeTo - This *mutates* the specified node to have the specified
6460 /// return type, opcode, and operands.
6462 /// Note that MorphNodeTo returns the resultant node. If there is already a
6463 /// node of the specified opcode and operands, it returns that node instead of
6464 /// the current one. Note that the SDLoc need not be the same.
6466 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6467 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6468 /// node, and because it doesn't require CSE recalculation for any of
6469 /// the node's users.
6471 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6472 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6473 /// the legalizer which maintain worklists that would need to be updated when
6474 /// deleting things.
6475 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6476 SDVTList VTs, ArrayRef<SDValue> Ops) {
6477 // If an identical node already exists, use it.
6479 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6480 FoldingSetNodeID ID;
6481 AddNodeIDNode(ID, Opc, VTs, Ops);
6482 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6483 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6486 if (!RemoveNodeFromCSEMaps(N))
6489 // Start the morphing.
6491 N->ValueList = VTs.VTs;
6492 N->NumValues = VTs.NumVTs;
6494 // Clear the operands list, updating used nodes to remove this from their
6495 // use list. Keep track of any operands that become dead as a result.
6496 SmallPtrSet<SDNode*, 16> DeadNodeSet;
6497 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6499 SDNode *Used = Use.getNode();
6501 if (Used->use_empty())
6502 DeadNodeSet.insert(Used);
6505 // For MachineNode, initialize the memory references information.
6506 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6507 MN->setMemRefs(nullptr, nullptr);
6509 // Swap for an appropriately sized array from the recycler.
6511 createOperands(N, Ops);
6513 // Delete any nodes that are still dead after adding the uses for the
6515 if (!DeadNodeSet.empty()) {
6516 SmallVector<SDNode *, 16> DeadNodes;
6517 for (SDNode *N : DeadNodeSet)
6519 DeadNodes.push_back(N);
6520 RemoveDeadNodes(DeadNodes);
6524 CSEMap.InsertNode(N, IP); // Memoize the new node.
6529 /// getMachineNode - These are used for target selectors to create a new node
6530 /// with specified return type(s), MachineInstr opcode, and operands.
6532 /// Note that getMachineNode returns the resultant node. If there is already a
6533 /// node of the specified opcode and operands, it returns that node instead of
6534 /// the current one.
6535 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6537 SDVTList VTs = getVTList(VT);
6538 return getMachineNode(Opcode, dl, VTs, None);
6541 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6542 EVT VT, SDValue Op1) {
6543 SDVTList VTs = getVTList(VT);
6544 SDValue Ops[] = { Op1 };
6545 return getMachineNode(Opcode, dl, VTs, Ops);
6548 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6549 EVT VT, SDValue Op1, SDValue Op2) {
6550 SDVTList VTs = getVTList(VT);
6551 SDValue Ops[] = { Op1, Op2 };
6552 return getMachineNode(Opcode, dl, VTs, Ops);
6555 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6556 EVT VT, SDValue Op1, SDValue Op2,
6558 SDVTList VTs = getVTList(VT);
6559 SDValue Ops[] = { Op1, Op2, Op3 };
6560 return getMachineNode(Opcode, dl, VTs, Ops);
6563 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6564 EVT VT, ArrayRef<SDValue> Ops) {
6565 SDVTList VTs = getVTList(VT);
6566 return getMachineNode(Opcode, dl, VTs, Ops);
6569 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6570 EVT VT1, EVT VT2, SDValue Op1,
6572 SDVTList VTs = getVTList(VT1, VT2);
6573 SDValue Ops[] = { Op1, Op2 };
6574 return getMachineNode(Opcode, dl, VTs, Ops);
6577 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6578 EVT VT1, EVT VT2, SDValue Op1,
6579 SDValue Op2, SDValue Op3) {
6580 SDVTList VTs = getVTList(VT1, VT2);
6581 SDValue Ops[] = { Op1, Op2, Op3 };
6582 return getMachineNode(Opcode, dl, VTs, Ops);
6585 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6587 ArrayRef<SDValue> Ops) {
6588 SDVTList VTs = getVTList(VT1, VT2);
6589 return getMachineNode(Opcode, dl, VTs, Ops);
6592 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6593 EVT VT1, EVT VT2, EVT VT3,
6594 SDValue Op1, SDValue Op2) {
6595 SDVTList VTs = getVTList(VT1, VT2, VT3);
6596 SDValue Ops[] = { Op1, Op2 };
6597 return getMachineNode(Opcode, dl, VTs, Ops);
6600 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6601 EVT VT1, EVT VT2, EVT VT3,
6602 SDValue Op1, SDValue Op2,
6604 SDVTList VTs = getVTList(VT1, VT2, VT3);
6605 SDValue Ops[] = { Op1, Op2, Op3 };
6606 return getMachineNode(Opcode, dl, VTs, Ops);
6609 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6610 EVT VT1, EVT VT2, EVT VT3,
6611 ArrayRef<SDValue> Ops) {
6612 SDVTList VTs = getVTList(VT1, VT2, VT3);
6613 return getMachineNode(Opcode, dl, VTs, Ops);
6616 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6617 ArrayRef<EVT> ResultTys,
6618 ArrayRef<SDValue> Ops) {
6619 SDVTList VTs = getVTList(ResultTys);
6620 return getMachineNode(Opcode, dl, VTs, Ops);
6623 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6625 ArrayRef<SDValue> Ops) {
6626 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6631 FoldingSetNodeID ID;
6632 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6634 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6635 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6639 // Allocate a new MachineSDNode.
6640 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6641 createOperands(N, Ops);
6644 CSEMap.InsertNode(N, IP);
6650 /// getTargetExtractSubreg - A convenience function for creating
6651 /// TargetOpcode::EXTRACT_SUBREG nodes.
6652 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6654 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6655 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6656 VT, Operand, SRIdxVal);
6657 return SDValue(Subreg, 0);
6660 /// getTargetInsertSubreg - A convenience function for creating
6661 /// TargetOpcode::INSERT_SUBREG nodes.
6662 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6663 SDValue Operand, SDValue Subreg) {
6664 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6665 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6666 VT, Operand, Subreg, SRIdxVal);
6667 return SDValue(Result, 0);
6670 /// getNodeIfExists - Get the specified node if it's already available, or
6671 /// else return NULL.
6672 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6673 ArrayRef<SDValue> Ops,
6674 const SDNodeFlags *Flags) {
6675 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6676 FoldingSetNodeID ID;
6677 AddNodeIDNode(ID, Opcode, VTList, Ops);
6679 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6681 E->intersectFlagsWith(Flags);
6688 /// getDbgValue - Creates a SDDbgValue node.
6691 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6692 unsigned R, bool IsIndirect, uint64_t Off,
6693 const DebugLoc &DL, unsigned O) {
6694 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6695 "Expected inlined-at fields to agree");
6696 return new (DbgInfo->getAlloc())
6697 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6701 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6702 const Value *C, uint64_t Off,
6703 const DebugLoc &DL, unsigned O) {
6704 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6705 "Expected inlined-at fields to agree");
6706 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6710 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6711 unsigned FI, uint64_t Off,
6714 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6715 "Expected inlined-at fields to agree");
6716 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6721 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6722 /// pointed to by a use iterator is deleted, increment the use iterator
6723 /// so that it doesn't dangle.
6725 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6726 SDNode::use_iterator &UI;
6727 SDNode::use_iterator &UE;
6729 void NodeDeleted(SDNode *N, SDNode *E) override {
6730 // Increment the iterator as needed.
6731 while (UI != UE && N == *UI)
6736 RAUWUpdateListener(SelectionDAG &d,
6737 SDNode::use_iterator &ui,
6738 SDNode::use_iterator &ue)
6739 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6744 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6745 /// This can cause recursive merging of nodes in the DAG.
6747 /// This version assumes From has a single result value.
6749 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6750 SDNode *From = FromN.getNode();
6751 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6752 "Cannot replace with this method!");
6753 assert(From != To.getNode() && "Cannot replace uses of with self");
6755 // Preserve Debug Values
6756 TransferDbgValues(FromN, To);
6758 // Iterate over all the existing uses of From. New uses will be added
6759 // to the beginning of the use list, which we avoid visiting.
6760 // This specifically avoids visiting uses of From that arise while the
6761 // replacement is happening, because any such uses would be the result
6762 // of CSE: If an existing node looks like From after one of its operands
6763 // is replaced by To, we don't want to replace of all its users with To
6764 // too. See PR3018 for more info.
6765 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6766 RAUWUpdateListener Listener(*this, UI, UE);
6770 // This node is about to morph, remove its old self from the CSE maps.
6771 RemoveNodeFromCSEMaps(User);
6773 // A user can appear in a use list multiple times, and when this
6774 // happens the uses are usually next to each other in the list.
6775 // To help reduce the number of CSE recomputations, process all
6776 // the uses of this user that we can find this way.
6778 SDUse &Use = UI.getUse();
6781 } while (UI != UE && *UI == User);
6783 // Now that we have modified User, add it back to the CSE maps. If it
6784 // already exists there, recursively merge the results together.
6785 AddModifiedNodeToCSEMaps(User);
6789 // If we just RAUW'd the root, take note.
6790 if (FromN == getRoot())
6794 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6795 /// This can cause recursive merging of nodes in the DAG.
6797 /// This version assumes that for each value of From, there is a
6798 /// corresponding value in To in the same position with the same type.
6800 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6802 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6803 assert((!From->hasAnyUseOfValue(i) ||
6804 From->getValueType(i) == To->getValueType(i)) &&
6805 "Cannot use this version of ReplaceAllUsesWith!");
6808 // Handle the trivial case.
6812 // Preserve Debug Info. Only do this if there's a use.
6813 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6814 if (From->hasAnyUseOfValue(i)) {
6815 assert((i < To->getNumValues()) && "Invalid To location");
6816 TransferDbgValues(SDValue(From, i), SDValue(To, i));
6819 // Iterate over just the existing users of From. See the comments in
6820 // the ReplaceAllUsesWith above.
6821 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6822 RAUWUpdateListener Listener(*this, UI, UE);
6826 // This node is about to morph, remove its old self from the CSE maps.
6827 RemoveNodeFromCSEMaps(User);
6829 // A user can appear in a use list multiple times, and when this
6830 // happens the uses are usually next to each other in the list.
6831 // To help reduce the number of CSE recomputations, process all
6832 // the uses of this user that we can find this way.
6834 SDUse &Use = UI.getUse();
6837 } while (UI != UE && *UI == User);
6839 // Now that we have modified User, add it back to the CSE maps. If it
6840 // already exists there, recursively merge the results together.
6841 AddModifiedNodeToCSEMaps(User);
6844 // If we just RAUW'd the root, take note.
6845 if (From == getRoot().getNode())
6846 setRoot(SDValue(To, getRoot().getResNo()));
6849 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6850 /// This can cause recursive merging of nodes in the DAG.
6852 /// This version can replace From with any result values. To must match the
6853 /// number and types of values returned by From.
6854 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6855 if (From->getNumValues() == 1) // Handle the simple case efficiently.
6856 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6858 // Preserve Debug Info.
6859 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6860 TransferDbgValues(SDValue(From, i), *To);
6862 // Iterate over just the existing users of From. See the comments in
6863 // the ReplaceAllUsesWith above.
6864 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6865 RAUWUpdateListener Listener(*this, UI, UE);
6869 // This node is about to morph, remove its old self from the CSE maps.
6870 RemoveNodeFromCSEMaps(User);
6872 // A user can appear in a use list multiple times, and when this
6873 // happens the uses are usually next to each other in the list.
6874 // To help reduce the number of CSE recomputations, process all
6875 // the uses of this user that we can find this way.
6877 SDUse &Use = UI.getUse();
6878 const SDValue &ToOp = To[Use.getResNo()];
6881 } while (UI != UE && *UI == User);
6883 // Now that we have modified User, add it back to the CSE maps. If it
6884 // already exists there, recursively merge the results together.
6885 AddModifiedNodeToCSEMaps(User);
6888 // If we just RAUW'd the root, take note.
6889 if (From == getRoot().getNode())
6890 setRoot(SDValue(To[getRoot().getResNo()]));
6893 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6894 /// uses of other values produced by From.getNode() alone. The Deleted
6895 /// vector is handled the same way as for ReplaceAllUsesWith.
6896 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6897 // Handle the really simple, really trivial case efficiently.
6898 if (From == To) return;
6900 // Handle the simple, trivial, case efficiently.
6901 if (From.getNode()->getNumValues() == 1) {
6902 ReplaceAllUsesWith(From, To);
6906 // Preserve Debug Info.
6907 TransferDbgValues(From, To);
6909 // Iterate over just the existing users of From. See the comments in
6910 // the ReplaceAllUsesWith above.
6911 SDNode::use_iterator UI = From.getNode()->use_begin(),
6912 UE = From.getNode()->use_end();
6913 RAUWUpdateListener Listener(*this, UI, UE);
6916 bool UserRemovedFromCSEMaps = false;
6918 // A user can appear in a use list multiple times, and when this
6919 // happens the uses are usually next to each other in the list.
6920 // To help reduce the number of CSE recomputations, process all
6921 // the uses of this user that we can find this way.
6923 SDUse &Use = UI.getUse();
6925 // Skip uses of different values from the same node.
6926 if (Use.getResNo() != From.getResNo()) {
6931 // If this node hasn't been modified yet, it's still in the CSE maps,
6932 // so remove its old self from the CSE maps.
6933 if (!UserRemovedFromCSEMaps) {
6934 RemoveNodeFromCSEMaps(User);
6935 UserRemovedFromCSEMaps = true;
6940 } while (UI != UE && *UI == User);
6942 // We are iterating over all uses of the From node, so if a use
6943 // doesn't use the specific value, no changes are made.
6944 if (!UserRemovedFromCSEMaps)
6947 // Now that we have modified User, add it back to the CSE maps. If it
6948 // already exists there, recursively merge the results together.
6949 AddModifiedNodeToCSEMaps(User);
6952 // If we just RAUW'd the root, take note.
6953 if (From == getRoot())
6958 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
6959 /// to record information about a use.
6966 /// operator< - Sort Memos by User.
6967 bool operator<(const UseMemo &L, const UseMemo &R) {
6968 return (intptr_t)L.User < (intptr_t)R.User;
6972 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
6973 /// uses of other values produced by From.getNode() alone. The same value
6974 /// may appear in both the From and To list. The Deleted vector is
6975 /// handled the same way as for ReplaceAllUsesWith.
6976 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
6979 // Handle the simple, trivial case efficiently.
6981 return ReplaceAllUsesOfValueWith(*From, *To);
6983 TransferDbgValues(*From, *To);
6985 // Read up all the uses and make records of them. This helps
6986 // processing new uses that are introduced during the
6987 // replacement process.
6988 SmallVector<UseMemo, 4> Uses;
6989 for (unsigned i = 0; i != Num; ++i) {
6990 unsigned FromResNo = From[i].getResNo();
6991 SDNode *FromNode = From[i].getNode();
6992 for (SDNode::use_iterator UI = FromNode->use_begin(),
6993 E = FromNode->use_end(); UI != E; ++UI) {
6994 SDUse &Use = UI.getUse();
6995 if (Use.getResNo() == FromResNo) {
6996 UseMemo Memo = { *UI, i, &Use };
6997 Uses.push_back(Memo);
7002 // Sort the uses, so that all the uses from a given User are together.
7003 std::sort(Uses.begin(), Uses.end());
7005 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
7006 UseIndex != UseIndexEnd; ) {
7007 // We know that this user uses some value of From. If it is the right
7008 // value, update it.
7009 SDNode *User = Uses[UseIndex].User;
7011 // This node is about to morph, remove its old self from the CSE maps.
7012 RemoveNodeFromCSEMaps(User);
7014 // The Uses array is sorted, so all the uses for a given User
7015 // are next to each other in the list.
7016 // To help reduce the number of CSE recomputations, process all
7017 // the uses of this user that we can find this way.
7019 unsigned i = Uses[UseIndex].Index;
7020 SDUse &Use = *Uses[UseIndex].Use;
7024 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
7026 // Now that we have modified User, add it back to the CSE maps. If it
7027 // already exists there, recursively merge the results together.
7028 AddModifiedNodeToCSEMaps(User);
7032 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
7033 /// based on their topological order. It returns the maximum id and a vector
7034 /// of the SDNodes* in assigned order by reference.
7035 unsigned SelectionDAG::AssignTopologicalOrder() {
7037 unsigned DAGSize = 0;
7039 // SortedPos tracks the progress of the algorithm. Nodes before it are
7040 // sorted, nodes after it are unsorted. When the algorithm completes
7041 // it is at the end of the list.
7042 allnodes_iterator SortedPos = allnodes_begin();
7044 // Visit all the nodes. Move nodes with no operands to the front of
7045 // the list immediately. Annotate nodes that do have operands with their
7046 // operand count. Before we do this, the Node Id fields of the nodes
7047 // may contain arbitrary values. After, the Node Id fields for nodes
7048 // before SortedPos will contain the topological sort index, and the
7049 // Node Id fields for nodes At SortedPos and after will contain the
7050 // count of outstanding operands.
7051 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7053 checkForCycles(N, this);
7054 unsigned Degree = N->getNumOperands();
7056 // A node with no uses, add it to the result array immediately.
7057 N->setNodeId(DAGSize++);
7058 allnodes_iterator Q(N);
7060 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7061 assert(SortedPos != AllNodes.end() && "Overran node list");
7064 // Temporarily use the Node Id as scratch space for the degree count.
7065 N->setNodeId(Degree);
7069 // Visit all the nodes. As we iterate, move nodes into sorted order,
7070 // such that by the time the end is reached all nodes will be sorted.
7071 for (SDNode &Node : allnodes()) {
7073 checkForCycles(N, this);
7074 // N is in sorted position, so all its uses have one less operand
7075 // that needs to be sorted.
7076 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7079 unsigned Degree = P->getNodeId();
7080 assert(Degree != 0 && "Invalid node degree");
7083 // All of P's operands are sorted, so P may sorted now.
7084 P->setNodeId(DAGSize++);
7085 if (P->getIterator() != SortedPos)
7086 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7087 assert(SortedPos != AllNodes.end() && "Overran node list");
7090 // Update P's outstanding operand count.
7091 P->setNodeId(Degree);
7094 if (Node.getIterator() == SortedPos) {
7096 allnodes_iterator I(N);
7098 dbgs() << "Overran sorted position:\n";
7099 S->dumprFull(this); dbgs() << "\n";
7100 dbgs() << "Checking if this is due to cycles\n";
7101 checkForCycles(this, true);
7103 llvm_unreachable(nullptr);
7107 assert(SortedPos == AllNodes.end() &&
7108 "Topological sort incomplete!");
7109 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7110 "First node in topological sort is not the entry token!");
7111 assert(AllNodes.front().getNodeId() == 0 &&
7112 "First node in topological sort has non-zero id!");
7113 assert(AllNodes.front().getNumOperands() == 0 &&
7114 "First node in topological sort has operands!");
7115 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7116 "Last node in topologic sort has unexpected id!");
7117 assert(AllNodes.back().use_empty() &&
7118 "Last node in topologic sort has users!");
7119 assert(DAGSize == allnodes_size() && "Node count mismatch!");
7123 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7124 /// value is produced by SD.
7125 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7127 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7128 SD->setHasDebugValue(true);
7130 DbgInfo->add(DB, SD, isParameter);
7133 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
7134 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
7135 if (From == To || !From.getNode()->getHasDebugValue())
7137 SDNode *FromNode = From.getNode();
7138 SDNode *ToNode = To.getNode();
7139 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
7140 SmallVector<SDDbgValue *, 2> ClonedDVs;
7141 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
7143 SDDbgValue *Dbg = *I;
7144 // Only add Dbgvalues attached to same ResNo.
7145 if (Dbg->getKind() == SDDbgValue::SDNODE &&
7146 Dbg->getSDNode() == From.getNode() &&
7147 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
7148 assert(FromNode != ToNode &&
7149 "Should not transfer Debug Values intranode");
7151 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
7152 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
7153 Dbg->getDebugLoc(), Dbg->getOrder());
7154 ClonedDVs.push_back(Clone);
7155 Dbg->setIsInvalidated();
7158 for (SDDbgValue *I : ClonedDVs)
7159 AddDbgValue(I, ToNode, false);
7162 //===----------------------------------------------------------------------===//
7164 //===----------------------------------------------------------------------===//
7166 bool llvm::isNullConstant(SDValue V) {
7167 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7168 return Const != nullptr && Const->isNullValue();
7171 bool llvm::isNullFPConstant(SDValue V) {
7172 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7173 return Const != nullptr && Const->isZero() && !Const->isNegative();
7176 bool llvm::isAllOnesConstant(SDValue V) {
7177 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7178 return Const != nullptr && Const->isAllOnesValue();
7181 bool llvm::isOneConstant(SDValue V) {
7182 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7183 return Const != nullptr && Const->isOne();
7186 bool llvm::isBitwiseNot(SDValue V) {
7187 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7190 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7191 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7194 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7195 BitVector UndefElements;
7196 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7198 // BuildVectors can truncate their operands. Ignore that case here.
7199 // FIXME: We blindly ignore splats which include undef which is overly
7201 if (CN && UndefElements.none() &&
7202 CN->getValueType(0) == N.getValueType().getScalarType())
7209 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7210 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7213 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7214 BitVector UndefElements;
7215 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7217 if (CN && UndefElements.none())
7224 HandleSDNode::~HandleSDNode() {
7228 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7230 const GlobalValue *GA, EVT VT,
7231 int64_t o, unsigned char TF)
7232 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7236 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7237 EVT VT, unsigned SrcAS,
7239 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7240 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7242 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7243 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7244 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7245 MemSDNodeBits.IsVolatile = MMO->isVolatile();
7246 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7247 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7248 MemSDNodeBits.IsInvariant = MMO->isInvariant();
7250 // We check here that the size of the memory operand fits within the size of
7251 // the MMO. This is because the MMO might indicate only a possible address
7252 // range instead of specifying the affected memory addresses precisely.
7253 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7256 /// Profile - Gather unique data for the node.
7258 void SDNode::Profile(FoldingSetNodeID &ID) const {
7259 AddNodeIDNode(ID, this);
7264 std::vector<EVT> VTs;
7267 VTs.reserve(MVT::LAST_VALUETYPE);
7268 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7269 VTs.push_back(MVT((MVT::SimpleValueType)i));
7274 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
7275 static ManagedStatic<EVTArray> SimpleVTArray;
7276 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
7278 /// getValueTypeList - Return a pointer to the specified value type.
7280 const EVT *SDNode::getValueTypeList(EVT VT) {
7281 if (VT.isExtended()) {
7282 sys::SmartScopedLock<true> Lock(*VTMutex);
7283 return &(*EVTs->insert(VT).first);
7285 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7286 "Value type out of range!");
7287 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7291 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7292 /// indicated value. This method ignores uses of other values defined by this
7294 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7295 assert(Value < getNumValues() && "Bad value!");
7297 // TODO: Only iterate over uses of a given value of the node
7298 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7299 if (UI.getUse().getResNo() == Value) {
7306 // Found exactly the right number of uses?
7311 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7312 /// value. This method ignores uses of other values defined by this operation.
7313 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7314 assert(Value < getNumValues() && "Bad value!");
7316 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7317 if (UI.getUse().getResNo() == Value)
7324 /// isOnlyUserOf - Return true if this node is the only use of N.
7326 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7328 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7339 /// Return true if the only users of N are contained in Nodes.
7340 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7342 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7344 if (llvm::any_of(Nodes,
7345 [&User](const SDNode *Node) { return User == Node; }))
7354 /// isOperand - Return true if this node is an operand of N.
7356 bool SDValue::isOperandOf(const SDNode *N) const {
7357 for (const SDValue &Op : N->op_values())
7363 bool SDNode::isOperandOf(const SDNode *N) const {
7364 for (const SDValue &Op : N->op_values())
7365 if (this == Op.getNode())
7370 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7371 /// be a chain) reaches the specified operand without crossing any
7372 /// side-effecting instructions on any chain path. In practice, this looks
7373 /// through token factors and non-volatile loads. In order to remain efficient,
7374 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7376 /// Note that we only need to examine chains when we're searching for
7377 /// side-effects; SelectionDAG requires that all side-effects are represented
7378 /// by chains, even if another operand would force a specific ordering. This
7379 /// constraint is necessary to allow transformations like splitting loads.
7380 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7381 unsigned Depth) const {
7382 if (*this == Dest) return true;
7384 // Don't search too deeply, we just want to be able to see through
7385 // TokenFactor's etc.
7386 if (Depth == 0) return false;
7388 // If this is a token factor, all inputs to the TF happen in parallel.
7389 if (getOpcode() == ISD::TokenFactor) {
7390 // First, try a shallow search.
7391 if (is_contained((*this)->ops(), Dest)) {
7392 // We found the chain we want as an operand of this TokenFactor.
7393 // Essentially, we reach the chain without side-effects if we could
7394 // serialize the TokenFactor into a simple chain of operations with
7395 // Dest as the last operation. This is automatically true if the
7396 // chain has one use: there are no other ordering constraints.
7397 // If the chain has more than one use, we give up: some other
7398 // use of Dest might force a side-effect between Dest and the current
7400 if (Dest.hasOneUse())
7403 // Next, try a deep search: check whether every operand of the TokenFactor
7405 return all_of((*this)->ops(), [=](SDValue Op) {
7406 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7410 // Loads don't have side effects, look through them.
7411 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7412 if (!Ld->isVolatile())
7413 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7418 bool SDNode::hasPredecessor(const SDNode *N) const {
7419 SmallPtrSet<const SDNode *, 32> Visited;
7420 SmallVector<const SDNode *, 16> Worklist;
7421 Worklist.push_back(this);
7422 return hasPredecessorHelper(N, Visited, Worklist);
7425 const SDNodeFlags *SDNode::getFlags() const {
7426 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
7427 return &FlagsNode->Flags;
7431 void SDNode::intersectFlagsWith(const SDNodeFlags *Flags) {
7432 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
7433 FlagsNode->Flags.intersectWith(Flags);
7436 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7437 assert(N->getNumValues() == 1 &&
7438 "Can't unroll a vector with multiple results!");
7440 EVT VT = N->getValueType(0);
7441 unsigned NE = VT.getVectorNumElements();
7442 EVT EltVT = VT.getVectorElementType();
7445 SmallVector<SDValue, 8> Scalars;
7446 SmallVector<SDValue, 4> Operands(N->getNumOperands());
7448 // If ResNE is 0, fully unroll the vector op.
7451 else if (NE > ResNE)
7455 for (i= 0; i != NE; ++i) {
7456 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7457 SDValue Operand = N->getOperand(j);
7458 EVT OperandVT = Operand.getValueType();
7459 if (OperandVT.isVector()) {
7460 // A vector operand; extract a single element.
7461 EVT OperandEltVT = OperandVT.getVectorElementType();
7463 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7464 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7466 // A scalar operand; just use it as is.
7467 Operands[j] = Operand;
7471 switch (N->getOpcode()) {
7473 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7478 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7485 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7486 getShiftAmountOperand(Operands[0].getValueType(),
7489 case ISD::SIGN_EXTEND_INREG:
7490 case ISD::FP_ROUND_INREG: {
7491 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7492 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7494 getValueType(ExtVT)));
7499 for (; i < ResNE; ++i)
7500 Scalars.push_back(getUNDEF(EltVT));
7502 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7503 return getBuildVector(VecVT, dl, Scalars);
7506 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7510 if (LD->isVolatile() || Base->isVolatile())
7512 if (LD->isIndexed() || Base->isIndexed())
7514 if (LD->getChain() != Base->getChain())
7516 EVT VT = LD->getValueType(0);
7517 if (VT.getSizeInBits() / 8 != Bytes)
7520 SDValue Loc = LD->getOperand(1);
7521 SDValue BaseLoc = Base->getOperand(1);
7522 if (Loc.getOpcode() == ISD::FrameIndex) {
7523 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7525 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7526 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7527 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7528 int FS = MFI.getObjectSize(FI);
7529 int BFS = MFI.getObjectSize(BFI);
7530 if (FS != BFS || FS != (int)Bytes) return false;
7531 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
7535 if (isBaseWithConstantOffset(Loc)) {
7536 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
7537 if (Loc.getOperand(0) == BaseLoc) {
7538 // If the base location is a simple address with no offset itself, then
7539 // the second load's first add operand should be the base address.
7540 if (LocOffset == Dist * (int)Bytes)
7542 } else if (isBaseWithConstantOffset(BaseLoc)) {
7543 // The base location itself has an offset, so subtract that value from the
7544 // second load's offset before comparing to distance * size.
7546 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
7547 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
7548 if ((LocOffset - BOffset) == Dist * (int)Bytes)
7553 const GlobalValue *GV1 = nullptr;
7554 const GlobalValue *GV2 = nullptr;
7555 int64_t Offset1 = 0;
7556 int64_t Offset2 = 0;
7557 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7558 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7559 if (isGA1 && isGA2 && GV1 == GV2)
7560 return Offset1 == (Offset2 + Dist*Bytes);
7565 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7566 /// it cannot be inferred.
7567 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7568 // If this is a GlobalAddress + cst, return the alignment.
7569 const GlobalValue *GV;
7570 int64_t GVOffset = 0;
7571 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7572 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7573 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
7574 llvm::computeKnownBits(const_cast<GlobalValue *>(GV), KnownZero, KnownOne,
7576 unsigned AlignBits = KnownZero.countTrailingOnes();
7577 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7579 return MinAlign(Align, GVOffset);
7582 // If this is a direct reference to a stack slot, use information about the
7583 // stack slot's alignment.
7584 int FrameIdx = 1 << 31;
7585 int64_t FrameOffset = 0;
7586 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7587 FrameIdx = FI->getIndex();
7588 } else if (isBaseWithConstantOffset(Ptr) &&
7589 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7591 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7592 FrameOffset = Ptr.getConstantOperandVal(1);
7595 if (FrameIdx != (1 << 31)) {
7596 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7597 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7605 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7606 /// which is split (or expanded) into two not necessarily identical pieces.
7607 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7608 // Currently all types are split in half.
7610 if (!VT.isVector()) {
7611 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7613 unsigned NumElements = VT.getVectorNumElements();
7614 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7615 LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
7618 return std::make_pair(LoVT, HiVT);
7621 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7623 std::pair<SDValue, SDValue>
7624 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7626 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7627 N.getValueType().getVectorNumElements() &&
7628 "More vector elements requested than available!");
7630 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7631 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7632 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7633 getConstant(LoVT.getVectorNumElements(), DL,
7634 TLI->getVectorIdxTy(getDataLayout())));
7635 return std::make_pair(Lo, Hi);
7638 void SelectionDAG::ExtractVectorElements(SDValue Op,
7639 SmallVectorImpl<SDValue> &Args,
7640 unsigned Start, unsigned Count) {
7641 EVT VT = Op.getValueType();
7643 Count = VT.getVectorNumElements();
7645 EVT EltVT = VT.getVectorElementType();
7646 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7648 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7649 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7650 Op, getConstant(i, SL, IdxTy)));
7654 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7655 unsigned GlobalAddressSDNode::getAddressSpace() const {
7656 return getGlobal()->getType()->getAddressSpace();
7660 Type *ConstantPoolSDNode::getType() const {
7661 if (isMachineConstantPoolEntry())
7662 return Val.MachineCPVal->getType();
7663 return Val.ConstVal->getType();
7666 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
7668 unsigned &SplatBitSize,
7670 unsigned MinSplatBits,
7671 bool isBigEndian) const {
7672 EVT VT = getValueType(0);
7673 assert(VT.isVector() && "Expected a vector type");
7674 unsigned sz = VT.getSizeInBits();
7675 if (MinSplatBits > sz)
7678 SplatValue = APInt(sz, 0);
7679 SplatUndef = APInt(sz, 0);
7681 // Get the bits. Bits with undefined values (when the corresponding element
7682 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7683 // in SplatValue. If any of the values are not constant, give up and return
7685 unsigned int nOps = getNumOperands();
7686 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
7687 unsigned EltBitSize = VT.getScalarSizeInBits();
7689 for (unsigned j = 0; j < nOps; ++j) {
7690 unsigned i = isBigEndian ? nOps-1-j : j;
7691 SDValue OpVal = getOperand(i);
7692 unsigned BitPos = j * EltBitSize;
7694 if (OpVal.isUndef())
7695 SplatUndef.setBits(BitPos, BitPos + EltBitSize);
7696 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
7697 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltBitSize),
7699 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7700 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
7705 // The build_vector is all constants or undefs. Find the smallest element
7706 // size that splats the vector.
7708 HasAnyUndefs = (SplatUndef != 0);
7711 unsigned HalfSize = sz / 2;
7712 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7713 APInt LowValue = SplatValue.trunc(HalfSize);
7714 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7715 APInt LowUndef = SplatUndef.trunc(HalfSize);
7717 // If the two halves do not match (ignoring undef bits), stop here.
7718 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7719 MinSplatBits > HalfSize)
7722 SplatValue = HighValue | LowValue;
7723 SplatUndef = HighUndef & LowUndef;
7732 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7733 if (UndefElements) {
7734 UndefElements->clear();
7735 UndefElements->resize(getNumOperands());
7738 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7739 SDValue Op = getOperand(i);
7742 (*UndefElements)[i] = true;
7743 } else if (!Splatted) {
7745 } else if (Splatted != Op) {
7751 assert(getOperand(0).isUndef() &&
7752 "Can only have a splat without a constant for all undefs.");
7753 return getOperand(0);
7760 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7761 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7765 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7766 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7770 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7771 uint32_t BitWidth) const {
7772 if (ConstantFPSDNode *CN =
7773 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7775 APSInt IntVal(BitWidth);
7776 const APFloat &APF = CN->getValueAPF();
7777 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7782 return IntVal.exactLogBase2();
7787 bool BuildVectorSDNode::isConstant() const {
7788 for (const SDValue &Op : op_values()) {
7789 unsigned Opc = Op.getOpcode();
7790 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7796 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7797 // Find the first non-undef value in the shuffle mask.
7799 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7802 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7804 // Make sure all remaining elements are either undef or the same as the first
7806 for (int Idx = Mask[i]; i != e; ++i)
7807 if (Mask[i] >= 0 && Mask[i] != Idx)
7812 // \brief Returns the SDNode if it is a constant integer BuildVector
7813 // or constant integer.
7814 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7815 if (isa<ConstantSDNode>(N))
7817 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7819 // Treat a GlobalAddress supporting constant offset folding as a
7820 // constant integer.
7821 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7822 if (GA->getOpcode() == ISD::GlobalAddress &&
7823 TLI->isOffsetFoldingLegal(GA))
7828 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
7829 if (isa<ConstantFPSDNode>(N))
7832 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
7839 static void checkForCyclesHelper(const SDNode *N,
7840 SmallPtrSetImpl<const SDNode*> &Visited,
7841 SmallPtrSetImpl<const SDNode*> &Checked,
7842 const llvm::SelectionDAG *DAG) {
7843 // If this node has already been checked, don't check it again.
7844 if (Checked.count(N))
7847 // If a node has already been visited on this depth-first walk, reject it as
7849 if (!Visited.insert(N).second) {
7850 errs() << "Detected cycle in SelectionDAG\n";
7851 dbgs() << "Offending node:\n";
7852 N->dumprFull(DAG); dbgs() << "\n";
7856 for (const SDValue &Op : N->op_values())
7857 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7864 void llvm::checkForCycles(const llvm::SDNode *N,
7865 const llvm::SelectionDAG *DAG,
7869 #ifdef EXPENSIVE_CHECKS
7871 #endif // EXPENSIVE_CHECKS
7873 assert(N && "Checking nonexistent SDNode");
7874 SmallPtrSet<const SDNode*, 32> visited;
7875 SmallPtrSet<const SDNode*, 32> checked;
7876 checkForCyclesHelper(N, visited, checked, DAG);
7881 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7882 checkForCycles(DAG->getRoot().getNode(), DAG, force);