1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/APSInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/ISDOpcodes.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineConstantPool.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineValueType.h"
36 #include "llvm/CodeGen/RuntimeLibcalls.h"
37 #include "llvm/CodeGen/SelectionDAGNodes.h"
38 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
39 #include "llvm/CodeGen/ValueTypes.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DebugInfoMetadata.h"
44 #include "llvm/IR/DebugLoc.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/GlobalValue.h"
48 #include "llvm/IR/Metadata.h"
49 #include "llvm/IR/Type.h"
50 #include "llvm/IR/Value.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CodeGen.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/KnownBits.h"
57 #include "llvm/Support/ManagedStatic.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/Mutex.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Target/TargetLowering.h"
62 #include "llvm/Target/TargetMachine.h"
63 #include "llvm/Target/TargetOptions.h"
64 #include "llvm/Target/TargetRegisterInfo.h"
65 #include "llvm/Target/TargetSubtargetInfo.h"
78 /// makeVTList - Return an instance of the SDVTList struct initialized with the
79 /// specified members.
80 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
81 SDVTList Res = {VTs, NumVTs};
85 // Default null implementations of the callbacks.
86 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
87 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
89 //===----------------------------------------------------------------------===//
90 // ConstantFPSDNode Class
91 //===----------------------------------------------------------------------===//
93 /// isExactlyValue - We don't rely on operator== working on double values, as
94 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
95 /// As such, this method can be used to do an exact bit-for-bit comparison of
96 /// two floating point values.
97 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
98 return getValueAPF().bitwiseIsEqual(V);
101 bool ConstantFPSDNode::isValueValidForType(EVT VT,
102 const APFloat& Val) {
103 assert(VT.isFloatingPoint() && "Can only convert between FP types");
105 // convert modifies in place, so make a copy.
106 APFloat Val2 = APFloat(Val);
108 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
109 APFloat::rmNearestTiesToEven,
114 //===----------------------------------------------------------------------===//
116 //===----------------------------------------------------------------------===//
118 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
119 auto *BV = dyn_cast<BuildVectorSDNode>(N);
124 unsigned SplatBitSize;
126 EVT EltVT = N->getValueType(0).getVectorElementType();
127 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs) &&
128 EltVT.getSizeInBits() >= SplatBitSize;
131 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
132 // specializations of the more general isConstantSplatVector()?
134 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
135 // Look through a bit convert.
136 while (N->getOpcode() == ISD::BITCAST)
137 N = N->getOperand(0).getNode();
139 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
141 unsigned i = 0, e = N->getNumOperands();
143 // Skip over all of the undef values.
144 while (i != e && N->getOperand(i).isUndef())
147 // Do not accept an all-undef vector.
148 if (i == e) return false;
150 // Do not accept build_vectors that aren't all constants or which have non-~0
151 // elements. We have to be a bit careful here, as the type of the constant
152 // may not be the same as the type of the vector elements due to type
153 // legalization (the elements are promoted to a legal type for the target and
154 // a vector of a type may be legal when the base element type is not).
155 // We only want to check enough bits to cover the vector elements, because
156 // we care if the resultant vector is all ones, not whether the individual
158 SDValue NotZero = N->getOperand(i);
159 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
160 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
161 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
163 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
164 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
169 // Okay, we have at least one ~0 value, check to see if the rest match or are
170 // undefs. Even with the above element type twiddling, this should be OK, as
171 // the same type legalization should have applied to all the elements.
172 for (++i; i != e; ++i)
173 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
178 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
179 // Look through a bit convert.
180 while (N->getOpcode() == ISD::BITCAST)
181 N = N->getOperand(0).getNode();
183 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
185 bool IsAllUndef = true;
186 for (const SDValue &Op : N->op_values()) {
190 // Do not accept build_vectors that aren't all constants or which have non-0
191 // elements. We have to be a bit careful here, as the type of the constant
192 // may not be the same as the type of the vector elements due to type
193 // legalization (the elements are promoted to a legal type for the target
194 // and a vector of a type may be legal when the base element type is not).
195 // We only want to check enough bits to cover the vector elements, because
196 // we care if the resultant vector is all zeros, not whether the individual
198 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
199 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
200 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
202 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
203 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
209 // Do not accept an all-undef vector.
215 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
216 if (N->getOpcode() != ISD::BUILD_VECTOR)
219 for (const SDValue &Op : N->op_values()) {
222 if (!isa<ConstantSDNode>(Op))
228 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
229 if (N->getOpcode() != ISD::BUILD_VECTOR)
232 for (const SDValue &Op : N->op_values()) {
235 if (!isa<ConstantFPSDNode>(Op))
241 bool ISD::allOperandsUndef(const SDNode *N) {
242 // Return false if the node has no operands.
243 // This is "logically inconsistent" with the definition of "all" but
244 // is probably the desired behavior.
245 if (N->getNumOperands() == 0)
248 for (const SDValue &Op : N->op_values())
255 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
258 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
260 return ISD::SIGN_EXTEND;
262 return ISD::ZERO_EXTEND;
267 llvm_unreachable("Invalid LoadExtType");
270 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
271 // To perform this operation, we just need to swap the L and G bits of the
273 unsigned OldL = (Operation >> 2) & 1;
274 unsigned OldG = (Operation >> 1) & 1;
275 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
276 (OldL << 1) | // New G bit
277 (OldG << 2)); // New L bit.
280 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
281 unsigned Operation = Op;
283 Operation ^= 7; // Flip L, G, E bits, but not U.
285 Operation ^= 15; // Flip all of the condition bits.
287 if (Operation > ISD::SETTRUE2)
288 Operation &= ~8; // Don't let N and U bits get set.
290 return ISD::CondCode(Operation);
293 /// For an integer comparison, return 1 if the comparison is a signed operation
294 /// and 2 if the result is an unsigned comparison. Return zero if the operation
295 /// does not depend on the sign of the input (setne and seteq).
296 static int isSignedOp(ISD::CondCode Opcode) {
298 default: llvm_unreachable("Illegal integer setcc operation!");
300 case ISD::SETNE: return 0;
304 case ISD::SETGE: return 1;
308 case ISD::SETUGE: return 2;
312 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
314 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
315 // Cannot fold a signed integer setcc with an unsigned integer setcc.
316 return ISD::SETCC_INVALID;
318 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
320 // If the N and U bits get set, then the resultant comparison DOES suddenly
321 // care about orderedness, and it is true when ordered.
322 if (Op > ISD::SETTRUE2)
323 Op &= ~16; // Clear the U bit if the N bit is set.
325 // Canonicalize illegal integer setcc's.
326 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
329 return ISD::CondCode(Op);
332 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
334 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
335 // Cannot fold a signed setcc with an unsigned setcc.
336 return ISD::SETCC_INVALID;
338 // Combine all of the condition bits.
339 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
341 // Canonicalize illegal integer setcc's.
345 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
346 case ISD::SETOEQ: // SETEQ & SETU[LG]E
347 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
348 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
349 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
356 //===----------------------------------------------------------------------===//
357 // SDNode Profile Support
358 //===----------------------------------------------------------------------===//
360 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
361 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
365 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
366 /// solely with their pointer.
367 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
368 ID.AddPointer(VTList.VTs);
371 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
372 static void AddNodeIDOperands(FoldingSetNodeID &ID,
373 ArrayRef<SDValue> Ops) {
374 for (auto& Op : Ops) {
375 ID.AddPointer(Op.getNode());
376 ID.AddInteger(Op.getResNo());
380 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
381 static void AddNodeIDOperands(FoldingSetNodeID &ID,
382 ArrayRef<SDUse> Ops) {
383 for (auto& Op : Ops) {
384 ID.AddPointer(Op.getNode());
385 ID.AddInteger(Op.getResNo());
389 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
390 SDVTList VTList, ArrayRef<SDValue> OpList) {
391 AddNodeIDOpcode(ID, OpC);
392 AddNodeIDValueTypes(ID, VTList);
393 AddNodeIDOperands(ID, OpList);
396 /// If this is an SDNode with special info, add this info to the NodeID data.
397 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
398 switch (N->getOpcode()) {
399 case ISD::TargetExternalSymbol:
400 case ISD::ExternalSymbol:
402 llvm_unreachable("Should only be used on nodes with operands");
403 default: break; // Normal nodes don't need extra info.
404 case ISD::TargetConstant:
405 case ISD::Constant: {
406 const ConstantSDNode *C = cast<ConstantSDNode>(N);
407 ID.AddPointer(C->getConstantIntValue());
408 ID.AddBoolean(C->isOpaque());
411 case ISD::TargetConstantFP:
412 case ISD::ConstantFP:
413 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
415 case ISD::TargetGlobalAddress:
416 case ISD::GlobalAddress:
417 case ISD::TargetGlobalTLSAddress:
418 case ISD::GlobalTLSAddress: {
419 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
420 ID.AddPointer(GA->getGlobal());
421 ID.AddInteger(GA->getOffset());
422 ID.AddInteger(GA->getTargetFlags());
425 case ISD::BasicBlock:
426 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
429 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
431 case ISD::RegisterMask:
432 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
435 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
437 case ISD::FrameIndex:
438 case ISD::TargetFrameIndex:
439 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
442 case ISD::TargetJumpTable:
443 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
444 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
446 case ISD::ConstantPool:
447 case ISD::TargetConstantPool: {
448 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
449 ID.AddInteger(CP->getAlignment());
450 ID.AddInteger(CP->getOffset());
451 if (CP->isMachineConstantPoolEntry())
452 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
454 ID.AddPointer(CP->getConstVal());
455 ID.AddInteger(CP->getTargetFlags());
458 case ISD::TargetIndex: {
459 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
460 ID.AddInteger(TI->getIndex());
461 ID.AddInteger(TI->getOffset());
462 ID.AddInteger(TI->getTargetFlags());
466 const LoadSDNode *LD = cast<LoadSDNode>(N);
467 ID.AddInteger(LD->getMemoryVT().getRawBits());
468 ID.AddInteger(LD->getRawSubclassData());
469 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
473 const StoreSDNode *ST = cast<StoreSDNode>(N);
474 ID.AddInteger(ST->getMemoryVT().getRawBits());
475 ID.AddInteger(ST->getRawSubclassData());
476 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
479 case ISD::ATOMIC_CMP_SWAP:
480 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
481 case ISD::ATOMIC_SWAP:
482 case ISD::ATOMIC_LOAD_ADD:
483 case ISD::ATOMIC_LOAD_SUB:
484 case ISD::ATOMIC_LOAD_AND:
485 case ISD::ATOMIC_LOAD_OR:
486 case ISD::ATOMIC_LOAD_XOR:
487 case ISD::ATOMIC_LOAD_NAND:
488 case ISD::ATOMIC_LOAD_MIN:
489 case ISD::ATOMIC_LOAD_MAX:
490 case ISD::ATOMIC_LOAD_UMIN:
491 case ISD::ATOMIC_LOAD_UMAX:
492 case ISD::ATOMIC_LOAD:
493 case ISD::ATOMIC_STORE: {
494 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
495 ID.AddInteger(AT->getMemoryVT().getRawBits());
496 ID.AddInteger(AT->getRawSubclassData());
497 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
500 case ISD::PREFETCH: {
501 const MemSDNode *PF = cast<MemSDNode>(N);
502 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
505 case ISD::VECTOR_SHUFFLE: {
506 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
507 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
509 ID.AddInteger(SVN->getMaskElt(i));
512 case ISD::TargetBlockAddress:
513 case ISD::BlockAddress: {
514 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
515 ID.AddPointer(BA->getBlockAddress());
516 ID.AddInteger(BA->getOffset());
517 ID.AddInteger(BA->getTargetFlags());
520 } // end switch (N->getOpcode())
522 // Target specific memory nodes could also have address spaces to check.
523 if (N->isTargetMemoryOpcode())
524 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
527 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
529 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
530 AddNodeIDOpcode(ID, N->getOpcode());
531 // Add the return value info.
532 AddNodeIDValueTypes(ID, N->getVTList());
533 // Add the operand info.
534 AddNodeIDOperands(ID, N->ops());
536 // Handle SDNode leafs with special info.
537 AddNodeIDCustom(ID, N);
540 //===----------------------------------------------------------------------===//
541 // SelectionDAG Class
542 //===----------------------------------------------------------------------===//
544 /// doNotCSE - Return true if CSE should not be performed for this node.
545 static bool doNotCSE(SDNode *N) {
546 if (N->getValueType(0) == MVT::Glue)
547 return true; // Never CSE anything that produces a flag.
549 switch (N->getOpcode()) {
551 case ISD::HANDLENODE:
553 return true; // Never CSE these nodes.
556 // Check that remaining values produced are not flags.
557 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
558 if (N->getValueType(i) == MVT::Glue)
559 return true; // Never CSE anything that produces a flag.
564 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
566 void SelectionDAG::RemoveDeadNodes() {
567 // Create a dummy node (which is not added to allnodes), that adds a reference
568 // to the root node, preventing it from being deleted.
569 HandleSDNode Dummy(getRoot());
571 SmallVector<SDNode*, 128> DeadNodes;
573 // Add all obviously-dead nodes to the DeadNodes worklist.
574 for (SDNode &Node : allnodes())
575 if (Node.use_empty())
576 DeadNodes.push_back(&Node);
578 RemoveDeadNodes(DeadNodes);
580 // If the root changed (e.g. it was a dead load, update the root).
581 setRoot(Dummy.getValue());
584 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
585 /// given list, and any nodes that become unreachable as a result.
586 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
588 // Process the worklist, deleting the nodes and adding their uses to the
590 while (!DeadNodes.empty()) {
591 SDNode *N = DeadNodes.pop_back_val();
592 // Skip to next node if we've already managed to delete the node. This could
593 // happen if replacing a node causes a node previously added to the node to
595 if (N->getOpcode() == ISD::DELETED_NODE)
598 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
599 DUL->NodeDeleted(N, nullptr);
601 // Take the node out of the appropriate CSE map.
602 RemoveNodeFromCSEMaps(N);
604 // Next, brutally remove the operand list. This is safe to do, as there are
605 // no cycles in the graph.
606 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
608 SDNode *Operand = Use.getNode();
611 // Now that we removed this operand, see if there are no uses of it left.
612 if (Operand->use_empty())
613 DeadNodes.push_back(Operand);
620 void SelectionDAG::RemoveDeadNode(SDNode *N){
621 SmallVector<SDNode*, 16> DeadNodes(1, N);
623 // Create a dummy node that adds a reference to the root node, preventing
624 // it from being deleted. (This matters if the root is an operand of the
626 HandleSDNode Dummy(getRoot());
628 RemoveDeadNodes(DeadNodes);
631 void SelectionDAG::DeleteNode(SDNode *N) {
632 // First take this out of the appropriate CSE map.
633 RemoveNodeFromCSEMaps(N);
635 // Finally, remove uses due to operands of this node, remove from the
636 // AllNodes list, and delete the node.
637 DeleteNodeNotInCSEMaps(N);
640 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
641 assert(N->getIterator() != AllNodes.begin() &&
642 "Cannot delete the entry node!");
643 assert(N->use_empty() && "Cannot delete a node that is not dead!");
645 // Drop all of the operands and decrement used node's use counts.
651 void SDDbgInfo::erase(const SDNode *Node) {
652 DbgValMapType::iterator I = DbgValMap.find(Node);
653 if (I == DbgValMap.end())
655 for (auto &Val: I->second)
656 Val->setIsInvalidated();
660 void SelectionDAG::DeallocateNode(SDNode *N) {
661 // If we have operands, deallocate them.
664 NodeAllocator.Deallocate(AllNodes.remove(N));
666 // Set the opcode to DELETED_NODE to help catch bugs when node
667 // memory is reallocated.
668 // FIXME: There are places in SDag that have grown a dependency on the opcode
669 // value in the released node.
670 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
671 N->NodeType = ISD::DELETED_NODE;
673 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
674 // them and forget about that node.
679 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
680 static void VerifySDNode(SDNode *N) {
681 switch (N->getOpcode()) {
684 case ISD::BUILD_PAIR: {
685 EVT VT = N->getValueType(0);
686 assert(N->getNumValues() == 1 && "Too many results!");
687 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
688 "Wrong return type!");
689 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
690 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
691 "Mismatched operand types!");
692 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
693 "Wrong operand type!");
694 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
695 "Wrong return type size");
698 case ISD::BUILD_VECTOR: {
699 assert(N->getNumValues() == 1 && "Too many results!");
700 assert(N->getValueType(0).isVector() && "Wrong return type!");
701 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
702 "Wrong number of operands!");
703 EVT EltVT = N->getValueType(0).getVectorElementType();
704 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
705 assert((I->getValueType() == EltVT ||
706 (EltVT.isInteger() && I->getValueType().isInteger() &&
707 EltVT.bitsLE(I->getValueType()))) &&
708 "Wrong operand type!");
709 assert(I->getValueType() == N->getOperand(0).getValueType() &&
710 "Operands must all have the same type");
718 /// \brief Insert a newly allocated node into the DAG.
720 /// Handles insertion into the all nodes list and CSE map, as well as
721 /// verification and other common operations when a new node is allocated.
722 void SelectionDAG::InsertNode(SDNode *N) {
723 AllNodes.push_back(N);
725 N->PersistentId = NextPersistentId++;
730 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
731 /// correspond to it. This is useful when we're about to delete or repurpose
732 /// the node. We don't want future request for structurally identical nodes
733 /// to return N anymore.
734 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
736 switch (N->getOpcode()) {
737 case ISD::HANDLENODE: return false; // noop.
739 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
740 "Cond code doesn't exist!");
741 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
742 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
744 case ISD::ExternalSymbol:
745 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
747 case ISD::TargetExternalSymbol: {
748 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
749 Erased = TargetExternalSymbols.erase(
750 std::pair<std::string,unsigned char>(ESN->getSymbol(),
751 ESN->getTargetFlags()));
754 case ISD::MCSymbol: {
755 auto *MCSN = cast<MCSymbolSDNode>(N);
756 Erased = MCSymbols.erase(MCSN->getMCSymbol());
759 case ISD::VALUETYPE: {
760 EVT VT = cast<VTSDNode>(N)->getVT();
761 if (VT.isExtended()) {
762 Erased = ExtendedValueTypeNodes.erase(VT);
764 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
765 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
770 // Remove it from the CSE Map.
771 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
772 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
773 Erased = CSEMap.RemoveNode(N);
777 // Verify that the node was actually in one of the CSE maps, unless it has a
778 // flag result (which cannot be CSE'd) or is one of the special cases that are
779 // not subject to CSE.
780 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
781 !N->isMachineOpcode() && !doNotCSE(N)) {
784 llvm_unreachable("Node is not in map!");
790 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
791 /// maps and modified in place. Add it back to the CSE maps, unless an identical
792 /// node already exists, in which case transfer all its users to the existing
793 /// node. This transfer can potentially trigger recursive merging.
795 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
796 // For node types that aren't CSE'd, just act as if no identical node
799 SDNode *Existing = CSEMap.GetOrInsertNode(N);
801 // If there was already an existing matching node, use ReplaceAllUsesWith
802 // to replace the dead one with the existing one. This can cause
803 // recursive merging of other unrelated nodes down the line.
804 ReplaceAllUsesWith(N, Existing);
806 // N is now dead. Inform the listeners and delete it.
807 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
808 DUL->NodeDeleted(N, Existing);
809 DeleteNodeNotInCSEMaps(N);
814 // If the node doesn't already exist, we updated it. Inform listeners.
815 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
819 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
820 /// were replaced with those specified. If this node is never memoized,
821 /// return null, otherwise return a pointer to the slot it would take. If a
822 /// node already exists with these operands, the slot will be non-null.
823 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
828 SDValue Ops[] = { Op };
830 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
831 AddNodeIDCustom(ID, N);
832 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
834 Node->intersectFlagsWith(N->getFlags());
838 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
839 /// were replaced with those specified. If this node is never memoized,
840 /// return null, otherwise return a pointer to the slot it would take. If a
841 /// node already exists with these operands, the slot will be non-null.
842 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
843 SDValue Op1, SDValue Op2,
848 SDValue Ops[] = { Op1, Op2 };
850 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
851 AddNodeIDCustom(ID, N);
852 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
854 Node->intersectFlagsWith(N->getFlags());
858 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
859 /// were replaced with those specified. If this node is never memoized,
860 /// return null, otherwise return a pointer to the slot it would take. If a
861 /// node already exists with these operands, the slot will be non-null.
862 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
868 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
869 AddNodeIDCustom(ID, N);
870 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
872 Node->intersectFlagsWith(N->getFlags());
876 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
877 Type *Ty = VT == MVT::iPTR ?
878 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
879 VT.getTypeForEVT(*getContext());
881 return getDataLayout().getABITypeAlignment(Ty);
884 // EntryNode could meaningfully have debug info if we can find it...
885 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
886 : TM(tm), OptLevel(OL),
887 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
888 Root(getEntryNode()) {
889 InsertNode(&EntryNode);
890 DbgInfo = new SDDbgInfo();
893 void SelectionDAG::init(MachineFunction &NewMF,
894 OptimizationRemarkEmitter &NewORE) {
897 TLI = getSubtarget().getTargetLowering();
898 TSI = getSubtarget().getSelectionDAGInfo();
899 Context = &MF->getFunction()->getContext();
902 SelectionDAG::~SelectionDAG() {
903 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
905 OperandRecycler.clear(OperandAllocator);
909 void SelectionDAG::allnodes_clear() {
910 assert(&*AllNodes.begin() == &EntryNode);
911 AllNodes.remove(AllNodes.begin());
912 while (!AllNodes.empty())
913 DeallocateNode(&AllNodes.front());
915 NextPersistentId = 0;
919 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
921 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
923 switch (N->getOpcode()) {
926 case ISD::ConstantFP:
927 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
928 "debug location. Use another overload.");
934 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
935 const SDLoc &DL, void *&InsertPos) {
936 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
938 switch (N->getOpcode()) {
940 case ISD::ConstantFP:
941 // Erase debug location from the node if the node is used at several
942 // different places. Do not propagate one location to all uses as it
943 // will cause a worse single stepping debugging experience.
944 if (N->getDebugLoc() != DL.getDebugLoc())
945 N->setDebugLoc(DebugLoc());
948 // When the node's point of use is located earlier in the instruction
949 // sequence than its prior point of use, update its debug info to the
951 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
952 N->setDebugLoc(DL.getDebugLoc());
959 void SelectionDAG::clear() {
961 OperandRecycler.clear(OperandAllocator);
962 OperandAllocator.Reset();
965 ExtendedValueTypeNodes.clear();
966 ExternalSymbols.clear();
967 TargetExternalSymbols.clear();
969 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
970 static_cast<CondCodeSDNode*>(nullptr));
971 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
972 static_cast<SDNode*>(nullptr));
974 EntryNode.UseList = nullptr;
975 InsertNode(&EntryNode);
976 Root = getEntryNode();
980 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
981 return VT.bitsGT(Op.getValueType())
982 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
983 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
986 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
987 return VT.bitsGT(Op.getValueType()) ?
988 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
989 getNode(ISD::TRUNCATE, DL, VT, Op);
992 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
993 return VT.bitsGT(Op.getValueType()) ?
994 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
995 getNode(ISD::TRUNCATE, DL, VT, Op);
998 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
999 return VT.bitsGT(Op.getValueType()) ?
1000 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1001 getNode(ISD::TRUNCATE, DL, VT, Op);
1004 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1006 if (VT.bitsLE(Op.getValueType()))
1007 return getNode(ISD::TRUNCATE, SL, VT, Op);
1009 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1010 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1013 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1014 assert(!VT.isVector() &&
1015 "getZeroExtendInReg should use the vector element type instead of "
1016 "the vector type!");
1017 if (Op.getValueType() == VT) return Op;
1018 unsigned BitWidth = Op.getScalarValueSizeInBits();
1019 APInt Imm = APInt::getLowBitsSet(BitWidth,
1020 VT.getSizeInBits());
1021 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1022 getConstant(Imm, DL, Op.getValueType()));
1025 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1027 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1028 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1029 "The sizes of the input and result must match in order to perform the "
1030 "extend in-register.");
1031 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1032 "The destination vector type must have fewer lanes than the input.");
1033 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1036 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1038 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1039 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1040 "The sizes of the input and result must match in order to perform the "
1041 "extend in-register.");
1042 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1043 "The destination vector type must have fewer lanes than the input.");
1044 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1047 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1049 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1050 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1051 "The sizes of the input and result must match in order to perform the "
1052 "extend in-register.");
1053 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1054 "The destination vector type must have fewer lanes than the input.");
1055 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1058 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1059 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1060 EVT EltVT = VT.getScalarType();
1062 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1063 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1066 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1067 EVT EltVT = VT.getScalarType();
1069 switch (TLI->getBooleanContents(VT)) {
1070 case TargetLowering::ZeroOrOneBooleanContent:
1071 case TargetLowering::UndefinedBooleanContent:
1072 TrueValue = getConstant(1, DL, VT);
1074 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1075 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1079 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1082 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1083 bool isT, bool isO) {
1084 EVT EltVT = VT.getScalarType();
1085 assert((EltVT.getSizeInBits() >= 64 ||
1086 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1087 "getConstant with a uint64_t value that doesn't fit in the type!");
1088 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1091 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1092 bool isT, bool isO) {
1093 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1096 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1097 EVT VT, bool isT, bool isO) {
1098 assert(VT.isInteger() && "Cannot create FP integer constant!");
1100 EVT EltVT = VT.getScalarType();
1101 const ConstantInt *Elt = &Val;
1103 // In some cases the vector type is legal but the element type is illegal and
1104 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1105 // inserted value (the type does not need to match the vector element type).
1106 // Any extra bits introduced will be truncated away.
1107 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1108 TargetLowering::TypePromoteInteger) {
1109 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1110 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1111 Elt = ConstantInt::get(*getContext(), NewVal);
1113 // In other cases the element type is illegal and needs to be expanded, for
1114 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1115 // the value into n parts and use a vector type with n-times the elements.
1116 // Then bitcast to the type requested.
1117 // Legalizing constants too early makes the DAGCombiner's job harder so we
1118 // only legalize if the DAG tells us we must produce legal types.
1119 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1120 TLI->getTypeAction(*getContext(), EltVT) ==
1121 TargetLowering::TypeExpandInteger) {
1122 const APInt &NewVal = Elt->getValue();
1123 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1124 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1125 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1126 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1128 // Check the temporary vector is the correct size. If this fails then
1129 // getTypeToTransformTo() probably returned a type whose size (in bits)
1130 // isn't a power-of-2 factor of the requested type size.
1131 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1133 SmallVector<SDValue, 2> EltParts;
1134 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1135 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1136 .zextOrTrunc(ViaEltSizeInBits), DL,
1137 ViaEltVT, isT, isO));
1140 // EltParts is currently in little endian order. If we actually want
1141 // big-endian order then reverse it now.
1142 if (getDataLayout().isBigEndian())
1143 std::reverse(EltParts.begin(), EltParts.end());
1145 // The elements must be reversed when the element order is different
1146 // to the endianness of the elements (because the BITCAST is itself a
1147 // vector shuffle in this situation). However, we do not need any code to
1148 // perform this reversal because getConstant() is producing a vector
1150 // This situation occurs in MIPS MSA.
1152 SmallVector<SDValue, 8> Ops;
1153 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1154 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1155 return getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1158 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1159 "APInt size does not match type size!");
1160 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1161 FoldingSetNodeID ID;
1162 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1166 SDNode *N = nullptr;
1167 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1169 return SDValue(N, 0);
1172 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1173 CSEMap.InsertNode(N, IP);
1177 SDValue Result(N, 0);
1179 Result = getSplatBuildVector(VT, DL, Result);
1183 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1185 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1188 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1190 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1193 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1194 EVT VT, bool isTarget) {
1195 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1197 EVT EltVT = VT.getScalarType();
1199 // Do the map lookup using the actual bit pattern for the floating point
1200 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1201 // we don't have issues with SNANs.
1202 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1203 FoldingSetNodeID ID;
1204 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1207 SDNode *N = nullptr;
1208 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1210 return SDValue(N, 0);
1213 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1214 CSEMap.InsertNode(N, IP);
1218 SDValue Result(N, 0);
1220 Result = getSplatBuildVector(VT, DL, Result);
1224 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1226 EVT EltVT = VT.getScalarType();
1227 if (EltVT == MVT::f32)
1228 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1229 else if (EltVT == MVT::f64)
1230 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1231 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1232 EltVT == MVT::f16) {
1234 APFloat APF = APFloat(Val);
1235 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1237 return getConstantFP(APF, DL, VT, isTarget);
1239 llvm_unreachable("Unsupported type in getConstantFP");
1242 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1243 EVT VT, int64_t Offset, bool isTargetGA,
1244 unsigned char TargetFlags) {
1245 assert((TargetFlags == 0 || isTargetGA) &&
1246 "Cannot set target flags on target-independent globals");
1248 // Truncate (with sign-extension) the offset value to the pointer size.
1249 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1251 Offset = SignExtend64(Offset, BitWidth);
1254 if (GV->isThreadLocal())
1255 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1257 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1259 FoldingSetNodeID ID;
1260 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1262 ID.AddInteger(Offset);
1263 ID.AddInteger(TargetFlags);
1265 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1266 return SDValue(E, 0);
1268 auto *N = newSDNode<GlobalAddressSDNode>(
1269 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1270 CSEMap.InsertNode(N, IP);
1272 return SDValue(N, 0);
1275 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1276 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1277 FoldingSetNodeID ID;
1278 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1281 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1282 return SDValue(E, 0);
1284 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1285 CSEMap.InsertNode(N, IP);
1287 return SDValue(N, 0);
1290 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1291 unsigned char TargetFlags) {
1292 assert((TargetFlags == 0 || isTarget) &&
1293 "Cannot set target flags on target-independent jump tables");
1294 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1295 FoldingSetNodeID ID;
1296 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1298 ID.AddInteger(TargetFlags);
1300 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1301 return SDValue(E, 0);
1303 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1304 CSEMap.InsertNode(N, IP);
1306 return SDValue(N, 0);
1309 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1310 unsigned Alignment, int Offset,
1312 unsigned char TargetFlags) {
1313 assert((TargetFlags == 0 || isTarget) &&
1314 "Cannot set target flags on target-independent globals");
1316 Alignment = MF->getFunction()->optForSize()
1317 ? getDataLayout().getABITypeAlignment(C->getType())
1318 : getDataLayout().getPrefTypeAlignment(C->getType());
1319 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1320 FoldingSetNodeID ID;
1321 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1322 ID.AddInteger(Alignment);
1323 ID.AddInteger(Offset);
1325 ID.AddInteger(TargetFlags);
1327 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1328 return SDValue(E, 0);
1330 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1332 CSEMap.InsertNode(N, IP);
1334 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(llvm::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->getFrameIndexTy(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->getFrameIndexTy(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::getSignMask(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 {
1967 computeKnownBits(Op, Known, Depth);
1968 return Mask.isSubsetOf(Known.Zero);
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 Known. For vectors, the known bits are those that are shared by
1985 /// every vector element.
1986 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
1987 unsigned Depth) const {
1988 EVT VT = Op.getValueType();
1989 APInt DemandedElts = VT.isVector()
1990 ? APInt::getAllOnesValue(VT.getVectorNumElements())
1992 computeKnownBits(Op, Known, DemandedElts, Depth);
1995 /// Determine which bits of Op are known to be either zero or one and return
1996 /// them in Known. The DemandedElts argument allows us to only collect the known
1997 /// bits that are shared by the requested vector elements.
1998 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
1999 const APInt &DemandedElts,
2000 unsigned Depth) const {
2001 unsigned BitWidth = Op.getScalarValueSizeInBits();
2003 Known = KnownBits(BitWidth); // Don't know anything.
2005 return; // Limit search depth.
2008 unsigned NumElts = DemandedElts.getBitWidth();
2011 return; // No demanded elts, better to assume we don't know anything.
2013 unsigned Opcode = Op.getOpcode();
2016 // We know all of the bits for a constant!
2017 Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
2018 Known.Zero = ~Known.One;
2020 case ISD::BUILD_VECTOR:
2021 // Collect the known bits that are shared by every demanded vector element.
2022 assert(NumElts == Op.getValueType().getVectorNumElements() &&
2023 "Unexpected vector size");
2024 Known.Zero.setAllBits(); Known.One.setAllBits();
2025 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2026 if (!DemandedElts[i])
2029 SDValue SrcOp = Op.getOperand(i);
2030 computeKnownBits(SrcOp, Known2, Depth + 1);
2032 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2033 if (SrcOp.getValueSizeInBits() != BitWidth) {
2034 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2035 "Expected BUILD_VECTOR implicit truncation");
2036 Known2 = Known2.trunc(BitWidth);
2039 // Known bits are the values that are shared by every demanded element.
2040 Known.One &= Known2.One;
2041 Known.Zero &= Known2.Zero;
2043 // If we don't know any bits, early out.
2044 if (!Known.One && !Known.Zero)
2048 case ISD::VECTOR_SHUFFLE: {
2049 // Collect the known bits that are shared by every vector element referenced
2051 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2052 Known.Zero.setAllBits(); Known.One.setAllBits();
2053 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2054 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2055 for (unsigned i = 0; i != NumElts; ++i) {
2056 if (!DemandedElts[i])
2059 int M = SVN->getMaskElt(i);
2061 // For UNDEF elements, we don't know anything about the common state of
2062 // the shuffle result.
2064 DemandedLHS.clearAllBits();
2065 DemandedRHS.clearAllBits();
2069 if ((unsigned)M < NumElts)
2070 DemandedLHS.setBit((unsigned)M % NumElts);
2072 DemandedRHS.setBit((unsigned)M % NumElts);
2074 // Known bits are the values that are shared by every demanded element.
2075 if (!!DemandedLHS) {
2076 SDValue LHS = Op.getOperand(0);
2077 computeKnownBits(LHS, Known2, DemandedLHS, Depth + 1);
2078 Known.One &= Known2.One;
2079 Known.Zero &= Known2.Zero;
2081 // If we don't know any bits, early out.
2082 if (!Known.One && !Known.Zero)
2084 if (!!DemandedRHS) {
2085 SDValue RHS = Op.getOperand(1);
2086 computeKnownBits(RHS, Known2, DemandedRHS, Depth + 1);
2087 Known.One &= Known2.One;
2088 Known.Zero &= Known2.Zero;
2092 case ISD::CONCAT_VECTORS: {
2093 // Split DemandedElts and test each of the demanded subvectors.
2094 Known.Zero.setAllBits(); Known.One.setAllBits();
2095 EVT SubVectorVT = Op.getOperand(0).getValueType();
2096 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2097 unsigned NumSubVectors = Op.getNumOperands();
2098 for (unsigned i = 0; i != NumSubVectors; ++i) {
2099 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2100 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2101 if (!!DemandedSub) {
2102 SDValue Sub = Op.getOperand(i);
2103 computeKnownBits(Sub, Known2, DemandedSub, Depth + 1);
2104 Known.One &= Known2.One;
2105 Known.Zero &= Known2.Zero;
2107 // If we don't know any bits, early out.
2108 if (!Known.One && !Known.Zero)
2113 case ISD::EXTRACT_SUBVECTOR: {
2114 // If we know the element index, just demand that subvector elements,
2115 // otherwise demand them all.
2116 SDValue Src = Op.getOperand(0);
2117 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2118 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2119 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2120 // Offset the demanded elts by the subvector index.
2121 uint64_t Idx = SubIdx->getZExtValue();
2122 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
2123 computeKnownBits(Src, Known, DemandedSrc, Depth + 1);
2125 computeKnownBits(Src, Known, Depth + 1);
2129 case ISD::BITCAST: {
2130 SDValue N0 = Op.getOperand(0);
2131 unsigned SubBitWidth = N0.getScalarValueSizeInBits();
2133 // Ignore bitcasts from floating point.
2134 if (!N0.getValueType().isInteger())
2137 // Fast handling of 'identity' bitcasts.
2138 if (BitWidth == SubBitWidth) {
2139 computeKnownBits(N0, Known, DemandedElts, Depth + 1);
2143 // Support big-endian targets when it becomes useful.
2144 bool IsLE = getDataLayout().isLittleEndian();
2148 // Bitcast 'small element' vector to 'large element' scalar/vector.
2149 if ((BitWidth % SubBitWidth) == 0) {
2150 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2152 // Collect known bits for the (larger) output by collecting the known
2153 // bits from each set of sub elements and shift these into place.
2154 // We need to separately call computeKnownBits for each set of
2155 // sub elements as the knownbits for each is likely to be different.
2156 unsigned SubScale = BitWidth / SubBitWidth;
2157 APInt SubDemandedElts(NumElts * SubScale, 0);
2158 for (unsigned i = 0; i != NumElts; ++i)
2159 if (DemandedElts[i])
2160 SubDemandedElts.setBit(i * SubScale);
2162 for (unsigned i = 0; i != SubScale; ++i) {
2163 computeKnownBits(N0, Known2, SubDemandedElts.shl(i),
2165 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * i);
2166 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * i);
2170 // Bitcast 'large element' scalar/vector to 'small element' vector.
2171 if ((SubBitWidth % BitWidth) == 0) {
2172 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2174 // Collect known bits for the (smaller) output by collecting the known
2175 // bits from the overlapping larger input elements and extracting the
2176 // sub sections we actually care about.
2177 unsigned SubScale = SubBitWidth / BitWidth;
2178 APInt SubDemandedElts(NumElts / SubScale, 0);
2179 for (unsigned i = 0; i != NumElts; ++i)
2180 if (DemandedElts[i])
2181 SubDemandedElts.setBit(i / SubScale);
2183 computeKnownBits(N0, Known2, SubDemandedElts, Depth + 1);
2185 Known.Zero.setAllBits(); Known.One.setAllBits();
2186 for (unsigned i = 0; i != NumElts; ++i)
2187 if (DemandedElts[i]) {
2188 unsigned Offset = (i % SubScale) * BitWidth;
2189 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2190 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2191 // If we don't know any bits, early out.
2192 if (!Known.One && !Known.Zero)
2199 // If either the LHS or the RHS are Zero, the result is zero.
2200 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2201 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2203 // Output known-1 bits are only known if set in both the LHS & RHS.
2204 Known.One &= Known2.One;
2205 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2206 Known.Zero |= Known2.Zero;
2209 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2210 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2212 // Output known-0 bits are only known if clear in both the LHS & RHS.
2213 Known.Zero &= Known2.Zero;
2214 // Output known-1 are known to be set if set in either the LHS | RHS.
2215 Known.One |= Known2.One;
2218 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2219 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2221 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2222 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2223 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2224 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2225 Known.Zero = KnownZeroOut;
2229 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2230 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2232 // If low bits are zero in either operand, output low known-0 bits.
2233 // Also compute a conservative estimate for high known-0 bits.
2234 // More trickiness is possible, but this is sufficient for the
2235 // interesting case of alignment computation.
2236 unsigned TrailZ = Known.countMinTrailingZeros() +
2237 Known2.countMinTrailingZeros();
2238 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2239 Known2.countMinLeadingZeros(),
2240 BitWidth) - BitWidth;
2243 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2244 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2248 // For the purposes of computing leading zeros we can conservatively
2249 // treat a udiv as a logical right shift by the power of 2 known to
2250 // be less than the denominator.
2251 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2252 unsigned LeadZ = Known2.countMinLeadingZeros();
2254 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2255 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2256 if (RHSMaxLeadingZeros != BitWidth)
2257 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2259 Known.Zero.setHighBits(LeadZ);
2263 computeKnownBits(Op.getOperand(2), Known, Depth+1);
2264 // If we don't know any bits, early out.
2265 if (!Known.One && !Known.Zero)
2267 computeKnownBits(Op.getOperand(1), Known2, Depth+1);
2269 // Only known if known in both the LHS and RHS.
2270 Known.One &= Known2.One;
2271 Known.Zero &= Known2.Zero;
2273 case ISD::SELECT_CC:
2274 computeKnownBits(Op.getOperand(3), Known, Depth+1);
2275 // If we don't know any bits, early out.
2276 if (!Known.One && !Known.Zero)
2278 computeKnownBits(Op.getOperand(2), Known2, Depth+1);
2280 // Only known if known in both the LHS and RHS.
2281 Known.One &= Known2.One;
2282 Known.Zero &= Known2.Zero;
2286 if (Op.getResNo() != 1)
2288 // The boolean result conforms to getBooleanContents.
2289 // If we know the result of a setcc has the top bits zero, use this info.
2290 // We know that we have an integer-based boolean since these operations
2291 // are only available for integer.
2292 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2293 TargetLowering::ZeroOrOneBooleanContent &&
2295 Known.Zero.setBitsFrom(1);
2298 // If we know the result of a setcc has the top bits zero, use this info.
2299 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2300 TargetLowering::ZeroOrOneBooleanContent &&
2302 Known.Zero.setBitsFrom(1);
2305 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2306 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2307 Known.Zero <<= *ShAmt;
2308 Known.One <<= *ShAmt;
2309 // Low bits are known zero.
2310 Known.Zero.setLowBits(ShAmt->getZExtValue());
2314 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2315 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2316 Known.Zero.lshrInPlace(*ShAmt);
2317 Known.One.lshrInPlace(*ShAmt);
2318 // High bits are known zero.
2319 Known.Zero.setHighBits(ShAmt->getZExtValue());
2323 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2324 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2325 Known.Zero.lshrInPlace(*ShAmt);
2326 Known.One.lshrInPlace(*ShAmt);
2327 // If we know the value of the sign bit, then we know it is copied across
2328 // the high bits by the shift amount.
2329 APInt SignMask = APInt::getSignMask(BitWidth);
2330 SignMask.lshrInPlace(*ShAmt); // Adjust to where it is now in the mask.
2331 if (Known.Zero.intersects(SignMask)) {
2332 Known.Zero.setHighBits(ShAmt->getZExtValue());// New bits are known zero.
2333 } else if (Known.One.intersects(SignMask)) {
2334 Known.One.setHighBits(ShAmt->getZExtValue()); // New bits are known one.
2338 case ISD::SIGN_EXTEND_INREG: {
2339 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2340 unsigned EBits = EVT.getScalarSizeInBits();
2342 // Sign extension. Compute the demanded bits in the result that are not
2343 // present in the input.
2344 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2346 APInt InSignMask = APInt::getSignMask(EBits);
2347 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2349 // If the sign extended bits are demanded, we know that the sign
2351 InSignMask = InSignMask.zext(BitWidth);
2352 if (NewBits.getBoolValue())
2353 InputDemandedBits |= InSignMask;
2355 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2356 Known.One &= InputDemandedBits;
2357 Known.Zero &= InputDemandedBits;
2359 // If the sign bit of the input is known set or clear, then we know the
2360 // top bits of the result.
2361 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2362 Known.Zero |= NewBits;
2363 Known.One &= ~NewBits;
2364 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2365 Known.One |= NewBits;
2366 Known.Zero &= ~NewBits;
2367 } else { // Input sign bit unknown
2368 Known.Zero &= ~NewBits;
2369 Known.One &= ~NewBits;
2374 case ISD::CTTZ_ZERO_UNDEF: {
2375 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2376 // If we have a known 1, its position is our upper bound.
2377 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2378 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2379 Known.Zero.setBitsFrom(LowBits);
2383 case ISD::CTLZ_ZERO_UNDEF: {
2384 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2385 // If we have a known 1, its position is our upper bound.
2386 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2387 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2388 Known.Zero.setBitsFrom(LowBits);
2392 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2393 // If we know some of the bits are zero, they can't be one.
2394 unsigned PossibleOnes = Known2.countMaxPopulation();
2395 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2399 LoadSDNode *LD = cast<LoadSDNode>(Op);
2400 // If this is a ZEXTLoad and we are looking at the loaded value.
2401 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2402 EVT VT = LD->getMemoryVT();
2403 unsigned MemBits = VT.getScalarSizeInBits();
2404 Known.Zero.setBitsFrom(MemBits);
2405 } else if (const MDNode *Ranges = LD->getRanges()) {
2406 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2407 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2411 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2412 EVT InVT = Op.getOperand(0).getValueType();
2413 unsigned InBits = InVT.getScalarSizeInBits();
2414 Known = Known.trunc(InBits);
2415 computeKnownBits(Op.getOperand(0), Known,
2416 DemandedElts.zext(InVT.getVectorNumElements()),
2418 Known = Known.zext(BitWidth);
2419 Known.Zero.setBitsFrom(InBits);
2422 case ISD::ZERO_EXTEND: {
2423 EVT InVT = Op.getOperand(0).getValueType();
2424 unsigned InBits = InVT.getScalarSizeInBits();
2425 Known = Known.trunc(InBits);
2426 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2427 Known = Known.zext(BitWidth);
2428 Known.Zero.setBitsFrom(InBits);
2431 // TODO ISD::SIGN_EXTEND_VECTOR_INREG
2432 case ISD::SIGN_EXTEND: {
2433 EVT InVT = Op.getOperand(0).getValueType();
2434 unsigned InBits = InVT.getScalarSizeInBits();
2436 Known = Known.trunc(InBits);
2437 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2439 // If the sign bit is known to be zero or one, then sext will extend
2440 // it to the top bits, else it will just zext.
2441 Known = Known.sext(BitWidth);
2444 case ISD::ANY_EXTEND: {
2445 EVT InVT = Op.getOperand(0).getValueType();
2446 unsigned InBits = InVT.getScalarSizeInBits();
2447 Known = Known.trunc(InBits);
2448 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2449 Known = Known.zext(BitWidth);
2452 case ISD::TRUNCATE: {
2453 EVT InVT = Op.getOperand(0).getValueType();
2454 unsigned InBits = InVT.getScalarSizeInBits();
2455 Known = Known.zext(InBits);
2456 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2457 Known = Known.trunc(BitWidth);
2460 case ISD::AssertZext: {
2461 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2462 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2463 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2464 Known.Zero |= (~InMask);
2465 Known.One &= (~Known.Zero);
2469 // All bits are zero except the low bit.
2470 Known.Zero.setBitsFrom(1);
2474 if (Op.getResNo() == 1) {
2475 // If we know the result of a setcc has the top bits zero, use this info.
2476 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2477 TargetLowering::ZeroOrOneBooleanContent &&
2479 Known.Zero.setBitsFrom(1);
2485 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2486 // We know that the top bits of C-X are clear if X contains less bits
2487 // than C (i.e. no wrap-around can happen). For example, 20-X is
2488 // positive if we can prove that X is >= 0 and < 16.
2489 if (CLHS->getAPIntValue().isNonNegative()) {
2490 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2491 // NLZ can't be BitWidth with no sign bit
2492 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2493 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2496 // If all of the MaskV bits are known to be zero, then we know the
2497 // output top bits are zero, because we now know that the output is
2499 if ((Known2.Zero & MaskV) == MaskV) {
2500 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2501 // Top bits known zero.
2502 Known.Zero.setHighBits(NLZ2);
2507 // If low bits are know to be zero in both operands, then we know they are
2508 // going to be 0 in the result. Both addition and complement operations
2509 // preserve the low zero bits.
2510 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2511 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2512 if (KnownZeroLow == 0)
2515 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2516 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2517 Known.Zero.setLowBits(KnownZeroLow);
2523 if (Op.getResNo() == 1) {
2524 // If we know the result of a setcc has the top bits zero, use this info.
2525 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2526 TargetLowering::ZeroOrOneBooleanContent &&
2528 Known.Zero.setBitsFrom(1);
2535 // Output known-0 bits are known if clear or set in both the low clear bits
2536 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2537 // low 3 bits clear.
2538 // Output known-0 bits are also known if the top bits of each input are
2539 // known to be clear. For example, if one input has the top 10 bits clear
2540 // and the other has the top 8 bits clear, we know the top 7 bits of the
2541 // output must be clear.
2542 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2543 unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
2544 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2546 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2548 KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
2549 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2551 if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) {
2552 // With ADDE and ADDCARRY, a carry bit may be added in, so we can only
2553 // use this information if we know (at least) that the low two bits are
2554 // clear. We then return to the caller that the low bit is unknown but
2555 // that other bits are known zero.
2556 if (KnownZeroLow >= 2)
2557 Known.Zero.setBits(1, KnownZeroLow);
2561 Known.Zero.setLowBits(KnownZeroLow);
2562 if (KnownZeroHigh > 1)
2563 Known.Zero.setHighBits(KnownZeroHigh - 1);
2567 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2568 const APInt &RA = Rem->getAPIntValue().abs();
2569 if (RA.isPowerOf2()) {
2570 APInt LowBits = RA - 1;
2571 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2573 // The low bits of the first operand are unchanged by the srem.
2574 Known.Zero = Known2.Zero & LowBits;
2575 Known.One = Known2.One & LowBits;
2577 // If the first operand is non-negative or has all low bits zero, then
2578 // the upper bits are all zero.
2579 if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
2580 Known.Zero |= ~LowBits;
2582 // If the first operand is negative and not all low bits are zero, then
2583 // the upper bits are all one.
2584 if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
2585 Known.One |= ~LowBits;
2586 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
2591 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2592 const APInt &RA = Rem->getAPIntValue();
2593 if (RA.isPowerOf2()) {
2594 APInt LowBits = (RA - 1);
2595 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2597 // The upper bits are all zero, the lower ones are unchanged.
2598 Known.Zero = Known2.Zero | ~LowBits;
2599 Known.One = Known2.One & LowBits;
2604 // Since the result is less than or equal to either operand, any leading
2605 // zero bits in either operand must also exist in the result.
2606 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2607 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2610 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
2612 Known.Zero.setHighBits(Leaders);
2615 case ISD::EXTRACT_ELEMENT: {
2616 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2617 const unsigned Index = Op.getConstantOperandVal(1);
2618 const unsigned BitWidth = Op.getValueSizeInBits();
2620 // Remove low part of known bits mask
2621 Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
2622 Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
2624 // Remove high part of known bit mask
2625 Known = Known.trunc(BitWidth);
2628 case ISD::EXTRACT_VECTOR_ELT: {
2629 SDValue InVec = Op.getOperand(0);
2630 SDValue EltNo = Op.getOperand(1);
2631 EVT VecVT = InVec.getValueType();
2632 const unsigned BitWidth = Op.getValueSizeInBits();
2633 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
2634 const unsigned NumSrcElts = VecVT.getVectorNumElements();
2635 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2636 // anything about the extended bits.
2637 if (BitWidth > EltBitWidth)
2638 Known = Known.trunc(EltBitWidth);
2639 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
2640 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
2641 // If we know the element index, just demand that vector element.
2642 unsigned Idx = ConstEltNo->getZExtValue();
2643 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
2644 computeKnownBits(InVec, Known, DemandedElt, Depth + 1);
2646 // Unknown element index, so ignore DemandedElts and demand them all.
2647 computeKnownBits(InVec, Known, Depth + 1);
2649 if (BitWidth > EltBitWidth)
2650 Known = Known.zext(BitWidth);
2653 case ISD::INSERT_VECTOR_ELT: {
2654 SDValue InVec = Op.getOperand(0);
2655 SDValue InVal = Op.getOperand(1);
2656 SDValue EltNo = Op.getOperand(2);
2658 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
2659 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
2660 // If we know the element index, split the demand between the
2661 // source vector and the inserted element.
2662 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
2663 unsigned EltIdx = CEltNo->getZExtValue();
2665 // If we demand the inserted element then add its common known bits.
2666 if (DemandedElts[EltIdx]) {
2667 computeKnownBits(InVal, Known2, Depth + 1);
2668 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2669 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
2672 // If we demand the source vector then add its common known bits, ensuring
2673 // that we don't demand the inserted element.
2674 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
2676 computeKnownBits(InVec, Known2, VectorElts, Depth + 1);
2677 Known.One &= Known2.One;
2678 Known.Zero &= Known2.Zero;
2681 // Unknown element index, so ignore DemandedElts and demand them all.
2682 computeKnownBits(InVec, Known, Depth + 1);
2683 computeKnownBits(InVal, Known2, Depth + 1);
2684 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2685 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
2689 case ISD::BITREVERSE: {
2690 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2691 Known.Zero = Known2.Zero.reverseBits();
2692 Known.One = Known2.One.reverseBits();
2696 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2697 Known.Zero = Known2.Zero.byteSwap();
2698 Known.One = Known2.One.byteSwap();
2702 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2704 // If the source's MSB is zero then we know the rest of the bits already.
2705 if (Known2.isNonNegative()) {
2706 Known.Zero = Known2.Zero;
2707 Known.One = Known2.One;
2711 // We only know that the absolute values's MSB will be zero iff there is
2712 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
2713 Known2.One.clearSignBit();
2714 if (Known2.One.getBoolValue()) {
2715 Known.Zero = APInt::getSignMask(BitWidth);
2721 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2722 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2724 // UMIN - we know that the result will have the maximum of the
2725 // known zero leading bits of the inputs.
2726 unsigned LeadZero = Known.countMinLeadingZeros();
2727 LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
2729 Known.Zero &= Known2.Zero;
2730 Known.One &= Known2.One;
2731 Known.Zero.setHighBits(LeadZero);
2735 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2737 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2739 // UMAX - we know that the result will have the maximum of the
2740 // known one leading bits of the inputs.
2741 unsigned LeadOne = Known.countMinLeadingOnes();
2742 LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
2744 Known.Zero &= Known2.Zero;
2745 Known.One &= Known2.One;
2746 Known.One.setHighBits(LeadOne);
2751 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2753 // If we don't know any bits, early out.
2754 if (!Known.One && !Known.Zero)
2756 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2757 Known.Zero &= Known2.Zero;
2758 Known.One &= Known2.One;
2761 case ISD::FrameIndex:
2762 case ISD::TargetFrameIndex:
2763 if (unsigned Align = InferPtrAlignment(Op)) {
2764 // The low bits are known zero if the pointer is aligned.
2765 Known.Zero.setLowBits(Log2_32(Align));
2771 if (Opcode < ISD::BUILTIN_OP_END)
2774 case ISD::INTRINSIC_WO_CHAIN:
2775 case ISD::INTRINSIC_W_CHAIN:
2776 case ISD::INTRINSIC_VOID:
2777 // Allow the target to implement this method for its nodes.
2778 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
2782 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
2785 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
2787 // X + 0 never overflow
2788 if (isNullConstant(N1))
2792 computeKnownBits(N1, N1Known);
2793 if (N1Known.Zero.getBoolValue()) {
2795 computeKnownBits(N0, N0Known);
2798 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
2803 // mulhi + 1 never overflow
2804 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
2805 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
2808 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
2810 computeKnownBits(N0, N0Known);
2812 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
2816 return OFK_Sometime;
2819 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2820 EVT OpVT = Val.getValueType();
2821 unsigned BitWidth = OpVT.getScalarSizeInBits();
2823 // Is the constant a known power of 2?
2824 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
2825 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2827 // A left-shift of a constant one will have exactly one bit set because
2828 // shifting the bit off the end is undefined.
2829 if (Val.getOpcode() == ISD::SHL) {
2830 auto *C = isConstOrConstSplat(Val.getOperand(0));
2831 if (C && C->getAPIntValue() == 1)
2835 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2837 if (Val.getOpcode() == ISD::SRL) {
2838 auto *C = isConstOrConstSplat(Val.getOperand(0));
2839 if (C && C->getAPIntValue().isSignMask())
2843 // Are all operands of a build vector constant powers of two?
2844 if (Val.getOpcode() == ISD::BUILD_VECTOR)
2845 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
2846 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
2847 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2852 // More could be done here, though the above checks are enough
2853 // to handle some common cases.
2855 // Fall back to computeKnownBits to catch other known cases.
2857 computeKnownBits(Val, Known);
2858 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
2861 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2862 EVT VT = Op.getValueType();
2863 APInt DemandedElts = VT.isVector()
2864 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2866 return ComputeNumSignBits(Op, DemandedElts, Depth);
2869 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2870 unsigned Depth) const {
2871 EVT VT = Op.getValueType();
2872 assert(VT.isInteger() && "Invalid VT!");
2873 unsigned VTBits = VT.getScalarSizeInBits();
2874 unsigned NumElts = DemandedElts.getBitWidth();
2876 unsigned FirstAnswer = 1;
2879 return 1; // Limit search depth.
2882 return 1; // No demanded elts, better to assume we don't know anything.
2884 switch (Op.getOpcode()) {
2886 case ISD::AssertSext:
2887 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2888 return VTBits-Tmp+1;
2889 case ISD::AssertZext:
2890 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2893 case ISD::Constant: {
2894 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2895 return Val.getNumSignBits();
2898 case ISD::BUILD_VECTOR:
2900 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
2901 if (!DemandedElts[i])
2904 SDValue SrcOp = Op.getOperand(i);
2905 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
2907 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2908 if (SrcOp.getValueSizeInBits() != VTBits) {
2909 assert(SrcOp.getValueSizeInBits() > VTBits &&
2910 "Expected BUILD_VECTOR implicit truncation");
2911 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
2912 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
2914 Tmp = std::min(Tmp, Tmp2);
2918 case ISD::VECTOR_SHUFFLE: {
2919 // Collect the minimum number of sign bits that are shared by every vector
2920 // element referenced by the shuffle.
2921 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2922 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2923 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2924 for (unsigned i = 0; i != NumElts; ++i) {
2925 int M = SVN->getMaskElt(i);
2926 if (!DemandedElts[i])
2928 // For UNDEF elements, we don't know anything about the common state of
2929 // the shuffle result.
2932 if ((unsigned)M < NumElts)
2933 DemandedLHS.setBit((unsigned)M % NumElts);
2935 DemandedRHS.setBit((unsigned)M % NumElts);
2937 Tmp = std::numeric_limits<unsigned>::max();
2939 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
2940 if (!!DemandedRHS) {
2941 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
2942 Tmp = std::min(Tmp, Tmp2);
2944 // If we don't know anything, early out and try computeKnownBits fall-back.
2947 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
2951 case ISD::SIGN_EXTEND:
2952 case ISD::SIGN_EXTEND_VECTOR_INREG:
2953 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
2954 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2956 case ISD::SIGN_EXTEND_INREG:
2957 // Max of the input and what this extends.
2958 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
2961 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2962 return std::max(Tmp, Tmp2);
2965 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
2966 // SRA X, C -> adds C sign bits.
2967 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2968 APInt ShiftVal = C->getAPIntValue();
2970 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
2974 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2975 // shl destroys sign bits.
2976 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2977 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
2978 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
2979 return Tmp - C->getZExtValue();
2984 case ISD::XOR: // NOT is handled here.
2985 // Logical binary ops preserve the number of sign bits at the worst.
2986 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2988 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2989 FirstAnswer = std::min(Tmp, Tmp2);
2990 // We computed what we know about the sign bits as our first
2991 // answer. Now proceed to the generic code that uses
2992 // computeKnownBits, and pick whichever answer is better.
2997 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2998 if (Tmp == 1) return 1; // Early out.
2999 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3000 return std::min(Tmp, Tmp2);
3001 case ISD::SELECT_CC:
3002 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
3003 if (Tmp == 1) return 1; // Early out.
3004 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
3005 return std::min(Tmp, Tmp2);
3010 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3012 return 1; // Early out.
3013 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3014 return std::min(Tmp, Tmp2);
3021 if (Op.getResNo() != 1)
3023 // The boolean result conforms to getBooleanContents. Fall through.
3024 // If setcc returns 0/-1, all bits are sign bits.
3025 // We know that we have an integer-based boolean since these operations
3026 // are only available for integer.
3027 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3028 TargetLowering::ZeroOrNegativeOneBooleanContent)
3032 // If setcc returns 0/-1, all bits are sign bits.
3033 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3034 TargetLowering::ZeroOrNegativeOneBooleanContent)
3039 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3040 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
3042 // Handle rotate right by N like a rotate left by 32-N.
3043 if (Op.getOpcode() == ISD::ROTR)
3044 RotAmt = (VTBits-RotAmt) & (VTBits-1);
3046 // If we aren't rotating out all of the known-in sign bits, return the
3047 // number that are left. This handles rotl(sext(x), 1) for example.
3048 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3049 if (Tmp > RotAmt+1) return Tmp-RotAmt;
3054 // Add can have at most one carry bit. Thus we know that the output
3055 // is, at worst, one more bit than the inputs.
3056 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3057 if (Tmp == 1) return 1; // Early out.
3059 // Special case decrementing a value (ADD X, -1):
3060 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3061 if (CRHS->isAllOnesValue()) {
3063 computeKnownBits(Op.getOperand(0), Known, Depth+1);
3065 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3067 if ((Known.Zero | 1).isAllOnesValue())
3070 // If we are subtracting one from a positive number, there is no carry
3071 // out of the result.
3072 if (Known.isNonNegative())
3076 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3077 if (Tmp2 == 1) return 1;
3078 return std::min(Tmp, Tmp2)-1;
3081 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3082 if (Tmp2 == 1) return 1;
3085 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3086 if (CLHS->isNullValue()) {
3088 computeKnownBits(Op.getOperand(1), Known, Depth+1);
3089 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3091 if ((Known.Zero | 1).isAllOnesValue())
3094 // If the input is known to be positive (the sign bit is known clear),
3095 // the output of the NEG has the same number of sign bits as the input.
3096 if (Known.isNonNegative())
3099 // Otherwise, we treat this like a SUB.
3102 // Sub can have at most one carry bit. Thus we know that the output
3103 // is, at worst, one more bit than the inputs.
3104 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3105 if (Tmp == 1) return 1; // Early out.
3106 return std::min(Tmp, Tmp2)-1;
3107 case ISD::TRUNCATE: {
3108 // Check if the sign bits of source go down as far as the truncated value.
3109 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3110 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3111 if (NumSrcSignBits > (NumSrcBits - VTBits))
3112 return NumSrcSignBits - (NumSrcBits - VTBits);
3115 case ISD::EXTRACT_ELEMENT: {
3116 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3117 const int BitWidth = Op.getValueSizeInBits();
3118 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3120 // Get reverse index (starting from 1), Op1 value indexes elements from
3121 // little end. Sign starts at big end.
3122 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3124 // If the sign portion ends in our element the subtraction gives correct
3125 // result. Otherwise it gives either negative or > bitwidth result
3126 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3128 case ISD::INSERT_VECTOR_ELT: {
3129 SDValue InVec = Op.getOperand(0);
3130 SDValue InVal = Op.getOperand(1);
3131 SDValue EltNo = Op.getOperand(2);
3132 unsigned NumElts = InVec.getValueType().getVectorNumElements();
3134 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3135 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3136 // If we know the element index, split the demand between the
3137 // source vector and the inserted element.
3138 unsigned EltIdx = CEltNo->getZExtValue();
3140 // If we demand the inserted element then get its sign bits.
3141 Tmp = std::numeric_limits<unsigned>::max();
3142 if (DemandedElts[EltIdx]) {
3143 // TODO - handle implicit truncation of inserted elements.
3144 if (InVal.getScalarValueSizeInBits() != VTBits)
3146 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3149 // If we demand the source vector then get its sign bits, and determine
3151 APInt VectorElts = DemandedElts;
3152 VectorElts.clearBit(EltIdx);
3154 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3155 Tmp = std::min(Tmp, Tmp2);
3158 // Unknown element index, so ignore DemandedElts and demand them all.
3159 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3160 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3161 Tmp = std::min(Tmp, Tmp2);
3163 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3166 case ISD::EXTRACT_VECTOR_ELT: {
3167 SDValue InVec = Op.getOperand(0);
3168 SDValue EltNo = Op.getOperand(1);
3169 EVT VecVT = InVec.getValueType();
3170 const unsigned BitWidth = Op.getValueSizeInBits();
3171 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3172 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3174 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3175 // anything about sign bits. But if the sizes match we can derive knowledge
3176 // about sign bits from the vector operand.
3177 if (BitWidth != EltBitWidth)
3180 // If we know the element index, just demand that vector element, else for
3181 // an unknown element index, ignore DemandedElts and demand them all.
3182 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3183 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3184 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3186 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3188 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3190 case ISD::EXTRACT_SUBVECTOR: {
3191 // If we know the element index, just demand that subvector elements,
3192 // otherwise demand them all.
3193 SDValue Src = Op.getOperand(0);
3194 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3195 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3196 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3197 // Offset the demanded elts by the subvector index.
3198 uint64_t Idx = SubIdx->getZExtValue();
3199 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
3200 return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3202 return ComputeNumSignBits(Src, Depth + 1);
3204 case ISD::CONCAT_VECTORS:
3205 // Determine the minimum number of sign bits across all demanded
3206 // elts of the input vectors. Early out if the result is already 1.
3207 Tmp = std::numeric_limits<unsigned>::max();
3208 EVT SubVectorVT = Op.getOperand(0).getValueType();
3209 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3210 unsigned NumSubVectors = Op.getNumOperands();
3211 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3212 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3213 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3216 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3217 Tmp = std::min(Tmp, Tmp2);
3219 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3223 // If we are looking at the loaded value of the SDNode.
3224 if (Op.getResNo() == 0) {
3225 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3226 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3227 unsigned ExtType = LD->getExtensionType();
3230 case ISD::SEXTLOAD: // '17' bits known
3231 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3232 return VTBits-Tmp+1;
3233 case ISD::ZEXTLOAD: // '16' bits known
3234 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3240 // Allow the target to implement this method for its nodes.
3241 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3242 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3243 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3244 Op.getOpcode() == ISD::INTRINSIC_VOID) {
3246 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3248 FirstAnswer = std::max(FirstAnswer, NumBits);
3251 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3252 // use this information.
3254 computeKnownBits(Op, Known, DemandedElts, Depth);
3257 if (Known.isNonNegative()) { // sign bit is 0
3259 } else if (Known.isNegative()) { // sign bit is 1;
3266 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3267 // the number of identical bits in the top of the input value.
3269 Mask <<= Mask.getBitWidth()-VTBits;
3270 // Return # leading zeros. We use 'min' here in case Val was zero before
3271 // shifting. We don't want to return '64' as for an i32 "0".
3272 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3275 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3276 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3277 !isa<ConstantSDNode>(Op.getOperand(1)))
3280 if (Op.getOpcode() == ISD::OR &&
3281 !MaskedValueIsZero(Op.getOperand(0),
3282 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3288 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
3289 // If we're told that NaNs won't happen, assume they won't.
3290 if (getTarget().Options.NoNaNsFPMath)
3293 if (Op->getFlags().hasNoNaNs())
3296 // If the value is a constant, we can obviously see if it is a NaN or not.
3297 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3298 return !C->getValueAPF().isNaN();
3300 // TODO: Recognize more cases here.
3305 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3306 // If the value is a constant, we can obviously see if it is a zero or not.
3307 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3308 return !C->isZero();
3310 // TODO: Recognize more cases here.
3311 switch (Op.getOpcode()) {
3314 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3315 return !C->isNullValue();
3322 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3323 // Check the obvious case.
3324 if (A == B) return true;
3326 // For for negative and positive zero.
3327 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3328 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3329 if (CA->isZero() && CB->isZero()) return true;
3331 // Otherwise they may not be equal.
3335 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3336 assert(A.getValueType() == B.getValueType() &&
3337 "Values must have the same type");
3338 KnownBits AKnown, BKnown;
3339 computeKnownBits(A, AKnown);
3340 computeKnownBits(B, BKnown);
3341 return (AKnown.Zero | BKnown.Zero).isAllOnesValue();
3344 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3345 ArrayRef<SDValue> Ops,
3346 SelectionDAG &DAG) {
3347 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3348 assert(llvm::all_of(Ops,
3350 return Ops[0].getValueType() == Op.getValueType();
3352 "Concatenation of vectors with inconsistent value types!");
3353 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3354 VT.getVectorNumElements() &&
3355 "Incorrect element count in vector concatenation!");
3357 if (Ops.size() == 1)
3360 // Concat of UNDEFs is UNDEF.
3361 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3362 return DAG.getUNDEF(VT);
3364 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3365 // simplified to one big BUILD_VECTOR.
3366 // FIXME: Add support for SCALAR_TO_VECTOR as well.
3367 EVT SVT = VT.getScalarType();
3368 SmallVector<SDValue, 16> Elts;
3369 for (SDValue Op : Ops) {
3370 EVT OpVT = Op.getValueType();
3372 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3373 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3374 Elts.append(Op->op_begin(), Op->op_end());
3379 // BUILD_VECTOR requires all inputs to be of the same type, find the
3380 // maximum type and extend them all.
3381 for (SDValue Op : Elts)
3382 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3384 if (SVT.bitsGT(VT.getScalarType()))
3385 for (SDValue &Op : Elts)
3386 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3387 ? DAG.getZExtOrTrunc(Op, DL, SVT)
3388 : DAG.getSExtOrTrunc(Op, DL, SVT);
3390 return DAG.getBuildVector(VT, DL, Elts);
3393 /// Gets or creates the specified node.
3394 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3395 FoldingSetNodeID ID;
3396 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3398 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3399 return SDValue(E, 0);
3401 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3403 CSEMap.InsertNode(N, IP);
3406 return SDValue(N, 0);
3409 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3410 SDValue Operand, const SDNodeFlags Flags) {
3411 // Constant fold unary operations with an integer constant operand. Even
3412 // opaque constant will be folded, because the folding of unary operations
3413 // doesn't create new constants with different values. Nevertheless, the
3414 // opaque flag is preserved during folding to prevent future folding with
3416 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3417 const APInt &Val = C->getAPIntValue();
3420 case ISD::SIGN_EXTEND:
3421 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3422 C->isTargetOpcode(), C->isOpaque());
3423 case ISD::ANY_EXTEND:
3424 case ISD::ZERO_EXTEND:
3426 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3427 C->isTargetOpcode(), C->isOpaque());
3428 case ISD::UINT_TO_FP:
3429 case ISD::SINT_TO_FP: {
3430 APFloat apf(EVTToAPFloatSemantics(VT),
3431 APInt::getNullValue(VT.getSizeInBits()));
3432 (void)apf.convertFromAPInt(Val,
3433 Opcode==ISD::SINT_TO_FP,
3434 APFloat::rmNearestTiesToEven);
3435 return getConstantFP(apf, DL, VT);
3438 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3439 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3440 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3441 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3442 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3443 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3444 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3445 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3448 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3450 case ISD::BITREVERSE:
3451 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3454 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3457 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3460 case ISD::CTLZ_ZERO_UNDEF:
3461 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3464 case ISD::CTTZ_ZERO_UNDEF:
3465 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3467 case ISD::FP16_TO_FP: {
3469 APFloat FPV(APFloat::IEEEhalf(),
3470 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3472 // This can return overflow, underflow, or inexact; we don't care.
3473 // FIXME need to be more flexible about rounding mode.
3474 (void)FPV.convert(EVTToAPFloatSemantics(VT),
3475 APFloat::rmNearestTiesToEven, &Ignored);
3476 return getConstantFP(FPV, DL, VT);
3481 // Constant fold unary operations with a floating point constant operand.
3482 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3483 APFloat V = C->getValueAPF(); // make copy
3487 return getConstantFP(V, DL, VT);
3490 return getConstantFP(V, DL, VT);
3492 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3493 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3494 return getConstantFP(V, DL, VT);
3498 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3499 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3500 return getConstantFP(V, DL, VT);
3504 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3505 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3506 return getConstantFP(V, DL, VT);
3509 case ISD::FP_EXTEND: {
3511 // This can return overflow, underflow, or inexact; we don't care.
3512 // FIXME need to be more flexible about rounding mode.
3513 (void)V.convert(EVTToAPFloatSemantics(VT),
3514 APFloat::rmNearestTiesToEven, &ignored);
3515 return getConstantFP(V, DL, VT);
3517 case ISD::FP_TO_SINT:
3518 case ISD::FP_TO_UINT: {
3520 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3521 // FIXME need to be more flexible about rounding mode.
3522 APFloat::opStatus s =
3523 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3524 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3526 return getConstant(IntVal, DL, VT);
3529 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3530 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3531 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3532 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3533 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3534 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3536 case ISD::FP_TO_FP16: {
3538 // This can return overflow, underflow, or inexact; we don't care.
3539 // FIXME need to be more flexible about rounding mode.
3540 (void)V.convert(APFloat::IEEEhalf(),
3541 APFloat::rmNearestTiesToEven, &Ignored);
3542 return getConstant(V.bitcastToAPInt(), DL, VT);
3547 // Constant fold unary operations with a vector integer or float operand.
3548 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3549 if (BV->isConstant()) {
3552 // FIXME: Entirely reasonable to perform folding of other unary
3553 // operations here as the need arises.
3560 case ISD::FP_EXTEND:
3561 case ISD::FP_TO_SINT:
3562 case ISD::FP_TO_UINT:
3564 case ISD::UINT_TO_FP:
3565 case ISD::SINT_TO_FP:
3567 case ISD::BITREVERSE:
3570 case ISD::CTLZ_ZERO_UNDEF:
3572 case ISD::CTTZ_ZERO_UNDEF:
3574 SDValue Ops = { Operand };
3575 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3582 unsigned OpOpcode = Operand.getNode()->getOpcode();
3584 case ISD::TokenFactor:
3585 case ISD::MERGE_VALUES:
3586 case ISD::CONCAT_VECTORS:
3587 return Operand; // Factor, merge or concat of one node? No need.
3588 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3589 case ISD::FP_EXTEND:
3590 assert(VT.isFloatingPoint() &&
3591 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3592 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3593 assert((!VT.isVector() ||
3594 VT.getVectorNumElements() ==
3595 Operand.getValueType().getVectorNumElements()) &&
3596 "Vector element count mismatch!");
3597 assert(Operand.getValueType().bitsLT(VT) &&
3598 "Invalid fpext node, dst < src!");
3599 if (Operand.isUndef())
3600 return getUNDEF(VT);
3602 case ISD::SIGN_EXTEND:
3603 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3604 "Invalid SIGN_EXTEND!");
3605 if (Operand.getValueType() == VT) return Operand; // noop extension
3606 assert((!VT.isVector() ||
3607 VT.getVectorNumElements() ==
3608 Operand.getValueType().getVectorNumElements()) &&
3609 "Vector element count mismatch!");
3610 assert(Operand.getValueType().bitsLT(VT) &&
3611 "Invalid sext node, dst < src!");
3612 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3613 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3614 else if (OpOpcode == ISD::UNDEF)
3615 // sext(undef) = 0, because the top bits will all be the same.
3616 return getConstant(0, DL, VT);
3618 case ISD::ZERO_EXTEND:
3619 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3620 "Invalid ZERO_EXTEND!");
3621 if (Operand.getValueType() == VT) return Operand; // noop extension
3622 assert((!VT.isVector() ||
3623 VT.getVectorNumElements() ==
3624 Operand.getValueType().getVectorNumElements()) &&
3625 "Vector element count mismatch!");
3626 assert(Operand.getValueType().bitsLT(VT) &&
3627 "Invalid zext node, dst < src!");
3628 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3629 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
3630 else if (OpOpcode == ISD::UNDEF)
3631 // zext(undef) = 0, because the top bits will be zero.
3632 return getConstant(0, DL, VT);
3634 case ISD::ANY_EXTEND:
3635 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3636 "Invalid ANY_EXTEND!");
3637 if (Operand.getValueType() == VT) return Operand; // noop extension
3638 assert((!VT.isVector() ||
3639 VT.getVectorNumElements() ==
3640 Operand.getValueType().getVectorNumElements()) &&
3641 "Vector element count mismatch!");
3642 assert(Operand.getValueType().bitsLT(VT) &&
3643 "Invalid anyext node, dst < src!");
3645 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3646 OpOpcode == ISD::ANY_EXTEND)
3647 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3648 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3649 else if (OpOpcode == ISD::UNDEF)
3650 return getUNDEF(VT);
3652 // (ext (trunx x)) -> x
3653 if (OpOpcode == ISD::TRUNCATE) {
3654 SDValue OpOp = Operand.getOperand(0);
3655 if (OpOp.getValueType() == VT)
3660 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3661 "Invalid TRUNCATE!");
3662 if (Operand.getValueType() == VT) return Operand; // noop truncate
3663 assert((!VT.isVector() ||
3664 VT.getVectorNumElements() ==
3665 Operand.getValueType().getVectorNumElements()) &&
3666 "Vector element count mismatch!");
3667 assert(Operand.getValueType().bitsGT(VT) &&
3668 "Invalid truncate node, src < dst!");
3669 if (OpOpcode == ISD::TRUNCATE)
3670 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
3671 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3672 OpOpcode == ISD::ANY_EXTEND) {
3673 // If the source is smaller than the dest, we still need an extend.
3674 if (Operand.getOperand(0).getValueType().getScalarType()
3675 .bitsLT(VT.getScalarType()))
3676 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3677 if (Operand.getOperand(0).getValueType().bitsGT(VT))
3678 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
3679 return Operand.getOperand(0);
3681 if (OpOpcode == ISD::UNDEF)
3682 return getUNDEF(VT);
3685 assert(VT.isInteger() && VT == Operand.getValueType() &&
3687 if (OpOpcode == ISD::UNDEF)
3688 return getUNDEF(VT);
3691 assert(VT.isInteger() && VT == Operand.getValueType() &&
3693 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3694 "BSWAP types must be a multiple of 16 bits!");
3695 if (OpOpcode == ISD::UNDEF)
3696 return getUNDEF(VT);
3698 case ISD::BITREVERSE:
3699 assert(VT.isInteger() && VT == Operand.getValueType() &&
3700 "Invalid BITREVERSE!");
3701 if (OpOpcode == ISD::UNDEF)
3702 return getUNDEF(VT);
3705 // Basic sanity checking.
3706 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3707 "Cannot BITCAST between types of different sizes!");
3708 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3709 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3710 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3711 if (OpOpcode == ISD::UNDEF)
3712 return getUNDEF(VT);
3714 case ISD::SCALAR_TO_VECTOR:
3715 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3716 (VT.getVectorElementType() == Operand.getValueType() ||
3717 (VT.getVectorElementType().isInteger() &&
3718 Operand.getValueType().isInteger() &&
3719 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3720 "Illegal SCALAR_TO_VECTOR node!");
3721 if (OpOpcode == ISD::UNDEF)
3722 return getUNDEF(VT);
3723 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3724 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3725 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3726 Operand.getConstantOperandVal(1) == 0 &&
3727 Operand.getOperand(0).getValueType() == VT)
3728 return Operand.getOperand(0);
3731 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3732 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3733 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3734 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
3735 Operand.getOperand(0), Operand.getNode()->getFlags());
3736 if (OpOpcode == ISD::FNEG) // --X -> X
3737 return Operand.getOperand(0);
3740 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3741 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
3746 SDVTList VTs = getVTList(VT);
3747 SDValue Ops[] = {Operand};
3748 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3749 FoldingSetNodeID ID;
3750 AddNodeIDNode(ID, Opcode, VTs, Ops);
3752 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
3753 E->intersectFlagsWith(Flags);
3754 return SDValue(E, 0);
3757 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3759 createOperands(N, Ops);
3760 CSEMap.InsertNode(N, IP);
3762 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3763 createOperands(N, Ops);
3767 return SDValue(N, 0);
3770 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3773 case ISD::ADD: return std::make_pair(C1 + C2, true);
3774 case ISD::SUB: return std::make_pair(C1 - C2, true);
3775 case ISD::MUL: return std::make_pair(C1 * C2, true);
3776 case ISD::AND: return std::make_pair(C1 & C2, true);
3777 case ISD::OR: return std::make_pair(C1 | C2, true);
3778 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3779 case ISD::SHL: return std::make_pair(C1 << C2, true);
3780 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3781 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3782 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3783 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3784 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3785 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3786 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3787 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3789 if (!C2.getBoolValue())
3791 return std::make_pair(C1.udiv(C2), true);
3793 if (!C2.getBoolValue())
3795 return std::make_pair(C1.urem(C2), true);
3797 if (!C2.getBoolValue())
3799 return std::make_pair(C1.sdiv(C2), true);
3801 if (!C2.getBoolValue())
3803 return std::make_pair(C1.srem(C2), true);
3805 return std::make_pair(APInt(1, 0), false);
3808 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3809 EVT VT, const ConstantSDNode *Cst1,
3810 const ConstantSDNode *Cst2) {
3811 if (Cst1->isOpaque() || Cst2->isOpaque())
3814 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3815 Cst2->getAPIntValue());
3818 return getConstant(Folded.first, DL, VT);
3821 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3822 const GlobalAddressSDNode *GA,
3824 if (GA->getOpcode() != ISD::GlobalAddress)
3826 if (!TLI->isOffsetFoldingLegal(GA))
3828 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3831 int64_t Offset = Cst2->getSExtValue();
3833 case ISD::ADD: break;
3834 case ISD::SUB: Offset = -uint64_t(Offset); break;
3835 default: return SDValue();
3837 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3838 GA->getOffset() + uint64_t(Offset));
3841 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
3847 // If a divisor is zero/undef or any element of a divisor vector is
3848 // zero/undef, the whole op is undef.
3849 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
3850 SDValue Divisor = Ops[1];
3851 if (Divisor.isUndef() || isNullConstant(Divisor))
3854 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
3855 llvm::any_of(Divisor->op_values(),
3856 [](SDValue V) { return V.isUndef() ||
3857 isNullConstant(V); });
3858 // TODO: Handle signed overflow.
3860 // TODO: Handle oversized shifts.
3866 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3867 EVT VT, SDNode *Cst1,
3869 // If the opcode is a target-specific ISD node, there's nothing we can
3870 // do here and the operand rules may not line up with the below, so
3872 if (Opcode >= ISD::BUILTIN_OP_END)
3875 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
3876 return getUNDEF(VT);
3878 // Handle the case of two scalars.
3879 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3880 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3881 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3882 assert((!Folded || !VT.isVector()) &&
3883 "Can't fold vectors ops with scalar operands");
3888 // fold (add Sym, c) -> Sym+c
3889 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3890 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3891 if (TLI->isCommutativeBinOp(Opcode))
3892 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3893 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3895 // For vectors extract each constant element into Inputs so we can constant
3896 // fold them individually.
3897 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3898 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3902 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3904 EVT SVT = VT.getScalarType();
3905 SmallVector<SDValue, 4> Outputs;
3906 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3907 SDValue V1 = BV1->getOperand(I);
3908 SDValue V2 = BV2->getOperand(I);
3910 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3911 // FIXME: This is valid and could be handled by truncation.
3912 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3915 // Fold one vector element.
3916 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
3918 // Scalar folding only succeeded if the result is a constant or UNDEF.
3919 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3920 ScalarResult.getOpcode() != ISD::ConstantFP)
3922 Outputs.push_back(ScalarResult);
3925 assert(VT.getVectorNumElements() == Outputs.size() &&
3926 "Vector size mismatch!");
3928 // We may have a vector type but a scalar result. Create a splat.
3929 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3931 // Build a big vector out of the scalar elements we generated.
3932 return getBuildVector(VT, SDLoc(), Outputs);
3935 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3936 const SDLoc &DL, EVT VT,
3937 ArrayRef<SDValue> Ops,
3938 const SDNodeFlags Flags) {
3939 // If the opcode is a target-specific ISD node, there's nothing we can
3940 // do here and the operand rules may not line up with the below, so
3942 if (Opcode >= ISD::BUILTIN_OP_END)
3945 if (isUndef(Opcode, Ops))
3946 return getUNDEF(VT);
3948 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3952 unsigned NumElts = VT.getVectorNumElements();
3954 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3955 return !Op.getValueType().isVector() ||
3956 Op.getValueType().getVectorNumElements() == NumElts;
3959 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3960 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3961 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3962 (BV && BV->isConstant());
3965 // All operands must be vector types with the same number of elements as
3966 // the result type and must be either UNDEF or a build vector of constant
3967 // or UNDEF scalars.
3968 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
3969 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
3972 // If we are comparing vectors, then the result needs to be a i1 boolean
3973 // that is then sign-extended back to the legal result type.
3974 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3976 // Find legal integer scalar type for constant promotion and
3977 // ensure that its scalar size is at least as large as source.
3978 EVT LegalSVT = VT.getScalarType();
3979 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
3980 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3981 if (LegalSVT.bitsLT(VT.getScalarType()))
3985 // Constant fold each scalar lane separately.
3986 SmallVector<SDValue, 4> ScalarResults;
3987 for (unsigned i = 0; i != NumElts; i++) {
3988 SmallVector<SDValue, 4> ScalarOps;
3989 for (SDValue Op : Ops) {
3990 EVT InSVT = Op.getValueType().getScalarType();
3991 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3993 // We've checked that this is UNDEF or a constant of some kind.
3995 ScalarOps.push_back(getUNDEF(InSVT));
3997 ScalarOps.push_back(Op);
4001 SDValue ScalarOp = InBV->getOperand(i);
4002 EVT ScalarVT = ScalarOp.getValueType();
4004 // Build vector (integer) scalar operands may need implicit
4005 // truncation - do this before constant folding.
4006 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4007 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4009 ScalarOps.push_back(ScalarOp);
4012 // Constant fold the scalar operands.
4013 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4015 // Legalize the (integer) scalar constant if necessary.
4016 if (LegalSVT != SVT)
4017 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4019 // Scalar folding only succeeded if the result is a constant or UNDEF.
4020 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4021 ScalarResult.getOpcode() != ISD::ConstantFP)
4023 ScalarResults.push_back(ScalarResult);
4026 return getBuildVector(VT, DL, ScalarResults);
4029 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4030 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
4031 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4032 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4033 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4034 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4036 // Canonicalize constant to RHS if commutative.
4037 if (TLI->isCommutativeBinOp(Opcode)) {
4039 std::swap(N1C, N2C);
4041 } else if (N1CFP && !N2CFP) {
4042 std::swap(N1CFP, N2CFP);
4049 case ISD::TokenFactor:
4050 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4051 N2.getValueType() == MVT::Other && "Invalid token factor!");
4052 // Fold trivial token factors.
4053 if (N1.getOpcode() == ISD::EntryToken) return N2;
4054 if (N2.getOpcode() == ISD::EntryToken) return N1;
4055 if (N1 == N2) return N1;
4057 case ISD::CONCAT_VECTORS: {
4058 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4059 SDValue Ops[] = {N1, N2};
4060 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4065 assert(VT.isInteger() && "This operator does not apply to FP types!");
4066 assert(N1.getValueType() == N2.getValueType() &&
4067 N1.getValueType() == VT && "Binary operator types must match!");
4068 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4069 // worth handling here.
4070 if (N2C && N2C->isNullValue())
4072 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4079 assert(VT.isInteger() && "This operator does not apply to FP types!");
4080 assert(N1.getValueType() == N2.getValueType() &&
4081 N1.getValueType() == VT && "Binary operator types must match!");
4082 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4083 // it's worth handling here.
4084 if (N2C && N2C->isNullValue())
4098 assert(VT.isInteger() && "This operator does not apply to FP types!");
4099 assert(N1.getValueType() == N2.getValueType() &&
4100 N1.getValueType() == VT && "Binary operator types must match!");
4107 if (getTarget().Options.UnsafeFPMath) {
4108 if (Opcode == ISD::FADD) {
4110 if (N2CFP && N2CFP->getValueAPF().isZero())
4112 } else if (Opcode == ISD::FSUB) {
4114 if (N2CFP && N2CFP->getValueAPF().isZero())
4116 } else if (Opcode == ISD::FMUL) {
4118 if (N2CFP && N2CFP->isZero())
4121 if (N2CFP && N2CFP->isExactlyValue(1.0))
4125 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4126 assert(N1.getValueType() == N2.getValueType() &&
4127 N1.getValueType() == VT && "Binary operator types must match!");
4129 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4130 assert(N1.getValueType() == VT &&
4131 N1.getValueType().isFloatingPoint() &&
4132 N2.getValueType().isFloatingPoint() &&
4133 "Invalid FCOPYSIGN!");
4140 assert(VT == N1.getValueType() &&
4141 "Shift operators return type must be the same as their first arg");
4142 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4143 "Shifts only work on integers");
4144 assert((!VT.isVector() || VT == N2.getValueType()) &&
4145 "Vector shift amounts must be in the same as their first arg");
4146 // Verify that the shift amount VT is bit enough to hold valid shift
4147 // amounts. This catches things like trying to shift an i1024 value by an
4148 // i8, which is easy to fall into in generic code that uses
4149 // TLI.getShiftAmount().
4150 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4151 "Invalid use of small shift amount with oversized value!");
4153 // Always fold shifts of i1 values so the code generator doesn't need to
4154 // handle them. Since we know the size of the shift has to be less than the
4155 // size of the value, the shift/rotate count is guaranteed to be zero.
4158 if (N2C && N2C->isNullValue())
4161 case ISD::FP_ROUND_INREG: {
4162 EVT EVT = cast<VTSDNode>(N2)->getVT();
4163 assert(VT == N1.getValueType() && "Not an inreg round!");
4164 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4165 "Cannot FP_ROUND_INREG integer types");
4166 assert(EVT.isVector() == VT.isVector() &&
4167 "FP_ROUND_INREG type should be vector iff the operand "
4169 assert((!EVT.isVector() ||
4170 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4171 "Vector element counts must match in FP_ROUND_INREG");
4172 assert(EVT.bitsLE(VT) && "Not rounding down!");
4174 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4178 assert(VT.isFloatingPoint() &&
4179 N1.getValueType().isFloatingPoint() &&
4180 VT.bitsLE(N1.getValueType()) &&
4181 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4182 "Invalid FP_ROUND!");
4183 if (N1.getValueType() == VT) return N1; // noop conversion.
4185 case ISD::AssertSext:
4186 case ISD::AssertZext: {
4187 EVT EVT = cast<VTSDNode>(N2)->getVT();
4188 assert(VT == N1.getValueType() && "Not an inreg extend!");
4189 assert(VT.isInteger() && EVT.isInteger() &&
4190 "Cannot *_EXTEND_INREG FP types");
4191 assert(!EVT.isVector() &&
4192 "AssertSExt/AssertZExt type should be the vector element type "
4193 "rather than the vector type!");
4194 assert(EVT.bitsLE(VT) && "Not extending!");
4195 if (VT == EVT) return N1; // noop assertion.
4198 case ISD::SIGN_EXTEND_INREG: {
4199 EVT EVT = cast<VTSDNode>(N2)->getVT();
4200 assert(VT == N1.getValueType() && "Not an inreg extend!");
4201 assert(VT.isInteger() && EVT.isInteger() &&
4202 "Cannot *_EXTEND_INREG FP types");
4203 assert(EVT.isVector() == VT.isVector() &&
4204 "SIGN_EXTEND_INREG type should be vector iff the operand "
4206 assert((!EVT.isVector() ||
4207 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4208 "Vector element counts must match in SIGN_EXTEND_INREG");
4209 assert(EVT.bitsLE(VT) && "Not extending!");
4210 if (EVT == VT) return N1; // Not actually extending
4212 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4213 unsigned FromBits = EVT.getScalarSizeInBits();
4214 Val <<= Val.getBitWidth() - FromBits;
4215 Val.ashrInPlace(Val.getBitWidth() - FromBits);
4216 return getConstant(Val, DL, ConstantVT);
4220 const APInt &Val = N1C->getAPIntValue();
4221 return SignExtendInReg(Val, VT);
4223 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4224 SmallVector<SDValue, 8> Ops;
4225 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4226 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4227 SDValue Op = N1.getOperand(i);
4229 Ops.push_back(getUNDEF(OpVT));
4232 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4233 APInt Val = C->getAPIntValue();
4234 Ops.push_back(SignExtendInReg(Val, OpVT));
4236 return getBuildVector(VT, DL, Ops);
4240 case ISD::EXTRACT_VECTOR_ELT:
4241 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4243 return getUNDEF(VT);
4245 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4246 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4247 return getUNDEF(VT);
4249 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4250 // expanding copies of large vectors from registers.
4252 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4253 N1.getNumOperands() > 0) {
4255 N1.getOperand(0).getValueType().getVectorNumElements();
4256 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4257 N1.getOperand(N2C->getZExtValue() / Factor),
4258 getConstant(N2C->getZExtValue() % Factor, DL,
4259 N2.getValueType()));
4262 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4263 // expanding large vector constants.
4264 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4265 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4267 if (VT != Elt.getValueType())
4268 // If the vector element type is not legal, the BUILD_VECTOR operands
4269 // are promoted and implicitly truncated, and the result implicitly
4270 // extended. Make that explicit here.
4271 Elt = getAnyExtOrTrunc(Elt, DL, VT);
4276 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4277 // operations are lowered to scalars.
4278 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4279 // If the indices are the same, return the inserted element else
4280 // if the indices are known different, extract the element from
4281 // the original vector.
4282 SDValue N1Op2 = N1.getOperand(2);
4283 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4285 if (N1Op2C && N2C) {
4286 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4287 if (VT == N1.getOperand(1).getValueType())
4288 return N1.getOperand(1);
4290 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4293 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4297 case ISD::EXTRACT_ELEMENT:
4298 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4299 assert(!N1.getValueType().isVector() && !VT.isVector() &&
4300 (N1.getValueType().isInteger() == VT.isInteger()) &&
4301 N1.getValueType() != VT &&
4302 "Wrong types for EXTRACT_ELEMENT!");
4304 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4305 // 64-bit integers into 32-bit parts. Instead of building the extract of
4306 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4307 if (N1.getOpcode() == ISD::BUILD_PAIR)
4308 return N1.getOperand(N2C->getZExtValue());
4310 // EXTRACT_ELEMENT of a constant int is also very common.
4312 unsigned ElementSize = VT.getSizeInBits();
4313 unsigned Shift = ElementSize * N2C->getZExtValue();
4314 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4315 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4318 case ISD::EXTRACT_SUBVECTOR:
4319 if (VT.isSimple() && N1.getValueType().isSimple()) {
4320 assert(VT.isVector() && N1.getValueType().isVector() &&
4321 "Extract subvector VTs must be a vectors!");
4322 assert(VT.getVectorElementType() ==
4323 N1.getValueType().getVectorElementType() &&
4324 "Extract subvector VTs must have the same element type!");
4325 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4326 "Extract subvector must be from larger vector to smaller vector!");
4329 assert((VT.getVectorNumElements() + N2C->getZExtValue()
4330 <= N1.getValueType().getVectorNumElements())
4331 && "Extract subvector overflow!");
4334 // Trivial extraction.
4335 if (VT.getSimpleVT() == N1.getSimpleValueType())
4338 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4340 return getUNDEF(VT);
4342 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4343 // the concat have the same type as the extract.
4344 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4345 N1.getNumOperands() > 0 &&
4346 VT == N1.getOperand(0).getValueType()) {
4347 unsigned Factor = VT.getVectorNumElements();
4348 return N1.getOperand(N2C->getZExtValue() / Factor);
4351 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4352 // during shuffle legalization.
4353 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4354 VT == N1.getOperand(1).getValueType())
4355 return N1.getOperand(1);
4360 // Perform trivial constant folding.
4362 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4365 // Constant fold FP operations.
4366 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4369 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4370 APFloat::opStatus s;
4373 s = V1.add(V2, APFloat::rmNearestTiesToEven);
4374 if (!HasFPExceptions || s != APFloat::opInvalidOp)
4375 return getConstantFP(V1, DL, VT);
4378 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4379 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4380 return getConstantFP(V1, DL, VT);
4383 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4384 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4385 return getConstantFP(V1, DL, VT);
4388 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4389 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4390 s!=APFloat::opDivByZero)) {
4391 return getConstantFP(V1, DL, VT);
4396 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4397 s!=APFloat::opDivByZero)) {
4398 return getConstantFP(V1, DL, VT);
4401 case ISD::FCOPYSIGN:
4403 return getConstantFP(V1, DL, VT);
4408 if (Opcode == ISD::FP_ROUND) {
4409 APFloat V = N1CFP->getValueAPF(); // make copy
4411 // This can return overflow, underflow, or inexact; we don't care.
4412 // FIXME need to be more flexible about rounding mode.
4413 (void)V.convert(EVTToAPFloatSemantics(VT),
4414 APFloat::rmNearestTiesToEven, &ignored);
4415 return getConstantFP(V, DL, VT);
4419 // Canonicalize an UNDEF to the RHS, even over a constant.
4421 if (TLI->isCommutativeBinOp(Opcode)) {
4425 case ISD::FP_ROUND_INREG:
4426 case ISD::SIGN_EXTEND_INREG:
4432 return N1; // fold op(undef, arg2) -> undef
4440 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
4441 // For vectors, we can't easily build an all zero vector, just return
4448 // Fold a bunch of operators when the RHS is undef.
4453 // Handle undef ^ undef -> 0 special case. This is a common
4455 return getConstant(0, DL, VT);
4465 return N2; // fold op(arg1, undef) -> undef
4471 if (getTarget().Options.UnsafeFPMath)
4479 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
4480 // For vectors, we can't easily build an all zero vector, just return
4485 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
4486 // For vectors, we can't easily build an all one vector, just return
4494 // Memoize this node if possible.
4496 SDVTList VTs = getVTList(VT);
4497 SDValue Ops[] = {N1, N2};
4498 if (VT != MVT::Glue) {
4499 FoldingSetNodeID ID;
4500 AddNodeIDNode(ID, Opcode, VTs, Ops);
4502 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4503 E->intersectFlagsWith(Flags);
4504 return SDValue(E, 0);
4507 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4509 createOperands(N, Ops);
4510 CSEMap.InsertNode(N, IP);
4512 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4513 createOperands(N, Ops);
4517 return SDValue(N, 0);
4520 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4521 SDValue N1, SDValue N2, SDValue N3) {
4522 // Perform various simplifications.
4525 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4526 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4527 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4528 if (N1CFP && N2CFP && N3CFP) {
4529 APFloat V1 = N1CFP->getValueAPF();
4530 const APFloat &V2 = N2CFP->getValueAPF();
4531 const APFloat &V3 = N3CFP->getValueAPF();
4532 APFloat::opStatus s =
4533 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4534 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4535 return getConstantFP(V1, DL, VT);
4539 case ISD::CONCAT_VECTORS: {
4540 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4541 SDValue Ops[] = {N1, N2, N3};
4542 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4547 // Use FoldSetCC to simplify SETCC's.
4548 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
4550 // Vector constant folding.
4551 SDValue Ops[] = {N1, N2, N3};
4552 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4557 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
4558 if (N1C->getZExtValue())
4559 return N2; // select true, X, Y -> X
4560 return N3; // select false, X, Y -> Y
4563 if (N2 == N3) return N2; // select C, X, X -> X
4565 case ISD::VECTOR_SHUFFLE:
4566 llvm_unreachable("should use getVectorShuffle constructor!");
4567 case ISD::INSERT_VECTOR_ELT: {
4568 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
4569 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
4570 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4571 return getUNDEF(VT);
4574 case ISD::INSERT_SUBVECTOR: {
4576 if (VT.isSimple() && N1.getValueType().isSimple()
4577 && N2.getValueType().isSimple()) {
4578 assert(VT.isVector() && N1.getValueType().isVector() &&
4579 N2.getValueType().isVector() &&
4580 "Insert subvector VTs must be a vectors");
4581 assert(VT == N1.getValueType() &&
4582 "Dest and insert subvector source types must match!");
4583 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4584 "Insert subvector must be from smaller vector to larger vector!");
4585 if (isa<ConstantSDNode>(Index)) {
4586 assert((N2.getValueType().getVectorNumElements() +
4587 cast<ConstantSDNode>(Index)->getZExtValue()
4588 <= VT.getVectorNumElements())
4589 && "Insert subvector overflow!");
4592 // Trivial insertion.
4593 if (VT.getSimpleVT() == N2.getSimpleValueType())
4599 // Fold bit_convert nodes from a type to themselves.
4600 if (N1.getValueType() == VT)
4605 // Memoize node if it doesn't produce a flag.
4607 SDVTList VTs = getVTList(VT);
4608 SDValue Ops[] = {N1, N2, N3};
4609 if (VT != MVT::Glue) {
4610 FoldingSetNodeID ID;
4611 AddNodeIDNode(ID, Opcode, VTs, Ops);
4613 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4614 return SDValue(E, 0);
4616 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4617 createOperands(N, Ops);
4618 CSEMap.InsertNode(N, IP);
4620 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4621 createOperands(N, Ops);
4625 return SDValue(N, 0);
4628 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4629 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4630 SDValue Ops[] = { N1, N2, N3, N4 };
4631 return getNode(Opcode, DL, VT, Ops);
4634 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4635 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4637 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4638 return getNode(Opcode, DL, VT, Ops);
4641 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4642 /// the incoming stack arguments to be loaded from the stack.
4643 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4644 SmallVector<SDValue, 8> ArgChains;
4646 // Include the original chain at the beginning of the list. When this is
4647 // used by target LowerCall hooks, this helps legalize find the
4648 // CALLSEQ_BEGIN node.
4649 ArgChains.push_back(Chain);
4651 // Add a chain value for each stack argument.
4652 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4653 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4654 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4655 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4656 if (FI->getIndex() < 0)
4657 ArgChains.push_back(SDValue(L, 1));
4659 // Build a tokenfactor for all the chains.
4660 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4663 /// getMemsetValue - Vectorized representation of the memset value
4665 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4667 assert(!Value.isUndef());
4669 unsigned NumBits = VT.getScalarSizeInBits();
4670 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4671 assert(C->getAPIntValue().getBitWidth() == 8);
4672 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4674 return DAG.getConstant(Val, dl, VT);
4675 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4679 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4680 EVT IntVT = VT.getScalarType();
4681 if (!IntVT.isInteger())
4682 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4684 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4686 // Use a multiplication with 0x010101... to extend the input to the
4688 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4689 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4690 DAG.getConstant(Magic, dl, IntVT));
4693 if (VT != Value.getValueType() && !VT.isInteger())
4694 Value = DAG.getBitcast(VT.getScalarType(), Value);
4695 if (VT != Value.getValueType())
4696 Value = DAG.getSplatBuildVector(VT, dl, Value);
4701 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4702 /// used when a memcpy is turned into a memset when the source is a constant
4704 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4705 const TargetLowering &TLI,
4706 const ConstantDataArraySlice &Slice) {
4707 // Handle vector with all elements zero.
4708 if (Slice.Array == nullptr) {
4710 return DAG.getConstant(0, dl, VT);
4711 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4712 return DAG.getConstantFP(0.0, dl, VT);
4713 else if (VT.isVector()) {
4714 unsigned NumElts = VT.getVectorNumElements();
4715 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4716 return DAG.getNode(ISD::BITCAST, dl, VT,
4717 DAG.getConstant(0, dl,
4718 EVT::getVectorVT(*DAG.getContext(),
4721 llvm_unreachable("Expected type!");
4724 assert(!VT.isVector() && "Can't handle vector type here!");
4725 unsigned NumVTBits = VT.getSizeInBits();
4726 unsigned NumVTBytes = NumVTBits / 8;
4727 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
4729 APInt Val(NumVTBits, 0);
4730 if (DAG.getDataLayout().isLittleEndian()) {
4731 for (unsigned i = 0; i != NumBytes; ++i)
4732 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
4734 for (unsigned i = 0; i != NumBytes; ++i)
4735 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
4738 // If the "cost" of materializing the integer immediate is less than the cost
4739 // of a load, then it is cost effective to turn the load into the immediate.
4740 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4741 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4742 return DAG.getConstant(Val, dl, VT);
4743 return SDValue(nullptr, 0);
4746 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4748 EVT VT = Base.getValueType();
4749 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4752 /// Returns true if memcpy source is constant data.
4753 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
4754 uint64_t SrcDelta = 0;
4755 GlobalAddressSDNode *G = nullptr;
4756 if (Src.getOpcode() == ISD::GlobalAddress)
4757 G = cast<GlobalAddressSDNode>(Src);
4758 else if (Src.getOpcode() == ISD::ADD &&
4759 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4760 Src.getOperand(1).getOpcode() == ISD::Constant) {
4761 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4762 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4767 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
4768 SrcDelta + G->getOffset());
4771 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4772 /// Return true if the number of memory ops is below the threshold (Limit).
4773 /// It returns the types of the sequence of memory ops to perform
4774 /// memset / memcpy by reference.
4775 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4776 unsigned Limit, uint64_t Size,
4777 unsigned DstAlign, unsigned SrcAlign,
4782 unsigned DstAS, unsigned SrcAS,
4784 const TargetLowering &TLI) {
4785 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4786 "Expecting memcpy / memset source to meet alignment requirement!");
4787 // If 'SrcAlign' is zero, that means the memory operation does not need to
4788 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4789 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4790 // is the specified alignment of the memory operation. If it is zero, that
4791 // means it's possible to change the alignment of the destination.
4792 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4793 // not need to be loaded.
4794 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4795 IsMemset, ZeroMemset, MemcpyStrSrc,
4796 DAG.getMachineFunction());
4798 if (VT == MVT::Other) {
4799 // Use the largest integer type whose alignment constraints are satisfied.
4800 // We only need to check DstAlign here as SrcAlign is always greater or
4801 // equal to DstAlign (or zero).
4803 while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
4804 !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
4805 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
4806 assert(VT.isInteger());
4808 // Find the largest legal integer type.
4810 while (!TLI.isTypeLegal(LVT))
4811 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4812 assert(LVT.isInteger());
4814 // If the type we've chosen is larger than the largest legal integer type
4815 // then use that instead.
4820 unsigned NumMemOps = 0;
4822 unsigned VTSize = VT.getSizeInBits() / 8;
4823 while (VTSize > Size) {
4824 // For now, only use non-vector load / store's for the left-over pieces.
4829 if (VT.isVector() || VT.isFloatingPoint()) {
4830 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4831 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4832 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4834 else if (NewVT == MVT::i64 &&
4835 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4836 TLI.isSafeMemOpType(MVT::f64)) {
4837 // i64 is usually not legal on 32-bit targets, but f64 may be.
4845 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4846 if (NewVT == MVT::i8)
4848 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4850 NewVTSize = NewVT.getSizeInBits() / 8;
4852 // If the new VT cannot cover all of the remaining bits, then consider
4853 // issuing a (or a pair of) unaligned and overlapping load / store.
4854 // FIXME: Only does this for 64-bit or more since we don't have proper
4855 // cost model for unaligned load / store.
4857 if (NumMemOps && AllowOverlap &&
4858 VTSize >= 8 && NewVTSize < Size &&
4859 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4867 if (++NumMemOps > Limit)
4870 MemOps.push_back(VT);
4877 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4878 // On Darwin, -Os means optimize for size without hurting performance, so
4879 // only really optimize for size when -Oz (MinSize) is used.
4880 if (MF.getTarget().getTargetTriple().isOSDarwin())
4881 return MF.getFunction()->optForMinSize();
4882 return MF.getFunction()->optForSize();
4885 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4886 SDValue Chain, SDValue Dst, SDValue Src,
4887 uint64_t Size, unsigned Align,
4888 bool isVol, bool AlwaysInline,
4889 MachinePointerInfo DstPtrInfo,
4890 MachinePointerInfo SrcPtrInfo) {
4891 // Turn a memcpy of undef to nop.
4895 // Expand memcpy to a series of load and store ops if the size operand falls
4896 // below a certain threshold.
4897 // TODO: In the AlwaysInline case, if the size is big then generate a loop
4898 // rather than maybe a humongous number of loads and stores.
4899 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4900 std::vector<EVT> MemOps;
4901 bool DstAlignCanChange = false;
4902 MachineFunction &MF = DAG.getMachineFunction();
4903 MachineFrameInfo &MFI = MF.getFrameInfo();
4904 bool OptSize = shouldLowerMemFuncForSize(MF);
4905 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4906 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4907 DstAlignCanChange = true;
4908 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4909 if (Align > SrcAlign)
4911 ConstantDataArraySlice Slice;
4912 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
4913 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
4914 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4916 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4917 (DstAlignCanChange ? 0 : Align),
4918 (isZeroConstant ? 0 : SrcAlign),
4919 false, false, CopyFromConstant, true,
4920 DstPtrInfo.getAddrSpace(),
4921 SrcPtrInfo.getAddrSpace(),
4925 if (DstAlignCanChange) {
4926 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4927 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4929 // Don't promote to an alignment that would require dynamic stack
4931 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4932 if (!TRI->needsStackRealignment(MF))
4933 while (NewAlign > Align &&
4934 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign))
4937 if (NewAlign > Align) {
4938 // Give the stack frame object a larger alignment if needed.
4939 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4940 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4945 MachineMemOperand::Flags MMOFlags =
4946 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4947 SmallVector<SDValue, 8> OutChains;
4948 unsigned NumMemOps = MemOps.size();
4949 uint64_t SrcOff = 0, DstOff = 0;
4950 for (unsigned i = 0; i != NumMemOps; ++i) {
4952 unsigned VTSize = VT.getSizeInBits() / 8;
4953 SDValue Value, Store;
4955 if (VTSize > Size) {
4956 // Issuing an unaligned load / store pair that overlaps with the previous
4957 // pair. Adjust the offset accordingly.
4958 assert(i == NumMemOps-1 && i != 0);
4959 SrcOff -= VTSize - Size;
4960 DstOff -= VTSize - Size;
4963 if (CopyFromConstant &&
4964 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
4965 // It's unlikely a store of a vector immediate can be done in a single
4966 // instruction. It would require a load from a constantpool first.
4967 // We only handle zero vectors here.
4968 // FIXME: Handle other cases where store of vector immediate is done in
4969 // a single instruction.
4970 ConstantDataArraySlice SubSlice;
4971 if (SrcOff < Slice.Length) {
4973 SubSlice.move(SrcOff);
4975 // This is an out-of-bounds access and hence UB. Pretend we read zero.
4976 SubSlice.Array = nullptr;
4977 SubSlice.Offset = 0;
4978 SubSlice.Length = VTSize;
4980 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
4981 if (Value.getNode())
4982 Store = DAG.getStore(Chain, dl, Value,
4983 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4984 DstPtrInfo.getWithOffset(DstOff), Align,
4988 if (!Store.getNode()) {
4989 // The type might not be legal for the target. This should only happen
4990 // if the type is smaller than a legal type, as on PPC, so the right
4991 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
4992 // to Load/Store if NVT==VT.
4993 // FIXME does the case above also need this?
4994 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4995 assert(NVT.bitsGE(VT));
4996 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4997 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4998 SrcPtrInfo.getWithOffset(SrcOff), VT,
4999 MinAlign(SrcAlign, SrcOff), MMOFlags);
5000 OutChains.push_back(Value.getValue(1));
5001 Store = DAG.getTruncStore(
5002 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5003 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5005 OutChains.push_back(Store);
5011 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5014 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5015 SDValue Chain, SDValue Dst, SDValue Src,
5016 uint64_t Size, unsigned Align,
5017 bool isVol, bool AlwaysInline,
5018 MachinePointerInfo DstPtrInfo,
5019 MachinePointerInfo SrcPtrInfo) {
5020 // Turn a memmove of undef to nop.
5024 // Expand memmove to a series of load and store ops if the size operand falls
5025 // below a certain threshold.
5026 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5027 std::vector<EVT> MemOps;
5028 bool DstAlignCanChange = false;
5029 MachineFunction &MF = DAG.getMachineFunction();
5030 MachineFrameInfo &MFI = MF.getFrameInfo();
5031 bool OptSize = shouldLowerMemFuncForSize(MF);
5032 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5033 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5034 DstAlignCanChange = true;
5035 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5036 if (Align > SrcAlign)
5038 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5040 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5041 (DstAlignCanChange ? 0 : Align), SrcAlign,
5042 false, false, false, false,
5043 DstPtrInfo.getAddrSpace(),
5044 SrcPtrInfo.getAddrSpace(),
5048 if (DstAlignCanChange) {
5049 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5050 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5051 if (NewAlign > Align) {
5052 // Give the stack frame object a larger alignment if needed.
5053 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5054 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5059 MachineMemOperand::Flags MMOFlags =
5060 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5061 uint64_t SrcOff = 0, DstOff = 0;
5062 SmallVector<SDValue, 8> LoadValues;
5063 SmallVector<SDValue, 8> LoadChains;
5064 SmallVector<SDValue, 8> OutChains;
5065 unsigned NumMemOps = MemOps.size();
5066 for (unsigned i = 0; i < NumMemOps; i++) {
5068 unsigned VTSize = VT.getSizeInBits() / 8;
5072 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5073 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags);
5074 LoadValues.push_back(Value);
5075 LoadChains.push_back(Value.getValue(1));
5078 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5080 for (unsigned i = 0; i < NumMemOps; i++) {
5082 unsigned VTSize = VT.getSizeInBits() / 8;
5085 Store = DAG.getStore(Chain, dl, LoadValues[i],
5086 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5087 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5088 OutChains.push_back(Store);
5092 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5095 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5098 /// \param DAG Selection DAG where lowered code is placed.
5099 /// \param dl Link to corresponding IR location.
5100 /// \param Chain Control flow dependency.
5101 /// \param Dst Pointer to destination memory location.
5102 /// \param Src Value of byte to write into the memory.
5103 /// \param Size Number of bytes to write.
5104 /// \param Align Alignment of the destination in bytes.
5105 /// \param isVol True if destination is volatile.
5106 /// \param DstPtrInfo IR information on the memory pointer.
5107 /// \returns New head in the control flow, if lowering was successful, empty
5108 /// SDValue otherwise.
5110 /// The function tries to replace 'llvm.memset' intrinsic with several store
5111 /// operations and value calculation code. This is usually profitable for small
5113 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5114 SDValue Chain, SDValue Dst, SDValue Src,
5115 uint64_t Size, unsigned Align, bool isVol,
5116 MachinePointerInfo DstPtrInfo) {
5117 // Turn a memset of undef to nop.
5121 // Expand memset to a series of load/store ops if the size operand
5122 // falls below a certain threshold.
5123 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5124 std::vector<EVT> MemOps;
5125 bool DstAlignCanChange = false;
5126 MachineFunction &MF = DAG.getMachineFunction();
5127 MachineFrameInfo &MFI = MF.getFrameInfo();
5128 bool OptSize = shouldLowerMemFuncForSize(MF);
5129 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5130 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5131 DstAlignCanChange = true;
5133 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5134 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5135 Size, (DstAlignCanChange ? 0 : Align), 0,
5136 true, IsZeroVal, false, true,
5137 DstPtrInfo.getAddrSpace(), ~0u,
5141 if (DstAlignCanChange) {
5142 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5143 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5144 if (NewAlign > Align) {
5145 // Give the stack frame object a larger alignment if needed.
5146 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5147 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5152 SmallVector<SDValue, 8> OutChains;
5153 uint64_t DstOff = 0;
5154 unsigned NumMemOps = MemOps.size();
5156 // Find the largest store and generate the bit pattern for it.
5157 EVT LargestVT = MemOps[0];
5158 for (unsigned i = 1; i < NumMemOps; i++)
5159 if (MemOps[i].bitsGT(LargestVT))
5160 LargestVT = MemOps[i];
5161 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5163 for (unsigned i = 0; i < NumMemOps; i++) {
5165 unsigned VTSize = VT.getSizeInBits() / 8;
5166 if (VTSize > Size) {
5167 // Issuing an unaligned load / store pair that overlaps with the previous
5168 // pair. Adjust the offset accordingly.
5169 assert(i == NumMemOps-1 && i != 0);
5170 DstOff -= VTSize - Size;
5173 // If this store is smaller than the largest store see whether we can get
5174 // the smaller value for free with a truncate.
5175 SDValue Value = MemSetValue;
5176 if (VT.bitsLT(LargestVT)) {
5177 if (!LargestVT.isVector() && !VT.isVector() &&
5178 TLI.isTruncateFree(LargestVT, VT))
5179 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5181 Value = getMemsetValue(Src, VT, DAG, dl);
5183 assert(Value.getValueType() == VT && "Value with wrong type.");
5184 SDValue Store = DAG.getStore(
5185 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5186 DstPtrInfo.getWithOffset(DstOff), Align,
5187 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5188 OutChains.push_back(Store);
5189 DstOff += VT.getSizeInBits() / 8;
5193 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5196 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5198 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5199 // pointer operands can be losslessly bitcasted to pointers of address space 0
5200 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5201 report_fatal_error("cannot lower memory intrinsic in address space " +
5206 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5207 SDValue Src, SDValue Size, unsigned Align,
5208 bool isVol, bool AlwaysInline, bool isTailCall,
5209 MachinePointerInfo DstPtrInfo,
5210 MachinePointerInfo SrcPtrInfo) {
5211 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5213 // Check to see if we should lower the memcpy to loads and stores first.
5214 // For cases within the target-specified limits, this is the best choice.
5215 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5217 // Memcpy with size zero? Just return the original chain.
5218 if (ConstantSize->isNullValue())
5221 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5222 ConstantSize->getZExtValue(),Align,
5223 isVol, false, DstPtrInfo, SrcPtrInfo);
5224 if (Result.getNode())
5228 // Then check to see if we should lower the memcpy with target-specific
5229 // code. If the target chooses to do this, this is the next best.
5231 SDValue Result = TSI->EmitTargetCodeForMemcpy(
5232 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5233 DstPtrInfo, SrcPtrInfo);
5234 if (Result.getNode())
5238 // If we really need inline code and the target declined to provide it,
5239 // use a (potentially long) sequence of loads and stores.
5241 assert(ConstantSize && "AlwaysInline requires a constant size!");
5242 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5243 ConstantSize->getZExtValue(), Align, isVol,
5244 true, DstPtrInfo, SrcPtrInfo);
5247 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5248 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5250 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5251 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5252 // respect volatile, so they may do things like read or write memory
5253 // beyond the given memory regions. But fixing this isn't easy, and most
5254 // people don't care.
5256 // Emit a library call.
5257 TargetLowering::ArgListTy Args;
5258 TargetLowering::ArgListEntry Entry;
5259 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5260 Entry.Node = Dst; Args.push_back(Entry);
5261 Entry.Node = Src; Args.push_back(Entry);
5262 Entry.Node = Size; Args.push_back(Entry);
5263 // FIXME: pass in SDLoc
5264 TargetLowering::CallLoweringInfo CLI(*this);
5267 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5268 Dst.getValueType().getTypeForEVT(*getContext()),
5269 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5270 TLI->getPointerTy(getDataLayout())),
5273 .setTailCall(isTailCall);
5275 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5276 return CallResult.second;
5279 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5280 SDValue Src, SDValue Size, unsigned Align,
5281 bool isVol, bool isTailCall,
5282 MachinePointerInfo DstPtrInfo,
5283 MachinePointerInfo SrcPtrInfo) {
5284 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5286 // Check to see if we should lower the memmove to loads and stores first.
5287 // For cases within the target-specified limits, this is the best choice.
5288 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5290 // Memmove with size zero? Just return the original chain.
5291 if (ConstantSize->isNullValue())
5295 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5296 ConstantSize->getZExtValue(), Align, isVol,
5297 false, DstPtrInfo, SrcPtrInfo);
5298 if (Result.getNode())
5302 // Then check to see if we should lower the memmove with target-specific
5303 // code. If the target chooses to do this, this is the next best.
5305 SDValue Result = TSI->EmitTargetCodeForMemmove(
5306 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5307 if (Result.getNode())
5311 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5312 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5314 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5315 // not be safe. See memcpy above for more details.
5317 // Emit a library call.
5318 TargetLowering::ArgListTy Args;
5319 TargetLowering::ArgListEntry Entry;
5320 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5321 Entry.Node = Dst; Args.push_back(Entry);
5322 Entry.Node = Src; Args.push_back(Entry);
5323 Entry.Node = Size; Args.push_back(Entry);
5324 // FIXME: pass in SDLoc
5325 TargetLowering::CallLoweringInfo CLI(*this);
5328 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5329 Dst.getValueType().getTypeForEVT(*getContext()),
5330 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5331 TLI->getPointerTy(getDataLayout())),
5334 .setTailCall(isTailCall);
5336 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5337 return CallResult.second;
5340 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5341 SDValue Src, SDValue Size, unsigned Align,
5342 bool isVol, bool isTailCall,
5343 MachinePointerInfo DstPtrInfo) {
5344 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5346 // Check to see if we should lower the memset to stores first.
5347 // For cases within the target-specified limits, this is the best choice.
5348 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5350 // Memset with size zero? Just return the original chain.
5351 if (ConstantSize->isNullValue())
5355 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5356 Align, isVol, DstPtrInfo);
5358 if (Result.getNode())
5362 // Then check to see if we should lower the memset with target-specific
5363 // code. If the target chooses to do this, this is the next best.
5365 SDValue Result = TSI->EmitTargetCodeForMemset(
5366 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5367 if (Result.getNode())
5371 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5373 // Emit a library call.
5374 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5375 TargetLowering::ArgListTy Args;
5376 TargetLowering::ArgListEntry Entry;
5377 Entry.Node = Dst; Entry.Ty = IntPtrTy;
5378 Args.push_back(Entry);
5380 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5381 Args.push_back(Entry);
5383 Entry.Ty = IntPtrTy;
5384 Args.push_back(Entry);
5386 // FIXME: pass in SDLoc
5387 TargetLowering::CallLoweringInfo CLI(*this);
5390 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5391 Dst.getValueType().getTypeForEVT(*getContext()),
5392 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5393 TLI->getPointerTy(getDataLayout())),
5396 .setTailCall(isTailCall);
5398 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5399 return CallResult.second;
5402 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5403 SDVTList VTList, ArrayRef<SDValue> Ops,
5404 MachineMemOperand *MMO) {
5405 FoldingSetNodeID ID;
5406 ID.AddInteger(MemVT.getRawBits());
5407 AddNodeIDNode(ID, Opcode, VTList, Ops);
5408 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5410 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5411 cast<AtomicSDNode>(E)->refineAlignment(MMO);
5412 return SDValue(E, 0);
5415 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5416 VTList, MemVT, MMO);
5417 createOperands(N, Ops);
5419 CSEMap.InsertNode(N, IP);
5421 return SDValue(N, 0);
5424 SDValue SelectionDAG::getAtomicCmpSwap(
5425 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5426 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5427 unsigned Alignment, AtomicOrdering SuccessOrdering,
5428 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
5429 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5430 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5431 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5433 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5434 Alignment = getEVTAlignment(MemVT);
5436 MachineFunction &MF = getMachineFunction();
5438 // FIXME: Volatile isn't really correct; we should keep track of atomic
5439 // orderings in the memoperand.
5440 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5441 MachineMemOperand::MOStore;
5442 MachineMemOperand *MMO =
5443 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5444 AAMDNodes(), nullptr, SynchScope, SuccessOrdering,
5447 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5450 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5451 EVT MemVT, SDVTList VTs, SDValue Chain,
5452 SDValue Ptr, SDValue Cmp, SDValue Swp,
5453 MachineMemOperand *MMO) {
5454 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5455 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5456 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5458 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5459 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5462 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5463 SDValue Chain, SDValue Ptr, SDValue Val,
5464 const Value *PtrVal, unsigned Alignment,
5465 AtomicOrdering Ordering,
5466 SynchronizationScope SynchScope) {
5467 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5468 Alignment = getEVTAlignment(MemVT);
5470 MachineFunction &MF = getMachineFunction();
5471 // An atomic store does not load. An atomic load does not store.
5472 // (An atomicrmw obviously both loads and stores.)
5473 // For now, atomics are considered to be volatile always, and they are
5475 // FIXME: Volatile isn't really correct; we should keep track of atomic
5476 // orderings in the memoperand.
5477 auto Flags = MachineMemOperand::MOVolatile;
5478 if (Opcode != ISD::ATOMIC_STORE)
5479 Flags |= MachineMemOperand::MOLoad;
5480 if (Opcode != ISD::ATOMIC_LOAD)
5481 Flags |= MachineMemOperand::MOStore;
5483 MachineMemOperand *MMO =
5484 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5485 MemVT.getStoreSize(), Alignment, AAMDNodes(),
5486 nullptr, SynchScope, Ordering);
5488 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5491 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5492 SDValue Chain, SDValue Ptr, SDValue Val,
5493 MachineMemOperand *MMO) {
5494 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5495 Opcode == ISD::ATOMIC_LOAD_SUB ||
5496 Opcode == ISD::ATOMIC_LOAD_AND ||
5497 Opcode == ISD::ATOMIC_LOAD_OR ||
5498 Opcode == ISD::ATOMIC_LOAD_XOR ||
5499 Opcode == ISD::ATOMIC_LOAD_NAND ||
5500 Opcode == ISD::ATOMIC_LOAD_MIN ||
5501 Opcode == ISD::ATOMIC_LOAD_MAX ||
5502 Opcode == ISD::ATOMIC_LOAD_UMIN ||
5503 Opcode == ISD::ATOMIC_LOAD_UMAX ||
5504 Opcode == ISD::ATOMIC_SWAP ||
5505 Opcode == ISD::ATOMIC_STORE) &&
5506 "Invalid Atomic Op");
5508 EVT VT = Val.getValueType();
5510 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5511 getVTList(VT, MVT::Other);
5512 SDValue Ops[] = {Chain, Ptr, Val};
5513 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5516 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5517 EVT VT, SDValue Chain, SDValue Ptr,
5518 MachineMemOperand *MMO) {
5519 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5521 SDVTList VTs = getVTList(VT, MVT::Other);
5522 SDValue Ops[] = {Chain, Ptr};
5523 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5526 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5527 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5528 if (Ops.size() == 1)
5531 SmallVector<EVT, 4> VTs;
5532 VTs.reserve(Ops.size());
5533 for (unsigned i = 0; i < Ops.size(); ++i)
5534 VTs.push_back(Ops[i].getValueType());
5535 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5538 SDValue SelectionDAG::getMemIntrinsicNode(
5539 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5540 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5541 bool ReadMem, bool WriteMem, unsigned Size) {
5542 if (Align == 0) // Ensure that codegen never sees alignment 0
5543 Align = getEVTAlignment(MemVT);
5545 MachineFunction &MF = getMachineFunction();
5546 auto Flags = MachineMemOperand::MONone;
5548 Flags |= MachineMemOperand::MOStore;
5550 Flags |= MachineMemOperand::MOLoad;
5552 Flags |= MachineMemOperand::MOVolatile;
5554 Size = MemVT.getStoreSize();
5555 MachineMemOperand *MMO =
5556 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5558 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5561 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5563 ArrayRef<SDValue> Ops, EVT MemVT,
5564 MachineMemOperand *MMO) {
5565 assert((Opcode == ISD::INTRINSIC_VOID ||
5566 Opcode == ISD::INTRINSIC_W_CHAIN ||
5567 Opcode == ISD::PREFETCH ||
5568 Opcode == ISD::LIFETIME_START ||
5569 Opcode == ISD::LIFETIME_END ||
5570 ((int)Opcode <= std::numeric_limits<int>::max() &&
5571 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5572 "Opcode is not a memory-accessing opcode!");
5574 // Memoize the node unless it returns a flag.
5575 MemIntrinsicSDNode *N;
5576 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5577 FoldingSetNodeID ID;
5578 AddNodeIDNode(ID, Opcode, VTList, Ops);
5579 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5581 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5582 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5583 return SDValue(E, 0);
5586 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5587 VTList, MemVT, MMO);
5588 createOperands(N, Ops);
5590 CSEMap.InsertNode(N, IP);
5592 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5593 VTList, MemVT, MMO);
5594 createOperands(N, Ops);
5597 return SDValue(N, 0);
5600 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5601 /// MachinePointerInfo record from it. This is particularly useful because the
5602 /// code generator has many cases where it doesn't bother passing in a
5603 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5604 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5605 int64_t Offset = 0) {
5606 // If this is FI+Offset, we can model it.
5607 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5608 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5609 FI->getIndex(), Offset);
5611 // If this is (FI+Offset1)+Offset2, we can model it.
5612 if (Ptr.getOpcode() != ISD::ADD ||
5613 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5614 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5615 return MachinePointerInfo();
5617 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5618 return MachinePointerInfo::getFixedStack(
5619 DAG.getMachineFunction(), FI,
5620 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5623 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5624 /// MachinePointerInfo record from it. This is particularly useful because the
5625 /// code generator has many cases where it doesn't bother passing in a
5626 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5627 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5629 // If the 'Offset' value isn't a constant, we can't handle this.
5630 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5631 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5632 if (OffsetOp.isUndef())
5633 return InferPointerInfo(DAG, Ptr);
5634 return MachinePointerInfo();
5637 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5638 EVT VT, const SDLoc &dl, SDValue Chain,
5639 SDValue Ptr, SDValue Offset,
5640 MachinePointerInfo PtrInfo, EVT MemVT,
5642 MachineMemOperand::Flags MMOFlags,
5643 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5644 assert(Chain.getValueType() == MVT::Other &&
5645 "Invalid chain type");
5646 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5647 Alignment = getEVTAlignment(MemVT);
5649 MMOFlags |= MachineMemOperand::MOLoad;
5650 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5651 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5653 if (PtrInfo.V.isNull())
5654 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5656 MachineFunction &MF = getMachineFunction();
5657 MachineMemOperand *MMO = MF.getMachineMemOperand(
5658 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5659 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5662 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5663 EVT VT, const SDLoc &dl, SDValue Chain,
5664 SDValue Ptr, SDValue Offset, EVT MemVT,
5665 MachineMemOperand *MMO) {
5667 ExtType = ISD::NON_EXTLOAD;
5668 } else if (ExtType == ISD::NON_EXTLOAD) {
5669 assert(VT == MemVT && "Non-extending load from different memory type!");
5672 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5673 "Should only be an extending load, not truncating!");
5674 assert(VT.isInteger() == MemVT.isInteger() &&
5675 "Cannot convert from FP to Int or Int -> FP!");
5676 assert(VT.isVector() == MemVT.isVector() &&
5677 "Cannot use an ext load to convert to or from a vector!");
5678 assert((!VT.isVector() ||
5679 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5680 "Cannot use an ext load to change the number of vector elements!");
5683 bool Indexed = AM != ISD::UNINDEXED;
5684 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5686 SDVTList VTs = Indexed ?
5687 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5688 SDValue Ops[] = { Chain, Ptr, Offset };
5689 FoldingSetNodeID ID;
5690 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5691 ID.AddInteger(MemVT.getRawBits());
5692 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5693 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5694 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5696 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5697 cast<LoadSDNode>(E)->refineAlignment(MMO);
5698 return SDValue(E, 0);
5700 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5701 ExtType, MemVT, MMO);
5702 createOperands(N, Ops);
5704 CSEMap.InsertNode(N, IP);
5706 return SDValue(N, 0);
5709 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5710 SDValue Ptr, MachinePointerInfo PtrInfo,
5712 MachineMemOperand::Flags MMOFlags,
5713 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5714 SDValue Undef = getUNDEF(Ptr.getValueType());
5715 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5716 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5719 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5720 SDValue Ptr, MachineMemOperand *MMO) {
5721 SDValue Undef = getUNDEF(Ptr.getValueType());
5722 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5726 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5727 EVT VT, SDValue Chain, SDValue Ptr,
5728 MachinePointerInfo PtrInfo, EVT MemVT,
5730 MachineMemOperand::Flags MMOFlags,
5731 const AAMDNodes &AAInfo) {
5732 SDValue Undef = getUNDEF(Ptr.getValueType());
5733 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5734 MemVT, Alignment, MMOFlags, AAInfo);
5737 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5738 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5739 MachineMemOperand *MMO) {
5740 SDValue Undef = getUNDEF(Ptr.getValueType());
5741 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5745 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5746 SDValue Base, SDValue Offset,
5747 ISD::MemIndexedMode AM) {
5748 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5749 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5750 // Don't propagate the invariant or dereferenceable flags.
5752 LD->getMemOperand()->getFlags() &
5753 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5754 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5755 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5756 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5760 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5761 SDValue Ptr, MachinePointerInfo PtrInfo,
5763 MachineMemOperand::Flags MMOFlags,
5764 const AAMDNodes &AAInfo) {
5765 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5766 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5767 Alignment = getEVTAlignment(Val.getValueType());
5769 MMOFlags |= MachineMemOperand::MOStore;
5770 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5772 if (PtrInfo.V.isNull())
5773 PtrInfo = InferPointerInfo(*this, Ptr);
5775 MachineFunction &MF = getMachineFunction();
5776 MachineMemOperand *MMO = MF.getMachineMemOperand(
5777 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5778 return getStore(Chain, dl, Val, Ptr, MMO);
5781 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5782 SDValue Ptr, MachineMemOperand *MMO) {
5783 assert(Chain.getValueType() == MVT::Other &&
5784 "Invalid chain type");
5785 EVT VT = Val.getValueType();
5786 SDVTList VTs = getVTList(MVT::Other);
5787 SDValue Undef = getUNDEF(Ptr.getValueType());
5788 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5789 FoldingSetNodeID ID;
5790 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5791 ID.AddInteger(VT.getRawBits());
5792 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5793 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5794 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5796 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5797 cast<StoreSDNode>(E)->refineAlignment(MMO);
5798 return SDValue(E, 0);
5800 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5801 ISD::UNINDEXED, false, VT, MMO);
5802 createOperands(N, Ops);
5804 CSEMap.InsertNode(N, IP);
5806 return SDValue(N, 0);
5809 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5810 SDValue Ptr, MachinePointerInfo PtrInfo,
5811 EVT SVT, unsigned Alignment,
5812 MachineMemOperand::Flags MMOFlags,
5813 const AAMDNodes &AAInfo) {
5814 assert(Chain.getValueType() == MVT::Other &&
5815 "Invalid chain type");
5816 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5817 Alignment = getEVTAlignment(SVT);
5819 MMOFlags |= MachineMemOperand::MOStore;
5820 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5822 if (PtrInfo.V.isNull())
5823 PtrInfo = InferPointerInfo(*this, Ptr);
5825 MachineFunction &MF = getMachineFunction();
5826 MachineMemOperand *MMO = MF.getMachineMemOperand(
5827 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5828 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5831 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5832 SDValue Ptr, EVT SVT,
5833 MachineMemOperand *MMO) {
5834 EVT VT = Val.getValueType();
5836 assert(Chain.getValueType() == MVT::Other &&
5837 "Invalid chain type");
5839 return getStore(Chain, dl, Val, Ptr, MMO);
5841 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5842 "Should only be a truncating store, not extending!");
5843 assert(VT.isInteger() == SVT.isInteger() &&
5844 "Can't do FP-INT conversion!");
5845 assert(VT.isVector() == SVT.isVector() &&
5846 "Cannot use trunc store to convert to or from a vector!");
5847 assert((!VT.isVector() ||
5848 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5849 "Cannot use trunc store to change the number of vector elements!");
5851 SDVTList VTs = getVTList(MVT::Other);
5852 SDValue Undef = getUNDEF(Ptr.getValueType());
5853 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5854 FoldingSetNodeID ID;
5855 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5856 ID.AddInteger(SVT.getRawBits());
5857 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5858 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5859 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5861 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5862 cast<StoreSDNode>(E)->refineAlignment(MMO);
5863 return SDValue(E, 0);
5865 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5866 ISD::UNINDEXED, true, SVT, MMO);
5867 createOperands(N, Ops);
5869 CSEMap.InsertNode(N, IP);
5871 return SDValue(N, 0);
5874 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5875 SDValue Base, SDValue Offset,
5876 ISD::MemIndexedMode AM) {
5877 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5878 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5879 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5880 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5881 FoldingSetNodeID ID;
5882 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5883 ID.AddInteger(ST->getMemoryVT().getRawBits());
5884 ID.AddInteger(ST->getRawSubclassData());
5885 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5887 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5888 return SDValue(E, 0);
5890 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5891 ST->isTruncatingStore(), ST->getMemoryVT(),
5892 ST->getMemOperand());
5893 createOperands(N, Ops);
5895 CSEMap.InsertNode(N, IP);
5897 return SDValue(N, 0);
5900 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5901 SDValue Ptr, SDValue Mask, SDValue Src0,
5902 EVT MemVT, MachineMemOperand *MMO,
5903 ISD::LoadExtType ExtTy, bool isExpanding) {
5904 SDVTList VTs = getVTList(VT, MVT::Other);
5905 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5906 FoldingSetNodeID ID;
5907 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5908 ID.AddInteger(VT.getRawBits());
5909 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5910 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5911 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5913 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5914 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5915 return SDValue(E, 0);
5917 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5918 ExtTy, isExpanding, MemVT, MMO);
5919 createOperands(N, Ops);
5921 CSEMap.InsertNode(N, IP);
5923 return SDValue(N, 0);
5926 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5927 SDValue Val, SDValue Ptr, SDValue Mask,
5928 EVT MemVT, MachineMemOperand *MMO,
5929 bool IsTruncating, bool IsCompressing) {
5930 assert(Chain.getValueType() == MVT::Other &&
5931 "Invalid chain type");
5932 EVT VT = Val.getValueType();
5933 SDVTList VTs = getVTList(MVT::Other);
5934 SDValue Ops[] = { Chain, Ptr, Mask, Val };
5935 FoldingSetNodeID ID;
5936 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5937 ID.AddInteger(VT.getRawBits());
5938 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5939 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5940 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5942 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5943 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5944 return SDValue(E, 0);
5946 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5947 IsTruncating, IsCompressing, MemVT, MMO);
5948 createOperands(N, Ops);
5950 CSEMap.InsertNode(N, IP);
5952 return SDValue(N, 0);
5955 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5956 ArrayRef<SDValue> Ops,
5957 MachineMemOperand *MMO) {
5958 assert(Ops.size() == 5 && "Incompatible number of operands");
5960 FoldingSetNodeID ID;
5961 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5962 ID.AddInteger(VT.getRawBits());
5963 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5964 dl.getIROrder(), VTs, VT, MMO));
5965 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5967 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5968 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5969 return SDValue(E, 0);
5972 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5974 createOperands(N, Ops);
5976 assert(N->getValue().getValueType() == N->getValueType(0) &&
5977 "Incompatible type of the PassThru value in MaskedGatherSDNode");
5978 assert(N->getMask().getValueType().getVectorNumElements() ==
5979 N->getValueType(0).getVectorNumElements() &&
5980 "Vector width mismatch between mask and data");
5981 assert(N->getIndex().getValueType().getVectorNumElements() ==
5982 N->getValueType(0).getVectorNumElements() &&
5983 "Vector width mismatch between index and data");
5985 CSEMap.InsertNode(N, IP);
5987 return SDValue(N, 0);
5990 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
5991 ArrayRef<SDValue> Ops,
5992 MachineMemOperand *MMO) {
5993 assert(Ops.size() == 5 && "Incompatible number of operands");
5995 FoldingSetNodeID ID;
5996 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5997 ID.AddInteger(VT.getRawBits());
5998 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
5999 dl.getIROrder(), VTs, VT, MMO));
6000 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6002 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6003 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
6004 return SDValue(E, 0);
6006 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6008 createOperands(N, Ops);
6010 assert(N->getMask().getValueType().getVectorNumElements() ==
6011 N->getValue().getValueType().getVectorNumElements() &&
6012 "Vector width mismatch between mask and data");
6013 assert(N->getIndex().getValueType().getVectorNumElements() ==
6014 N->getValue().getValueType().getVectorNumElements() &&
6015 "Vector width mismatch between index and data");
6017 CSEMap.InsertNode(N, IP);
6019 return SDValue(N, 0);
6022 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
6023 SDValue Ptr, SDValue SV, unsigned Align) {
6024 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
6025 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
6028 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6029 ArrayRef<SDUse> Ops) {
6030 switch (Ops.size()) {
6031 case 0: return getNode(Opcode, DL, VT);
6032 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
6033 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
6034 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6038 // Copy from an SDUse array into an SDValue array for use with
6039 // the regular getNode logic.
6040 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
6041 return getNode(Opcode, DL, VT, NewOps);
6044 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6045 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
6046 unsigned NumOps = Ops.size();
6048 case 0: return getNode(Opcode, DL, VT);
6049 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
6050 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
6051 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6057 case ISD::CONCAT_VECTORS:
6058 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
6059 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
6062 case ISD::SELECT_CC:
6063 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6064 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6065 "LHS and RHS of condition must have same type!");
6066 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6067 "True and False arms of SelectCC must have same type!");
6068 assert(Ops[2].getValueType() == VT &&
6069 "select_cc node must be of same type as true and false value!");
6072 assert(NumOps == 5 && "BR_CC takes 5 operands!");
6073 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6074 "LHS/RHS of comparison should match types!");
6080 SDVTList VTs = getVTList(VT);
6082 if (VT != MVT::Glue) {
6083 FoldingSetNodeID ID;
6084 AddNodeIDNode(ID, Opcode, VTs, Ops);
6087 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6088 return SDValue(E, 0);
6090 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6091 createOperands(N, Ops);
6093 CSEMap.InsertNode(N, IP);
6095 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6096 createOperands(N, Ops);
6100 return SDValue(N, 0);
6103 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6104 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6105 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6108 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6109 ArrayRef<SDValue> Ops) {
6110 if (VTList.NumVTs == 1)
6111 return getNode(Opcode, DL, VTList.VTs[0], Ops);
6115 // FIXME: figure out how to safely handle things like
6116 // int foo(int x) { return 1 << (x & 255); }
6117 // int bar() { return foo(256); }
6118 case ISD::SRA_PARTS:
6119 case ISD::SRL_PARTS:
6120 case ISD::SHL_PARTS:
6121 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6122 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6123 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6124 else if (N3.getOpcode() == ISD::AND)
6125 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6126 // If the and is only masking out bits that cannot effect the shift,
6127 // eliminate the and.
6128 unsigned NumBits = VT.getScalarSizeInBits()*2;
6129 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6130 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6136 // Memoize the node unless it returns a flag.
6138 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6139 FoldingSetNodeID ID;
6140 AddNodeIDNode(ID, Opcode, VTList, Ops);
6142 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6143 return SDValue(E, 0);
6145 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6146 createOperands(N, Ops);
6147 CSEMap.InsertNode(N, IP);
6149 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6150 createOperands(N, Ops);
6153 return SDValue(N, 0);
6156 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6158 return getNode(Opcode, DL, VTList, None);
6161 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6163 SDValue Ops[] = { N1 };
6164 return getNode(Opcode, DL, VTList, Ops);
6167 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6168 SDValue N1, SDValue N2) {
6169 SDValue Ops[] = { N1, N2 };
6170 return getNode(Opcode, DL, VTList, Ops);
6173 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6174 SDValue N1, SDValue N2, SDValue N3) {
6175 SDValue Ops[] = { N1, N2, N3 };
6176 return getNode(Opcode, DL, VTList, Ops);
6179 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6180 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6181 SDValue Ops[] = { N1, N2, N3, N4 };
6182 return getNode(Opcode, DL, VTList, Ops);
6185 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6186 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6188 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6189 return getNode(Opcode, DL, VTList, Ops);
6192 SDVTList SelectionDAG::getVTList(EVT VT) {
6193 return makeVTList(SDNode::getValueTypeList(VT), 1);
6196 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6197 FoldingSetNodeID ID;
6199 ID.AddInteger(VT1.getRawBits());
6200 ID.AddInteger(VT2.getRawBits());
6203 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6205 EVT *Array = Allocator.Allocate<EVT>(2);
6208 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6209 VTListMap.InsertNode(Result, IP);
6211 return Result->getSDVTList();
6214 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6215 FoldingSetNodeID ID;
6217 ID.AddInteger(VT1.getRawBits());
6218 ID.AddInteger(VT2.getRawBits());
6219 ID.AddInteger(VT3.getRawBits());
6222 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6224 EVT *Array = Allocator.Allocate<EVT>(3);
6228 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6229 VTListMap.InsertNode(Result, IP);
6231 return Result->getSDVTList();
6234 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6235 FoldingSetNodeID ID;
6237 ID.AddInteger(VT1.getRawBits());
6238 ID.AddInteger(VT2.getRawBits());
6239 ID.AddInteger(VT3.getRawBits());
6240 ID.AddInteger(VT4.getRawBits());
6243 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6245 EVT *Array = Allocator.Allocate<EVT>(4);
6250 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6251 VTListMap.InsertNode(Result, IP);
6253 return Result->getSDVTList();
6256 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6257 unsigned NumVTs = VTs.size();
6258 FoldingSetNodeID ID;
6259 ID.AddInteger(NumVTs);
6260 for (unsigned index = 0; index < NumVTs; index++) {
6261 ID.AddInteger(VTs[index].getRawBits());
6265 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6267 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6268 std::copy(VTs.begin(), VTs.end(), Array);
6269 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6270 VTListMap.InsertNode(Result, IP);
6272 return Result->getSDVTList();
6276 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6277 /// specified operands. If the resultant node already exists in the DAG,
6278 /// this does not modify the specified node, instead it returns the node that
6279 /// already exists. If the resultant node does not exist in the DAG, the
6280 /// input node is returned. As a degenerate case, if you specify the same
6281 /// input operands as the node already has, the input node is returned.
6282 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6283 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6285 // Check to see if there is no change.
6286 if (Op == N->getOperand(0)) return N;
6288 // See if the modified node already exists.
6289 void *InsertPos = nullptr;
6290 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6293 // Nope it doesn't. Remove the node from its current place in the maps.
6295 if (!RemoveNodeFromCSEMaps(N))
6296 InsertPos = nullptr;
6298 // Now we update the operands.
6299 N->OperandList[0].set(Op);
6301 // If this gets put into a CSE map, add it.
6302 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6306 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6307 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6309 // Check to see if there is no change.
6310 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6311 return N; // No operands changed, just return the input node.
6313 // See if the modified node already exists.
6314 void *InsertPos = nullptr;
6315 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6318 // Nope it doesn't. Remove the node from its current place in the maps.
6320 if (!RemoveNodeFromCSEMaps(N))
6321 InsertPos = nullptr;
6323 // Now we update the operands.
6324 if (N->OperandList[0] != Op1)
6325 N->OperandList[0].set(Op1);
6326 if (N->OperandList[1] != Op2)
6327 N->OperandList[1].set(Op2);
6329 // If this gets put into a CSE map, add it.
6330 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6334 SDNode *SelectionDAG::
6335 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6336 SDValue Ops[] = { Op1, Op2, Op3 };
6337 return UpdateNodeOperands(N, Ops);
6340 SDNode *SelectionDAG::
6341 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6342 SDValue Op3, SDValue Op4) {
6343 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6344 return UpdateNodeOperands(N, Ops);
6347 SDNode *SelectionDAG::
6348 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6349 SDValue Op3, SDValue Op4, SDValue Op5) {
6350 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6351 return UpdateNodeOperands(N, Ops);
6354 SDNode *SelectionDAG::
6355 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6356 unsigned NumOps = Ops.size();
6357 assert(N->getNumOperands() == NumOps &&
6358 "Update with wrong number of operands");
6360 // If no operands changed just return the input node.
6361 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6364 // See if the modified node already exists.
6365 void *InsertPos = nullptr;
6366 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6369 // Nope it doesn't. Remove the node from its current place in the maps.
6371 if (!RemoveNodeFromCSEMaps(N))
6372 InsertPos = nullptr;
6374 // Now we update the operands.
6375 for (unsigned i = 0; i != NumOps; ++i)
6376 if (N->OperandList[i] != Ops[i])
6377 N->OperandList[i].set(Ops[i]);
6379 // If this gets put into a CSE map, add it.
6380 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6384 /// DropOperands - Release the operands and set this node to have
6386 void SDNode::DropOperands() {
6387 // Unlike the code in MorphNodeTo that does this, we don't need to
6388 // watch for dead nodes here.
6389 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6395 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6398 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6400 SDVTList VTs = getVTList(VT);
6401 return SelectNodeTo(N, MachineOpc, VTs, None);
6404 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6405 EVT VT, SDValue Op1) {
6406 SDVTList VTs = getVTList(VT);
6407 SDValue Ops[] = { Op1 };
6408 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6411 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6412 EVT VT, SDValue Op1,
6414 SDVTList VTs = getVTList(VT);
6415 SDValue Ops[] = { Op1, Op2 };
6416 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6419 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6420 EVT VT, SDValue Op1,
6421 SDValue Op2, SDValue Op3) {
6422 SDVTList VTs = getVTList(VT);
6423 SDValue Ops[] = { Op1, Op2, Op3 };
6424 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6427 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6428 EVT VT, ArrayRef<SDValue> Ops) {
6429 SDVTList VTs = getVTList(VT);
6430 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6433 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6434 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6435 SDVTList VTs = getVTList(VT1, VT2);
6436 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6439 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6441 SDVTList VTs = getVTList(VT1, VT2);
6442 return SelectNodeTo(N, MachineOpc, VTs, None);
6445 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6446 EVT VT1, EVT VT2, EVT VT3,
6447 ArrayRef<SDValue> Ops) {
6448 SDVTList VTs = getVTList(VT1, VT2, VT3);
6449 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6452 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6454 SDValue Op1, SDValue Op2) {
6455 SDVTList VTs = getVTList(VT1, VT2);
6456 SDValue Ops[] = { Op1, Op2 };
6457 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6460 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6461 SDVTList VTs,ArrayRef<SDValue> Ops) {
6462 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6463 // Reset the NodeID to -1.
6466 ReplaceAllUsesWith(N, New);
6472 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6473 /// the line number information on the merged node since it is not possible to
6474 /// preserve the information that operation is associated with multiple lines.
6475 /// This will make the debugger working better at -O0, were there is a higher
6476 /// probability having other instructions associated with that line.
6478 /// For IROrder, we keep the smaller of the two
6479 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6480 DebugLoc NLoc = N->getDebugLoc();
6481 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6482 N->setDebugLoc(DebugLoc());
6484 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6485 N->setIROrder(Order);
6489 /// MorphNodeTo - This *mutates* the specified node to have the specified
6490 /// return type, opcode, and operands.
6492 /// Note that MorphNodeTo returns the resultant node. If there is already a
6493 /// node of the specified opcode and operands, it returns that node instead of
6494 /// the current one. Note that the SDLoc need not be the same.
6496 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6497 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6498 /// node, and because it doesn't require CSE recalculation for any of
6499 /// the node's users.
6501 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6502 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6503 /// the legalizer which maintain worklists that would need to be updated when
6504 /// deleting things.
6505 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6506 SDVTList VTs, ArrayRef<SDValue> Ops) {
6507 // If an identical node already exists, use it.
6509 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6510 FoldingSetNodeID ID;
6511 AddNodeIDNode(ID, Opc, VTs, Ops);
6512 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6513 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6516 if (!RemoveNodeFromCSEMaps(N))
6519 // Start the morphing.
6521 N->ValueList = VTs.VTs;
6522 N->NumValues = VTs.NumVTs;
6524 // Clear the operands list, updating used nodes to remove this from their
6525 // use list. Keep track of any operands that become dead as a result.
6526 SmallPtrSet<SDNode*, 16> DeadNodeSet;
6527 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6529 SDNode *Used = Use.getNode();
6531 if (Used->use_empty())
6532 DeadNodeSet.insert(Used);
6535 // For MachineNode, initialize the memory references information.
6536 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6537 MN->setMemRefs(nullptr, nullptr);
6539 // Swap for an appropriately sized array from the recycler.
6541 createOperands(N, Ops);
6543 // Delete any nodes that are still dead after adding the uses for the
6545 if (!DeadNodeSet.empty()) {
6546 SmallVector<SDNode *, 16> DeadNodes;
6547 for (SDNode *N : DeadNodeSet)
6549 DeadNodes.push_back(N);
6550 RemoveDeadNodes(DeadNodes);
6554 CSEMap.InsertNode(N, IP); // Memoize the new node.
6558 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
6559 unsigned OrigOpc = Node->getOpcode();
6561 bool IsUnary = false;
6564 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
6565 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
6566 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
6567 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
6568 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
6569 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
6570 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
6571 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
6572 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
6573 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
6574 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
6575 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
6576 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
6577 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
6578 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
6579 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
6580 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
6581 case ISD::STRICT_FNEARBYINT:
6582 NewOpc = ISD::FNEARBYINT;
6587 // We're taking this node out of the chain, so we need to re-link things.
6588 SDValue InputChain = Node->getOperand(0);
6589 SDValue OutputChain = SDValue(Node, 1);
6590 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
6592 SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
6593 SDNode *Res = nullptr;
6595 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
6597 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
6598 Node->getOperand(2) });
6600 // MorphNodeTo can operate in two ways: if an existing node with the
6601 // specified operands exists, it can just return it. Otherwise, it
6602 // updates the node in place to have the requested operands.
6604 // If we updated the node in place, reset the node ID. To the isel,
6605 // this should be just like a newly allocated machine node.
6608 ReplaceAllUsesWith(Node, Res);
6609 RemoveDeadNode(Node);
6615 /// getMachineNode - These are used for target selectors to create a new node
6616 /// with specified return type(s), MachineInstr opcode, and operands.
6618 /// Note that getMachineNode returns the resultant node. If there is already a
6619 /// node of the specified opcode and operands, it returns that node instead of
6620 /// the current one.
6621 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6623 SDVTList VTs = getVTList(VT);
6624 return getMachineNode(Opcode, dl, VTs, None);
6627 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6628 EVT VT, SDValue Op1) {
6629 SDVTList VTs = getVTList(VT);
6630 SDValue Ops[] = { Op1 };
6631 return getMachineNode(Opcode, dl, VTs, Ops);
6634 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6635 EVT VT, SDValue Op1, SDValue Op2) {
6636 SDVTList VTs = getVTList(VT);
6637 SDValue Ops[] = { Op1, Op2 };
6638 return getMachineNode(Opcode, dl, VTs, Ops);
6641 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6642 EVT VT, SDValue Op1, SDValue Op2,
6644 SDVTList VTs = getVTList(VT);
6645 SDValue Ops[] = { Op1, Op2, Op3 };
6646 return getMachineNode(Opcode, dl, VTs, Ops);
6649 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6650 EVT VT, ArrayRef<SDValue> Ops) {
6651 SDVTList VTs = getVTList(VT);
6652 return getMachineNode(Opcode, dl, VTs, Ops);
6655 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6656 EVT VT1, EVT VT2, SDValue Op1,
6658 SDVTList VTs = getVTList(VT1, VT2);
6659 SDValue Ops[] = { Op1, Op2 };
6660 return getMachineNode(Opcode, dl, VTs, Ops);
6663 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6664 EVT VT1, EVT VT2, SDValue Op1,
6665 SDValue Op2, SDValue Op3) {
6666 SDVTList VTs = getVTList(VT1, VT2);
6667 SDValue Ops[] = { Op1, Op2, Op3 };
6668 return getMachineNode(Opcode, dl, VTs, Ops);
6671 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6673 ArrayRef<SDValue> Ops) {
6674 SDVTList VTs = getVTList(VT1, VT2);
6675 return getMachineNode(Opcode, dl, VTs, Ops);
6678 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6679 EVT VT1, EVT VT2, EVT VT3,
6680 SDValue Op1, SDValue Op2) {
6681 SDVTList VTs = getVTList(VT1, VT2, VT3);
6682 SDValue Ops[] = { Op1, Op2 };
6683 return getMachineNode(Opcode, dl, VTs, Ops);
6686 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6687 EVT VT1, EVT VT2, EVT VT3,
6688 SDValue Op1, SDValue Op2,
6690 SDVTList VTs = getVTList(VT1, VT2, VT3);
6691 SDValue Ops[] = { Op1, Op2, Op3 };
6692 return getMachineNode(Opcode, dl, VTs, Ops);
6695 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6696 EVT VT1, EVT VT2, EVT VT3,
6697 ArrayRef<SDValue> Ops) {
6698 SDVTList VTs = getVTList(VT1, VT2, VT3);
6699 return getMachineNode(Opcode, dl, VTs, Ops);
6702 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6703 ArrayRef<EVT> ResultTys,
6704 ArrayRef<SDValue> Ops) {
6705 SDVTList VTs = getVTList(ResultTys);
6706 return getMachineNode(Opcode, dl, VTs, Ops);
6709 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6711 ArrayRef<SDValue> Ops) {
6712 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6717 FoldingSetNodeID ID;
6718 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6720 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6721 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6725 // Allocate a new MachineSDNode.
6726 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6727 createOperands(N, Ops);
6730 CSEMap.InsertNode(N, IP);
6736 /// getTargetExtractSubreg - A convenience function for creating
6737 /// TargetOpcode::EXTRACT_SUBREG nodes.
6738 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6740 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6741 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6742 VT, Operand, SRIdxVal);
6743 return SDValue(Subreg, 0);
6746 /// getTargetInsertSubreg - A convenience function for creating
6747 /// TargetOpcode::INSERT_SUBREG nodes.
6748 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6749 SDValue Operand, SDValue Subreg) {
6750 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6751 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6752 VT, Operand, Subreg, SRIdxVal);
6753 return SDValue(Result, 0);
6756 /// getNodeIfExists - Get the specified node if it's already available, or
6757 /// else return NULL.
6758 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6759 ArrayRef<SDValue> Ops,
6760 const SDNodeFlags Flags) {
6761 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6762 FoldingSetNodeID ID;
6763 AddNodeIDNode(ID, Opcode, VTList, Ops);
6765 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6766 E->intersectFlagsWith(Flags);
6773 /// getDbgValue - Creates a SDDbgValue node.
6776 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6777 unsigned R, bool IsIndirect, uint64_t Off,
6778 const DebugLoc &DL, unsigned O) {
6779 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6780 "Expected inlined-at fields to agree");
6781 return new (DbgInfo->getAlloc())
6782 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6786 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6787 const Value *C, uint64_t Off,
6788 const DebugLoc &DL, unsigned O) {
6789 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6790 "Expected inlined-at fields to agree");
6791 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6795 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6796 unsigned FI, uint64_t Off,
6799 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6800 "Expected inlined-at fields to agree");
6801 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6806 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6807 /// pointed to by a use iterator is deleted, increment the use iterator
6808 /// so that it doesn't dangle.
6810 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6811 SDNode::use_iterator &UI;
6812 SDNode::use_iterator &UE;
6814 void NodeDeleted(SDNode *N, SDNode *E) override {
6815 // Increment the iterator as needed.
6816 while (UI != UE && N == *UI)
6821 RAUWUpdateListener(SelectionDAG &d,
6822 SDNode::use_iterator &ui,
6823 SDNode::use_iterator &ue)
6824 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6827 } // end anonymous namespace
6829 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6830 /// This can cause recursive merging of nodes in the DAG.
6832 /// This version assumes From has a single result value.
6834 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6835 SDNode *From = FromN.getNode();
6836 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6837 "Cannot replace with this method!");
6838 assert(From != To.getNode() && "Cannot replace uses of with self");
6840 // Preserve Debug Values
6841 TransferDbgValues(FromN, To);
6843 // Iterate over all the existing uses of From. New uses will be added
6844 // to the beginning of the use list, which we avoid visiting.
6845 // This specifically avoids visiting uses of From that arise while the
6846 // replacement is happening, because any such uses would be the result
6847 // of CSE: If an existing node looks like From after one of its operands
6848 // is replaced by To, we don't want to replace of all its users with To
6849 // too. See PR3018 for more info.
6850 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6851 RAUWUpdateListener Listener(*this, UI, UE);
6855 // This node is about to morph, remove its old self from the CSE maps.
6856 RemoveNodeFromCSEMaps(User);
6858 // A user can appear in a use list multiple times, and when this
6859 // happens the uses are usually next to each other in the list.
6860 // To help reduce the number of CSE recomputations, process all
6861 // the uses of this user that we can find this way.
6863 SDUse &Use = UI.getUse();
6866 } while (UI != UE && *UI == User);
6868 // Now that we have modified User, add it back to the CSE maps. If it
6869 // already exists there, recursively merge the results together.
6870 AddModifiedNodeToCSEMaps(User);
6873 // If we just RAUW'd the root, take note.
6874 if (FromN == getRoot())
6878 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6879 /// This can cause recursive merging of nodes in the DAG.
6881 /// This version assumes that for each value of From, there is a
6882 /// corresponding value in To in the same position with the same type.
6884 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6886 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6887 assert((!From->hasAnyUseOfValue(i) ||
6888 From->getValueType(i) == To->getValueType(i)) &&
6889 "Cannot use this version of ReplaceAllUsesWith!");
6892 // Handle the trivial case.
6896 // Preserve Debug Info. Only do this if there's a use.
6897 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6898 if (From->hasAnyUseOfValue(i)) {
6899 assert((i < To->getNumValues()) && "Invalid To location");
6900 TransferDbgValues(SDValue(From, i), SDValue(To, i));
6903 // Iterate over just the existing users of From. See the comments in
6904 // the ReplaceAllUsesWith above.
6905 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6906 RAUWUpdateListener Listener(*this, UI, UE);
6910 // This node is about to morph, remove its old self from the CSE maps.
6911 RemoveNodeFromCSEMaps(User);
6913 // A user can appear in a use list multiple times, and when this
6914 // happens the uses are usually next to each other in the list.
6915 // To help reduce the number of CSE recomputations, process all
6916 // the uses of this user that we can find this way.
6918 SDUse &Use = UI.getUse();
6921 } while (UI != UE && *UI == User);
6923 // Now that we have modified User, add it back to the CSE maps. If it
6924 // already exists there, recursively merge the results together.
6925 AddModifiedNodeToCSEMaps(User);
6928 // If we just RAUW'd the root, take note.
6929 if (From == getRoot().getNode())
6930 setRoot(SDValue(To, getRoot().getResNo()));
6933 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6934 /// This can cause recursive merging of nodes in the DAG.
6936 /// This version can replace From with any result values. To must match the
6937 /// number and types of values returned by From.
6938 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6939 if (From->getNumValues() == 1) // Handle the simple case efficiently.
6940 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6942 // Preserve Debug Info.
6943 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6944 TransferDbgValues(SDValue(From, i), *To);
6946 // Iterate over just the existing users of From. See the comments in
6947 // the ReplaceAllUsesWith above.
6948 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6949 RAUWUpdateListener Listener(*this, UI, UE);
6953 // This node is about to morph, remove its old self from the CSE maps.
6954 RemoveNodeFromCSEMaps(User);
6956 // A user can appear in a use list multiple times, and when this
6957 // happens the uses are usually next to each other in the list.
6958 // To help reduce the number of CSE recomputations, process all
6959 // the uses of this user that we can find this way.
6961 SDUse &Use = UI.getUse();
6962 const SDValue &ToOp = To[Use.getResNo()];
6965 } while (UI != UE && *UI == User);
6967 // Now that we have modified User, add it back to the CSE maps. If it
6968 // already exists there, recursively merge the results together.
6969 AddModifiedNodeToCSEMaps(User);
6972 // If we just RAUW'd the root, take note.
6973 if (From == getRoot().getNode())
6974 setRoot(SDValue(To[getRoot().getResNo()]));
6977 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6978 /// uses of other values produced by From.getNode() alone. The Deleted
6979 /// vector is handled the same way as for ReplaceAllUsesWith.
6980 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6981 // Handle the really simple, really trivial case efficiently.
6982 if (From == To) return;
6984 // Handle the simple, trivial, case efficiently.
6985 if (From.getNode()->getNumValues() == 1) {
6986 ReplaceAllUsesWith(From, To);
6990 // Preserve Debug Info.
6991 TransferDbgValues(From, To);
6993 // Iterate over just the existing users of From. See the comments in
6994 // the ReplaceAllUsesWith above.
6995 SDNode::use_iterator UI = From.getNode()->use_begin(),
6996 UE = From.getNode()->use_end();
6997 RAUWUpdateListener Listener(*this, UI, UE);
7000 bool UserRemovedFromCSEMaps = false;
7002 // A user can appear in a use list multiple times, and when this
7003 // happens the uses are usually next to each other in the list.
7004 // To help reduce the number of CSE recomputations, process all
7005 // the uses of this user that we can find this way.
7007 SDUse &Use = UI.getUse();
7009 // Skip uses of different values from the same node.
7010 if (Use.getResNo() != From.getResNo()) {
7015 // If this node hasn't been modified yet, it's still in the CSE maps,
7016 // so remove its old self from the CSE maps.
7017 if (!UserRemovedFromCSEMaps) {
7018 RemoveNodeFromCSEMaps(User);
7019 UserRemovedFromCSEMaps = true;
7024 } while (UI != UE && *UI == User);
7026 // We are iterating over all uses of the From node, so if a use
7027 // doesn't use the specific value, no changes are made.
7028 if (!UserRemovedFromCSEMaps)
7031 // Now that we have modified User, add it back to the CSE maps. If it
7032 // already exists there, recursively merge the results together.
7033 AddModifiedNodeToCSEMaps(User);
7036 // If we just RAUW'd the root, take note.
7037 if (From == getRoot())
7043 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
7044 /// to record information about a use.
7051 /// operator< - Sort Memos by User.
7052 bool operator<(const UseMemo &L, const UseMemo &R) {
7053 return (intptr_t)L.User < (intptr_t)R.User;
7056 } // end anonymous namespace
7058 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
7059 /// uses of other values produced by From.getNode() alone. The same value
7060 /// may appear in both the From and To list. The Deleted vector is
7061 /// handled the same way as for ReplaceAllUsesWith.
7062 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
7065 // Handle the simple, trivial case efficiently.
7067 return ReplaceAllUsesOfValueWith(*From, *To);
7069 TransferDbgValues(*From, *To);
7071 // Read up all the uses and make records of them. This helps
7072 // processing new uses that are introduced during the
7073 // replacement process.
7074 SmallVector<UseMemo, 4> Uses;
7075 for (unsigned i = 0; i != Num; ++i) {
7076 unsigned FromResNo = From[i].getResNo();
7077 SDNode *FromNode = From[i].getNode();
7078 for (SDNode::use_iterator UI = FromNode->use_begin(),
7079 E = FromNode->use_end(); UI != E; ++UI) {
7080 SDUse &Use = UI.getUse();
7081 if (Use.getResNo() == FromResNo) {
7082 UseMemo Memo = { *UI, i, &Use };
7083 Uses.push_back(Memo);
7088 // Sort the uses, so that all the uses from a given User are together.
7089 std::sort(Uses.begin(), Uses.end());
7091 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
7092 UseIndex != UseIndexEnd; ) {
7093 // We know that this user uses some value of From. If it is the right
7094 // value, update it.
7095 SDNode *User = Uses[UseIndex].User;
7097 // This node is about to morph, remove its old self from the CSE maps.
7098 RemoveNodeFromCSEMaps(User);
7100 // The Uses array is sorted, so all the uses for a given User
7101 // are next to each other in the list.
7102 // To help reduce the number of CSE recomputations, process all
7103 // the uses of this user that we can find this way.
7105 unsigned i = Uses[UseIndex].Index;
7106 SDUse &Use = *Uses[UseIndex].Use;
7110 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
7112 // Now that we have modified User, add it back to the CSE maps. If it
7113 // already exists there, recursively merge the results together.
7114 AddModifiedNodeToCSEMaps(User);
7118 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
7119 /// based on their topological order. It returns the maximum id and a vector
7120 /// of the SDNodes* in assigned order by reference.
7121 unsigned SelectionDAG::AssignTopologicalOrder() {
7122 unsigned DAGSize = 0;
7124 // SortedPos tracks the progress of the algorithm. Nodes before it are
7125 // sorted, nodes after it are unsorted. When the algorithm completes
7126 // it is at the end of the list.
7127 allnodes_iterator SortedPos = allnodes_begin();
7129 // Visit all the nodes. Move nodes with no operands to the front of
7130 // the list immediately. Annotate nodes that do have operands with their
7131 // operand count. Before we do this, the Node Id fields of the nodes
7132 // may contain arbitrary values. After, the Node Id fields for nodes
7133 // before SortedPos will contain the topological sort index, and the
7134 // Node Id fields for nodes At SortedPos and after will contain the
7135 // count of outstanding operands.
7136 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7138 checkForCycles(N, this);
7139 unsigned Degree = N->getNumOperands();
7141 // A node with no uses, add it to the result array immediately.
7142 N->setNodeId(DAGSize++);
7143 allnodes_iterator Q(N);
7145 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7146 assert(SortedPos != AllNodes.end() && "Overran node list");
7149 // Temporarily use the Node Id as scratch space for the degree count.
7150 N->setNodeId(Degree);
7154 // Visit all the nodes. As we iterate, move nodes into sorted order,
7155 // such that by the time the end is reached all nodes will be sorted.
7156 for (SDNode &Node : allnodes()) {
7158 checkForCycles(N, this);
7159 // N is in sorted position, so all its uses have one less operand
7160 // that needs to be sorted.
7161 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7164 unsigned Degree = P->getNodeId();
7165 assert(Degree != 0 && "Invalid node degree");
7168 // All of P's operands are sorted, so P may sorted now.
7169 P->setNodeId(DAGSize++);
7170 if (P->getIterator() != SortedPos)
7171 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7172 assert(SortedPos != AllNodes.end() && "Overran node list");
7175 // Update P's outstanding operand count.
7176 P->setNodeId(Degree);
7179 if (Node.getIterator() == SortedPos) {
7181 allnodes_iterator I(N);
7183 dbgs() << "Overran sorted position:\n";
7184 S->dumprFull(this); dbgs() << "\n";
7185 dbgs() << "Checking if this is due to cycles\n";
7186 checkForCycles(this, true);
7188 llvm_unreachable(nullptr);
7192 assert(SortedPos == AllNodes.end() &&
7193 "Topological sort incomplete!");
7194 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7195 "First node in topological sort is not the entry token!");
7196 assert(AllNodes.front().getNodeId() == 0 &&
7197 "First node in topological sort has non-zero id!");
7198 assert(AllNodes.front().getNumOperands() == 0 &&
7199 "First node in topological sort has operands!");
7200 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7201 "Last node in topologic sort has unexpected id!");
7202 assert(AllNodes.back().use_empty() &&
7203 "Last node in topologic sort has users!");
7204 assert(DAGSize == allnodes_size() && "Node count mismatch!");
7208 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7209 /// value is produced by SD.
7210 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7212 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7213 SD->setHasDebugValue(true);
7215 DbgInfo->add(DB, SD, isParameter);
7218 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
7219 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
7220 if (From == To || !From.getNode()->getHasDebugValue())
7222 SDNode *FromNode = From.getNode();
7223 SDNode *ToNode = To.getNode();
7224 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
7225 SmallVector<SDDbgValue *, 2> ClonedDVs;
7226 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
7228 SDDbgValue *Dbg = *I;
7229 // Only add Dbgvalues attached to same ResNo.
7230 if (Dbg->getKind() == SDDbgValue::SDNODE &&
7231 Dbg->getSDNode() == From.getNode() &&
7232 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
7233 assert(FromNode != ToNode &&
7234 "Should not transfer Debug Values intranode");
7236 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
7237 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
7238 Dbg->getDebugLoc(), Dbg->getOrder());
7239 ClonedDVs.push_back(Clone);
7240 Dbg->setIsInvalidated();
7243 for (SDDbgValue *I : ClonedDVs)
7244 AddDbgValue(I, ToNode, false);
7247 void SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
7249 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
7250 if (!OldLoad->hasAnyUseOfValue(1))
7253 // The new memory operation must have the same position as the old load in
7254 // terms of memory dependency. Create a TokenFactor for the old load and new
7255 // memory operation and update uses of the old load's output chain to use that
7257 SDValue OldChain = SDValue(OldLoad, 1);
7258 SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
7259 SDValue TokenFactor =
7260 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
7261 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
7262 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
7265 //===----------------------------------------------------------------------===//
7267 //===----------------------------------------------------------------------===//
7269 bool llvm::isNullConstant(SDValue V) {
7270 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7271 return Const != nullptr && Const->isNullValue();
7274 bool llvm::isNullFPConstant(SDValue V) {
7275 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7276 return Const != nullptr && Const->isZero() && !Const->isNegative();
7279 bool llvm::isAllOnesConstant(SDValue V) {
7280 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7281 return Const != nullptr && Const->isAllOnesValue();
7284 bool llvm::isOneConstant(SDValue V) {
7285 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7286 return Const != nullptr && Const->isOne();
7289 bool llvm::isBitwiseNot(SDValue V) {
7290 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7293 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7294 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7297 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7298 BitVector UndefElements;
7299 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7301 // BuildVectors can truncate their operands. Ignore that case here.
7302 // FIXME: We blindly ignore splats which include undef which is overly
7304 if (CN && UndefElements.none() &&
7305 CN->getValueType(0) == N.getValueType().getScalarType())
7312 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7313 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7316 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7317 BitVector UndefElements;
7318 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7320 if (CN && UndefElements.none())
7327 HandleSDNode::~HandleSDNode() {
7331 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7333 const GlobalValue *GA, EVT VT,
7334 int64_t o, unsigned char TF)
7335 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7339 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7340 EVT VT, unsigned SrcAS,
7342 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7343 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7345 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7346 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7347 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7348 MemSDNodeBits.IsVolatile = MMO->isVolatile();
7349 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7350 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7351 MemSDNodeBits.IsInvariant = MMO->isInvariant();
7353 // We check here that the size of the memory operand fits within the size of
7354 // the MMO. This is because the MMO might indicate only a possible address
7355 // range instead of specifying the affected memory addresses precisely.
7356 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7359 /// Profile - Gather unique data for the node.
7361 void SDNode::Profile(FoldingSetNodeID &ID) const {
7362 AddNodeIDNode(ID, this);
7368 std::vector<EVT> VTs;
7371 VTs.reserve(MVT::LAST_VALUETYPE);
7372 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7373 VTs.push_back(MVT((MVT::SimpleValueType)i));
7377 } // end anonymous namespace
7379 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
7380 static ManagedStatic<EVTArray> SimpleVTArray;
7381 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
7383 /// getValueTypeList - Return a pointer to the specified value type.
7385 const EVT *SDNode::getValueTypeList(EVT VT) {
7386 if (VT.isExtended()) {
7387 sys::SmartScopedLock<true> Lock(*VTMutex);
7388 return &(*EVTs->insert(VT).first);
7390 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7391 "Value type out of range!");
7392 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7396 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7397 /// indicated value. This method ignores uses of other values defined by this
7399 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7400 assert(Value < getNumValues() && "Bad value!");
7402 // TODO: Only iterate over uses of a given value of the node
7403 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7404 if (UI.getUse().getResNo() == Value) {
7411 // Found exactly the right number of uses?
7415 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7416 /// value. This method ignores uses of other values defined by this operation.
7417 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7418 assert(Value < getNumValues() && "Bad value!");
7420 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7421 if (UI.getUse().getResNo() == Value)
7427 /// isOnlyUserOf - Return true if this node is the only use of N.
7428 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7430 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7441 /// Return true if the only users of N are contained in Nodes.
7442 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7444 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7446 if (llvm::any_of(Nodes,
7447 [&User](const SDNode *Node) { return User == Node; }))
7456 /// isOperand - Return true if this node is an operand of N.
7457 bool SDValue::isOperandOf(const SDNode *N) const {
7458 for (const SDValue &Op : N->op_values())
7464 bool SDNode::isOperandOf(const SDNode *N) const {
7465 for (const SDValue &Op : N->op_values())
7466 if (this == Op.getNode())
7471 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7472 /// be a chain) reaches the specified operand without crossing any
7473 /// side-effecting instructions on any chain path. In practice, this looks
7474 /// through token factors and non-volatile loads. In order to remain efficient,
7475 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7477 /// Note that we only need to examine chains when we're searching for
7478 /// side-effects; SelectionDAG requires that all side-effects are represented
7479 /// by chains, even if another operand would force a specific ordering. This
7480 /// constraint is necessary to allow transformations like splitting loads.
7481 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7482 unsigned Depth) const {
7483 if (*this == Dest) return true;
7485 // Don't search too deeply, we just want to be able to see through
7486 // TokenFactor's etc.
7487 if (Depth == 0) return false;
7489 // If this is a token factor, all inputs to the TF happen in parallel.
7490 if (getOpcode() == ISD::TokenFactor) {
7491 // First, try a shallow search.
7492 if (is_contained((*this)->ops(), Dest)) {
7493 // We found the chain we want as an operand of this TokenFactor.
7494 // Essentially, we reach the chain without side-effects if we could
7495 // serialize the TokenFactor into a simple chain of operations with
7496 // Dest as the last operation. This is automatically true if the
7497 // chain has one use: there are no other ordering constraints.
7498 // If the chain has more than one use, we give up: some other
7499 // use of Dest might force a side-effect between Dest and the current
7501 if (Dest.hasOneUse())
7504 // Next, try a deep search: check whether every operand of the TokenFactor
7506 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
7507 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7511 // Loads don't have side effects, look through them.
7512 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7513 if (!Ld->isVolatile())
7514 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7519 bool SDNode::hasPredecessor(const SDNode *N) const {
7520 SmallPtrSet<const SDNode *, 32> Visited;
7521 SmallVector<const SDNode *, 16> Worklist;
7522 Worklist.push_back(this);
7523 return hasPredecessorHelper(N, Visited, Worklist);
7526 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
7527 this->Flags.intersectWith(Flags);
7530 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7531 assert(N->getNumValues() == 1 &&
7532 "Can't unroll a vector with multiple results!");
7534 EVT VT = N->getValueType(0);
7535 unsigned NE = VT.getVectorNumElements();
7536 EVT EltVT = VT.getVectorElementType();
7539 SmallVector<SDValue, 8> Scalars;
7540 SmallVector<SDValue, 4> Operands(N->getNumOperands());
7542 // If ResNE is 0, fully unroll the vector op.
7545 else if (NE > ResNE)
7549 for (i= 0; i != NE; ++i) {
7550 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7551 SDValue Operand = N->getOperand(j);
7552 EVT OperandVT = Operand.getValueType();
7553 if (OperandVT.isVector()) {
7554 // A vector operand; extract a single element.
7555 EVT OperandEltVT = OperandVT.getVectorElementType();
7557 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7558 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7560 // A scalar operand; just use it as is.
7561 Operands[j] = Operand;
7565 switch (N->getOpcode()) {
7567 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7572 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7579 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7580 getShiftAmountOperand(Operands[0].getValueType(),
7583 case ISD::SIGN_EXTEND_INREG:
7584 case ISD::FP_ROUND_INREG: {
7585 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7586 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7588 getValueType(ExtVT)));
7593 for (; i < ResNE; ++i)
7594 Scalars.push_back(getUNDEF(EltVT));
7596 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7597 return getBuildVector(VecVT, dl, Scalars);
7600 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7604 if (LD->isVolatile() || Base->isVolatile())
7606 if (LD->isIndexed() || Base->isIndexed())
7608 if (LD->getChain() != Base->getChain())
7610 EVT VT = LD->getValueType(0);
7611 if (VT.getSizeInBits() / 8 != Bytes)
7614 SDValue Loc = LD->getOperand(1);
7615 SDValue BaseLoc = Base->getOperand(1);
7616 if (Loc.getOpcode() == ISD::FrameIndex) {
7617 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7619 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7620 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7621 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7622 int FS = MFI.getObjectSize(FI);
7623 int BFS = MFI.getObjectSize(BFI);
7624 if (FS != BFS || FS != (int)Bytes) return false;
7625 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
7629 if (isBaseWithConstantOffset(Loc)) {
7630 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
7631 if (Loc.getOperand(0) == BaseLoc) {
7632 // If the base location is a simple address with no offset itself, then
7633 // the second load's first add operand should be the base address.
7634 if (LocOffset == Dist * (int)Bytes)
7636 } else if (isBaseWithConstantOffset(BaseLoc)) {
7637 // The base location itself has an offset, so subtract that value from the
7638 // second load's offset before comparing to distance * size.
7640 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
7641 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
7642 if ((LocOffset - BOffset) == Dist * (int)Bytes)
7647 const GlobalValue *GV1 = nullptr;
7648 const GlobalValue *GV2 = nullptr;
7649 int64_t Offset1 = 0;
7650 int64_t Offset2 = 0;
7651 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7652 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7653 if (isGA1 && isGA2 && GV1 == GV2)
7654 return Offset1 == (Offset2 + Dist*Bytes);
7658 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7659 /// it cannot be inferred.
7660 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7661 // If this is a GlobalAddress + cst, return the alignment.
7662 const GlobalValue *GV;
7663 int64_t GVOffset = 0;
7664 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7665 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7666 KnownBits Known(PtrWidth);
7667 llvm::computeKnownBits(GV, Known, getDataLayout());
7668 unsigned AlignBits = Known.countMinTrailingZeros();
7669 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7671 return MinAlign(Align, GVOffset);
7674 // If this is a direct reference to a stack slot, use information about the
7675 // stack slot's alignment.
7676 int FrameIdx = 1 << 31;
7677 int64_t FrameOffset = 0;
7678 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7679 FrameIdx = FI->getIndex();
7680 } else if (isBaseWithConstantOffset(Ptr) &&
7681 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7683 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7684 FrameOffset = Ptr.getConstantOperandVal(1);
7687 if (FrameIdx != (1 << 31)) {
7688 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7689 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7697 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7698 /// which is split (or expanded) into two not necessarily identical pieces.
7699 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7700 // Currently all types are split in half.
7703 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7705 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
7707 return std::make_pair(LoVT, HiVT);
7710 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7712 std::pair<SDValue, SDValue>
7713 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7715 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7716 N.getValueType().getVectorNumElements() &&
7717 "More vector elements requested than available!");
7719 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7720 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7721 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7722 getConstant(LoVT.getVectorNumElements(), DL,
7723 TLI->getVectorIdxTy(getDataLayout())));
7724 return std::make_pair(Lo, Hi);
7727 void SelectionDAG::ExtractVectorElements(SDValue Op,
7728 SmallVectorImpl<SDValue> &Args,
7729 unsigned Start, unsigned Count) {
7730 EVT VT = Op.getValueType();
7732 Count = VT.getVectorNumElements();
7734 EVT EltVT = VT.getVectorElementType();
7735 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7737 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7738 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7739 Op, getConstant(i, SL, IdxTy)));
7743 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7744 unsigned GlobalAddressSDNode::getAddressSpace() const {
7745 return getGlobal()->getType()->getAddressSpace();
7748 Type *ConstantPoolSDNode::getType() const {
7749 if (isMachineConstantPoolEntry())
7750 return Val.MachineCPVal->getType();
7751 return Val.ConstVal->getType();
7754 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
7755 unsigned &SplatBitSize,
7757 unsigned MinSplatBits,
7758 bool IsBigEndian) const {
7759 EVT VT = getValueType(0);
7760 assert(VT.isVector() && "Expected a vector type");
7761 unsigned VecWidth = VT.getSizeInBits();
7762 if (MinSplatBits > VecWidth)
7765 // FIXME: The widths are based on this node's type, but build vectors can
7766 // truncate their operands.
7767 SplatValue = APInt(VecWidth, 0);
7768 SplatUndef = APInt(VecWidth, 0);
7770 // Get the bits. Bits with undefined values (when the corresponding element
7771 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7772 // in SplatValue. If any of the values are not constant, give up and return
7774 unsigned int NumOps = getNumOperands();
7775 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
7776 unsigned EltWidth = VT.getScalarSizeInBits();
7778 for (unsigned j = 0; j < NumOps; ++j) {
7779 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
7780 SDValue OpVal = getOperand(i);
7781 unsigned BitPos = j * EltWidth;
7783 if (OpVal.isUndef())
7784 SplatUndef.setBits(BitPos, BitPos + EltWidth);
7785 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
7786 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
7787 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7788 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
7793 // The build_vector is all constants or undefs. Find the smallest element
7794 // size that splats the vector.
7795 HasAnyUndefs = (SplatUndef != 0);
7797 // FIXME: This does not work for vectors with elements less than 8 bits.
7798 while (VecWidth > 8) {
7799 unsigned HalfSize = VecWidth / 2;
7800 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7801 APInt LowValue = SplatValue.trunc(HalfSize);
7802 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7803 APInt LowUndef = SplatUndef.trunc(HalfSize);
7805 // If the two halves do not match (ignoring undef bits), stop here.
7806 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7807 MinSplatBits > HalfSize)
7810 SplatValue = HighValue | LowValue;
7811 SplatUndef = HighUndef & LowUndef;
7813 VecWidth = HalfSize;
7816 SplatBitSize = VecWidth;
7820 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7821 if (UndefElements) {
7822 UndefElements->clear();
7823 UndefElements->resize(getNumOperands());
7826 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7827 SDValue Op = getOperand(i);
7830 (*UndefElements)[i] = true;
7831 } else if (!Splatted) {
7833 } else if (Splatted != Op) {
7839 assert(getOperand(0).isUndef() &&
7840 "Can only have a splat without a constant for all undefs.");
7841 return getOperand(0);
7848 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7849 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7853 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7854 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7858 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7859 uint32_t BitWidth) const {
7860 if (ConstantFPSDNode *CN =
7861 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7863 APSInt IntVal(BitWidth);
7864 const APFloat &APF = CN->getValueAPF();
7865 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7870 return IntVal.exactLogBase2();
7875 bool BuildVectorSDNode::isConstant() const {
7876 for (const SDValue &Op : op_values()) {
7877 unsigned Opc = Op.getOpcode();
7878 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7884 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7885 // Find the first non-undef value in the shuffle mask.
7887 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7890 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7892 // Make sure all remaining elements are either undef or the same as the first
7894 for (int Idx = Mask[i]; i != e; ++i)
7895 if (Mask[i] >= 0 && Mask[i] != Idx)
7900 // \brief Returns the SDNode if it is a constant integer BuildVector
7901 // or constant integer.
7902 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7903 if (isa<ConstantSDNode>(N))
7905 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7907 // Treat a GlobalAddress supporting constant offset folding as a
7908 // constant integer.
7909 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7910 if (GA->getOpcode() == ISD::GlobalAddress &&
7911 TLI->isOffsetFoldingLegal(GA))
7916 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
7917 if (isa<ConstantFPSDNode>(N))
7920 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
7927 static void checkForCyclesHelper(const SDNode *N,
7928 SmallPtrSetImpl<const SDNode*> &Visited,
7929 SmallPtrSetImpl<const SDNode*> &Checked,
7930 const llvm::SelectionDAG *DAG) {
7931 // If this node has already been checked, don't check it again.
7932 if (Checked.count(N))
7935 // If a node has already been visited on this depth-first walk, reject it as
7937 if (!Visited.insert(N).second) {
7938 errs() << "Detected cycle in SelectionDAG\n";
7939 dbgs() << "Offending node:\n";
7940 N->dumprFull(DAG); dbgs() << "\n";
7944 for (const SDValue &Op : N->op_values())
7945 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7952 void llvm::checkForCycles(const llvm::SDNode *N,
7953 const llvm::SelectionDAG *DAG,
7957 #ifdef EXPENSIVE_CHECKS
7959 #endif // EXPENSIVE_CHECKS
7961 assert(N && "Checking nonexistent SDNode");
7962 SmallPtrSet<const SDNode*, 32> visited;
7963 SmallPtrSet<const SDNode*, 32> checked;
7964 checkForCyclesHelper(N, visited, checked, DAG);
7969 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7970 checkForCycles(DAG->getRoot().getNode(), DAG, force);