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 "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/CodeGen/ISDOpcodes.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineValueType.h"
35 #include "llvm/CodeGen/RuntimeLibcalls.h"
36 #include "llvm/CodeGen/SelectionDAG.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();
593 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
594 DUL->NodeDeleted(N, nullptr);
596 // Take the node out of the appropriate CSE map.
597 RemoveNodeFromCSEMaps(N);
599 // Next, brutally remove the operand list. This is safe to do, as there are
600 // no cycles in the graph.
601 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
603 SDNode *Operand = Use.getNode();
606 // Now that we removed this operand, see if there are no uses of it left.
607 if (Operand->use_empty())
608 DeadNodes.push_back(Operand);
615 void SelectionDAG::RemoveDeadNode(SDNode *N){
616 SmallVector<SDNode*, 16> DeadNodes(1, N);
618 // Create a dummy node that adds a reference to the root node, preventing
619 // it from being deleted. (This matters if the root is an operand of the
621 HandleSDNode Dummy(getRoot());
623 RemoveDeadNodes(DeadNodes);
626 void SelectionDAG::DeleteNode(SDNode *N) {
627 // First take this out of the appropriate CSE map.
628 RemoveNodeFromCSEMaps(N);
630 // Finally, remove uses due to operands of this node, remove from the
631 // AllNodes list, and delete the node.
632 DeleteNodeNotInCSEMaps(N);
635 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
636 assert(N->getIterator() != AllNodes.begin() &&
637 "Cannot delete the entry node!");
638 assert(N->use_empty() && "Cannot delete a node that is not dead!");
640 // Drop all of the operands and decrement used node's use counts.
646 void SDDbgInfo::erase(const SDNode *Node) {
647 DbgValMapType::iterator I = DbgValMap.find(Node);
648 if (I == DbgValMap.end())
650 for (auto &Val: I->second)
651 Val->setIsInvalidated();
655 void SelectionDAG::DeallocateNode(SDNode *N) {
656 // If we have operands, deallocate them.
659 NodeAllocator.Deallocate(AllNodes.remove(N));
661 // Set the opcode to DELETED_NODE to help catch bugs when node
662 // memory is reallocated.
663 // FIXME: There are places in SDag that have grown a dependency on the opcode
664 // value in the released node.
665 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
666 N->NodeType = ISD::DELETED_NODE;
668 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
669 // them and forget about that node.
674 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
675 static void VerifySDNode(SDNode *N) {
676 switch (N->getOpcode()) {
679 case ISD::BUILD_PAIR: {
680 EVT VT = N->getValueType(0);
681 assert(N->getNumValues() == 1 && "Too many results!");
682 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
683 "Wrong return type!");
684 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
685 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
686 "Mismatched operand types!");
687 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
688 "Wrong operand type!");
689 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
690 "Wrong return type size");
693 case ISD::BUILD_VECTOR: {
694 assert(N->getNumValues() == 1 && "Too many results!");
695 assert(N->getValueType(0).isVector() && "Wrong return type!");
696 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
697 "Wrong number of operands!");
698 EVT EltVT = N->getValueType(0).getVectorElementType();
699 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
700 assert((I->getValueType() == EltVT ||
701 (EltVT.isInteger() && I->getValueType().isInteger() &&
702 EltVT.bitsLE(I->getValueType()))) &&
703 "Wrong operand type!");
704 assert(I->getValueType() == N->getOperand(0).getValueType() &&
705 "Operands must all have the same type");
713 /// \brief Insert a newly allocated node into the DAG.
715 /// Handles insertion into the all nodes list and CSE map, as well as
716 /// verification and other common operations when a new node is allocated.
717 void SelectionDAG::InsertNode(SDNode *N) {
718 AllNodes.push_back(N);
720 N->PersistentId = NextPersistentId++;
725 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
726 /// correspond to it. This is useful when we're about to delete or repurpose
727 /// the node. We don't want future request for structurally identical nodes
728 /// to return N anymore.
729 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
731 switch (N->getOpcode()) {
732 case ISD::HANDLENODE: return false; // noop.
734 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
735 "Cond code doesn't exist!");
736 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
737 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
739 case ISD::ExternalSymbol:
740 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
742 case ISD::TargetExternalSymbol: {
743 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
744 Erased = TargetExternalSymbols.erase(
745 std::pair<std::string,unsigned char>(ESN->getSymbol(),
746 ESN->getTargetFlags()));
749 case ISD::MCSymbol: {
750 auto *MCSN = cast<MCSymbolSDNode>(N);
751 Erased = MCSymbols.erase(MCSN->getMCSymbol());
754 case ISD::VALUETYPE: {
755 EVT VT = cast<VTSDNode>(N)->getVT();
756 if (VT.isExtended()) {
757 Erased = ExtendedValueTypeNodes.erase(VT);
759 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
760 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
765 // Remove it from the CSE Map.
766 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
767 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
768 Erased = CSEMap.RemoveNode(N);
772 // Verify that the node was actually in one of the CSE maps, unless it has a
773 // flag result (which cannot be CSE'd) or is one of the special cases that are
774 // not subject to CSE.
775 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
776 !N->isMachineOpcode() && !doNotCSE(N)) {
779 llvm_unreachable("Node is not in map!");
785 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
786 /// maps and modified in place. Add it back to the CSE maps, unless an identical
787 /// node already exists, in which case transfer all its users to the existing
788 /// node. This transfer can potentially trigger recursive merging.
790 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
791 // For node types that aren't CSE'd, just act as if no identical node
794 SDNode *Existing = CSEMap.GetOrInsertNode(N);
796 // If there was already an existing matching node, use ReplaceAllUsesWith
797 // to replace the dead one with the existing one. This can cause
798 // recursive merging of other unrelated nodes down the line.
799 ReplaceAllUsesWith(N, Existing);
801 // N is now dead. Inform the listeners and delete it.
802 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
803 DUL->NodeDeleted(N, Existing);
804 DeleteNodeNotInCSEMaps(N);
809 // If the node doesn't already exist, we updated it. Inform listeners.
810 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
814 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
815 /// were replaced with those specified. If this node is never memoized,
816 /// return null, otherwise return a pointer to the slot it would take. If a
817 /// node already exists with these operands, the slot will be non-null.
818 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
823 SDValue Ops[] = { Op };
825 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
826 AddNodeIDCustom(ID, N);
827 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
829 Node->intersectFlagsWith(N->getFlags());
833 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
834 /// were replaced with those specified. If this node is never memoized,
835 /// return null, otherwise return a pointer to the slot it would take. If a
836 /// node already exists with these operands, the slot will be non-null.
837 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
838 SDValue Op1, SDValue Op2,
843 SDValue Ops[] = { Op1, Op2 };
845 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
846 AddNodeIDCustom(ID, N);
847 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
849 Node->intersectFlagsWith(N->getFlags());
853 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
854 /// were replaced with those specified. If this node is never memoized,
855 /// return null, otherwise return a pointer to the slot it would take. If a
856 /// node already exists with these operands, the slot will be non-null.
857 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
863 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
864 AddNodeIDCustom(ID, N);
865 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
867 Node->intersectFlagsWith(N->getFlags());
871 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
872 Type *Ty = VT == MVT::iPTR ?
873 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
874 VT.getTypeForEVT(*getContext());
876 return getDataLayout().getABITypeAlignment(Ty);
879 // EntryNode could meaningfully have debug info if we can find it...
880 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
881 : TM(tm), OptLevel(OL),
882 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
883 Root(getEntryNode()) {
884 InsertNode(&EntryNode);
885 DbgInfo = new SDDbgInfo();
888 void SelectionDAG::init(MachineFunction &NewMF,
889 OptimizationRemarkEmitter &NewORE) {
892 TLI = getSubtarget().getTargetLowering();
893 TSI = getSubtarget().getSelectionDAGInfo();
894 Context = &MF->getFunction()->getContext();
897 SelectionDAG::~SelectionDAG() {
898 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
900 OperandRecycler.clear(OperandAllocator);
904 void SelectionDAG::allnodes_clear() {
905 assert(&*AllNodes.begin() == &EntryNode);
906 AllNodes.remove(AllNodes.begin());
907 while (!AllNodes.empty())
908 DeallocateNode(&AllNodes.front());
910 NextPersistentId = 0;
914 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
916 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
918 switch (N->getOpcode()) {
921 case ISD::ConstantFP:
922 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
923 "debug location. Use another overload.");
929 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
930 const SDLoc &DL, void *&InsertPos) {
931 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
933 switch (N->getOpcode()) {
935 case ISD::ConstantFP:
936 // Erase debug location from the node if the node is used at several
937 // different places. Do not propagate one location to all uses as it
938 // will cause a worse single stepping debugging experience.
939 if (N->getDebugLoc() != DL.getDebugLoc())
940 N->setDebugLoc(DebugLoc());
943 // When the node's point of use is located earlier in the instruction
944 // sequence than its prior point of use, update its debug info to the
946 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
947 N->setDebugLoc(DL.getDebugLoc());
954 void SelectionDAG::clear() {
956 OperandRecycler.clear(OperandAllocator);
957 OperandAllocator.Reset();
960 ExtendedValueTypeNodes.clear();
961 ExternalSymbols.clear();
962 TargetExternalSymbols.clear();
964 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
965 static_cast<CondCodeSDNode*>(nullptr));
966 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
967 static_cast<SDNode*>(nullptr));
969 EntryNode.UseList = nullptr;
970 InsertNode(&EntryNode);
971 Root = getEntryNode();
975 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
976 return VT.bitsGT(Op.getValueType())
977 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
978 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
981 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
982 return VT.bitsGT(Op.getValueType()) ?
983 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
984 getNode(ISD::TRUNCATE, DL, VT, Op);
987 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
988 return VT.bitsGT(Op.getValueType()) ?
989 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
990 getNode(ISD::TRUNCATE, DL, VT, Op);
993 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
994 return VT.bitsGT(Op.getValueType()) ?
995 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
996 getNode(ISD::TRUNCATE, DL, VT, Op);
999 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1001 if (VT.bitsLE(Op.getValueType()))
1002 return getNode(ISD::TRUNCATE, SL, VT, Op);
1004 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1005 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1008 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1009 assert(!VT.isVector() &&
1010 "getZeroExtendInReg should use the vector element type instead of "
1011 "the vector type!");
1012 if (Op.getValueType() == VT) return Op;
1013 unsigned BitWidth = Op.getScalarValueSizeInBits();
1014 APInt Imm = APInt::getLowBitsSet(BitWidth,
1015 VT.getSizeInBits());
1016 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1017 getConstant(Imm, DL, Op.getValueType()));
1020 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1022 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1023 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1024 "The sizes of the input and result must match in order to perform the "
1025 "extend in-register.");
1026 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1027 "The destination vector type must have fewer lanes than the input.");
1028 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1031 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1033 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1034 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1035 "The sizes of the input and result must match in order to perform the "
1036 "extend in-register.");
1037 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1038 "The destination vector type must have fewer lanes than the input.");
1039 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1042 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1044 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1045 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1046 "The sizes of the input and result must match in order to perform the "
1047 "extend in-register.");
1048 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1049 "The destination vector type must have fewer lanes than the input.");
1050 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1053 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1054 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1055 EVT EltVT = VT.getScalarType();
1057 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1058 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1061 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1062 EVT EltVT = VT.getScalarType();
1064 switch (TLI->getBooleanContents(VT)) {
1065 case TargetLowering::ZeroOrOneBooleanContent:
1066 case TargetLowering::UndefinedBooleanContent:
1067 TrueValue = getConstant(1, DL, VT);
1069 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1070 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1074 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1077 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1078 bool isT, bool isO) {
1079 EVT EltVT = VT.getScalarType();
1080 assert((EltVT.getSizeInBits() >= 64 ||
1081 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1082 "getConstant with a uint64_t value that doesn't fit in the type!");
1083 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1086 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1087 bool isT, bool isO) {
1088 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1091 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1092 EVT VT, bool isT, bool isO) {
1093 assert(VT.isInteger() && "Cannot create FP integer constant!");
1095 EVT EltVT = VT.getScalarType();
1096 const ConstantInt *Elt = &Val;
1098 // In some cases the vector type is legal but the element type is illegal and
1099 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1100 // inserted value (the type does not need to match the vector element type).
1101 // Any extra bits introduced will be truncated away.
1102 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1103 TargetLowering::TypePromoteInteger) {
1104 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1105 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1106 Elt = ConstantInt::get(*getContext(), NewVal);
1108 // In other cases the element type is illegal and needs to be expanded, for
1109 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1110 // the value into n parts and use a vector type with n-times the elements.
1111 // Then bitcast to the type requested.
1112 // Legalizing constants too early makes the DAGCombiner's job harder so we
1113 // only legalize if the DAG tells us we must produce legal types.
1114 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1115 TLI->getTypeAction(*getContext(), EltVT) ==
1116 TargetLowering::TypeExpandInteger) {
1117 const APInt &NewVal = Elt->getValue();
1118 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1119 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1120 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1121 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1123 // Check the temporary vector is the correct size. If this fails then
1124 // getTypeToTransformTo() probably returned a type whose size (in bits)
1125 // isn't a power-of-2 factor of the requested type size.
1126 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1128 SmallVector<SDValue, 2> EltParts;
1129 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1130 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1131 .zextOrTrunc(ViaEltSizeInBits), DL,
1132 ViaEltVT, isT, isO));
1135 // EltParts is currently in little endian order. If we actually want
1136 // big-endian order then reverse it now.
1137 if (getDataLayout().isBigEndian())
1138 std::reverse(EltParts.begin(), EltParts.end());
1140 // The elements must be reversed when the element order is different
1141 // to the endianness of the elements (because the BITCAST is itself a
1142 // vector shuffle in this situation). However, we do not need any code to
1143 // perform this reversal because getConstant() is producing a vector
1145 // This situation occurs in MIPS MSA.
1147 SmallVector<SDValue, 8> Ops;
1148 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1149 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1150 return getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1153 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1154 "APInt size does not match type size!");
1155 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1156 FoldingSetNodeID ID;
1157 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1161 SDNode *N = nullptr;
1162 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1164 return SDValue(N, 0);
1167 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1168 CSEMap.InsertNode(N, IP);
1172 SDValue Result(N, 0);
1174 Result = getSplatBuildVector(VT, DL, Result);
1178 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1180 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1183 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1185 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1188 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1189 EVT VT, bool isTarget) {
1190 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1192 EVT EltVT = VT.getScalarType();
1194 // Do the map lookup using the actual bit pattern for the floating point
1195 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1196 // we don't have issues with SNANs.
1197 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1198 FoldingSetNodeID ID;
1199 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1202 SDNode *N = nullptr;
1203 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1205 return SDValue(N, 0);
1208 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1209 CSEMap.InsertNode(N, IP);
1213 SDValue Result(N, 0);
1215 Result = getSplatBuildVector(VT, DL, Result);
1219 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1221 EVT EltVT = VT.getScalarType();
1222 if (EltVT == MVT::f32)
1223 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1224 else if (EltVT == MVT::f64)
1225 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1226 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1227 EltVT == MVT::f16) {
1229 APFloat APF = APFloat(Val);
1230 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1232 return getConstantFP(APF, DL, VT, isTarget);
1234 llvm_unreachable("Unsupported type in getConstantFP");
1237 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1238 EVT VT, int64_t Offset, bool isTargetGA,
1239 unsigned char TargetFlags) {
1240 assert((TargetFlags == 0 || isTargetGA) &&
1241 "Cannot set target flags on target-independent globals");
1243 // Truncate (with sign-extension) the offset value to the pointer size.
1244 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1246 Offset = SignExtend64(Offset, BitWidth);
1249 if (GV->isThreadLocal())
1250 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1252 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1254 FoldingSetNodeID ID;
1255 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1257 ID.AddInteger(Offset);
1258 ID.AddInteger(TargetFlags);
1260 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1261 return SDValue(E, 0);
1263 auto *N = newSDNode<GlobalAddressSDNode>(
1264 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1265 CSEMap.InsertNode(N, IP);
1267 return SDValue(N, 0);
1270 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1271 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1272 FoldingSetNodeID ID;
1273 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1276 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1277 return SDValue(E, 0);
1279 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1280 CSEMap.InsertNode(N, IP);
1282 return SDValue(N, 0);
1285 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1286 unsigned char TargetFlags) {
1287 assert((TargetFlags == 0 || isTarget) &&
1288 "Cannot set target flags on target-independent jump tables");
1289 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1290 FoldingSetNodeID ID;
1291 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1293 ID.AddInteger(TargetFlags);
1295 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1296 return SDValue(E, 0);
1298 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1299 CSEMap.InsertNode(N, IP);
1301 return SDValue(N, 0);
1304 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1305 unsigned Alignment, int Offset,
1307 unsigned char TargetFlags) {
1308 assert((TargetFlags == 0 || isTarget) &&
1309 "Cannot set target flags on target-independent globals");
1311 Alignment = MF->getFunction()->optForSize()
1312 ? getDataLayout().getABITypeAlignment(C->getType())
1313 : getDataLayout().getPrefTypeAlignment(C->getType());
1314 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1315 FoldingSetNodeID ID;
1316 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1317 ID.AddInteger(Alignment);
1318 ID.AddInteger(Offset);
1320 ID.AddInteger(TargetFlags);
1322 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1323 return SDValue(E, 0);
1325 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1327 CSEMap.InsertNode(N, IP);
1329 return SDValue(N, 0);
1332 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1333 unsigned Alignment, int Offset,
1335 unsigned char TargetFlags) {
1336 assert((TargetFlags == 0 || isTarget) &&
1337 "Cannot set target flags on target-independent globals");
1339 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1340 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1341 FoldingSetNodeID ID;
1342 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1343 ID.AddInteger(Alignment);
1344 ID.AddInteger(Offset);
1345 C->addSelectionDAGCSEId(ID);
1346 ID.AddInteger(TargetFlags);
1348 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1349 return SDValue(E, 0);
1351 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1353 CSEMap.InsertNode(N, IP);
1355 return SDValue(N, 0);
1358 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1359 unsigned char TargetFlags) {
1360 FoldingSetNodeID ID;
1361 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1362 ID.AddInteger(Index);
1363 ID.AddInteger(Offset);
1364 ID.AddInteger(TargetFlags);
1366 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1367 return SDValue(E, 0);
1369 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1370 CSEMap.InsertNode(N, IP);
1372 return SDValue(N, 0);
1375 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1376 FoldingSetNodeID ID;
1377 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1380 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1381 return SDValue(E, 0);
1383 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1384 CSEMap.InsertNode(N, IP);
1386 return SDValue(N, 0);
1389 SDValue SelectionDAG::getValueType(EVT VT) {
1390 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1391 ValueTypeNodes.size())
1392 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1394 SDNode *&N = VT.isExtended() ?
1395 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1397 if (N) return SDValue(N, 0);
1398 N = newSDNode<VTSDNode>(VT);
1400 return SDValue(N, 0);
1403 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1404 SDNode *&N = ExternalSymbols[Sym];
1405 if (N) return SDValue(N, 0);
1406 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1408 return SDValue(N, 0);
1411 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1412 SDNode *&N = MCSymbols[Sym];
1414 return SDValue(N, 0);
1415 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1417 return SDValue(N, 0);
1420 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1421 unsigned char TargetFlags) {
1423 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1425 if (N) return SDValue(N, 0);
1426 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1428 return SDValue(N, 0);
1431 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1432 if ((unsigned)Cond >= CondCodeNodes.size())
1433 CondCodeNodes.resize(Cond+1);
1435 if (!CondCodeNodes[Cond]) {
1436 auto *N = newSDNode<CondCodeSDNode>(Cond);
1437 CondCodeNodes[Cond] = N;
1441 return SDValue(CondCodeNodes[Cond], 0);
1444 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1445 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1446 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1448 ShuffleVectorSDNode::commuteMask(M);
1451 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1452 SDValue N2, ArrayRef<int> Mask) {
1453 assert(VT.getVectorNumElements() == Mask.size() &&
1454 "Must have the same number of vector elements as mask elements!");
1455 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1456 "Invalid VECTOR_SHUFFLE");
1458 // Canonicalize shuffle undef, undef -> undef
1459 if (N1.isUndef() && N2.isUndef())
1460 return getUNDEF(VT);
1462 // Validate that all indices in Mask are within the range of the elements
1463 // input to the shuffle.
1464 int NElts = Mask.size();
1465 assert(llvm::all_of(Mask, [&](int M) { return M < (NElts * 2); }) &&
1466 "Index out of range");
1468 // Copy the mask so we can do any needed cleanup.
1469 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1471 // Canonicalize shuffle v, v -> v, undef
1474 for (int i = 0; i != NElts; ++i)
1475 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1478 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1480 commuteShuffle(N1, N2, MaskVec);
1482 // If shuffling a splat, try to blend the splat instead. We do this here so
1483 // that even when this arises during lowering we don't have to re-handle it.
1484 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1485 BitVector UndefElements;
1486 SDValue Splat = BV->getSplatValue(&UndefElements);
1490 for (int i = 0; i < NElts; ++i) {
1491 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1494 // If this input comes from undef, mark it as such.
1495 if (UndefElements[MaskVec[i] - Offset]) {
1500 // If we can blend a non-undef lane, use that instead.
1501 if (!UndefElements[i])
1502 MaskVec[i] = i + Offset;
1505 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1506 BlendSplat(N1BV, 0);
1507 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1508 BlendSplat(N2BV, NElts);
1510 // Canonicalize all index into lhs, -> shuffle lhs, undef
1511 // Canonicalize all index into rhs, -> shuffle rhs, undef
1512 bool AllLHS = true, AllRHS = true;
1513 bool N2Undef = N2.isUndef();
1514 for (int i = 0; i != NElts; ++i) {
1515 if (MaskVec[i] >= NElts) {
1520 } else if (MaskVec[i] >= 0) {
1524 if (AllLHS && AllRHS)
1525 return getUNDEF(VT);
1526 if (AllLHS && !N2Undef)
1530 commuteShuffle(N1, N2, MaskVec);
1532 // Reset our undef status after accounting for the mask.
1533 N2Undef = N2.isUndef();
1534 // Re-check whether both sides ended up undef.
1535 if (N1.isUndef() && N2Undef)
1536 return getUNDEF(VT);
1538 // If Identity shuffle return that node.
1539 bool Identity = true, AllSame = true;
1540 for (int i = 0; i != NElts; ++i) {
1541 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1542 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1544 if (Identity && NElts)
1547 // Shuffling a constant splat doesn't change the result.
1551 // Look through any bitcasts. We check that these don't change the number
1552 // (and size) of elements and just changes their types.
1553 while (V.getOpcode() == ISD::BITCAST)
1554 V = V->getOperand(0);
1556 // A splat should always show up as a build vector node.
1557 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1558 BitVector UndefElements;
1559 SDValue Splat = BV->getSplatValue(&UndefElements);
1560 // If this is a splat of an undef, shuffling it is also undef.
1561 if (Splat && Splat.isUndef())
1562 return getUNDEF(VT);
1565 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1567 // We only have a splat which can skip shuffles if there is a splatted
1568 // value and no undef lanes rearranged by the shuffle.
1569 if (Splat && UndefElements.none()) {
1570 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1571 // number of elements match or the value splatted is a zero constant.
1574 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1575 if (C->isNullValue())
1579 // If the shuffle itself creates a splat, build the vector directly.
1580 if (AllSame && SameNumElts) {
1581 EVT BuildVT = BV->getValueType(0);
1582 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1583 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1585 // We may have jumped through bitcasts, so the type of the
1586 // BUILD_VECTOR may not match the type of the shuffle.
1588 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1594 FoldingSetNodeID ID;
1595 SDValue Ops[2] = { N1, N2 };
1596 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1597 for (int i = 0; i != NElts; ++i)
1598 ID.AddInteger(MaskVec[i]);
1601 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1602 return SDValue(E, 0);
1604 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1605 // SDNode doesn't have access to it. This memory will be "leaked" when
1606 // the node is deallocated, but recovered when the NodeAllocator is released.
1607 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1608 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1610 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1611 dl.getDebugLoc(), MaskAlloc);
1612 createOperands(N, Ops);
1614 CSEMap.InsertNode(N, IP);
1616 return SDValue(N, 0);
1619 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1620 MVT VT = SV.getSimpleValueType(0);
1621 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1622 ShuffleVectorSDNode::commuteMask(MaskVec);
1624 SDValue Op0 = SV.getOperand(0);
1625 SDValue Op1 = SV.getOperand(1);
1626 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1629 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1630 FoldingSetNodeID ID;
1631 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1632 ID.AddInteger(RegNo);
1634 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1635 return SDValue(E, 0);
1637 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1638 CSEMap.InsertNode(N, IP);
1640 return SDValue(N, 0);
1643 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1644 FoldingSetNodeID ID;
1645 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1646 ID.AddPointer(RegMask);
1648 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1649 return SDValue(E, 0);
1651 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1652 CSEMap.InsertNode(N, IP);
1654 return SDValue(N, 0);
1657 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1659 FoldingSetNodeID ID;
1660 SDValue Ops[] = { Root };
1661 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1662 ID.AddPointer(Label);
1664 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1665 return SDValue(E, 0);
1667 auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1668 createOperands(N, Ops);
1670 CSEMap.InsertNode(N, IP);
1672 return SDValue(N, 0);
1675 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1678 unsigned char TargetFlags) {
1679 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1681 FoldingSetNodeID ID;
1682 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1684 ID.AddInteger(Offset);
1685 ID.AddInteger(TargetFlags);
1687 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1688 return SDValue(E, 0);
1690 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1691 CSEMap.InsertNode(N, IP);
1693 return SDValue(N, 0);
1696 SDValue SelectionDAG::getSrcValue(const Value *V) {
1697 assert((!V || V->getType()->isPointerTy()) &&
1698 "SrcValue is not a pointer?");
1700 FoldingSetNodeID ID;
1701 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1705 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1706 return SDValue(E, 0);
1708 auto *N = newSDNode<SrcValueSDNode>(V);
1709 CSEMap.InsertNode(N, IP);
1711 return SDValue(N, 0);
1714 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1715 FoldingSetNodeID ID;
1716 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1720 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1721 return SDValue(E, 0);
1723 auto *N = newSDNode<MDNodeSDNode>(MD);
1724 CSEMap.InsertNode(N, IP);
1726 return SDValue(N, 0);
1729 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1730 if (VT == V.getValueType())
1733 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1736 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1737 unsigned SrcAS, unsigned DestAS) {
1738 SDValue Ops[] = {Ptr};
1739 FoldingSetNodeID ID;
1740 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1741 ID.AddInteger(SrcAS);
1742 ID.AddInteger(DestAS);
1745 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1746 return SDValue(E, 0);
1748 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1750 createOperands(N, Ops);
1752 CSEMap.InsertNode(N, IP);
1754 return SDValue(N, 0);
1757 /// getShiftAmountOperand - Return the specified value casted to
1758 /// the target's desired shift amount type.
1759 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1760 EVT OpTy = Op.getValueType();
1761 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1762 if (OpTy == ShTy || OpTy.isVector()) return Op;
1764 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1767 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1769 const TargetLowering &TLI = getTargetLoweringInfo();
1770 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1771 EVT VT = Node->getValueType(0);
1772 SDValue Tmp1 = Node->getOperand(0);
1773 SDValue Tmp2 = Node->getOperand(1);
1774 unsigned Align = Node->getConstantOperandVal(3);
1776 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1777 Tmp2, MachinePointerInfo(V));
1778 SDValue VAList = VAListLoad;
1780 if (Align > TLI.getMinStackArgumentAlignment()) {
1781 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1783 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1784 getConstant(Align - 1, dl, VAList.getValueType()));
1786 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1787 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1790 // Increment the pointer, VAList, to the next vaarg
1791 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1792 getConstant(getDataLayout().getTypeAllocSize(
1793 VT.getTypeForEVT(*getContext())),
1794 dl, VAList.getValueType()));
1795 // Store the incremented VAList to the legalized pointer
1797 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1798 // Load the actual argument out of the pointer VAList
1799 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1802 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1804 const TargetLowering &TLI = getTargetLoweringInfo();
1805 // This defaults to loading a pointer from the input and storing it to the
1806 // output, returning the chain.
1807 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1808 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1810 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1811 Node->getOperand(2), MachinePointerInfo(VS));
1812 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1813 MachinePointerInfo(VD));
1816 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1817 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1818 unsigned ByteSize = VT.getStoreSize();
1819 Type *Ty = VT.getTypeForEVT(*getContext());
1820 unsigned StackAlign =
1821 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1823 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1824 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1827 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1828 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1829 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1830 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1831 const DataLayout &DL = getDataLayout();
1833 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1835 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1836 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1837 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1840 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1841 ISD::CondCode Cond, const SDLoc &dl) {
1842 // These setcc operations always fold.
1846 case ISD::SETFALSE2: return getConstant(0, dl, VT);
1848 case ISD::SETTRUE2: {
1849 TargetLowering::BooleanContent Cnt =
1850 TLI->getBooleanContents(N1->getValueType(0));
1852 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1866 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1870 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1871 const APInt &C2 = N2C->getAPIntValue();
1872 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1873 const APInt &C1 = N1C->getAPIntValue();
1876 default: llvm_unreachable("Unknown integer setcc!");
1877 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT);
1878 case ISD::SETNE: return getConstant(C1 != C2, dl, VT);
1879 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1880 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1881 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1882 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1883 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT);
1884 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT);
1885 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT);
1886 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT);
1890 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1891 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1892 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1895 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1896 return getUNDEF(VT);
1898 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1899 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1900 return getUNDEF(VT);
1902 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1903 R==APFloat::cmpLessThan, dl, VT);
1904 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1905 return getUNDEF(VT);
1907 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1908 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1909 return getUNDEF(VT);
1911 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1912 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1913 return getUNDEF(VT);
1915 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1916 R==APFloat::cmpEqual, dl, VT);
1917 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1918 return getUNDEF(VT);
1920 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1921 R==APFloat::cmpEqual, dl, VT);
1922 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1923 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT);
1924 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1925 R==APFloat::cmpEqual, dl, VT);
1926 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1927 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1928 R==APFloat::cmpLessThan, dl, VT);
1929 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1930 R==APFloat::cmpUnordered, dl, VT);
1931 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1932 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1935 // Ensure that the constant occurs on the RHS.
1936 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1937 MVT CompVT = N1.getValueType().getSimpleVT();
1938 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1941 return getSetCC(dl, VT, N2, N1, SwappedCond);
1945 // Could not fold it.
1949 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1950 /// use this predicate to simplify operations downstream.
1951 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1952 unsigned BitWidth = Op.getScalarValueSizeInBits();
1953 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
1956 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1957 /// this predicate to simplify operations downstream. Mask is known to be zero
1958 /// for bits that V cannot have.
1959 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1960 unsigned Depth) const {
1962 computeKnownBits(Op, Known, Depth);
1963 return Mask.isSubsetOf(Known.Zero);
1966 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
1967 /// is less than the element bit-width of the shift node, return it.
1968 static const APInt *getValidShiftAmountConstant(SDValue V) {
1969 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
1970 // Shifting more than the bitwidth is not valid.
1971 const APInt &ShAmt = SA->getAPIntValue();
1972 if (ShAmt.ult(V.getScalarValueSizeInBits()))
1978 /// Determine which bits of Op are known to be either zero or one and return
1979 /// them in Known. For vectors, the known bits are those that are shared by
1980 /// every vector element.
1981 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
1982 unsigned Depth) const {
1983 EVT VT = Op.getValueType();
1984 APInt DemandedElts = VT.isVector()
1985 ? APInt::getAllOnesValue(VT.getVectorNumElements())
1987 computeKnownBits(Op, Known, DemandedElts, Depth);
1990 /// Determine which bits of Op are known to be either zero or one and return
1991 /// them in Known. The DemandedElts argument allows us to only collect the known
1992 /// bits that are shared by the requested vector elements.
1993 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
1994 const APInt &DemandedElts,
1995 unsigned Depth) const {
1996 unsigned BitWidth = Op.getScalarValueSizeInBits();
1998 Known = KnownBits(BitWidth); // Don't know anything.
2000 return; // Limit search depth.
2003 unsigned NumElts = DemandedElts.getBitWidth();
2006 return; // No demanded elts, better to assume we don't know anything.
2008 unsigned Opcode = Op.getOpcode();
2011 // We know all of the bits for a constant!
2012 Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
2013 Known.Zero = ~Known.One;
2015 case ISD::BUILD_VECTOR:
2016 // Collect the known bits that are shared by every demanded vector element.
2017 assert(NumElts == Op.getValueType().getVectorNumElements() &&
2018 "Unexpected vector size");
2019 Known.Zero.setAllBits(); Known.One.setAllBits();
2020 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2021 if (!DemandedElts[i])
2024 SDValue SrcOp = Op.getOperand(i);
2025 computeKnownBits(SrcOp, Known2, Depth + 1);
2027 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2028 if (SrcOp.getValueSizeInBits() != BitWidth) {
2029 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2030 "Expected BUILD_VECTOR implicit truncation");
2031 Known2 = Known2.trunc(BitWidth);
2034 // Known bits are the values that are shared by every demanded element.
2035 Known.One &= Known2.One;
2036 Known.Zero &= Known2.Zero;
2038 // If we don't know any bits, early out.
2039 if (!Known.One && !Known.Zero)
2043 case ISD::VECTOR_SHUFFLE: {
2044 // Collect the known bits that are shared by every vector element referenced
2046 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2047 Known.Zero.setAllBits(); Known.One.setAllBits();
2048 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2049 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2050 for (unsigned i = 0; i != NumElts; ++i) {
2051 if (!DemandedElts[i])
2054 int M = SVN->getMaskElt(i);
2056 // For UNDEF elements, we don't know anything about the common state of
2057 // the shuffle result.
2059 DemandedLHS.clearAllBits();
2060 DemandedRHS.clearAllBits();
2064 if ((unsigned)M < NumElts)
2065 DemandedLHS.setBit((unsigned)M % NumElts);
2067 DemandedRHS.setBit((unsigned)M % NumElts);
2069 // Known bits are the values that are shared by every demanded element.
2070 if (!!DemandedLHS) {
2071 SDValue LHS = Op.getOperand(0);
2072 computeKnownBits(LHS, Known2, DemandedLHS, Depth + 1);
2073 Known.One &= Known2.One;
2074 Known.Zero &= Known2.Zero;
2076 // If we don't know any bits, early out.
2077 if (!Known.One && !Known.Zero)
2079 if (!!DemandedRHS) {
2080 SDValue RHS = Op.getOperand(1);
2081 computeKnownBits(RHS, Known2, DemandedRHS, Depth + 1);
2082 Known.One &= Known2.One;
2083 Known.Zero &= Known2.Zero;
2087 case ISD::CONCAT_VECTORS: {
2088 // Split DemandedElts and test each of the demanded subvectors.
2089 Known.Zero.setAllBits(); Known.One.setAllBits();
2090 EVT SubVectorVT = Op.getOperand(0).getValueType();
2091 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2092 unsigned NumSubVectors = Op.getNumOperands();
2093 for (unsigned i = 0; i != NumSubVectors; ++i) {
2094 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2095 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2096 if (!!DemandedSub) {
2097 SDValue Sub = Op.getOperand(i);
2098 computeKnownBits(Sub, Known2, DemandedSub, Depth + 1);
2099 Known.One &= Known2.One;
2100 Known.Zero &= Known2.Zero;
2102 // If we don't know any bits, early out.
2103 if (!Known.One && !Known.Zero)
2108 case ISD::EXTRACT_SUBVECTOR: {
2109 // If we know the element index, just demand that subvector elements,
2110 // otherwise demand them all.
2111 SDValue Src = Op.getOperand(0);
2112 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2113 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2114 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2115 // Offset the demanded elts by the subvector index.
2116 uint64_t Idx = SubIdx->getZExtValue();
2117 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
2118 computeKnownBits(Src, Known, DemandedSrc, Depth + 1);
2120 computeKnownBits(Src, Known, Depth + 1);
2124 case ISD::BITCAST: {
2125 SDValue N0 = Op.getOperand(0);
2126 unsigned SubBitWidth = N0.getScalarValueSizeInBits();
2128 // Ignore bitcasts from floating point.
2129 if (!N0.getValueType().isInteger())
2132 // Fast handling of 'identity' bitcasts.
2133 if (BitWidth == SubBitWidth) {
2134 computeKnownBits(N0, Known, DemandedElts, Depth + 1);
2138 // Support big-endian targets when it becomes useful.
2139 bool IsLE = getDataLayout().isLittleEndian();
2143 // Bitcast 'small element' vector to 'large element' scalar/vector.
2144 if ((BitWidth % SubBitWidth) == 0) {
2145 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2147 // Collect known bits for the (larger) output by collecting the known
2148 // bits from each set of sub elements and shift these into place.
2149 // We need to separately call computeKnownBits for each set of
2150 // sub elements as the knownbits for each is likely to be different.
2151 unsigned SubScale = BitWidth / SubBitWidth;
2152 APInt SubDemandedElts(NumElts * SubScale, 0);
2153 for (unsigned i = 0; i != NumElts; ++i)
2154 if (DemandedElts[i])
2155 SubDemandedElts.setBit(i * SubScale);
2157 for (unsigned i = 0; i != SubScale; ++i) {
2158 computeKnownBits(N0, Known2, SubDemandedElts.shl(i),
2160 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * i);
2161 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * i);
2165 // Bitcast 'large element' scalar/vector to 'small element' vector.
2166 if ((SubBitWidth % BitWidth) == 0) {
2167 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2169 // Collect known bits for the (smaller) output by collecting the known
2170 // bits from the overlapping larger input elements and extracting the
2171 // sub sections we actually care about.
2172 unsigned SubScale = SubBitWidth / BitWidth;
2173 APInt SubDemandedElts(NumElts / SubScale, 0);
2174 for (unsigned i = 0; i != NumElts; ++i)
2175 if (DemandedElts[i])
2176 SubDemandedElts.setBit(i / SubScale);
2178 computeKnownBits(N0, Known2, SubDemandedElts, Depth + 1);
2180 Known.Zero.setAllBits(); Known.One.setAllBits();
2181 for (unsigned i = 0; i != NumElts; ++i)
2182 if (DemandedElts[i]) {
2183 unsigned Offset = (i % SubScale) * BitWidth;
2184 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2185 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2186 // If we don't know any bits, early out.
2187 if (!Known.One && !Known.Zero)
2194 // If either the LHS or the RHS are Zero, the result is zero.
2195 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2196 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2198 // Output known-1 bits are only known if set in both the LHS & RHS.
2199 Known.One &= Known2.One;
2200 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2201 Known.Zero |= Known2.Zero;
2204 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2205 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2207 // Output known-0 bits are only known if clear in both the LHS & RHS.
2208 Known.Zero &= Known2.Zero;
2209 // Output known-1 are known to be set if set in either the LHS | RHS.
2210 Known.One |= Known2.One;
2213 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2214 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2216 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2217 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2218 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2219 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2220 Known.Zero = KnownZeroOut;
2224 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2225 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2227 // If low bits are zero in either operand, output low known-0 bits.
2228 // Also compute a conservative estimate for high known-0 bits.
2229 // More trickiness is possible, but this is sufficient for the
2230 // interesting case of alignment computation.
2231 unsigned TrailZ = Known.countMinTrailingZeros() +
2232 Known2.countMinTrailingZeros();
2233 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2234 Known2.countMinLeadingZeros(),
2235 BitWidth) - BitWidth;
2238 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2239 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2243 // For the purposes of computing leading zeros we can conservatively
2244 // treat a udiv as a logical right shift by the power of 2 known to
2245 // be less than the denominator.
2246 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2247 unsigned LeadZ = Known2.countMinLeadingZeros();
2249 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2250 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2251 if (RHSMaxLeadingZeros != BitWidth)
2252 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2254 Known.Zero.setHighBits(LeadZ);
2258 computeKnownBits(Op.getOperand(2), Known, Depth+1);
2259 // If we don't know any bits, early out.
2260 if (!Known.One && !Known.Zero)
2262 computeKnownBits(Op.getOperand(1), Known2, Depth+1);
2264 // Only known if known in both the LHS and RHS.
2265 Known.One &= Known2.One;
2266 Known.Zero &= Known2.Zero;
2268 case ISD::SELECT_CC:
2269 computeKnownBits(Op.getOperand(3), Known, Depth+1);
2270 // If we don't know any bits, early out.
2271 if (!Known.One && !Known.Zero)
2273 computeKnownBits(Op.getOperand(2), Known2, Depth+1);
2275 // Only known if known in both the LHS and RHS.
2276 Known.One &= Known2.One;
2277 Known.Zero &= Known2.Zero;
2281 if (Op.getResNo() != 1)
2283 // The boolean result conforms to getBooleanContents.
2284 // If we know the result of a setcc has the top bits zero, use this info.
2285 // We know that we have an integer-based boolean since these operations
2286 // are only available for integer.
2287 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2288 TargetLowering::ZeroOrOneBooleanContent &&
2290 Known.Zero.setBitsFrom(1);
2293 // If we know the result of a setcc has the top bits zero, use this info.
2294 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2295 TargetLowering::ZeroOrOneBooleanContent &&
2297 Known.Zero.setBitsFrom(1);
2300 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2301 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2302 Known.Zero <<= *ShAmt;
2303 Known.One <<= *ShAmt;
2304 // Low bits are known zero.
2305 Known.Zero.setLowBits(ShAmt->getZExtValue());
2309 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2310 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2311 Known.Zero.lshrInPlace(*ShAmt);
2312 Known.One.lshrInPlace(*ShAmt);
2313 // High bits are known zero.
2314 Known.Zero.setHighBits(ShAmt->getZExtValue());
2318 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2319 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2320 Known.Zero.lshrInPlace(*ShAmt);
2321 Known.One.lshrInPlace(*ShAmt);
2322 // If we know the value of the sign bit, then we know it is copied across
2323 // the high bits by the shift amount.
2324 APInt SignMask = APInt::getSignMask(BitWidth);
2325 SignMask.lshrInPlace(*ShAmt); // Adjust to where it is now in the mask.
2326 if (Known.Zero.intersects(SignMask)) {
2327 Known.Zero.setHighBits(ShAmt->getZExtValue());// New bits are known zero.
2328 } else if (Known.One.intersects(SignMask)) {
2329 Known.One.setHighBits(ShAmt->getZExtValue()); // New bits are known one.
2333 case ISD::SIGN_EXTEND_INREG: {
2334 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2335 unsigned EBits = EVT.getScalarSizeInBits();
2337 // Sign extension. Compute the demanded bits in the result that are not
2338 // present in the input.
2339 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2341 APInt InSignMask = APInt::getSignMask(EBits);
2342 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2344 // If the sign extended bits are demanded, we know that the sign
2346 InSignMask = InSignMask.zext(BitWidth);
2347 if (NewBits.getBoolValue())
2348 InputDemandedBits |= InSignMask;
2350 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2351 Known.One &= InputDemandedBits;
2352 Known.Zero &= InputDemandedBits;
2354 // If the sign bit of the input is known set or clear, then we know the
2355 // top bits of the result.
2356 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2357 Known.Zero |= NewBits;
2358 Known.One &= ~NewBits;
2359 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2360 Known.One |= NewBits;
2361 Known.Zero &= ~NewBits;
2362 } else { // Input sign bit unknown
2363 Known.Zero &= ~NewBits;
2364 Known.One &= ~NewBits;
2369 case ISD::CTTZ_ZERO_UNDEF: {
2370 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2371 // If we have a known 1, its position is our upper bound.
2372 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2373 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2374 Known.Zero.setBitsFrom(LowBits);
2378 case ISD::CTLZ_ZERO_UNDEF: {
2379 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2380 // If we have a known 1, its position is our upper bound.
2381 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2382 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2383 Known.Zero.setBitsFrom(LowBits);
2387 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2388 // If we know some of the bits are zero, they can't be one.
2389 unsigned PossibleOnes = Known2.countMaxPopulation();
2390 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2394 LoadSDNode *LD = cast<LoadSDNode>(Op);
2395 // If this is a ZEXTLoad and we are looking at the loaded value.
2396 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2397 EVT VT = LD->getMemoryVT();
2398 unsigned MemBits = VT.getScalarSizeInBits();
2399 Known.Zero.setBitsFrom(MemBits);
2400 } else if (const MDNode *Ranges = LD->getRanges()) {
2401 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2402 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2406 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2407 EVT InVT = Op.getOperand(0).getValueType();
2408 unsigned InBits = InVT.getScalarSizeInBits();
2409 Known = Known.trunc(InBits);
2410 computeKnownBits(Op.getOperand(0), Known,
2411 DemandedElts.zext(InVT.getVectorNumElements()),
2413 Known = Known.zext(BitWidth);
2414 Known.Zero.setBitsFrom(InBits);
2417 case ISD::ZERO_EXTEND: {
2418 EVT InVT = Op.getOperand(0).getValueType();
2419 unsigned InBits = InVT.getScalarSizeInBits();
2420 Known = Known.trunc(InBits);
2421 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2422 Known = Known.zext(BitWidth);
2423 Known.Zero.setBitsFrom(InBits);
2426 // TODO ISD::SIGN_EXTEND_VECTOR_INREG
2427 case ISD::SIGN_EXTEND: {
2428 EVT InVT = Op.getOperand(0).getValueType();
2429 unsigned InBits = InVT.getScalarSizeInBits();
2431 Known = Known.trunc(InBits);
2432 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2434 // If the sign bit is known to be zero or one, then sext will extend
2435 // it to the top bits, else it will just zext.
2436 Known = Known.sext(BitWidth);
2439 case ISD::ANY_EXTEND: {
2440 EVT InVT = Op.getOperand(0).getValueType();
2441 unsigned InBits = InVT.getScalarSizeInBits();
2442 Known = Known.trunc(InBits);
2443 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2444 Known = Known.zext(BitWidth);
2447 case ISD::TRUNCATE: {
2448 EVT InVT = Op.getOperand(0).getValueType();
2449 unsigned InBits = InVT.getScalarSizeInBits();
2450 Known = Known.zext(InBits);
2451 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2452 Known = Known.trunc(BitWidth);
2455 case ISD::AssertZext: {
2456 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2457 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2458 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2459 Known.Zero |= (~InMask);
2460 Known.One &= (~Known.Zero);
2464 // All bits are zero except the low bit.
2465 Known.Zero.setBitsFrom(1);
2469 if (Op.getResNo() == 1) {
2470 // If we know the result of a setcc has the top bits zero, use this info.
2471 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2472 TargetLowering::ZeroOrOneBooleanContent &&
2474 Known.Zero.setBitsFrom(1);
2480 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2481 // We know that the top bits of C-X are clear if X contains less bits
2482 // than C (i.e. no wrap-around can happen). For example, 20-X is
2483 // positive if we can prove that X is >= 0 and < 16.
2484 if (CLHS->getAPIntValue().isNonNegative()) {
2485 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2486 // NLZ can't be BitWidth with no sign bit
2487 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2488 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2491 // If all of the MaskV bits are known to be zero, then we know the
2492 // output top bits are zero, because we now know that the output is
2494 if ((Known2.Zero & MaskV) == MaskV) {
2495 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2496 // Top bits known zero.
2497 Known.Zero.setHighBits(NLZ2);
2502 // If low bits are know to be zero in both operands, then we know they are
2503 // going to be 0 in the result. Both addition and complement operations
2504 // preserve the low zero bits.
2505 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2506 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2507 if (KnownZeroLow == 0)
2510 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2511 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2512 Known.Zero.setLowBits(KnownZeroLow);
2518 if (Op.getResNo() == 1) {
2519 // If we know the result of a setcc has the top bits zero, use this info.
2520 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2521 TargetLowering::ZeroOrOneBooleanContent &&
2523 Known.Zero.setBitsFrom(1);
2530 // Output known-0 bits are known if clear or set in both the low clear bits
2531 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2532 // low 3 bits clear.
2533 // Output known-0 bits are also known if the top bits of each input are
2534 // known to be clear. For example, if one input has the top 10 bits clear
2535 // and the other has the top 8 bits clear, we know the top 7 bits of the
2536 // output must be clear.
2537 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2538 unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
2539 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2541 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2543 KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
2544 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2546 if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) {
2547 // With ADDE and ADDCARRY, a carry bit may be added in, so we can only
2548 // use this information if we know (at least) that the low two bits are
2549 // clear. We then return to the caller that the low bit is unknown but
2550 // that other bits are known zero.
2551 if (KnownZeroLow >= 2)
2552 Known.Zero.setBits(1, KnownZeroLow);
2556 Known.Zero.setLowBits(KnownZeroLow);
2557 if (KnownZeroHigh > 1)
2558 Known.Zero.setHighBits(KnownZeroHigh - 1);
2562 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2563 const APInt &RA = Rem->getAPIntValue().abs();
2564 if (RA.isPowerOf2()) {
2565 APInt LowBits = RA - 1;
2566 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2568 // The low bits of the first operand are unchanged by the srem.
2569 Known.Zero = Known2.Zero & LowBits;
2570 Known.One = Known2.One & LowBits;
2572 // If the first operand is non-negative or has all low bits zero, then
2573 // the upper bits are all zero.
2574 if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
2575 Known.Zero |= ~LowBits;
2577 // If the first operand is negative and not all low bits are zero, then
2578 // the upper bits are all one.
2579 if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
2580 Known.One |= ~LowBits;
2581 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
2586 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2587 const APInt &RA = Rem->getAPIntValue();
2588 if (RA.isPowerOf2()) {
2589 APInt LowBits = (RA - 1);
2590 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2592 // The upper bits are all zero, the lower ones are unchanged.
2593 Known.Zero = Known2.Zero | ~LowBits;
2594 Known.One = Known2.One & LowBits;
2599 // Since the result is less than or equal to either operand, any leading
2600 // zero bits in either operand must also exist in the result.
2601 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2602 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2605 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
2607 Known.Zero.setHighBits(Leaders);
2610 case ISD::EXTRACT_ELEMENT: {
2611 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2612 const unsigned Index = Op.getConstantOperandVal(1);
2613 const unsigned BitWidth = Op.getValueSizeInBits();
2615 // Remove low part of known bits mask
2616 Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
2617 Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
2619 // Remove high part of known bit mask
2620 Known = Known.trunc(BitWidth);
2623 case ISD::EXTRACT_VECTOR_ELT: {
2624 SDValue InVec = Op.getOperand(0);
2625 SDValue EltNo = Op.getOperand(1);
2626 EVT VecVT = InVec.getValueType();
2627 const unsigned BitWidth = Op.getValueSizeInBits();
2628 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
2629 const unsigned NumSrcElts = VecVT.getVectorNumElements();
2630 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2631 // anything about the extended bits.
2632 if (BitWidth > EltBitWidth)
2633 Known = Known.trunc(EltBitWidth);
2634 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
2635 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
2636 // If we know the element index, just demand that vector element.
2637 unsigned Idx = ConstEltNo->getZExtValue();
2638 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
2639 computeKnownBits(InVec, Known, DemandedElt, Depth + 1);
2641 // Unknown element index, so ignore DemandedElts and demand them all.
2642 computeKnownBits(InVec, Known, Depth + 1);
2644 if (BitWidth > EltBitWidth)
2645 Known = Known.zext(BitWidth);
2648 case ISD::INSERT_VECTOR_ELT: {
2649 SDValue InVec = Op.getOperand(0);
2650 SDValue InVal = Op.getOperand(1);
2651 SDValue EltNo = Op.getOperand(2);
2653 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
2654 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
2655 // If we know the element index, split the demand between the
2656 // source vector and the inserted element.
2657 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
2658 unsigned EltIdx = CEltNo->getZExtValue();
2660 // If we demand the inserted element then add its common known bits.
2661 if (DemandedElts[EltIdx]) {
2662 computeKnownBits(InVal, Known2, Depth + 1);
2663 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2664 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
2667 // If we demand the source vector then add its common known bits, ensuring
2668 // that we don't demand the inserted element.
2669 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
2671 computeKnownBits(InVec, Known2, VectorElts, Depth + 1);
2672 Known.One &= Known2.One;
2673 Known.Zero &= Known2.Zero;
2676 // Unknown element index, so ignore DemandedElts and demand them all.
2677 computeKnownBits(InVec, Known, Depth + 1);
2678 computeKnownBits(InVal, Known2, Depth + 1);
2679 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2680 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
2684 case ISD::BITREVERSE: {
2685 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2686 Known.Zero = Known2.Zero.reverseBits();
2687 Known.One = Known2.One.reverseBits();
2691 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2692 Known.Zero = Known2.Zero.byteSwap();
2693 Known.One = Known2.One.byteSwap();
2697 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2699 // If the source's MSB is zero then we know the rest of the bits already.
2700 if (Known2.isNonNegative()) {
2701 Known.Zero = Known2.Zero;
2702 Known.One = Known2.One;
2706 // We only know that the absolute values's MSB will be zero iff there is
2707 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
2708 Known2.One.clearSignBit();
2709 if (Known2.One.getBoolValue()) {
2710 Known.Zero = APInt::getSignMask(BitWidth);
2716 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2717 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2719 // UMIN - we know that the result will have the maximum of the
2720 // known zero leading bits of the inputs.
2721 unsigned LeadZero = Known.countMinLeadingZeros();
2722 LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
2724 Known.Zero &= Known2.Zero;
2725 Known.One &= Known2.One;
2726 Known.Zero.setHighBits(LeadZero);
2730 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2732 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2734 // UMAX - we know that the result will have the maximum of the
2735 // known one leading bits of the inputs.
2736 unsigned LeadOne = Known.countMinLeadingOnes();
2737 LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
2739 Known.Zero &= Known2.Zero;
2740 Known.One &= Known2.One;
2741 Known.One.setHighBits(LeadOne);
2746 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2748 // If we don't know any bits, early out.
2749 if (!Known.One && !Known.Zero)
2751 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2752 Known.Zero &= Known2.Zero;
2753 Known.One &= Known2.One;
2756 case ISD::FrameIndex:
2757 case ISD::TargetFrameIndex:
2758 if (unsigned Align = InferPtrAlignment(Op)) {
2759 // The low bits are known zero if the pointer is aligned.
2760 Known.Zero.setLowBits(Log2_32(Align));
2766 if (Opcode < ISD::BUILTIN_OP_END)
2769 case ISD::INTRINSIC_WO_CHAIN:
2770 case ISD::INTRINSIC_W_CHAIN:
2771 case ISD::INTRINSIC_VOID:
2772 // Allow the target to implement this method for its nodes.
2773 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
2777 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
2780 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
2782 // X + 0 never overflow
2783 if (isNullConstant(N1))
2787 computeKnownBits(N1, N1Known);
2788 if (N1Known.Zero.getBoolValue()) {
2790 computeKnownBits(N0, N0Known);
2793 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
2798 // mulhi + 1 never overflow
2799 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
2800 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
2803 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
2805 computeKnownBits(N0, N0Known);
2807 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
2811 return OFK_Sometime;
2814 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2815 EVT OpVT = Val.getValueType();
2816 unsigned BitWidth = OpVT.getScalarSizeInBits();
2818 // Is the constant a known power of 2?
2819 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
2820 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2822 // A left-shift of a constant one will have exactly one bit set because
2823 // shifting the bit off the end is undefined.
2824 if (Val.getOpcode() == ISD::SHL) {
2825 auto *C = isConstOrConstSplat(Val.getOperand(0));
2826 if (C && C->getAPIntValue() == 1)
2830 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2832 if (Val.getOpcode() == ISD::SRL) {
2833 auto *C = isConstOrConstSplat(Val.getOperand(0));
2834 if (C && C->getAPIntValue().isSignMask())
2838 // Are all operands of a build vector constant powers of two?
2839 if (Val.getOpcode() == ISD::BUILD_VECTOR)
2840 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
2841 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
2842 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2847 // More could be done here, though the above checks are enough
2848 // to handle some common cases.
2850 // Fall back to computeKnownBits to catch other known cases.
2852 computeKnownBits(Val, Known);
2853 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
2856 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2857 EVT VT = Op.getValueType();
2858 APInt DemandedElts = VT.isVector()
2859 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2861 return ComputeNumSignBits(Op, DemandedElts, Depth);
2864 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2865 unsigned Depth) const {
2866 EVT VT = Op.getValueType();
2867 assert(VT.isInteger() && "Invalid VT!");
2868 unsigned VTBits = VT.getScalarSizeInBits();
2869 unsigned NumElts = DemandedElts.getBitWidth();
2871 unsigned FirstAnswer = 1;
2874 return 1; // Limit search depth.
2877 return 1; // No demanded elts, better to assume we don't know anything.
2879 switch (Op.getOpcode()) {
2881 case ISD::AssertSext:
2882 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2883 return VTBits-Tmp+1;
2884 case ISD::AssertZext:
2885 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2888 case ISD::Constant: {
2889 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2890 return Val.getNumSignBits();
2893 case ISD::BUILD_VECTOR:
2895 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
2896 if (!DemandedElts[i])
2899 SDValue SrcOp = Op.getOperand(i);
2900 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
2902 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2903 if (SrcOp.getValueSizeInBits() != VTBits) {
2904 assert(SrcOp.getValueSizeInBits() > VTBits &&
2905 "Expected BUILD_VECTOR implicit truncation");
2906 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
2907 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
2909 Tmp = std::min(Tmp, Tmp2);
2913 case ISD::VECTOR_SHUFFLE: {
2914 // Collect the minimum number of sign bits that are shared by every vector
2915 // element referenced by the shuffle.
2916 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2917 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2918 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2919 for (unsigned i = 0; i != NumElts; ++i) {
2920 int M = SVN->getMaskElt(i);
2921 if (!DemandedElts[i])
2923 // For UNDEF elements, we don't know anything about the common state of
2924 // the shuffle result.
2927 if ((unsigned)M < NumElts)
2928 DemandedLHS.setBit((unsigned)M % NumElts);
2930 DemandedRHS.setBit((unsigned)M % NumElts);
2932 Tmp = std::numeric_limits<unsigned>::max();
2934 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
2935 if (!!DemandedRHS) {
2936 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
2937 Tmp = std::min(Tmp, Tmp2);
2939 // If we don't know anything, early out and try computeKnownBits fall-back.
2942 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
2946 case ISD::SIGN_EXTEND:
2947 case ISD::SIGN_EXTEND_VECTOR_INREG:
2948 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
2949 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2951 case ISD::SIGN_EXTEND_INREG:
2952 // Max of the input and what this extends.
2953 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
2956 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2957 return std::max(Tmp, Tmp2);
2960 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
2961 // SRA X, C -> adds C sign bits.
2962 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2963 APInt ShiftVal = C->getAPIntValue();
2965 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
2969 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2970 // shl destroys sign bits.
2971 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2972 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
2973 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
2974 return Tmp - C->getZExtValue();
2979 case ISD::XOR: // NOT is handled here.
2980 // Logical binary ops preserve the number of sign bits at the worst.
2981 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2983 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2984 FirstAnswer = std::min(Tmp, Tmp2);
2985 // We computed what we know about the sign bits as our first
2986 // answer. Now proceed to the generic code that uses
2987 // computeKnownBits, and pick whichever answer is better.
2992 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2993 if (Tmp == 1) return 1; // Early out.
2994 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2995 return std::min(Tmp, Tmp2);
2996 case ISD::SELECT_CC:
2997 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2998 if (Tmp == 1) return 1; // Early out.
2999 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
3000 return std::min(Tmp, Tmp2);
3005 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3007 return 1; // Early out.
3008 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3009 return std::min(Tmp, Tmp2);
3016 if (Op.getResNo() != 1)
3018 // The boolean result conforms to getBooleanContents. Fall through.
3019 // If setcc returns 0/-1, all bits are sign bits.
3020 // We know that we have an integer-based boolean since these operations
3021 // are only available for integer.
3022 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3023 TargetLowering::ZeroOrNegativeOneBooleanContent)
3027 // If setcc returns 0/-1, all bits are sign bits.
3028 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3029 TargetLowering::ZeroOrNegativeOneBooleanContent)
3034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3035 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
3037 // Handle rotate right by N like a rotate left by 32-N.
3038 if (Op.getOpcode() == ISD::ROTR)
3039 RotAmt = (VTBits-RotAmt) & (VTBits-1);
3041 // If we aren't rotating out all of the known-in sign bits, return the
3042 // number that are left. This handles rotl(sext(x), 1) for example.
3043 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3044 if (Tmp > RotAmt+1) return Tmp-RotAmt;
3049 // Add can have at most one carry bit. Thus we know that the output
3050 // is, at worst, one more bit than the inputs.
3051 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3052 if (Tmp == 1) return 1; // Early out.
3054 // Special case decrementing a value (ADD X, -1):
3055 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3056 if (CRHS->isAllOnesValue()) {
3058 computeKnownBits(Op.getOperand(0), Known, Depth+1);
3060 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3062 if ((Known.Zero | 1).isAllOnesValue())
3065 // If we are subtracting one from a positive number, there is no carry
3066 // out of the result.
3067 if (Known.isNonNegative())
3071 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3072 if (Tmp2 == 1) return 1;
3073 return std::min(Tmp, Tmp2)-1;
3076 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3077 if (Tmp2 == 1) return 1;
3080 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3081 if (CLHS->isNullValue()) {
3083 computeKnownBits(Op.getOperand(1), Known, Depth+1);
3084 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3086 if ((Known.Zero | 1).isAllOnesValue())
3089 // If the input is known to be positive (the sign bit is known clear),
3090 // the output of the NEG has the same number of sign bits as the input.
3091 if (Known.isNonNegative())
3094 // Otherwise, we treat this like a SUB.
3097 // Sub can have at most one carry bit. Thus we know that the output
3098 // is, at worst, one more bit than the inputs.
3099 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3100 if (Tmp == 1) return 1; // Early out.
3101 return std::min(Tmp, Tmp2)-1;
3102 case ISD::TRUNCATE: {
3103 // Check if the sign bits of source go down as far as the truncated value.
3104 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3105 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3106 if (NumSrcSignBits > (NumSrcBits - VTBits))
3107 return NumSrcSignBits - (NumSrcBits - VTBits);
3110 case ISD::EXTRACT_ELEMENT: {
3111 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3112 const int BitWidth = Op.getValueSizeInBits();
3113 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3115 // Get reverse index (starting from 1), Op1 value indexes elements from
3116 // little end. Sign starts at big end.
3117 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3119 // If the sign portion ends in our element the subtraction gives correct
3120 // result. Otherwise it gives either negative or > bitwidth result
3121 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3123 case ISD::INSERT_VECTOR_ELT: {
3124 SDValue InVec = Op.getOperand(0);
3125 SDValue InVal = Op.getOperand(1);
3126 SDValue EltNo = Op.getOperand(2);
3127 unsigned NumElts = InVec.getValueType().getVectorNumElements();
3129 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3130 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3131 // If we know the element index, split the demand between the
3132 // source vector and the inserted element.
3133 unsigned EltIdx = CEltNo->getZExtValue();
3135 // If we demand the inserted element then get its sign bits.
3136 Tmp = std::numeric_limits<unsigned>::max();
3137 if (DemandedElts[EltIdx]) {
3138 // TODO - handle implicit truncation of inserted elements.
3139 if (InVal.getScalarValueSizeInBits() != VTBits)
3141 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3144 // If we demand the source vector then get its sign bits, and determine
3146 APInt VectorElts = DemandedElts;
3147 VectorElts.clearBit(EltIdx);
3149 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3150 Tmp = std::min(Tmp, Tmp2);
3153 // Unknown element index, so ignore DemandedElts and demand them all.
3154 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3155 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3156 Tmp = std::min(Tmp, Tmp2);
3158 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3161 case ISD::EXTRACT_VECTOR_ELT: {
3162 SDValue InVec = Op.getOperand(0);
3163 SDValue EltNo = Op.getOperand(1);
3164 EVT VecVT = InVec.getValueType();
3165 const unsigned BitWidth = Op.getValueSizeInBits();
3166 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3167 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3169 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3170 // anything about sign bits. But if the sizes match we can derive knowledge
3171 // about sign bits from the vector operand.
3172 if (BitWidth != EltBitWidth)
3175 // If we know the element index, just demand that vector element, else for
3176 // an unknown element index, ignore DemandedElts and demand them all.
3177 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3178 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3179 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3181 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3183 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3185 case ISD::EXTRACT_SUBVECTOR: {
3186 // If we know the element index, just demand that subvector elements,
3187 // otherwise demand them all.
3188 SDValue Src = Op.getOperand(0);
3189 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3190 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3191 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3192 // Offset the demanded elts by the subvector index.
3193 uint64_t Idx = SubIdx->getZExtValue();
3194 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
3195 return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3197 return ComputeNumSignBits(Src, Depth + 1);
3199 case ISD::CONCAT_VECTORS:
3200 // Determine the minimum number of sign bits across all demanded
3201 // elts of the input vectors. Early out if the result is already 1.
3202 Tmp = std::numeric_limits<unsigned>::max();
3203 EVT SubVectorVT = Op.getOperand(0).getValueType();
3204 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3205 unsigned NumSubVectors = Op.getNumOperands();
3206 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3207 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3208 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3211 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3212 Tmp = std::min(Tmp, Tmp2);
3214 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3218 // If we are looking at the loaded value of the SDNode.
3219 if (Op.getResNo() == 0) {
3220 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3221 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3222 unsigned ExtType = LD->getExtensionType();
3225 case ISD::SEXTLOAD: // '17' bits known
3226 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3227 return VTBits-Tmp+1;
3228 case ISD::ZEXTLOAD: // '16' bits known
3229 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3235 // Allow the target to implement this method for its nodes.
3236 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3237 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3238 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3239 Op.getOpcode() == ISD::INTRINSIC_VOID) {
3241 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3243 FirstAnswer = std::max(FirstAnswer, NumBits);
3246 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3247 // use this information.
3249 computeKnownBits(Op, Known, DemandedElts, Depth);
3252 if (Known.isNonNegative()) { // sign bit is 0
3254 } else if (Known.isNegative()) { // sign bit is 1;
3261 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3262 // the number of identical bits in the top of the input value.
3264 Mask <<= Mask.getBitWidth()-VTBits;
3265 // Return # leading zeros. We use 'min' here in case Val was zero before
3266 // shifting. We don't want to return '64' as for an i32 "0".
3267 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3270 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3271 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3272 !isa<ConstantSDNode>(Op.getOperand(1)))
3275 if (Op.getOpcode() == ISD::OR &&
3276 !MaskedValueIsZero(Op.getOperand(0),
3277 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3283 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
3284 // If we're told that NaNs won't happen, assume they won't.
3285 if (getTarget().Options.NoNaNsFPMath)
3288 if (Op->getFlags().hasNoNaNs())
3291 // If the value is a constant, we can obviously see if it is a NaN or not.
3292 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3293 return !C->getValueAPF().isNaN();
3295 // TODO: Recognize more cases here.
3300 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3301 // If the value is a constant, we can obviously see if it is a zero or not.
3302 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3303 return !C->isZero();
3305 // TODO: Recognize more cases here.
3306 switch (Op.getOpcode()) {
3309 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3310 return !C->isNullValue();
3317 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3318 // Check the obvious case.
3319 if (A == B) return true;
3321 // For for negative and positive zero.
3322 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3323 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3324 if (CA->isZero() && CB->isZero()) return true;
3326 // Otherwise they may not be equal.
3330 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3331 assert(A.getValueType() == B.getValueType() &&
3332 "Values must have the same type");
3333 KnownBits AKnown, BKnown;
3334 computeKnownBits(A, AKnown);
3335 computeKnownBits(B, BKnown);
3336 return (AKnown.Zero | BKnown.Zero).isAllOnesValue();
3339 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3340 ArrayRef<SDValue> Ops,
3341 SelectionDAG &DAG) {
3342 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3343 assert(llvm::all_of(Ops,
3345 return Ops[0].getValueType() == Op.getValueType();
3347 "Concatenation of vectors with inconsistent value types!");
3348 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3349 VT.getVectorNumElements() &&
3350 "Incorrect element count in vector concatenation!");
3352 if (Ops.size() == 1)
3355 // Concat of UNDEFs is UNDEF.
3356 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3357 return DAG.getUNDEF(VT);
3359 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3360 // simplified to one big BUILD_VECTOR.
3361 // FIXME: Add support for SCALAR_TO_VECTOR as well.
3362 EVT SVT = VT.getScalarType();
3363 SmallVector<SDValue, 16> Elts;
3364 for (SDValue Op : Ops) {
3365 EVT OpVT = Op.getValueType();
3367 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3368 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3369 Elts.append(Op->op_begin(), Op->op_end());
3374 // BUILD_VECTOR requires all inputs to be of the same type, find the
3375 // maximum type and extend them all.
3376 for (SDValue Op : Elts)
3377 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3379 if (SVT.bitsGT(VT.getScalarType()))
3380 for (SDValue &Op : Elts)
3381 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3382 ? DAG.getZExtOrTrunc(Op, DL, SVT)
3383 : DAG.getSExtOrTrunc(Op, DL, SVT);
3385 return DAG.getBuildVector(VT, DL, Elts);
3388 /// Gets or creates the specified node.
3389 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3390 FoldingSetNodeID ID;
3391 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3393 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3394 return SDValue(E, 0);
3396 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3398 CSEMap.InsertNode(N, IP);
3401 return SDValue(N, 0);
3404 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3405 SDValue Operand, const SDNodeFlags Flags) {
3406 // Constant fold unary operations with an integer constant operand. Even
3407 // opaque constant will be folded, because the folding of unary operations
3408 // doesn't create new constants with different values. Nevertheless, the
3409 // opaque flag is preserved during folding to prevent future folding with
3411 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3412 const APInt &Val = C->getAPIntValue();
3415 case ISD::SIGN_EXTEND:
3416 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3417 C->isTargetOpcode(), C->isOpaque());
3418 case ISD::ANY_EXTEND:
3419 case ISD::ZERO_EXTEND:
3421 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3422 C->isTargetOpcode(), C->isOpaque());
3423 case ISD::UINT_TO_FP:
3424 case ISD::SINT_TO_FP: {
3425 APFloat apf(EVTToAPFloatSemantics(VT),
3426 APInt::getNullValue(VT.getSizeInBits()));
3427 (void)apf.convertFromAPInt(Val,
3428 Opcode==ISD::SINT_TO_FP,
3429 APFloat::rmNearestTiesToEven);
3430 return getConstantFP(apf, DL, VT);
3433 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3434 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3435 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3436 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3437 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3438 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3439 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3440 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3443 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3445 case ISD::BITREVERSE:
3446 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3449 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3452 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3455 case ISD::CTLZ_ZERO_UNDEF:
3456 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3459 case ISD::CTTZ_ZERO_UNDEF:
3460 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3462 case ISD::FP16_TO_FP: {
3464 APFloat FPV(APFloat::IEEEhalf(),
3465 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3467 // This can return overflow, underflow, or inexact; we don't care.
3468 // FIXME need to be more flexible about rounding mode.
3469 (void)FPV.convert(EVTToAPFloatSemantics(VT),
3470 APFloat::rmNearestTiesToEven, &Ignored);
3471 return getConstantFP(FPV, DL, VT);
3476 // Constant fold unary operations with a floating point constant operand.
3477 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3478 APFloat V = C->getValueAPF(); // make copy
3482 return getConstantFP(V, DL, VT);
3485 return getConstantFP(V, DL, VT);
3487 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3488 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3489 return getConstantFP(V, DL, VT);
3493 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3494 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3495 return getConstantFP(V, DL, VT);
3499 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3500 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3501 return getConstantFP(V, DL, VT);
3504 case ISD::FP_EXTEND: {
3506 // This can return overflow, underflow, or inexact; we don't care.
3507 // FIXME need to be more flexible about rounding mode.
3508 (void)V.convert(EVTToAPFloatSemantics(VT),
3509 APFloat::rmNearestTiesToEven, &ignored);
3510 return getConstantFP(V, DL, VT);
3512 case ISD::FP_TO_SINT:
3513 case ISD::FP_TO_UINT: {
3515 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3516 // FIXME need to be more flexible about rounding mode.
3517 APFloat::opStatus s =
3518 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3519 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3521 return getConstant(IntVal, DL, VT);
3524 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3525 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3526 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3527 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3528 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3529 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3531 case ISD::FP_TO_FP16: {
3533 // This can return overflow, underflow, or inexact; we don't care.
3534 // FIXME need to be more flexible about rounding mode.
3535 (void)V.convert(APFloat::IEEEhalf(),
3536 APFloat::rmNearestTiesToEven, &Ignored);
3537 return getConstant(V.bitcastToAPInt(), DL, VT);
3542 // Constant fold unary operations with a vector integer or float operand.
3543 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3544 if (BV->isConstant()) {
3547 // FIXME: Entirely reasonable to perform folding of other unary
3548 // operations here as the need arises.
3555 case ISD::FP_EXTEND:
3556 case ISD::FP_TO_SINT:
3557 case ISD::FP_TO_UINT:
3559 case ISD::UINT_TO_FP:
3560 case ISD::SINT_TO_FP:
3562 case ISD::BITREVERSE:
3565 case ISD::CTLZ_ZERO_UNDEF:
3567 case ISD::CTTZ_ZERO_UNDEF:
3569 SDValue Ops = { Operand };
3570 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3577 unsigned OpOpcode = Operand.getNode()->getOpcode();
3579 case ISD::TokenFactor:
3580 case ISD::MERGE_VALUES:
3581 case ISD::CONCAT_VECTORS:
3582 return Operand; // Factor, merge or concat of one node? No need.
3583 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3584 case ISD::FP_EXTEND:
3585 assert(VT.isFloatingPoint() &&
3586 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3587 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3588 assert((!VT.isVector() ||
3589 VT.getVectorNumElements() ==
3590 Operand.getValueType().getVectorNumElements()) &&
3591 "Vector element count mismatch!");
3592 assert(Operand.getValueType().bitsLT(VT) &&
3593 "Invalid fpext node, dst < src!");
3594 if (Operand.isUndef())
3595 return getUNDEF(VT);
3597 case ISD::SIGN_EXTEND:
3598 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3599 "Invalid SIGN_EXTEND!");
3600 if (Operand.getValueType() == VT) return Operand; // noop extension
3601 assert((!VT.isVector() ||
3602 VT.getVectorNumElements() ==
3603 Operand.getValueType().getVectorNumElements()) &&
3604 "Vector element count mismatch!");
3605 assert(Operand.getValueType().bitsLT(VT) &&
3606 "Invalid sext node, dst < src!");
3607 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3608 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3609 else if (OpOpcode == ISD::UNDEF)
3610 // sext(undef) = 0, because the top bits will all be the same.
3611 return getConstant(0, DL, VT);
3613 case ISD::ZERO_EXTEND:
3614 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3615 "Invalid ZERO_EXTEND!");
3616 if (Operand.getValueType() == VT) return Operand; // noop extension
3617 assert((!VT.isVector() ||
3618 VT.getVectorNumElements() ==
3619 Operand.getValueType().getVectorNumElements()) &&
3620 "Vector element count mismatch!");
3621 assert(Operand.getValueType().bitsLT(VT) &&
3622 "Invalid zext node, dst < src!");
3623 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3624 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
3625 else if (OpOpcode == ISD::UNDEF)
3626 // zext(undef) = 0, because the top bits will be zero.
3627 return getConstant(0, DL, VT);
3629 case ISD::ANY_EXTEND:
3630 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3631 "Invalid ANY_EXTEND!");
3632 if (Operand.getValueType() == VT) return Operand; // noop extension
3633 assert((!VT.isVector() ||
3634 VT.getVectorNumElements() ==
3635 Operand.getValueType().getVectorNumElements()) &&
3636 "Vector element count mismatch!");
3637 assert(Operand.getValueType().bitsLT(VT) &&
3638 "Invalid anyext node, dst < src!");
3640 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3641 OpOpcode == ISD::ANY_EXTEND)
3642 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3643 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3644 else if (OpOpcode == ISD::UNDEF)
3645 return getUNDEF(VT);
3647 // (ext (trunx x)) -> x
3648 if (OpOpcode == ISD::TRUNCATE) {
3649 SDValue OpOp = Operand.getOperand(0);
3650 if (OpOp.getValueType() == VT)
3655 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3656 "Invalid TRUNCATE!");
3657 if (Operand.getValueType() == VT) return Operand; // noop truncate
3658 assert((!VT.isVector() ||
3659 VT.getVectorNumElements() ==
3660 Operand.getValueType().getVectorNumElements()) &&
3661 "Vector element count mismatch!");
3662 assert(Operand.getValueType().bitsGT(VT) &&
3663 "Invalid truncate node, src < dst!");
3664 if (OpOpcode == ISD::TRUNCATE)
3665 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
3666 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3667 OpOpcode == ISD::ANY_EXTEND) {
3668 // If the source is smaller than the dest, we still need an extend.
3669 if (Operand.getOperand(0).getValueType().getScalarType()
3670 .bitsLT(VT.getScalarType()))
3671 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3672 if (Operand.getOperand(0).getValueType().bitsGT(VT))
3673 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
3674 return Operand.getOperand(0);
3676 if (OpOpcode == ISD::UNDEF)
3677 return getUNDEF(VT);
3680 assert(VT.isInteger() && VT == Operand.getValueType() &&
3682 if (OpOpcode == ISD::UNDEF)
3683 return getUNDEF(VT);
3686 assert(VT.isInteger() && VT == Operand.getValueType() &&
3688 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3689 "BSWAP types must be a multiple of 16 bits!");
3690 if (OpOpcode == ISD::UNDEF)
3691 return getUNDEF(VT);
3693 case ISD::BITREVERSE:
3694 assert(VT.isInteger() && VT == Operand.getValueType() &&
3695 "Invalid BITREVERSE!");
3696 if (OpOpcode == ISD::UNDEF)
3697 return getUNDEF(VT);
3700 // Basic sanity checking.
3701 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3702 "Cannot BITCAST between types of different sizes!");
3703 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3704 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3705 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3706 if (OpOpcode == ISD::UNDEF)
3707 return getUNDEF(VT);
3709 case ISD::SCALAR_TO_VECTOR:
3710 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3711 (VT.getVectorElementType() == Operand.getValueType() ||
3712 (VT.getVectorElementType().isInteger() &&
3713 Operand.getValueType().isInteger() &&
3714 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3715 "Illegal SCALAR_TO_VECTOR node!");
3716 if (OpOpcode == ISD::UNDEF)
3717 return getUNDEF(VT);
3718 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3719 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3720 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3721 Operand.getConstantOperandVal(1) == 0 &&
3722 Operand.getOperand(0).getValueType() == VT)
3723 return Operand.getOperand(0);
3726 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3727 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3728 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3729 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
3730 Operand.getOperand(0), Operand.getNode()->getFlags());
3731 if (OpOpcode == ISD::FNEG) // --X -> X
3732 return Operand.getOperand(0);
3735 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3736 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
3741 SDVTList VTs = getVTList(VT);
3742 SDValue Ops[] = {Operand};
3743 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3744 FoldingSetNodeID ID;
3745 AddNodeIDNode(ID, Opcode, VTs, Ops);
3747 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
3748 E->intersectFlagsWith(Flags);
3749 return SDValue(E, 0);
3752 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3754 createOperands(N, Ops);
3755 CSEMap.InsertNode(N, IP);
3757 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3758 createOperands(N, Ops);
3762 return SDValue(N, 0);
3765 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3768 case ISD::ADD: return std::make_pair(C1 + C2, true);
3769 case ISD::SUB: return std::make_pair(C1 - C2, true);
3770 case ISD::MUL: return std::make_pair(C1 * C2, true);
3771 case ISD::AND: return std::make_pair(C1 & C2, true);
3772 case ISD::OR: return std::make_pair(C1 | C2, true);
3773 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3774 case ISD::SHL: return std::make_pair(C1 << C2, true);
3775 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3776 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3777 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3778 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3779 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3780 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3781 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3782 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3784 if (!C2.getBoolValue())
3786 return std::make_pair(C1.udiv(C2), true);
3788 if (!C2.getBoolValue())
3790 return std::make_pair(C1.urem(C2), true);
3792 if (!C2.getBoolValue())
3794 return std::make_pair(C1.sdiv(C2), true);
3796 if (!C2.getBoolValue())
3798 return std::make_pair(C1.srem(C2), true);
3800 return std::make_pair(APInt(1, 0), false);
3803 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3804 EVT VT, const ConstantSDNode *Cst1,
3805 const ConstantSDNode *Cst2) {
3806 if (Cst1->isOpaque() || Cst2->isOpaque())
3809 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3810 Cst2->getAPIntValue());
3813 return getConstant(Folded.first, DL, VT);
3816 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3817 const GlobalAddressSDNode *GA,
3819 if (GA->getOpcode() != ISD::GlobalAddress)
3821 if (!TLI->isOffsetFoldingLegal(GA))
3823 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3826 int64_t Offset = Cst2->getSExtValue();
3828 case ISD::ADD: break;
3829 case ISD::SUB: Offset = -uint64_t(Offset); break;
3830 default: return SDValue();
3832 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3833 GA->getOffset() + uint64_t(Offset));
3836 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
3842 // If a divisor is zero/undef or any element of a divisor vector is
3843 // zero/undef, the whole op is undef.
3844 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
3845 SDValue Divisor = Ops[1];
3846 if (Divisor.isUndef() || isNullConstant(Divisor))
3849 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
3850 llvm::any_of(Divisor->op_values(),
3851 [](SDValue V) { return V.isUndef() ||
3852 isNullConstant(V); });
3853 // TODO: Handle signed overflow.
3855 // TODO: Handle oversized shifts.
3861 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3862 EVT VT, SDNode *Cst1,
3864 // If the opcode is a target-specific ISD node, there's nothing we can
3865 // do here and the operand rules may not line up with the below, so
3867 if (Opcode >= ISD::BUILTIN_OP_END)
3870 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
3871 return getUNDEF(VT);
3873 // Handle the case of two scalars.
3874 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3875 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3876 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3877 assert((!Folded || !VT.isVector()) &&
3878 "Can't fold vectors ops with scalar operands");
3883 // fold (add Sym, c) -> Sym+c
3884 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3885 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3886 if (isCommutativeBinOp(Opcode))
3887 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3888 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3890 // For vectors extract each constant element into Inputs so we can constant
3891 // fold them individually.
3892 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3893 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3897 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3899 EVT SVT = VT.getScalarType();
3900 SmallVector<SDValue, 4> Outputs;
3901 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3902 SDValue V1 = BV1->getOperand(I);
3903 SDValue V2 = BV2->getOperand(I);
3905 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3906 // FIXME: This is valid and could be handled by truncation.
3907 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3910 // Fold one vector element.
3911 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
3913 // Scalar folding only succeeded if the result is a constant or UNDEF.
3914 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3915 ScalarResult.getOpcode() != ISD::ConstantFP)
3917 Outputs.push_back(ScalarResult);
3920 assert(VT.getVectorNumElements() == Outputs.size() &&
3921 "Vector size mismatch!");
3923 // We may have a vector type but a scalar result. Create a splat.
3924 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3926 // Build a big vector out of the scalar elements we generated.
3927 return getBuildVector(VT, SDLoc(), Outputs);
3930 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3931 const SDLoc &DL, EVT VT,
3932 ArrayRef<SDValue> Ops,
3933 const SDNodeFlags Flags) {
3934 // If the opcode is a target-specific ISD node, there's nothing we can
3935 // do here and the operand rules may not line up with the below, so
3937 if (Opcode >= ISD::BUILTIN_OP_END)
3940 if (isUndef(Opcode, Ops))
3941 return getUNDEF(VT);
3943 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3947 unsigned NumElts = VT.getVectorNumElements();
3949 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3950 return !Op.getValueType().isVector() ||
3951 Op.getValueType().getVectorNumElements() == NumElts;
3954 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3955 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3956 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3957 (BV && BV->isConstant());
3960 // All operands must be vector types with the same number of elements as
3961 // the result type and must be either UNDEF or a build vector of constant
3962 // or UNDEF scalars.
3963 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
3964 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
3967 // If we are comparing vectors, then the result needs to be a i1 boolean
3968 // that is then sign-extended back to the legal result type.
3969 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3971 // Find legal integer scalar type for constant promotion and
3972 // ensure that its scalar size is at least as large as source.
3973 EVT LegalSVT = VT.getScalarType();
3974 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
3975 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3976 if (LegalSVT.bitsLT(VT.getScalarType()))
3980 // Constant fold each scalar lane separately.
3981 SmallVector<SDValue, 4> ScalarResults;
3982 for (unsigned i = 0; i != NumElts; i++) {
3983 SmallVector<SDValue, 4> ScalarOps;
3984 for (SDValue Op : Ops) {
3985 EVT InSVT = Op.getValueType().getScalarType();
3986 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3988 // We've checked that this is UNDEF or a constant of some kind.
3990 ScalarOps.push_back(getUNDEF(InSVT));
3992 ScalarOps.push_back(Op);
3996 SDValue ScalarOp = InBV->getOperand(i);
3997 EVT ScalarVT = ScalarOp.getValueType();
3999 // Build vector (integer) scalar operands may need implicit
4000 // truncation - do this before constant folding.
4001 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4002 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4004 ScalarOps.push_back(ScalarOp);
4007 // Constant fold the scalar operands.
4008 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4010 // Legalize the (integer) scalar constant if necessary.
4011 if (LegalSVT != SVT)
4012 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4014 // Scalar folding only succeeded if the result is a constant or UNDEF.
4015 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4016 ScalarResult.getOpcode() != ISD::ConstantFP)
4018 ScalarResults.push_back(ScalarResult);
4021 return getBuildVector(VT, DL, ScalarResults);
4024 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4025 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
4026 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4027 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4028 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4029 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4031 // Canonicalize constant to RHS if commutative.
4032 if (isCommutativeBinOp(Opcode)) {
4034 std::swap(N1C, N2C);
4036 } else if (N1CFP && !N2CFP) {
4037 std::swap(N1CFP, N2CFP);
4044 case ISD::TokenFactor:
4045 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4046 N2.getValueType() == MVT::Other && "Invalid token factor!");
4047 // Fold trivial token factors.
4048 if (N1.getOpcode() == ISD::EntryToken) return N2;
4049 if (N2.getOpcode() == ISD::EntryToken) return N1;
4050 if (N1 == N2) return N1;
4052 case ISD::CONCAT_VECTORS: {
4053 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4054 SDValue Ops[] = {N1, N2};
4055 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4060 assert(VT.isInteger() && "This operator does not apply to FP types!");
4061 assert(N1.getValueType() == N2.getValueType() &&
4062 N1.getValueType() == VT && "Binary operator types must match!");
4063 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4064 // worth handling here.
4065 if (N2C && N2C->isNullValue())
4067 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4074 assert(VT.isInteger() && "This operator does not apply to FP types!");
4075 assert(N1.getValueType() == N2.getValueType() &&
4076 N1.getValueType() == VT && "Binary operator types must match!");
4077 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4078 // it's worth handling here.
4079 if (N2C && N2C->isNullValue())
4093 assert(VT.isInteger() && "This operator does not apply to FP types!");
4094 assert(N1.getValueType() == N2.getValueType() &&
4095 N1.getValueType() == VT && "Binary operator types must match!");
4102 if (getTarget().Options.UnsafeFPMath) {
4103 if (Opcode == ISD::FADD) {
4105 if (N2CFP && N2CFP->getValueAPF().isZero())
4107 } else if (Opcode == ISD::FSUB) {
4109 if (N2CFP && N2CFP->getValueAPF().isZero())
4111 } else if (Opcode == ISD::FMUL) {
4113 if (N2CFP && N2CFP->isZero())
4116 if (N2CFP && N2CFP->isExactlyValue(1.0))
4120 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4121 assert(N1.getValueType() == N2.getValueType() &&
4122 N1.getValueType() == VT && "Binary operator types must match!");
4124 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4125 assert(N1.getValueType() == VT &&
4126 N1.getValueType().isFloatingPoint() &&
4127 N2.getValueType().isFloatingPoint() &&
4128 "Invalid FCOPYSIGN!");
4135 assert(VT == N1.getValueType() &&
4136 "Shift operators return type must be the same as their first arg");
4137 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4138 "Shifts only work on integers");
4139 assert((!VT.isVector() || VT == N2.getValueType()) &&
4140 "Vector shift amounts must be in the same as their first arg");
4141 // Verify that the shift amount VT is bit enough to hold valid shift
4142 // amounts. This catches things like trying to shift an i1024 value by an
4143 // i8, which is easy to fall into in generic code that uses
4144 // TLI.getShiftAmount().
4145 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4146 "Invalid use of small shift amount with oversized value!");
4148 // Always fold shifts of i1 values so the code generator doesn't need to
4149 // handle them. Since we know the size of the shift has to be less than the
4150 // size of the value, the shift/rotate count is guaranteed to be zero.
4153 if (N2C && N2C->isNullValue())
4156 case ISD::FP_ROUND_INREG: {
4157 EVT EVT = cast<VTSDNode>(N2)->getVT();
4158 assert(VT == N1.getValueType() && "Not an inreg round!");
4159 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4160 "Cannot FP_ROUND_INREG integer types");
4161 assert(EVT.isVector() == VT.isVector() &&
4162 "FP_ROUND_INREG type should be vector iff the operand "
4164 assert((!EVT.isVector() ||
4165 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4166 "Vector element counts must match in FP_ROUND_INREG");
4167 assert(EVT.bitsLE(VT) && "Not rounding down!");
4169 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4173 assert(VT.isFloatingPoint() &&
4174 N1.getValueType().isFloatingPoint() &&
4175 VT.bitsLE(N1.getValueType()) &&
4176 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4177 "Invalid FP_ROUND!");
4178 if (N1.getValueType() == VT) return N1; // noop conversion.
4180 case ISD::AssertSext:
4181 case ISD::AssertZext: {
4182 EVT EVT = cast<VTSDNode>(N2)->getVT();
4183 assert(VT == N1.getValueType() && "Not an inreg extend!");
4184 assert(VT.isInteger() && EVT.isInteger() &&
4185 "Cannot *_EXTEND_INREG FP types");
4186 assert(!EVT.isVector() &&
4187 "AssertSExt/AssertZExt type should be the vector element type "
4188 "rather than the vector type!");
4189 assert(EVT.bitsLE(VT) && "Not extending!");
4190 if (VT == EVT) return N1; // noop assertion.
4193 case ISD::SIGN_EXTEND_INREG: {
4194 EVT EVT = cast<VTSDNode>(N2)->getVT();
4195 assert(VT == N1.getValueType() && "Not an inreg extend!");
4196 assert(VT.isInteger() && EVT.isInteger() &&
4197 "Cannot *_EXTEND_INREG FP types");
4198 assert(EVT.isVector() == VT.isVector() &&
4199 "SIGN_EXTEND_INREG type should be vector iff the operand "
4201 assert((!EVT.isVector() ||
4202 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4203 "Vector element counts must match in SIGN_EXTEND_INREG");
4204 assert(EVT.bitsLE(VT) && "Not extending!");
4205 if (EVT == VT) return N1; // Not actually extending
4207 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4208 unsigned FromBits = EVT.getScalarSizeInBits();
4209 Val <<= Val.getBitWidth() - FromBits;
4210 Val.ashrInPlace(Val.getBitWidth() - FromBits);
4211 return getConstant(Val, DL, ConstantVT);
4215 const APInt &Val = N1C->getAPIntValue();
4216 return SignExtendInReg(Val, VT);
4218 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4219 SmallVector<SDValue, 8> Ops;
4220 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4221 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4222 SDValue Op = N1.getOperand(i);
4224 Ops.push_back(getUNDEF(OpVT));
4227 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4228 APInt Val = C->getAPIntValue();
4229 Ops.push_back(SignExtendInReg(Val, OpVT));
4231 return getBuildVector(VT, DL, Ops);
4235 case ISD::EXTRACT_VECTOR_ELT:
4236 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4238 return getUNDEF(VT);
4240 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4241 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4242 return getUNDEF(VT);
4244 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4245 // expanding copies of large vectors from registers.
4247 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4248 N1.getNumOperands() > 0) {
4250 N1.getOperand(0).getValueType().getVectorNumElements();
4251 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4252 N1.getOperand(N2C->getZExtValue() / Factor),
4253 getConstant(N2C->getZExtValue() % Factor, DL,
4254 N2.getValueType()));
4257 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4258 // expanding large vector constants.
4259 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4260 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4262 if (VT != Elt.getValueType())
4263 // If the vector element type is not legal, the BUILD_VECTOR operands
4264 // are promoted and implicitly truncated, and the result implicitly
4265 // extended. Make that explicit here.
4266 Elt = getAnyExtOrTrunc(Elt, DL, VT);
4271 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4272 // operations are lowered to scalars.
4273 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4274 // If the indices are the same, return the inserted element else
4275 // if the indices are known different, extract the element from
4276 // the original vector.
4277 SDValue N1Op2 = N1.getOperand(2);
4278 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4280 if (N1Op2C && N2C) {
4281 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4282 if (VT == N1.getOperand(1).getValueType())
4283 return N1.getOperand(1);
4285 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4288 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4292 case ISD::EXTRACT_ELEMENT:
4293 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4294 assert(!N1.getValueType().isVector() && !VT.isVector() &&
4295 (N1.getValueType().isInteger() == VT.isInteger()) &&
4296 N1.getValueType() != VT &&
4297 "Wrong types for EXTRACT_ELEMENT!");
4299 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4300 // 64-bit integers into 32-bit parts. Instead of building the extract of
4301 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4302 if (N1.getOpcode() == ISD::BUILD_PAIR)
4303 return N1.getOperand(N2C->getZExtValue());
4305 // EXTRACT_ELEMENT of a constant int is also very common.
4307 unsigned ElementSize = VT.getSizeInBits();
4308 unsigned Shift = ElementSize * N2C->getZExtValue();
4309 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4310 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4313 case ISD::EXTRACT_SUBVECTOR:
4314 if (VT.isSimple() && N1.getValueType().isSimple()) {
4315 assert(VT.isVector() && N1.getValueType().isVector() &&
4316 "Extract subvector VTs must be a vectors!");
4317 assert(VT.getVectorElementType() ==
4318 N1.getValueType().getVectorElementType() &&
4319 "Extract subvector VTs must have the same element type!");
4320 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4321 "Extract subvector must be from larger vector to smaller vector!");
4324 assert((VT.getVectorNumElements() + N2C->getZExtValue()
4325 <= N1.getValueType().getVectorNumElements())
4326 && "Extract subvector overflow!");
4329 // Trivial extraction.
4330 if (VT.getSimpleVT() == N1.getSimpleValueType())
4333 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4335 return getUNDEF(VT);
4337 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4338 // the concat have the same type as the extract.
4339 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4340 N1.getNumOperands() > 0 &&
4341 VT == N1.getOperand(0).getValueType()) {
4342 unsigned Factor = VT.getVectorNumElements();
4343 return N1.getOperand(N2C->getZExtValue() / Factor);
4346 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4347 // during shuffle legalization.
4348 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4349 VT == N1.getOperand(1).getValueType())
4350 return N1.getOperand(1);
4355 // Perform trivial constant folding.
4357 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4360 // Constant fold FP operations.
4361 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4364 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4365 APFloat::opStatus s;
4368 s = V1.add(V2, APFloat::rmNearestTiesToEven);
4369 if (!HasFPExceptions || s != APFloat::opInvalidOp)
4370 return getConstantFP(V1, DL, VT);
4373 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4374 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4375 return getConstantFP(V1, DL, VT);
4378 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4379 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4380 return getConstantFP(V1, DL, VT);
4383 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4384 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4385 s!=APFloat::opDivByZero)) {
4386 return getConstantFP(V1, DL, VT);
4391 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4392 s!=APFloat::opDivByZero)) {
4393 return getConstantFP(V1, DL, VT);
4396 case ISD::FCOPYSIGN:
4398 return getConstantFP(V1, DL, VT);
4403 if (Opcode == ISD::FP_ROUND) {
4404 APFloat V = N1CFP->getValueAPF(); // make copy
4406 // This can return overflow, underflow, or inexact; we don't care.
4407 // FIXME need to be more flexible about rounding mode.
4408 (void)V.convert(EVTToAPFloatSemantics(VT),
4409 APFloat::rmNearestTiesToEven, &ignored);
4410 return getConstantFP(V, DL, VT);
4414 // Canonicalize an UNDEF to the RHS, even over a constant.
4416 if (isCommutativeBinOp(Opcode)) {
4420 case ISD::FP_ROUND_INREG:
4421 case ISD::SIGN_EXTEND_INREG:
4427 return N1; // fold op(undef, arg2) -> undef
4435 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
4436 // For vectors, we can't easily build an all zero vector, just return
4443 // Fold a bunch of operators when the RHS is undef.
4448 // Handle undef ^ undef -> 0 special case. This is a common
4450 return getConstant(0, DL, VT);
4460 return N2; // fold op(arg1, undef) -> undef
4466 if (getTarget().Options.UnsafeFPMath)
4474 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
4475 // For vectors, we can't easily build an all zero vector, just return
4480 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
4481 // For vectors, we can't easily build an all one vector, just return
4489 // Memoize this node if possible.
4491 SDVTList VTs = getVTList(VT);
4492 SDValue Ops[] = {N1, N2};
4493 if (VT != MVT::Glue) {
4494 FoldingSetNodeID ID;
4495 AddNodeIDNode(ID, Opcode, VTs, Ops);
4497 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4498 E->intersectFlagsWith(Flags);
4499 return SDValue(E, 0);
4502 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4504 createOperands(N, Ops);
4505 CSEMap.InsertNode(N, IP);
4507 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4508 createOperands(N, Ops);
4512 return SDValue(N, 0);
4515 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4516 SDValue N1, SDValue N2, SDValue N3) {
4517 // Perform various simplifications.
4520 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4521 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4522 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4523 if (N1CFP && N2CFP && N3CFP) {
4524 APFloat V1 = N1CFP->getValueAPF();
4525 const APFloat &V2 = N2CFP->getValueAPF();
4526 const APFloat &V3 = N3CFP->getValueAPF();
4527 APFloat::opStatus s =
4528 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4529 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4530 return getConstantFP(V1, DL, VT);
4534 case ISD::CONCAT_VECTORS: {
4535 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4536 SDValue Ops[] = {N1, N2, N3};
4537 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4542 // Use FoldSetCC to simplify SETCC's.
4543 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
4545 // Vector constant folding.
4546 SDValue Ops[] = {N1, N2, N3};
4547 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4552 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
4553 if (N1C->getZExtValue())
4554 return N2; // select true, X, Y -> X
4555 return N3; // select false, X, Y -> Y
4558 if (N2 == N3) return N2; // select C, X, X -> X
4560 case ISD::VECTOR_SHUFFLE:
4561 llvm_unreachable("should use getVectorShuffle constructor!");
4562 case ISD::INSERT_VECTOR_ELT: {
4563 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
4564 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
4565 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4566 return getUNDEF(VT);
4569 case ISD::INSERT_SUBVECTOR: {
4571 if (VT.isSimple() && N1.getValueType().isSimple()
4572 && N2.getValueType().isSimple()) {
4573 assert(VT.isVector() && N1.getValueType().isVector() &&
4574 N2.getValueType().isVector() &&
4575 "Insert subvector VTs must be a vectors");
4576 assert(VT == N1.getValueType() &&
4577 "Dest and insert subvector source types must match!");
4578 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4579 "Insert subvector must be from smaller vector to larger vector!");
4580 if (isa<ConstantSDNode>(Index)) {
4581 assert((N2.getValueType().getVectorNumElements() +
4582 cast<ConstantSDNode>(Index)->getZExtValue()
4583 <= VT.getVectorNumElements())
4584 && "Insert subvector overflow!");
4587 // Trivial insertion.
4588 if (VT.getSimpleVT() == N2.getSimpleValueType())
4594 // Fold bit_convert nodes from a type to themselves.
4595 if (N1.getValueType() == VT)
4600 // Memoize node if it doesn't produce a flag.
4602 SDVTList VTs = getVTList(VT);
4603 SDValue Ops[] = {N1, N2, N3};
4604 if (VT != MVT::Glue) {
4605 FoldingSetNodeID ID;
4606 AddNodeIDNode(ID, Opcode, VTs, Ops);
4608 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4609 return SDValue(E, 0);
4611 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4612 createOperands(N, Ops);
4613 CSEMap.InsertNode(N, IP);
4615 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4616 createOperands(N, Ops);
4620 return SDValue(N, 0);
4623 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4624 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4625 SDValue Ops[] = { N1, N2, N3, N4 };
4626 return getNode(Opcode, DL, VT, Ops);
4629 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4630 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4632 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4633 return getNode(Opcode, DL, VT, Ops);
4636 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4637 /// the incoming stack arguments to be loaded from the stack.
4638 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4639 SmallVector<SDValue, 8> ArgChains;
4641 // Include the original chain at the beginning of the list. When this is
4642 // used by target LowerCall hooks, this helps legalize find the
4643 // CALLSEQ_BEGIN node.
4644 ArgChains.push_back(Chain);
4646 // Add a chain value for each stack argument.
4647 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4648 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4649 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4650 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4651 if (FI->getIndex() < 0)
4652 ArgChains.push_back(SDValue(L, 1));
4654 // Build a tokenfactor for all the chains.
4655 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4658 /// getMemsetValue - Vectorized representation of the memset value
4660 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4662 assert(!Value.isUndef());
4664 unsigned NumBits = VT.getScalarSizeInBits();
4665 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4666 assert(C->getAPIntValue().getBitWidth() == 8);
4667 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4669 return DAG.getConstant(Val, dl, VT);
4670 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4674 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4675 EVT IntVT = VT.getScalarType();
4676 if (!IntVT.isInteger())
4677 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4679 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4681 // Use a multiplication with 0x010101... to extend the input to the
4683 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4684 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4685 DAG.getConstant(Magic, dl, IntVT));
4688 if (VT != Value.getValueType() && !VT.isInteger())
4689 Value = DAG.getBitcast(VT.getScalarType(), Value);
4690 if (VT != Value.getValueType())
4691 Value = DAG.getSplatBuildVector(VT, dl, Value);
4696 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4697 /// used when a memcpy is turned into a memset when the source is a constant
4699 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4700 const TargetLowering &TLI,
4701 const ConstantDataArraySlice &Slice) {
4702 // Handle vector with all elements zero.
4703 if (Slice.Array == nullptr) {
4705 return DAG.getConstant(0, dl, VT);
4706 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4707 return DAG.getConstantFP(0.0, dl, VT);
4708 else if (VT.isVector()) {
4709 unsigned NumElts = VT.getVectorNumElements();
4710 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4711 return DAG.getNode(ISD::BITCAST, dl, VT,
4712 DAG.getConstant(0, dl,
4713 EVT::getVectorVT(*DAG.getContext(),
4716 llvm_unreachable("Expected type!");
4719 assert(!VT.isVector() && "Can't handle vector type here!");
4720 unsigned NumVTBits = VT.getSizeInBits();
4721 unsigned NumVTBytes = NumVTBits / 8;
4722 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
4724 APInt Val(NumVTBits, 0);
4725 if (DAG.getDataLayout().isLittleEndian()) {
4726 for (unsigned i = 0; i != NumBytes; ++i)
4727 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
4729 for (unsigned i = 0; i != NumBytes; ++i)
4730 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
4733 // If the "cost" of materializing the integer immediate is less than the cost
4734 // of a load, then it is cost effective to turn the load into the immediate.
4735 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4736 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4737 return DAG.getConstant(Val, dl, VT);
4738 return SDValue(nullptr, 0);
4741 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4743 EVT VT = Base.getValueType();
4744 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4747 /// Returns true if memcpy source is constant data.
4748 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
4749 uint64_t SrcDelta = 0;
4750 GlobalAddressSDNode *G = nullptr;
4751 if (Src.getOpcode() == ISD::GlobalAddress)
4752 G = cast<GlobalAddressSDNode>(Src);
4753 else if (Src.getOpcode() == ISD::ADD &&
4754 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4755 Src.getOperand(1).getOpcode() == ISD::Constant) {
4756 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4757 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4762 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
4763 SrcDelta + G->getOffset());
4766 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4767 /// Return true if the number of memory ops is below the threshold (Limit).
4768 /// It returns the types of the sequence of memory ops to perform
4769 /// memset / memcpy by reference.
4770 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4771 unsigned Limit, uint64_t Size,
4772 unsigned DstAlign, unsigned SrcAlign,
4777 unsigned DstAS, unsigned SrcAS,
4779 const TargetLowering &TLI) {
4780 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4781 "Expecting memcpy / memset source to meet alignment requirement!");
4782 // If 'SrcAlign' is zero, that means the memory operation does not need to
4783 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4784 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4785 // is the specified alignment of the memory operation. If it is zero, that
4786 // means it's possible to change the alignment of the destination.
4787 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4788 // not need to be loaded.
4789 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4790 IsMemset, ZeroMemset, MemcpyStrSrc,
4791 DAG.getMachineFunction());
4793 if (VT == MVT::Other) {
4794 // Use the largest integer type whose alignment constraints are satisfied.
4795 // We only need to check DstAlign here as SrcAlign is always greater or
4796 // equal to DstAlign (or zero).
4798 while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
4799 !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
4800 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
4801 assert(VT.isInteger());
4803 // Find the largest legal integer type.
4805 while (!TLI.isTypeLegal(LVT))
4806 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4807 assert(LVT.isInteger());
4809 // If the type we've chosen is larger than the largest legal integer type
4810 // then use that instead.
4815 unsigned NumMemOps = 0;
4817 unsigned VTSize = VT.getSizeInBits() / 8;
4818 while (VTSize > Size) {
4819 // For now, only use non-vector load / store's for the left-over pieces.
4824 if (VT.isVector() || VT.isFloatingPoint()) {
4825 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4826 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4827 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4829 else if (NewVT == MVT::i64 &&
4830 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4831 TLI.isSafeMemOpType(MVT::f64)) {
4832 // i64 is usually not legal on 32-bit targets, but f64 may be.
4840 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4841 if (NewVT == MVT::i8)
4843 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4845 NewVTSize = NewVT.getSizeInBits() / 8;
4847 // If the new VT cannot cover all of the remaining bits, then consider
4848 // issuing a (or a pair of) unaligned and overlapping load / store.
4849 // FIXME: Only does this for 64-bit or more since we don't have proper
4850 // cost model for unaligned load / store.
4852 if (NumMemOps && AllowOverlap &&
4853 VTSize >= 8 && NewVTSize < Size &&
4854 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4862 if (++NumMemOps > Limit)
4865 MemOps.push_back(VT);
4872 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4873 // On Darwin, -Os means optimize for size without hurting performance, so
4874 // only really optimize for size when -Oz (MinSize) is used.
4875 if (MF.getTarget().getTargetTriple().isOSDarwin())
4876 return MF.getFunction()->optForMinSize();
4877 return MF.getFunction()->optForSize();
4880 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4881 SDValue Chain, SDValue Dst, SDValue Src,
4882 uint64_t Size, unsigned Align,
4883 bool isVol, bool AlwaysInline,
4884 MachinePointerInfo DstPtrInfo,
4885 MachinePointerInfo SrcPtrInfo) {
4886 // Turn a memcpy of undef to nop.
4890 // Expand memcpy to a series of load and store ops if the size operand falls
4891 // below a certain threshold.
4892 // TODO: In the AlwaysInline case, if the size is big then generate a loop
4893 // rather than maybe a humongous number of loads and stores.
4894 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4895 std::vector<EVT> MemOps;
4896 bool DstAlignCanChange = false;
4897 MachineFunction &MF = DAG.getMachineFunction();
4898 MachineFrameInfo &MFI = MF.getFrameInfo();
4899 bool OptSize = shouldLowerMemFuncForSize(MF);
4900 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4901 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4902 DstAlignCanChange = true;
4903 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4904 if (Align > SrcAlign)
4906 ConstantDataArraySlice Slice;
4907 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
4908 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
4909 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4911 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4912 (DstAlignCanChange ? 0 : Align),
4913 (isZeroConstant ? 0 : SrcAlign),
4914 false, false, CopyFromConstant, true,
4915 DstPtrInfo.getAddrSpace(),
4916 SrcPtrInfo.getAddrSpace(),
4920 if (DstAlignCanChange) {
4921 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4922 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4924 // Don't promote to an alignment that would require dynamic stack
4926 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4927 if (!TRI->needsStackRealignment(MF))
4928 while (NewAlign > Align &&
4929 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign))
4932 if (NewAlign > Align) {
4933 // Give the stack frame object a larger alignment if needed.
4934 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4935 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4940 MachineMemOperand::Flags MMOFlags =
4941 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4942 SmallVector<SDValue, 8> OutChains;
4943 unsigned NumMemOps = MemOps.size();
4944 uint64_t SrcOff = 0, DstOff = 0;
4945 for (unsigned i = 0; i != NumMemOps; ++i) {
4947 unsigned VTSize = VT.getSizeInBits() / 8;
4948 SDValue Value, Store;
4950 if (VTSize > Size) {
4951 // Issuing an unaligned load / store pair that overlaps with the previous
4952 // pair. Adjust the offset accordingly.
4953 assert(i == NumMemOps-1 && i != 0);
4954 SrcOff -= VTSize - Size;
4955 DstOff -= VTSize - Size;
4958 if (CopyFromConstant &&
4959 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
4960 // It's unlikely a store of a vector immediate can be done in a single
4961 // instruction. It would require a load from a constantpool first.
4962 // We only handle zero vectors here.
4963 // FIXME: Handle other cases where store of vector immediate is done in
4964 // a single instruction.
4965 ConstantDataArraySlice SubSlice;
4966 if (SrcOff < Slice.Length) {
4968 SubSlice.move(SrcOff);
4970 // This is an out-of-bounds access and hence UB. Pretend we read zero.
4971 SubSlice.Array = nullptr;
4972 SubSlice.Offset = 0;
4973 SubSlice.Length = VTSize;
4975 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
4976 if (Value.getNode())
4977 Store = DAG.getStore(Chain, dl, Value,
4978 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4979 DstPtrInfo.getWithOffset(DstOff), Align,
4983 if (!Store.getNode()) {
4984 // The type might not be legal for the target. This should only happen
4985 // if the type is smaller than a legal type, as on PPC, so the right
4986 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
4987 // to Load/Store if NVT==VT.
4988 // FIXME does the case above also need this?
4989 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4990 assert(NVT.bitsGE(VT));
4991 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4992 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4993 SrcPtrInfo.getWithOffset(SrcOff), VT,
4994 MinAlign(SrcAlign, SrcOff), MMOFlags);
4995 OutChains.push_back(Value.getValue(1));
4996 Store = DAG.getTruncStore(
4997 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4998 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5000 OutChains.push_back(Store);
5006 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5009 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5010 SDValue Chain, SDValue Dst, SDValue Src,
5011 uint64_t Size, unsigned Align,
5012 bool isVol, bool AlwaysInline,
5013 MachinePointerInfo DstPtrInfo,
5014 MachinePointerInfo SrcPtrInfo) {
5015 // Turn a memmove of undef to nop.
5019 // Expand memmove to a series of load and store ops if the size operand falls
5020 // below a certain threshold.
5021 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5022 std::vector<EVT> MemOps;
5023 bool DstAlignCanChange = false;
5024 MachineFunction &MF = DAG.getMachineFunction();
5025 MachineFrameInfo &MFI = MF.getFrameInfo();
5026 bool OptSize = shouldLowerMemFuncForSize(MF);
5027 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5028 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5029 DstAlignCanChange = true;
5030 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5031 if (Align > SrcAlign)
5033 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5035 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5036 (DstAlignCanChange ? 0 : Align), SrcAlign,
5037 false, false, false, false,
5038 DstPtrInfo.getAddrSpace(),
5039 SrcPtrInfo.getAddrSpace(),
5043 if (DstAlignCanChange) {
5044 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5045 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5046 if (NewAlign > Align) {
5047 // Give the stack frame object a larger alignment if needed.
5048 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5049 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5054 MachineMemOperand::Flags MMOFlags =
5055 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5056 uint64_t SrcOff = 0, DstOff = 0;
5057 SmallVector<SDValue, 8> LoadValues;
5058 SmallVector<SDValue, 8> LoadChains;
5059 SmallVector<SDValue, 8> OutChains;
5060 unsigned NumMemOps = MemOps.size();
5061 for (unsigned i = 0; i < NumMemOps; i++) {
5063 unsigned VTSize = VT.getSizeInBits() / 8;
5067 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5068 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags);
5069 LoadValues.push_back(Value);
5070 LoadChains.push_back(Value.getValue(1));
5073 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5075 for (unsigned i = 0; i < NumMemOps; i++) {
5077 unsigned VTSize = VT.getSizeInBits() / 8;
5080 Store = DAG.getStore(Chain, dl, LoadValues[i],
5081 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5082 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5083 OutChains.push_back(Store);
5087 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5090 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5093 /// \param DAG Selection DAG where lowered code is placed.
5094 /// \param dl Link to corresponding IR location.
5095 /// \param Chain Control flow dependency.
5096 /// \param Dst Pointer to destination memory location.
5097 /// \param Src Value of byte to write into the memory.
5098 /// \param Size Number of bytes to write.
5099 /// \param Align Alignment of the destination in bytes.
5100 /// \param isVol True if destination is volatile.
5101 /// \param DstPtrInfo IR information on the memory pointer.
5102 /// \returns New head in the control flow, if lowering was successful, empty
5103 /// SDValue otherwise.
5105 /// The function tries to replace 'llvm.memset' intrinsic with several store
5106 /// operations and value calculation code. This is usually profitable for small
5108 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5109 SDValue Chain, SDValue Dst, SDValue Src,
5110 uint64_t Size, unsigned Align, bool isVol,
5111 MachinePointerInfo DstPtrInfo) {
5112 // Turn a memset of undef to nop.
5116 // Expand memset to a series of load/store ops if the size operand
5117 // falls below a certain threshold.
5118 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5119 std::vector<EVT> MemOps;
5120 bool DstAlignCanChange = false;
5121 MachineFunction &MF = DAG.getMachineFunction();
5122 MachineFrameInfo &MFI = MF.getFrameInfo();
5123 bool OptSize = shouldLowerMemFuncForSize(MF);
5124 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5125 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5126 DstAlignCanChange = true;
5128 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5129 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5130 Size, (DstAlignCanChange ? 0 : Align), 0,
5131 true, IsZeroVal, false, true,
5132 DstPtrInfo.getAddrSpace(), ~0u,
5136 if (DstAlignCanChange) {
5137 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5138 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5139 if (NewAlign > Align) {
5140 // Give the stack frame object a larger alignment if needed.
5141 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5142 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5147 SmallVector<SDValue, 8> OutChains;
5148 uint64_t DstOff = 0;
5149 unsigned NumMemOps = MemOps.size();
5151 // Find the largest store and generate the bit pattern for it.
5152 EVT LargestVT = MemOps[0];
5153 for (unsigned i = 1; i < NumMemOps; i++)
5154 if (MemOps[i].bitsGT(LargestVT))
5155 LargestVT = MemOps[i];
5156 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5158 for (unsigned i = 0; i < NumMemOps; i++) {
5160 unsigned VTSize = VT.getSizeInBits() / 8;
5161 if (VTSize > Size) {
5162 // Issuing an unaligned load / store pair that overlaps with the previous
5163 // pair. Adjust the offset accordingly.
5164 assert(i == NumMemOps-1 && i != 0);
5165 DstOff -= VTSize - Size;
5168 // If this store is smaller than the largest store see whether we can get
5169 // the smaller value for free with a truncate.
5170 SDValue Value = MemSetValue;
5171 if (VT.bitsLT(LargestVT)) {
5172 if (!LargestVT.isVector() && !VT.isVector() &&
5173 TLI.isTruncateFree(LargestVT, VT))
5174 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5176 Value = getMemsetValue(Src, VT, DAG, dl);
5178 assert(Value.getValueType() == VT && "Value with wrong type.");
5179 SDValue Store = DAG.getStore(
5180 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5181 DstPtrInfo.getWithOffset(DstOff), Align,
5182 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5183 OutChains.push_back(Store);
5184 DstOff += VT.getSizeInBits() / 8;
5188 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5191 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5193 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5194 // pointer operands can be losslessly bitcasted to pointers of address space 0
5195 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5196 report_fatal_error("cannot lower memory intrinsic in address space " +
5201 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5202 SDValue Src, SDValue Size, unsigned Align,
5203 bool isVol, bool AlwaysInline, bool isTailCall,
5204 MachinePointerInfo DstPtrInfo,
5205 MachinePointerInfo SrcPtrInfo) {
5206 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5208 // Check to see if we should lower the memcpy to loads and stores first.
5209 // For cases within the target-specified limits, this is the best choice.
5210 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5212 // Memcpy with size zero? Just return the original chain.
5213 if (ConstantSize->isNullValue())
5216 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5217 ConstantSize->getZExtValue(),Align,
5218 isVol, false, DstPtrInfo, SrcPtrInfo);
5219 if (Result.getNode())
5223 // Then check to see if we should lower the memcpy with target-specific
5224 // code. If the target chooses to do this, this is the next best.
5226 SDValue Result = TSI->EmitTargetCodeForMemcpy(
5227 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5228 DstPtrInfo, SrcPtrInfo);
5229 if (Result.getNode())
5233 // If we really need inline code and the target declined to provide it,
5234 // use a (potentially long) sequence of loads and stores.
5236 assert(ConstantSize && "AlwaysInline requires a constant size!");
5237 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5238 ConstantSize->getZExtValue(), Align, isVol,
5239 true, DstPtrInfo, SrcPtrInfo);
5242 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5243 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5245 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5246 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5247 // respect volatile, so they may do things like read or write memory
5248 // beyond the given memory regions. But fixing this isn't easy, and most
5249 // people don't care.
5251 // Emit a library call.
5252 TargetLowering::ArgListTy Args;
5253 TargetLowering::ArgListEntry Entry;
5254 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5255 Entry.Node = Dst; Args.push_back(Entry);
5256 Entry.Node = Src; Args.push_back(Entry);
5257 Entry.Node = Size; Args.push_back(Entry);
5258 // FIXME: pass in SDLoc
5259 TargetLowering::CallLoweringInfo CLI(*this);
5262 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5263 Dst.getValueType().getTypeForEVT(*getContext()),
5264 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5265 TLI->getPointerTy(getDataLayout())),
5268 .setTailCall(isTailCall);
5270 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5271 return CallResult.second;
5274 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5275 SDValue Src, SDValue Size, unsigned Align,
5276 bool isVol, bool isTailCall,
5277 MachinePointerInfo DstPtrInfo,
5278 MachinePointerInfo SrcPtrInfo) {
5279 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5281 // Check to see if we should lower the memmove to loads and stores first.
5282 // For cases within the target-specified limits, this is the best choice.
5283 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5285 // Memmove with size zero? Just return the original chain.
5286 if (ConstantSize->isNullValue())
5290 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5291 ConstantSize->getZExtValue(), Align, isVol,
5292 false, DstPtrInfo, SrcPtrInfo);
5293 if (Result.getNode())
5297 // Then check to see if we should lower the memmove with target-specific
5298 // code. If the target chooses to do this, this is the next best.
5300 SDValue Result = TSI->EmitTargetCodeForMemmove(
5301 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5302 if (Result.getNode())
5306 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5307 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5309 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5310 // not be safe. See memcpy above for more details.
5312 // Emit a library call.
5313 TargetLowering::ArgListTy Args;
5314 TargetLowering::ArgListEntry Entry;
5315 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5316 Entry.Node = Dst; Args.push_back(Entry);
5317 Entry.Node = Src; Args.push_back(Entry);
5318 Entry.Node = Size; Args.push_back(Entry);
5319 // FIXME: pass in SDLoc
5320 TargetLowering::CallLoweringInfo CLI(*this);
5323 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5324 Dst.getValueType().getTypeForEVT(*getContext()),
5325 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5326 TLI->getPointerTy(getDataLayout())),
5329 .setTailCall(isTailCall);
5331 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5332 return CallResult.second;
5335 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5336 SDValue Src, SDValue Size, unsigned Align,
5337 bool isVol, bool isTailCall,
5338 MachinePointerInfo DstPtrInfo) {
5339 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5341 // Check to see if we should lower the memset to stores first.
5342 // For cases within the target-specified limits, this is the best choice.
5343 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5345 // Memset with size zero? Just return the original chain.
5346 if (ConstantSize->isNullValue())
5350 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5351 Align, isVol, DstPtrInfo);
5353 if (Result.getNode())
5357 // Then check to see if we should lower the memset with target-specific
5358 // code. If the target chooses to do this, this is the next best.
5360 SDValue Result = TSI->EmitTargetCodeForMemset(
5361 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5362 if (Result.getNode())
5366 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5368 // Emit a library call.
5369 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5370 TargetLowering::ArgListTy Args;
5371 TargetLowering::ArgListEntry Entry;
5372 Entry.Node = Dst; Entry.Ty = IntPtrTy;
5373 Args.push_back(Entry);
5375 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5376 Args.push_back(Entry);
5378 Entry.Ty = IntPtrTy;
5379 Args.push_back(Entry);
5381 // FIXME: pass in SDLoc
5382 TargetLowering::CallLoweringInfo CLI(*this);
5385 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5386 Dst.getValueType().getTypeForEVT(*getContext()),
5387 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5388 TLI->getPointerTy(getDataLayout())),
5391 .setTailCall(isTailCall);
5393 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5394 return CallResult.second;
5397 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5398 SDVTList VTList, ArrayRef<SDValue> Ops,
5399 MachineMemOperand *MMO) {
5400 FoldingSetNodeID ID;
5401 ID.AddInteger(MemVT.getRawBits());
5402 AddNodeIDNode(ID, Opcode, VTList, Ops);
5403 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5405 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5406 cast<AtomicSDNode>(E)->refineAlignment(MMO);
5407 return SDValue(E, 0);
5410 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5411 VTList, MemVT, MMO);
5412 createOperands(N, Ops);
5414 CSEMap.InsertNode(N, IP);
5416 return SDValue(N, 0);
5419 SDValue SelectionDAG::getAtomicCmpSwap(
5420 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5421 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5422 unsigned Alignment, AtomicOrdering SuccessOrdering,
5423 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
5424 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5425 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5426 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5428 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5429 Alignment = getEVTAlignment(MemVT);
5431 MachineFunction &MF = getMachineFunction();
5433 // FIXME: Volatile isn't really correct; we should keep track of atomic
5434 // orderings in the memoperand.
5435 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5436 MachineMemOperand::MOStore;
5437 MachineMemOperand *MMO =
5438 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5439 AAMDNodes(), nullptr, SynchScope, SuccessOrdering,
5442 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5445 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5446 EVT MemVT, SDVTList VTs, SDValue Chain,
5447 SDValue Ptr, SDValue Cmp, SDValue Swp,
5448 MachineMemOperand *MMO) {
5449 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5450 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5451 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5453 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5454 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5457 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5458 SDValue Chain, SDValue Ptr, SDValue Val,
5459 const Value *PtrVal, unsigned Alignment,
5460 AtomicOrdering Ordering,
5461 SynchronizationScope SynchScope) {
5462 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5463 Alignment = getEVTAlignment(MemVT);
5465 MachineFunction &MF = getMachineFunction();
5466 // An atomic store does not load. An atomic load does not store.
5467 // (An atomicrmw obviously both loads and stores.)
5468 // For now, atomics are considered to be volatile always, and they are
5470 // FIXME: Volatile isn't really correct; we should keep track of atomic
5471 // orderings in the memoperand.
5472 auto Flags = MachineMemOperand::MOVolatile;
5473 if (Opcode != ISD::ATOMIC_STORE)
5474 Flags |= MachineMemOperand::MOLoad;
5475 if (Opcode != ISD::ATOMIC_LOAD)
5476 Flags |= MachineMemOperand::MOStore;
5478 MachineMemOperand *MMO =
5479 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5480 MemVT.getStoreSize(), Alignment, AAMDNodes(),
5481 nullptr, SynchScope, Ordering);
5483 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5486 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5487 SDValue Chain, SDValue Ptr, SDValue Val,
5488 MachineMemOperand *MMO) {
5489 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5490 Opcode == ISD::ATOMIC_LOAD_SUB ||
5491 Opcode == ISD::ATOMIC_LOAD_AND ||
5492 Opcode == ISD::ATOMIC_LOAD_OR ||
5493 Opcode == ISD::ATOMIC_LOAD_XOR ||
5494 Opcode == ISD::ATOMIC_LOAD_NAND ||
5495 Opcode == ISD::ATOMIC_LOAD_MIN ||
5496 Opcode == ISD::ATOMIC_LOAD_MAX ||
5497 Opcode == ISD::ATOMIC_LOAD_UMIN ||
5498 Opcode == ISD::ATOMIC_LOAD_UMAX ||
5499 Opcode == ISD::ATOMIC_SWAP ||
5500 Opcode == ISD::ATOMIC_STORE) &&
5501 "Invalid Atomic Op");
5503 EVT VT = Val.getValueType();
5505 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5506 getVTList(VT, MVT::Other);
5507 SDValue Ops[] = {Chain, Ptr, Val};
5508 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5511 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5512 EVT VT, SDValue Chain, SDValue Ptr,
5513 MachineMemOperand *MMO) {
5514 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5516 SDVTList VTs = getVTList(VT, MVT::Other);
5517 SDValue Ops[] = {Chain, Ptr};
5518 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5521 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5522 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5523 if (Ops.size() == 1)
5526 SmallVector<EVT, 4> VTs;
5527 VTs.reserve(Ops.size());
5528 for (unsigned i = 0; i < Ops.size(); ++i)
5529 VTs.push_back(Ops[i].getValueType());
5530 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5533 SDValue SelectionDAG::getMemIntrinsicNode(
5534 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5535 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5536 bool ReadMem, bool WriteMem, unsigned Size) {
5537 if (Align == 0) // Ensure that codegen never sees alignment 0
5538 Align = getEVTAlignment(MemVT);
5540 MachineFunction &MF = getMachineFunction();
5541 auto Flags = MachineMemOperand::MONone;
5543 Flags |= MachineMemOperand::MOStore;
5545 Flags |= MachineMemOperand::MOLoad;
5547 Flags |= MachineMemOperand::MOVolatile;
5549 Size = MemVT.getStoreSize();
5550 MachineMemOperand *MMO =
5551 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5553 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5556 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5558 ArrayRef<SDValue> Ops, EVT MemVT,
5559 MachineMemOperand *MMO) {
5560 assert((Opcode == ISD::INTRINSIC_VOID ||
5561 Opcode == ISD::INTRINSIC_W_CHAIN ||
5562 Opcode == ISD::PREFETCH ||
5563 Opcode == ISD::LIFETIME_START ||
5564 Opcode == ISD::LIFETIME_END ||
5565 ((int)Opcode <= std::numeric_limits<int>::max() &&
5566 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5567 "Opcode is not a memory-accessing opcode!");
5569 // Memoize the node unless it returns a flag.
5570 MemIntrinsicSDNode *N;
5571 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5572 FoldingSetNodeID ID;
5573 AddNodeIDNode(ID, Opcode, VTList, Ops);
5574 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5576 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5577 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5578 return SDValue(E, 0);
5581 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5582 VTList, MemVT, MMO);
5583 createOperands(N, Ops);
5585 CSEMap.InsertNode(N, IP);
5587 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5588 VTList, MemVT, MMO);
5589 createOperands(N, Ops);
5592 return SDValue(N, 0);
5595 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5596 /// MachinePointerInfo record from it. This is particularly useful because the
5597 /// code generator has many cases where it doesn't bother passing in a
5598 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5599 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5600 int64_t Offset = 0) {
5601 // If this is FI+Offset, we can model it.
5602 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5603 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5604 FI->getIndex(), Offset);
5606 // If this is (FI+Offset1)+Offset2, we can model it.
5607 if (Ptr.getOpcode() != ISD::ADD ||
5608 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5609 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5610 return MachinePointerInfo();
5612 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5613 return MachinePointerInfo::getFixedStack(
5614 DAG.getMachineFunction(), FI,
5615 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5618 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5619 /// MachinePointerInfo record from it. This is particularly useful because the
5620 /// code generator has many cases where it doesn't bother passing in a
5621 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5622 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5624 // If the 'Offset' value isn't a constant, we can't handle this.
5625 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5626 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5627 if (OffsetOp.isUndef())
5628 return InferPointerInfo(DAG, Ptr);
5629 return MachinePointerInfo();
5632 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5633 EVT VT, const SDLoc &dl, SDValue Chain,
5634 SDValue Ptr, SDValue Offset,
5635 MachinePointerInfo PtrInfo, EVT MemVT,
5637 MachineMemOperand::Flags MMOFlags,
5638 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5639 assert(Chain.getValueType() == MVT::Other &&
5640 "Invalid chain type");
5641 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5642 Alignment = getEVTAlignment(MemVT);
5644 MMOFlags |= MachineMemOperand::MOLoad;
5645 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5646 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5648 if (PtrInfo.V.isNull())
5649 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5651 MachineFunction &MF = getMachineFunction();
5652 MachineMemOperand *MMO = MF.getMachineMemOperand(
5653 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5654 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5657 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5658 EVT VT, const SDLoc &dl, SDValue Chain,
5659 SDValue Ptr, SDValue Offset, EVT MemVT,
5660 MachineMemOperand *MMO) {
5662 ExtType = ISD::NON_EXTLOAD;
5663 } else if (ExtType == ISD::NON_EXTLOAD) {
5664 assert(VT == MemVT && "Non-extending load from different memory type!");
5667 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5668 "Should only be an extending load, not truncating!");
5669 assert(VT.isInteger() == MemVT.isInteger() &&
5670 "Cannot convert from FP to Int or Int -> FP!");
5671 assert(VT.isVector() == MemVT.isVector() &&
5672 "Cannot use an ext load to convert to or from a vector!");
5673 assert((!VT.isVector() ||
5674 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5675 "Cannot use an ext load to change the number of vector elements!");
5678 bool Indexed = AM != ISD::UNINDEXED;
5679 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5681 SDVTList VTs = Indexed ?
5682 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5683 SDValue Ops[] = { Chain, Ptr, Offset };
5684 FoldingSetNodeID ID;
5685 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5686 ID.AddInteger(MemVT.getRawBits());
5687 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5688 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5689 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5691 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5692 cast<LoadSDNode>(E)->refineAlignment(MMO);
5693 return SDValue(E, 0);
5695 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5696 ExtType, MemVT, MMO);
5697 createOperands(N, Ops);
5699 CSEMap.InsertNode(N, IP);
5701 return SDValue(N, 0);
5704 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5705 SDValue Ptr, MachinePointerInfo PtrInfo,
5707 MachineMemOperand::Flags MMOFlags,
5708 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5709 SDValue Undef = getUNDEF(Ptr.getValueType());
5710 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5711 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5714 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5715 SDValue Ptr, MachineMemOperand *MMO) {
5716 SDValue Undef = getUNDEF(Ptr.getValueType());
5717 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5721 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5722 EVT VT, SDValue Chain, SDValue Ptr,
5723 MachinePointerInfo PtrInfo, EVT MemVT,
5725 MachineMemOperand::Flags MMOFlags,
5726 const AAMDNodes &AAInfo) {
5727 SDValue Undef = getUNDEF(Ptr.getValueType());
5728 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5729 MemVT, Alignment, MMOFlags, AAInfo);
5732 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5733 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5734 MachineMemOperand *MMO) {
5735 SDValue Undef = getUNDEF(Ptr.getValueType());
5736 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5740 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5741 SDValue Base, SDValue Offset,
5742 ISD::MemIndexedMode AM) {
5743 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5744 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5745 // Don't propagate the invariant or dereferenceable flags.
5747 LD->getMemOperand()->getFlags() &
5748 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5749 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5750 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5751 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5755 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5756 SDValue Ptr, MachinePointerInfo PtrInfo,
5758 MachineMemOperand::Flags MMOFlags,
5759 const AAMDNodes &AAInfo) {
5760 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5761 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5762 Alignment = getEVTAlignment(Val.getValueType());
5764 MMOFlags |= MachineMemOperand::MOStore;
5765 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5767 if (PtrInfo.V.isNull())
5768 PtrInfo = InferPointerInfo(*this, Ptr);
5770 MachineFunction &MF = getMachineFunction();
5771 MachineMemOperand *MMO = MF.getMachineMemOperand(
5772 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5773 return getStore(Chain, dl, Val, Ptr, MMO);
5776 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5777 SDValue Ptr, MachineMemOperand *MMO) {
5778 assert(Chain.getValueType() == MVT::Other &&
5779 "Invalid chain type");
5780 EVT VT = Val.getValueType();
5781 SDVTList VTs = getVTList(MVT::Other);
5782 SDValue Undef = getUNDEF(Ptr.getValueType());
5783 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5784 FoldingSetNodeID ID;
5785 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5786 ID.AddInteger(VT.getRawBits());
5787 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5788 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5789 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5791 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5792 cast<StoreSDNode>(E)->refineAlignment(MMO);
5793 return SDValue(E, 0);
5795 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5796 ISD::UNINDEXED, false, VT, MMO);
5797 createOperands(N, Ops);
5799 CSEMap.InsertNode(N, IP);
5801 return SDValue(N, 0);
5804 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5805 SDValue Ptr, MachinePointerInfo PtrInfo,
5806 EVT SVT, unsigned Alignment,
5807 MachineMemOperand::Flags MMOFlags,
5808 const AAMDNodes &AAInfo) {
5809 assert(Chain.getValueType() == MVT::Other &&
5810 "Invalid chain type");
5811 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5812 Alignment = getEVTAlignment(SVT);
5814 MMOFlags |= MachineMemOperand::MOStore;
5815 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5817 if (PtrInfo.V.isNull())
5818 PtrInfo = InferPointerInfo(*this, Ptr);
5820 MachineFunction &MF = getMachineFunction();
5821 MachineMemOperand *MMO = MF.getMachineMemOperand(
5822 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5823 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5826 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5827 SDValue Ptr, EVT SVT,
5828 MachineMemOperand *MMO) {
5829 EVT VT = Val.getValueType();
5831 assert(Chain.getValueType() == MVT::Other &&
5832 "Invalid chain type");
5834 return getStore(Chain, dl, Val, Ptr, MMO);
5836 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5837 "Should only be a truncating store, not extending!");
5838 assert(VT.isInteger() == SVT.isInteger() &&
5839 "Can't do FP-INT conversion!");
5840 assert(VT.isVector() == SVT.isVector() &&
5841 "Cannot use trunc store to convert to or from a vector!");
5842 assert((!VT.isVector() ||
5843 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5844 "Cannot use trunc store to change the number of vector elements!");
5846 SDVTList VTs = getVTList(MVT::Other);
5847 SDValue Undef = getUNDEF(Ptr.getValueType());
5848 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5849 FoldingSetNodeID ID;
5850 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5851 ID.AddInteger(SVT.getRawBits());
5852 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5853 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5854 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5856 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5857 cast<StoreSDNode>(E)->refineAlignment(MMO);
5858 return SDValue(E, 0);
5860 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5861 ISD::UNINDEXED, true, SVT, MMO);
5862 createOperands(N, Ops);
5864 CSEMap.InsertNode(N, IP);
5866 return SDValue(N, 0);
5869 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5870 SDValue Base, SDValue Offset,
5871 ISD::MemIndexedMode AM) {
5872 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5873 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5874 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5875 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5876 FoldingSetNodeID ID;
5877 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5878 ID.AddInteger(ST->getMemoryVT().getRawBits());
5879 ID.AddInteger(ST->getRawSubclassData());
5880 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5882 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5883 return SDValue(E, 0);
5885 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5886 ST->isTruncatingStore(), ST->getMemoryVT(),
5887 ST->getMemOperand());
5888 createOperands(N, Ops);
5890 CSEMap.InsertNode(N, IP);
5892 return SDValue(N, 0);
5895 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5896 SDValue Ptr, SDValue Mask, SDValue Src0,
5897 EVT MemVT, MachineMemOperand *MMO,
5898 ISD::LoadExtType ExtTy, bool isExpanding) {
5899 SDVTList VTs = getVTList(VT, MVT::Other);
5900 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5901 FoldingSetNodeID ID;
5902 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5903 ID.AddInteger(VT.getRawBits());
5904 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5905 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5906 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5908 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5909 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5910 return SDValue(E, 0);
5912 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5913 ExtTy, isExpanding, MemVT, MMO);
5914 createOperands(N, Ops);
5916 CSEMap.InsertNode(N, IP);
5918 return SDValue(N, 0);
5921 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5922 SDValue Val, SDValue Ptr, SDValue Mask,
5923 EVT MemVT, MachineMemOperand *MMO,
5924 bool IsTruncating, bool IsCompressing) {
5925 assert(Chain.getValueType() == MVT::Other &&
5926 "Invalid chain type");
5927 EVT VT = Val.getValueType();
5928 SDVTList VTs = getVTList(MVT::Other);
5929 SDValue Ops[] = { Chain, Ptr, Mask, Val };
5930 FoldingSetNodeID ID;
5931 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5932 ID.AddInteger(VT.getRawBits());
5933 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5934 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5935 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5937 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5938 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5939 return SDValue(E, 0);
5941 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5942 IsTruncating, IsCompressing, MemVT, MMO);
5943 createOperands(N, Ops);
5945 CSEMap.InsertNode(N, IP);
5947 return SDValue(N, 0);
5950 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5951 ArrayRef<SDValue> Ops,
5952 MachineMemOperand *MMO) {
5953 assert(Ops.size() == 5 && "Incompatible number of operands");
5955 FoldingSetNodeID ID;
5956 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5957 ID.AddInteger(VT.getRawBits());
5958 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5959 dl.getIROrder(), VTs, VT, MMO));
5960 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5962 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5963 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5964 return SDValue(E, 0);
5967 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5969 createOperands(N, Ops);
5971 assert(N->getValue().getValueType() == N->getValueType(0) &&
5972 "Incompatible type of the PassThru value in MaskedGatherSDNode");
5973 assert(N->getMask().getValueType().getVectorNumElements() ==
5974 N->getValueType(0).getVectorNumElements() &&
5975 "Vector width mismatch between mask and data");
5976 assert(N->getIndex().getValueType().getVectorNumElements() ==
5977 N->getValueType(0).getVectorNumElements() &&
5978 "Vector width mismatch between index and data");
5980 CSEMap.InsertNode(N, IP);
5982 return SDValue(N, 0);
5985 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
5986 ArrayRef<SDValue> Ops,
5987 MachineMemOperand *MMO) {
5988 assert(Ops.size() == 5 && "Incompatible number of operands");
5990 FoldingSetNodeID ID;
5991 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5992 ID.AddInteger(VT.getRawBits());
5993 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
5994 dl.getIROrder(), VTs, VT, MMO));
5995 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5997 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5998 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
5999 return SDValue(E, 0);
6001 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6003 createOperands(N, Ops);
6005 assert(N->getMask().getValueType().getVectorNumElements() ==
6006 N->getValue().getValueType().getVectorNumElements() &&
6007 "Vector width mismatch between mask and data");
6008 assert(N->getIndex().getValueType().getVectorNumElements() ==
6009 N->getValue().getValueType().getVectorNumElements() &&
6010 "Vector width mismatch between index and data");
6012 CSEMap.InsertNode(N, IP);
6014 return SDValue(N, 0);
6017 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
6018 SDValue Ptr, SDValue SV, unsigned Align) {
6019 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
6020 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
6023 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6024 ArrayRef<SDUse> Ops) {
6025 switch (Ops.size()) {
6026 case 0: return getNode(Opcode, DL, VT);
6027 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
6028 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
6029 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6033 // Copy from an SDUse array into an SDValue array for use with
6034 // the regular getNode logic.
6035 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
6036 return getNode(Opcode, DL, VT, NewOps);
6039 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6040 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
6041 unsigned NumOps = Ops.size();
6043 case 0: return getNode(Opcode, DL, VT);
6044 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
6045 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
6046 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6052 case ISD::CONCAT_VECTORS:
6053 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
6054 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
6057 case ISD::SELECT_CC:
6058 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6059 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6060 "LHS and RHS of condition must have same type!");
6061 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6062 "True and False arms of SelectCC must have same type!");
6063 assert(Ops[2].getValueType() == VT &&
6064 "select_cc node must be of same type as true and false value!");
6067 assert(NumOps == 5 && "BR_CC takes 5 operands!");
6068 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6069 "LHS/RHS of comparison should match types!");
6075 SDVTList VTs = getVTList(VT);
6077 if (VT != MVT::Glue) {
6078 FoldingSetNodeID ID;
6079 AddNodeIDNode(ID, Opcode, VTs, Ops);
6082 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6083 return SDValue(E, 0);
6085 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6086 createOperands(N, Ops);
6088 CSEMap.InsertNode(N, IP);
6090 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6091 createOperands(N, Ops);
6095 return SDValue(N, 0);
6098 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6099 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6100 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6103 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6104 ArrayRef<SDValue> Ops) {
6105 if (VTList.NumVTs == 1)
6106 return getNode(Opcode, DL, VTList.VTs[0], Ops);
6110 // FIXME: figure out how to safely handle things like
6111 // int foo(int x) { return 1 << (x & 255); }
6112 // int bar() { return foo(256); }
6113 case ISD::SRA_PARTS:
6114 case ISD::SRL_PARTS:
6115 case ISD::SHL_PARTS:
6116 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6117 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6118 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6119 else if (N3.getOpcode() == ISD::AND)
6120 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6121 // If the and is only masking out bits that cannot effect the shift,
6122 // eliminate the and.
6123 unsigned NumBits = VT.getScalarSizeInBits()*2;
6124 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6125 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6131 // Memoize the node unless it returns a flag.
6133 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6134 FoldingSetNodeID ID;
6135 AddNodeIDNode(ID, Opcode, VTList, Ops);
6137 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6138 return SDValue(E, 0);
6140 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6141 createOperands(N, Ops);
6142 CSEMap.InsertNode(N, IP);
6144 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6145 createOperands(N, Ops);
6148 return SDValue(N, 0);
6151 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6153 return getNode(Opcode, DL, VTList, None);
6156 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6158 SDValue Ops[] = { N1 };
6159 return getNode(Opcode, DL, VTList, Ops);
6162 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6163 SDValue N1, SDValue N2) {
6164 SDValue Ops[] = { N1, N2 };
6165 return getNode(Opcode, DL, VTList, Ops);
6168 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6169 SDValue N1, SDValue N2, SDValue N3) {
6170 SDValue Ops[] = { N1, N2, N3 };
6171 return getNode(Opcode, DL, VTList, Ops);
6174 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6175 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6176 SDValue Ops[] = { N1, N2, N3, N4 };
6177 return getNode(Opcode, DL, VTList, Ops);
6180 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6181 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6183 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6184 return getNode(Opcode, DL, VTList, Ops);
6187 SDVTList SelectionDAG::getVTList(EVT VT) {
6188 return makeVTList(SDNode::getValueTypeList(VT), 1);
6191 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6192 FoldingSetNodeID ID;
6194 ID.AddInteger(VT1.getRawBits());
6195 ID.AddInteger(VT2.getRawBits());
6198 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6200 EVT *Array = Allocator.Allocate<EVT>(2);
6203 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6204 VTListMap.InsertNode(Result, IP);
6206 return Result->getSDVTList();
6209 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6210 FoldingSetNodeID ID;
6212 ID.AddInteger(VT1.getRawBits());
6213 ID.AddInteger(VT2.getRawBits());
6214 ID.AddInteger(VT3.getRawBits());
6217 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6219 EVT *Array = Allocator.Allocate<EVT>(3);
6223 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6224 VTListMap.InsertNode(Result, IP);
6226 return Result->getSDVTList();
6229 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6230 FoldingSetNodeID ID;
6232 ID.AddInteger(VT1.getRawBits());
6233 ID.AddInteger(VT2.getRawBits());
6234 ID.AddInteger(VT3.getRawBits());
6235 ID.AddInteger(VT4.getRawBits());
6238 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6240 EVT *Array = Allocator.Allocate<EVT>(4);
6245 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6246 VTListMap.InsertNode(Result, IP);
6248 return Result->getSDVTList();
6251 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6252 unsigned NumVTs = VTs.size();
6253 FoldingSetNodeID ID;
6254 ID.AddInteger(NumVTs);
6255 for (unsigned index = 0; index < NumVTs; index++) {
6256 ID.AddInteger(VTs[index].getRawBits());
6260 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6262 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6263 std::copy(VTs.begin(), VTs.end(), Array);
6264 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6265 VTListMap.InsertNode(Result, IP);
6267 return Result->getSDVTList();
6271 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6272 /// specified operands. If the resultant node already exists in the DAG,
6273 /// this does not modify the specified node, instead it returns the node that
6274 /// already exists. If the resultant node does not exist in the DAG, the
6275 /// input node is returned. As a degenerate case, if you specify the same
6276 /// input operands as the node already has, the input node is returned.
6277 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6278 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6280 // Check to see if there is no change.
6281 if (Op == N->getOperand(0)) return N;
6283 // See if the modified node already exists.
6284 void *InsertPos = nullptr;
6285 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6288 // Nope it doesn't. Remove the node from its current place in the maps.
6290 if (!RemoveNodeFromCSEMaps(N))
6291 InsertPos = nullptr;
6293 // Now we update the operands.
6294 N->OperandList[0].set(Op);
6296 // If this gets put into a CSE map, add it.
6297 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6301 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6302 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6304 // Check to see if there is no change.
6305 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6306 return N; // No operands changed, just return the input node.
6308 // See if the modified node already exists.
6309 void *InsertPos = nullptr;
6310 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6313 // Nope it doesn't. Remove the node from its current place in the maps.
6315 if (!RemoveNodeFromCSEMaps(N))
6316 InsertPos = nullptr;
6318 // Now we update the operands.
6319 if (N->OperandList[0] != Op1)
6320 N->OperandList[0].set(Op1);
6321 if (N->OperandList[1] != Op2)
6322 N->OperandList[1].set(Op2);
6324 // If this gets put into a CSE map, add it.
6325 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6329 SDNode *SelectionDAG::
6330 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6331 SDValue Ops[] = { Op1, Op2, Op3 };
6332 return UpdateNodeOperands(N, Ops);
6335 SDNode *SelectionDAG::
6336 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6337 SDValue Op3, SDValue Op4) {
6338 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6339 return UpdateNodeOperands(N, Ops);
6342 SDNode *SelectionDAG::
6343 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6344 SDValue Op3, SDValue Op4, SDValue Op5) {
6345 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6346 return UpdateNodeOperands(N, Ops);
6349 SDNode *SelectionDAG::
6350 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6351 unsigned NumOps = Ops.size();
6352 assert(N->getNumOperands() == NumOps &&
6353 "Update with wrong number of operands");
6355 // If no operands changed just return the input node.
6356 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6359 // See if the modified node already exists.
6360 void *InsertPos = nullptr;
6361 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6364 // Nope it doesn't. Remove the node from its current place in the maps.
6366 if (!RemoveNodeFromCSEMaps(N))
6367 InsertPos = nullptr;
6369 // Now we update the operands.
6370 for (unsigned i = 0; i != NumOps; ++i)
6371 if (N->OperandList[i] != Ops[i])
6372 N->OperandList[i].set(Ops[i]);
6374 // If this gets put into a CSE map, add it.
6375 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6379 /// DropOperands - Release the operands and set this node to have
6381 void SDNode::DropOperands() {
6382 // Unlike the code in MorphNodeTo that does this, we don't need to
6383 // watch for dead nodes here.
6384 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6390 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6393 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6395 SDVTList VTs = getVTList(VT);
6396 return SelectNodeTo(N, MachineOpc, VTs, None);
6399 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6400 EVT VT, SDValue Op1) {
6401 SDVTList VTs = getVTList(VT);
6402 SDValue Ops[] = { Op1 };
6403 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6406 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6407 EVT VT, SDValue Op1,
6409 SDVTList VTs = getVTList(VT);
6410 SDValue Ops[] = { Op1, Op2 };
6411 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6414 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6415 EVT VT, SDValue Op1,
6416 SDValue Op2, SDValue Op3) {
6417 SDVTList VTs = getVTList(VT);
6418 SDValue Ops[] = { Op1, Op2, Op3 };
6419 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6422 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6423 EVT VT, ArrayRef<SDValue> Ops) {
6424 SDVTList VTs = getVTList(VT);
6425 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6428 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6429 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6430 SDVTList VTs = getVTList(VT1, VT2);
6431 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6434 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6436 SDVTList VTs = getVTList(VT1, VT2);
6437 return SelectNodeTo(N, MachineOpc, VTs, None);
6440 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6441 EVT VT1, EVT VT2, EVT VT3,
6442 ArrayRef<SDValue> Ops) {
6443 SDVTList VTs = getVTList(VT1, VT2, VT3);
6444 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6447 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6449 SDValue Op1, SDValue Op2) {
6450 SDVTList VTs = getVTList(VT1, VT2);
6451 SDValue Ops[] = { Op1, Op2 };
6452 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6455 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6456 SDVTList VTs,ArrayRef<SDValue> Ops) {
6457 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6458 // Reset the NodeID to -1.
6461 ReplaceAllUsesWith(N, New);
6467 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6468 /// the line number information on the merged node since it is not possible to
6469 /// preserve the information that operation is associated with multiple lines.
6470 /// This will make the debugger working better at -O0, were there is a higher
6471 /// probability having other instructions associated with that line.
6473 /// For IROrder, we keep the smaller of the two
6474 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6475 DebugLoc NLoc = N->getDebugLoc();
6476 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6477 N->setDebugLoc(DebugLoc());
6479 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6480 N->setIROrder(Order);
6484 /// MorphNodeTo - This *mutates* the specified node to have the specified
6485 /// return type, opcode, and operands.
6487 /// Note that MorphNodeTo returns the resultant node. If there is already a
6488 /// node of the specified opcode and operands, it returns that node instead of
6489 /// the current one. Note that the SDLoc need not be the same.
6491 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6492 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6493 /// node, and because it doesn't require CSE recalculation for any of
6494 /// the node's users.
6496 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6497 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6498 /// the legalizer which maintain worklists that would need to be updated when
6499 /// deleting things.
6500 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6501 SDVTList VTs, ArrayRef<SDValue> Ops) {
6502 // If an identical node already exists, use it.
6504 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6505 FoldingSetNodeID ID;
6506 AddNodeIDNode(ID, Opc, VTs, Ops);
6507 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6508 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6511 if (!RemoveNodeFromCSEMaps(N))
6514 // Start the morphing.
6516 N->ValueList = VTs.VTs;
6517 N->NumValues = VTs.NumVTs;
6519 // Clear the operands list, updating used nodes to remove this from their
6520 // use list. Keep track of any operands that become dead as a result.
6521 SmallPtrSet<SDNode*, 16> DeadNodeSet;
6522 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6524 SDNode *Used = Use.getNode();
6526 if (Used->use_empty())
6527 DeadNodeSet.insert(Used);
6530 // For MachineNode, initialize the memory references information.
6531 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6532 MN->setMemRefs(nullptr, nullptr);
6534 // Swap for an appropriately sized array from the recycler.
6536 createOperands(N, Ops);
6538 // Delete any nodes that are still dead after adding the uses for the
6540 if (!DeadNodeSet.empty()) {
6541 SmallVector<SDNode *, 16> DeadNodes;
6542 for (SDNode *N : DeadNodeSet)
6544 DeadNodes.push_back(N);
6545 RemoveDeadNodes(DeadNodes);
6549 CSEMap.InsertNode(N, IP); // Memoize the new node.
6553 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
6554 unsigned OrigOpc = Node->getOpcode();
6556 bool IsUnary = false;
6559 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
6560 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
6561 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
6562 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
6563 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
6564 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
6565 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
6566 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
6567 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
6568 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
6569 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
6570 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
6571 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
6572 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
6573 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
6574 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
6575 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
6576 case ISD::STRICT_FNEARBYINT:
6577 NewOpc = ISD::FNEARBYINT;
6582 // We're taking this node out of the chain, so we need to re-link things.
6583 SDValue InputChain = Node->getOperand(0);
6584 SDValue OutputChain = SDValue(Node, 1);
6585 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
6587 SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
6588 SDNode *Res = nullptr;
6590 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
6592 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
6593 Node->getOperand(2) });
6595 // MorphNodeTo can operate in two ways: if an existing node with the
6596 // specified operands exists, it can just return it. Otherwise, it
6597 // updates the node in place to have the requested operands.
6599 // If we updated the node in place, reset the node ID. To the isel,
6600 // this should be just like a newly allocated machine node.
6603 ReplaceAllUsesWith(Node, Res);
6604 RemoveDeadNode(Node);
6610 /// getMachineNode - These are used for target selectors to create a new node
6611 /// with specified return type(s), MachineInstr opcode, and operands.
6613 /// Note that getMachineNode returns the resultant node. If there is already a
6614 /// node of the specified opcode and operands, it returns that node instead of
6615 /// the current one.
6616 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6618 SDVTList VTs = getVTList(VT);
6619 return getMachineNode(Opcode, dl, VTs, None);
6622 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6623 EVT VT, SDValue Op1) {
6624 SDVTList VTs = getVTList(VT);
6625 SDValue Ops[] = { Op1 };
6626 return getMachineNode(Opcode, dl, VTs, Ops);
6629 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6630 EVT VT, SDValue Op1, SDValue Op2) {
6631 SDVTList VTs = getVTList(VT);
6632 SDValue Ops[] = { Op1, Op2 };
6633 return getMachineNode(Opcode, dl, VTs, Ops);
6636 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6637 EVT VT, SDValue Op1, SDValue Op2,
6639 SDVTList VTs = getVTList(VT);
6640 SDValue Ops[] = { Op1, Op2, Op3 };
6641 return getMachineNode(Opcode, dl, VTs, Ops);
6644 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6645 EVT VT, ArrayRef<SDValue> Ops) {
6646 SDVTList VTs = getVTList(VT);
6647 return getMachineNode(Opcode, dl, VTs, Ops);
6650 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6651 EVT VT1, EVT VT2, SDValue Op1,
6653 SDVTList VTs = getVTList(VT1, VT2);
6654 SDValue Ops[] = { Op1, Op2 };
6655 return getMachineNode(Opcode, dl, VTs, Ops);
6658 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6659 EVT VT1, EVT VT2, SDValue Op1,
6660 SDValue Op2, SDValue Op3) {
6661 SDVTList VTs = getVTList(VT1, VT2);
6662 SDValue Ops[] = { Op1, Op2, Op3 };
6663 return getMachineNode(Opcode, dl, VTs, Ops);
6666 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6668 ArrayRef<SDValue> Ops) {
6669 SDVTList VTs = getVTList(VT1, VT2);
6670 return getMachineNode(Opcode, dl, VTs, Ops);
6673 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6674 EVT VT1, EVT VT2, EVT VT3,
6675 SDValue Op1, SDValue Op2) {
6676 SDVTList VTs = getVTList(VT1, VT2, VT3);
6677 SDValue Ops[] = { Op1, Op2 };
6678 return getMachineNode(Opcode, dl, VTs, Ops);
6681 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6682 EVT VT1, EVT VT2, EVT VT3,
6683 SDValue Op1, SDValue Op2,
6685 SDVTList VTs = getVTList(VT1, VT2, VT3);
6686 SDValue Ops[] = { Op1, Op2, Op3 };
6687 return getMachineNode(Opcode, dl, VTs, Ops);
6690 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6691 EVT VT1, EVT VT2, EVT VT3,
6692 ArrayRef<SDValue> Ops) {
6693 SDVTList VTs = getVTList(VT1, VT2, VT3);
6694 return getMachineNode(Opcode, dl, VTs, Ops);
6697 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6698 ArrayRef<EVT> ResultTys,
6699 ArrayRef<SDValue> Ops) {
6700 SDVTList VTs = getVTList(ResultTys);
6701 return getMachineNode(Opcode, dl, VTs, Ops);
6704 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6706 ArrayRef<SDValue> Ops) {
6707 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6712 FoldingSetNodeID ID;
6713 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6715 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6716 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6720 // Allocate a new MachineSDNode.
6721 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6722 createOperands(N, Ops);
6725 CSEMap.InsertNode(N, IP);
6731 /// getTargetExtractSubreg - A convenience function for creating
6732 /// TargetOpcode::EXTRACT_SUBREG nodes.
6733 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6735 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6736 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6737 VT, Operand, SRIdxVal);
6738 return SDValue(Subreg, 0);
6741 /// getTargetInsertSubreg - A convenience function for creating
6742 /// TargetOpcode::INSERT_SUBREG nodes.
6743 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6744 SDValue Operand, SDValue Subreg) {
6745 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6746 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6747 VT, Operand, Subreg, SRIdxVal);
6748 return SDValue(Result, 0);
6751 /// getNodeIfExists - Get the specified node if it's already available, or
6752 /// else return NULL.
6753 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6754 ArrayRef<SDValue> Ops,
6755 const SDNodeFlags Flags) {
6756 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6757 FoldingSetNodeID ID;
6758 AddNodeIDNode(ID, Opcode, VTList, Ops);
6760 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6761 E->intersectFlagsWith(Flags);
6768 /// getDbgValue - Creates a SDDbgValue node.
6771 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6772 unsigned R, bool IsIndirect, uint64_t Off,
6773 const DebugLoc &DL, unsigned O) {
6774 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6775 "Expected inlined-at fields to agree");
6776 return new (DbgInfo->getAlloc())
6777 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6781 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6782 const Value *C, uint64_t Off,
6783 const DebugLoc &DL, unsigned O) {
6784 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6785 "Expected inlined-at fields to agree");
6786 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6790 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6791 unsigned FI, uint64_t Off,
6794 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6795 "Expected inlined-at fields to agree");
6796 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6801 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6802 /// pointed to by a use iterator is deleted, increment the use iterator
6803 /// so that it doesn't dangle.
6805 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6806 SDNode::use_iterator &UI;
6807 SDNode::use_iterator &UE;
6809 void NodeDeleted(SDNode *N, SDNode *E) override {
6810 // Increment the iterator as needed.
6811 while (UI != UE && N == *UI)
6816 RAUWUpdateListener(SelectionDAG &d,
6817 SDNode::use_iterator &ui,
6818 SDNode::use_iterator &ue)
6819 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6822 } // end anonymous namespace
6824 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6825 /// This can cause recursive merging of nodes in the DAG.
6827 /// This version assumes From has a single result value.
6829 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6830 SDNode *From = FromN.getNode();
6831 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6832 "Cannot replace with this method!");
6833 assert(From != To.getNode() && "Cannot replace uses of with self");
6835 // Preserve Debug Values
6836 TransferDbgValues(FromN, To);
6838 // Iterate over all the existing uses of From. New uses will be added
6839 // to the beginning of the use list, which we avoid visiting.
6840 // This specifically avoids visiting uses of From that arise while the
6841 // replacement is happening, because any such uses would be the result
6842 // of CSE: If an existing node looks like From after one of its operands
6843 // is replaced by To, we don't want to replace of all its users with To
6844 // too. See PR3018 for more info.
6845 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6846 RAUWUpdateListener Listener(*this, UI, UE);
6850 // This node is about to morph, remove its old self from the CSE maps.
6851 RemoveNodeFromCSEMaps(User);
6853 // A user can appear in a use list multiple times, and when this
6854 // happens the uses are usually next to each other in the list.
6855 // To help reduce the number of CSE recomputations, process all
6856 // the uses of this user that we can find this way.
6858 SDUse &Use = UI.getUse();
6861 } while (UI != UE && *UI == User);
6863 // Now that we have modified User, add it back to the CSE maps. If it
6864 // already exists there, recursively merge the results together.
6865 AddModifiedNodeToCSEMaps(User);
6868 // If we just RAUW'd the root, take note.
6869 if (FromN == getRoot())
6873 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6874 /// This can cause recursive merging of nodes in the DAG.
6876 /// This version assumes that for each value of From, there is a
6877 /// corresponding value in To in the same position with the same type.
6879 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6881 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6882 assert((!From->hasAnyUseOfValue(i) ||
6883 From->getValueType(i) == To->getValueType(i)) &&
6884 "Cannot use this version of ReplaceAllUsesWith!");
6887 // Handle the trivial case.
6891 // Preserve Debug Info. Only do this if there's a use.
6892 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6893 if (From->hasAnyUseOfValue(i)) {
6894 assert((i < To->getNumValues()) && "Invalid To location");
6895 TransferDbgValues(SDValue(From, i), SDValue(To, i));
6898 // Iterate over just the existing users of From. See the comments in
6899 // the ReplaceAllUsesWith above.
6900 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6901 RAUWUpdateListener Listener(*this, UI, UE);
6905 // This node is about to morph, remove its old self from the CSE maps.
6906 RemoveNodeFromCSEMaps(User);
6908 // A user can appear in a use list multiple times, and when this
6909 // happens the uses are usually next to each other in the list.
6910 // To help reduce the number of CSE recomputations, process all
6911 // the uses of this user that we can find this way.
6913 SDUse &Use = UI.getUse();
6916 } while (UI != UE && *UI == User);
6918 // Now that we have modified User, add it back to the CSE maps. If it
6919 // already exists there, recursively merge the results together.
6920 AddModifiedNodeToCSEMaps(User);
6923 // If we just RAUW'd the root, take note.
6924 if (From == getRoot().getNode())
6925 setRoot(SDValue(To, getRoot().getResNo()));
6928 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6929 /// This can cause recursive merging of nodes in the DAG.
6931 /// This version can replace From with any result values. To must match the
6932 /// number and types of values returned by From.
6933 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6934 if (From->getNumValues() == 1) // Handle the simple case efficiently.
6935 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6937 // Preserve Debug Info.
6938 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6939 TransferDbgValues(SDValue(From, i), *To);
6941 // Iterate over just the existing users of From. See the comments in
6942 // the ReplaceAllUsesWith above.
6943 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6944 RAUWUpdateListener Listener(*this, UI, UE);
6948 // This node is about to morph, remove its old self from the CSE maps.
6949 RemoveNodeFromCSEMaps(User);
6951 // A user can appear in a use list multiple times, and when this
6952 // happens the uses are usually next to each other in the list.
6953 // To help reduce the number of CSE recomputations, process all
6954 // the uses of this user that we can find this way.
6956 SDUse &Use = UI.getUse();
6957 const SDValue &ToOp = To[Use.getResNo()];
6960 } while (UI != UE && *UI == User);
6962 // Now that we have modified User, add it back to the CSE maps. If it
6963 // already exists there, recursively merge the results together.
6964 AddModifiedNodeToCSEMaps(User);
6967 // If we just RAUW'd the root, take note.
6968 if (From == getRoot().getNode())
6969 setRoot(SDValue(To[getRoot().getResNo()]));
6972 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6973 /// uses of other values produced by From.getNode() alone. The Deleted
6974 /// vector is handled the same way as for ReplaceAllUsesWith.
6975 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6976 // Handle the really simple, really trivial case efficiently.
6977 if (From == To) return;
6979 // Handle the simple, trivial, case efficiently.
6980 if (From.getNode()->getNumValues() == 1) {
6981 ReplaceAllUsesWith(From, To);
6985 // Preserve Debug Info.
6986 TransferDbgValues(From, To);
6988 // Iterate over just the existing users of From. See the comments in
6989 // the ReplaceAllUsesWith above.
6990 SDNode::use_iterator UI = From.getNode()->use_begin(),
6991 UE = From.getNode()->use_end();
6992 RAUWUpdateListener Listener(*this, UI, UE);
6995 bool UserRemovedFromCSEMaps = false;
6997 // A user can appear in a use list multiple times, and when this
6998 // happens the uses are usually next to each other in the list.
6999 // To help reduce the number of CSE recomputations, process all
7000 // the uses of this user that we can find this way.
7002 SDUse &Use = UI.getUse();
7004 // Skip uses of different values from the same node.
7005 if (Use.getResNo() != From.getResNo()) {
7010 // If this node hasn't been modified yet, it's still in the CSE maps,
7011 // so remove its old self from the CSE maps.
7012 if (!UserRemovedFromCSEMaps) {
7013 RemoveNodeFromCSEMaps(User);
7014 UserRemovedFromCSEMaps = true;
7019 } while (UI != UE && *UI == User);
7021 // We are iterating over all uses of the From node, so if a use
7022 // doesn't use the specific value, no changes are made.
7023 if (!UserRemovedFromCSEMaps)
7026 // Now that we have modified User, add it back to the CSE maps. If it
7027 // already exists there, recursively merge the results together.
7028 AddModifiedNodeToCSEMaps(User);
7031 // If we just RAUW'd the root, take note.
7032 if (From == getRoot())
7038 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
7039 /// to record information about a use.
7046 /// operator< - Sort Memos by User.
7047 bool operator<(const UseMemo &L, const UseMemo &R) {
7048 return (intptr_t)L.User < (intptr_t)R.User;
7051 } // end anonymous namespace
7053 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
7054 /// uses of other values produced by From.getNode() alone. The same value
7055 /// may appear in both the From and To list. The Deleted vector is
7056 /// handled the same way as for ReplaceAllUsesWith.
7057 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
7060 // Handle the simple, trivial case efficiently.
7062 return ReplaceAllUsesOfValueWith(*From, *To);
7064 TransferDbgValues(*From, *To);
7066 // Read up all the uses and make records of them. This helps
7067 // processing new uses that are introduced during the
7068 // replacement process.
7069 SmallVector<UseMemo, 4> Uses;
7070 for (unsigned i = 0; i != Num; ++i) {
7071 unsigned FromResNo = From[i].getResNo();
7072 SDNode *FromNode = From[i].getNode();
7073 for (SDNode::use_iterator UI = FromNode->use_begin(),
7074 E = FromNode->use_end(); UI != E; ++UI) {
7075 SDUse &Use = UI.getUse();
7076 if (Use.getResNo() == FromResNo) {
7077 UseMemo Memo = { *UI, i, &Use };
7078 Uses.push_back(Memo);
7083 // Sort the uses, so that all the uses from a given User are together.
7084 std::sort(Uses.begin(), Uses.end());
7086 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
7087 UseIndex != UseIndexEnd; ) {
7088 // We know that this user uses some value of From. If it is the right
7089 // value, update it.
7090 SDNode *User = Uses[UseIndex].User;
7092 // This node is about to morph, remove its old self from the CSE maps.
7093 RemoveNodeFromCSEMaps(User);
7095 // The Uses array is sorted, so all the uses for a given User
7096 // are next to each other in the list.
7097 // To help reduce the number of CSE recomputations, process all
7098 // the uses of this user that we can find this way.
7100 unsigned i = Uses[UseIndex].Index;
7101 SDUse &Use = *Uses[UseIndex].Use;
7105 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
7107 // Now that we have modified User, add it back to the CSE maps. If it
7108 // already exists there, recursively merge the results together.
7109 AddModifiedNodeToCSEMaps(User);
7113 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
7114 /// based on their topological order. It returns the maximum id and a vector
7115 /// of the SDNodes* in assigned order by reference.
7116 unsigned SelectionDAG::AssignTopologicalOrder() {
7117 unsigned DAGSize = 0;
7119 // SortedPos tracks the progress of the algorithm. Nodes before it are
7120 // sorted, nodes after it are unsorted. When the algorithm completes
7121 // it is at the end of the list.
7122 allnodes_iterator SortedPos = allnodes_begin();
7124 // Visit all the nodes. Move nodes with no operands to the front of
7125 // the list immediately. Annotate nodes that do have operands with their
7126 // operand count. Before we do this, the Node Id fields of the nodes
7127 // may contain arbitrary values. After, the Node Id fields for nodes
7128 // before SortedPos will contain the topological sort index, and the
7129 // Node Id fields for nodes At SortedPos and after will contain the
7130 // count of outstanding operands.
7131 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7133 checkForCycles(N, this);
7134 unsigned Degree = N->getNumOperands();
7136 // A node with no uses, add it to the result array immediately.
7137 N->setNodeId(DAGSize++);
7138 allnodes_iterator Q(N);
7140 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7141 assert(SortedPos != AllNodes.end() && "Overran node list");
7144 // Temporarily use the Node Id as scratch space for the degree count.
7145 N->setNodeId(Degree);
7149 // Visit all the nodes. As we iterate, move nodes into sorted order,
7150 // such that by the time the end is reached all nodes will be sorted.
7151 for (SDNode &Node : allnodes()) {
7153 checkForCycles(N, this);
7154 // N is in sorted position, so all its uses have one less operand
7155 // that needs to be sorted.
7156 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7159 unsigned Degree = P->getNodeId();
7160 assert(Degree != 0 && "Invalid node degree");
7163 // All of P's operands are sorted, so P may sorted now.
7164 P->setNodeId(DAGSize++);
7165 if (P->getIterator() != SortedPos)
7166 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7167 assert(SortedPos != AllNodes.end() && "Overran node list");
7170 // Update P's outstanding operand count.
7171 P->setNodeId(Degree);
7174 if (Node.getIterator() == SortedPos) {
7176 allnodes_iterator I(N);
7178 dbgs() << "Overran sorted position:\n";
7179 S->dumprFull(this); dbgs() << "\n";
7180 dbgs() << "Checking if this is due to cycles\n";
7181 checkForCycles(this, true);
7183 llvm_unreachable(nullptr);
7187 assert(SortedPos == AllNodes.end() &&
7188 "Topological sort incomplete!");
7189 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7190 "First node in topological sort is not the entry token!");
7191 assert(AllNodes.front().getNodeId() == 0 &&
7192 "First node in topological sort has non-zero id!");
7193 assert(AllNodes.front().getNumOperands() == 0 &&
7194 "First node in topological sort has operands!");
7195 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7196 "Last node in topologic sort has unexpected id!");
7197 assert(AllNodes.back().use_empty() &&
7198 "Last node in topologic sort has users!");
7199 assert(DAGSize == allnodes_size() && "Node count mismatch!");
7203 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7204 /// value is produced by SD.
7205 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7207 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7208 SD->setHasDebugValue(true);
7210 DbgInfo->add(DB, SD, isParameter);
7213 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
7214 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
7215 if (From == To || !From.getNode()->getHasDebugValue())
7217 SDNode *FromNode = From.getNode();
7218 SDNode *ToNode = To.getNode();
7219 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
7220 SmallVector<SDDbgValue *, 2> ClonedDVs;
7221 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
7223 SDDbgValue *Dbg = *I;
7224 // Only add Dbgvalues attached to same ResNo.
7225 if (Dbg->getKind() == SDDbgValue::SDNODE &&
7226 Dbg->getSDNode() == From.getNode() &&
7227 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
7228 assert(FromNode != ToNode &&
7229 "Should not transfer Debug Values intranode");
7231 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
7232 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
7233 Dbg->getDebugLoc(), Dbg->getOrder());
7234 ClonedDVs.push_back(Clone);
7235 Dbg->setIsInvalidated();
7238 for (SDDbgValue *I : ClonedDVs)
7239 AddDbgValue(I, ToNode, false);
7242 //===----------------------------------------------------------------------===//
7244 //===----------------------------------------------------------------------===//
7246 bool llvm::isNullConstant(SDValue V) {
7247 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7248 return Const != nullptr && Const->isNullValue();
7251 bool llvm::isNullFPConstant(SDValue V) {
7252 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7253 return Const != nullptr && Const->isZero() && !Const->isNegative();
7256 bool llvm::isAllOnesConstant(SDValue V) {
7257 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7258 return Const != nullptr && Const->isAllOnesValue();
7261 bool llvm::isOneConstant(SDValue V) {
7262 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7263 return Const != nullptr && Const->isOne();
7266 bool llvm::isBitwiseNot(SDValue V) {
7267 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7270 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7271 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7274 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7275 BitVector UndefElements;
7276 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7278 // BuildVectors can truncate their operands. Ignore that case here.
7279 // FIXME: We blindly ignore splats which include undef which is overly
7281 if (CN && UndefElements.none() &&
7282 CN->getValueType(0) == N.getValueType().getScalarType())
7289 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7290 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7293 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7294 BitVector UndefElements;
7295 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7297 if (CN && UndefElements.none())
7304 HandleSDNode::~HandleSDNode() {
7308 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7310 const GlobalValue *GA, EVT VT,
7311 int64_t o, unsigned char TF)
7312 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7316 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7317 EVT VT, unsigned SrcAS,
7319 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7320 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7322 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7323 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7324 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7325 MemSDNodeBits.IsVolatile = MMO->isVolatile();
7326 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7327 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7328 MemSDNodeBits.IsInvariant = MMO->isInvariant();
7330 // We check here that the size of the memory operand fits within the size of
7331 // the MMO. This is because the MMO might indicate only a possible address
7332 // range instead of specifying the affected memory addresses precisely.
7333 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7336 /// Profile - Gather unique data for the node.
7338 void SDNode::Profile(FoldingSetNodeID &ID) const {
7339 AddNodeIDNode(ID, this);
7345 std::vector<EVT> VTs;
7348 VTs.reserve(MVT::LAST_VALUETYPE);
7349 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7350 VTs.push_back(MVT((MVT::SimpleValueType)i));
7354 } // end anonymous namespace
7356 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
7357 static ManagedStatic<EVTArray> SimpleVTArray;
7358 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
7360 /// getValueTypeList - Return a pointer to the specified value type.
7362 const EVT *SDNode::getValueTypeList(EVT VT) {
7363 if (VT.isExtended()) {
7364 sys::SmartScopedLock<true> Lock(*VTMutex);
7365 return &(*EVTs->insert(VT).first);
7367 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7368 "Value type out of range!");
7369 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7373 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7374 /// indicated value. This method ignores uses of other values defined by this
7376 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7377 assert(Value < getNumValues() && "Bad value!");
7379 // TODO: Only iterate over uses of a given value of the node
7380 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7381 if (UI.getUse().getResNo() == Value) {
7388 // Found exactly the right number of uses?
7392 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7393 /// value. This method ignores uses of other values defined by this operation.
7394 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7395 assert(Value < getNumValues() && "Bad value!");
7397 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7398 if (UI.getUse().getResNo() == Value)
7404 /// isOnlyUserOf - Return true if this node is the only use of N.
7405 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7407 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7418 /// Return true if the only users of N are contained in Nodes.
7419 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7421 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7423 if (llvm::any_of(Nodes,
7424 [&User](const SDNode *Node) { return User == Node; }))
7433 /// isOperand - Return true if this node is an operand of N.
7434 bool SDValue::isOperandOf(const SDNode *N) const {
7435 for (const SDValue &Op : N->op_values())
7441 bool SDNode::isOperandOf(const SDNode *N) const {
7442 for (const SDValue &Op : N->op_values())
7443 if (this == Op.getNode())
7448 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7449 /// be a chain) reaches the specified operand without crossing any
7450 /// side-effecting instructions on any chain path. In practice, this looks
7451 /// through token factors and non-volatile loads. In order to remain efficient,
7452 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7454 /// Note that we only need to examine chains when we're searching for
7455 /// side-effects; SelectionDAG requires that all side-effects are represented
7456 /// by chains, even if another operand would force a specific ordering. This
7457 /// constraint is necessary to allow transformations like splitting loads.
7458 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7459 unsigned Depth) const {
7460 if (*this == Dest) return true;
7462 // Don't search too deeply, we just want to be able to see through
7463 // TokenFactor's etc.
7464 if (Depth == 0) return false;
7466 // If this is a token factor, all inputs to the TF happen in parallel.
7467 if (getOpcode() == ISD::TokenFactor) {
7468 // First, try a shallow search.
7469 if (is_contained((*this)->ops(), Dest)) {
7470 // We found the chain we want as an operand of this TokenFactor.
7471 // Essentially, we reach the chain without side-effects if we could
7472 // serialize the TokenFactor into a simple chain of operations with
7473 // Dest as the last operation. This is automatically true if the
7474 // chain has one use: there are no other ordering constraints.
7475 // If the chain has more than one use, we give up: some other
7476 // use of Dest might force a side-effect between Dest and the current
7478 if (Dest.hasOneUse())
7481 // Next, try a deep search: check whether every operand of the TokenFactor
7483 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
7484 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7488 // Loads don't have side effects, look through them.
7489 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7490 if (!Ld->isVolatile())
7491 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7496 bool SDNode::hasPredecessor(const SDNode *N) const {
7497 SmallPtrSet<const SDNode *, 32> Visited;
7498 SmallVector<const SDNode *, 16> Worklist;
7499 Worklist.push_back(this);
7500 return hasPredecessorHelper(N, Visited, Worklist);
7503 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
7504 this->Flags.intersectWith(Flags);
7507 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7508 assert(N->getNumValues() == 1 &&
7509 "Can't unroll a vector with multiple results!");
7511 EVT VT = N->getValueType(0);
7512 unsigned NE = VT.getVectorNumElements();
7513 EVT EltVT = VT.getVectorElementType();
7516 SmallVector<SDValue, 8> Scalars;
7517 SmallVector<SDValue, 4> Operands(N->getNumOperands());
7519 // If ResNE is 0, fully unroll the vector op.
7522 else if (NE > ResNE)
7526 for (i= 0; i != NE; ++i) {
7527 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7528 SDValue Operand = N->getOperand(j);
7529 EVT OperandVT = Operand.getValueType();
7530 if (OperandVT.isVector()) {
7531 // A vector operand; extract a single element.
7532 EVT OperandEltVT = OperandVT.getVectorElementType();
7534 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7535 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7537 // A scalar operand; just use it as is.
7538 Operands[j] = Operand;
7542 switch (N->getOpcode()) {
7544 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7549 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7556 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7557 getShiftAmountOperand(Operands[0].getValueType(),
7560 case ISD::SIGN_EXTEND_INREG:
7561 case ISD::FP_ROUND_INREG: {
7562 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7563 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7565 getValueType(ExtVT)));
7570 for (; i < ResNE; ++i)
7571 Scalars.push_back(getUNDEF(EltVT));
7573 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7574 return getBuildVector(VecVT, dl, Scalars);
7577 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7581 if (LD->isVolatile() || Base->isVolatile())
7583 if (LD->isIndexed() || Base->isIndexed())
7585 if (LD->getChain() != Base->getChain())
7587 EVT VT = LD->getValueType(0);
7588 if (VT.getSizeInBits() / 8 != Bytes)
7591 SDValue Loc = LD->getOperand(1);
7592 SDValue BaseLoc = Base->getOperand(1);
7593 if (Loc.getOpcode() == ISD::FrameIndex) {
7594 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7596 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7597 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7598 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7599 int FS = MFI.getObjectSize(FI);
7600 int BFS = MFI.getObjectSize(BFI);
7601 if (FS != BFS || FS != (int)Bytes) return false;
7602 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
7606 if (isBaseWithConstantOffset(Loc)) {
7607 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
7608 if (Loc.getOperand(0) == BaseLoc) {
7609 // If the base location is a simple address with no offset itself, then
7610 // the second load's first add operand should be the base address.
7611 if (LocOffset == Dist * (int)Bytes)
7613 } else if (isBaseWithConstantOffset(BaseLoc)) {
7614 // The base location itself has an offset, so subtract that value from the
7615 // second load's offset before comparing to distance * size.
7617 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
7618 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
7619 if ((LocOffset - BOffset) == Dist * (int)Bytes)
7624 const GlobalValue *GV1 = nullptr;
7625 const GlobalValue *GV2 = nullptr;
7626 int64_t Offset1 = 0;
7627 int64_t Offset2 = 0;
7628 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7629 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7630 if (isGA1 && isGA2 && GV1 == GV2)
7631 return Offset1 == (Offset2 + Dist*Bytes);
7635 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7636 /// it cannot be inferred.
7637 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7638 // If this is a GlobalAddress + cst, return the alignment.
7639 const GlobalValue *GV;
7640 int64_t GVOffset = 0;
7641 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7642 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7643 KnownBits Known(PtrWidth);
7644 llvm::computeKnownBits(GV, Known, getDataLayout());
7645 unsigned AlignBits = Known.countMinTrailingZeros();
7646 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7648 return MinAlign(Align, GVOffset);
7651 // If this is a direct reference to a stack slot, use information about the
7652 // stack slot's alignment.
7653 int FrameIdx = 1 << 31;
7654 int64_t FrameOffset = 0;
7655 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7656 FrameIdx = FI->getIndex();
7657 } else if (isBaseWithConstantOffset(Ptr) &&
7658 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7660 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7661 FrameOffset = Ptr.getConstantOperandVal(1);
7664 if (FrameIdx != (1 << 31)) {
7665 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7666 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7674 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7675 /// which is split (or expanded) into two not necessarily identical pieces.
7676 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7677 // Currently all types are split in half.
7680 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7682 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
7684 return std::make_pair(LoVT, HiVT);
7687 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7689 std::pair<SDValue, SDValue>
7690 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7692 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7693 N.getValueType().getVectorNumElements() &&
7694 "More vector elements requested than available!");
7696 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7697 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7698 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7699 getConstant(LoVT.getVectorNumElements(), DL,
7700 TLI->getVectorIdxTy(getDataLayout())));
7701 return std::make_pair(Lo, Hi);
7704 void SelectionDAG::ExtractVectorElements(SDValue Op,
7705 SmallVectorImpl<SDValue> &Args,
7706 unsigned Start, unsigned Count) {
7707 EVT VT = Op.getValueType();
7709 Count = VT.getVectorNumElements();
7711 EVT EltVT = VT.getVectorElementType();
7712 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7714 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7715 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7716 Op, getConstant(i, SL, IdxTy)));
7720 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7721 unsigned GlobalAddressSDNode::getAddressSpace() const {
7722 return getGlobal()->getType()->getAddressSpace();
7725 Type *ConstantPoolSDNode::getType() const {
7726 if (isMachineConstantPoolEntry())
7727 return Val.MachineCPVal->getType();
7728 return Val.ConstVal->getType();
7731 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
7732 unsigned &SplatBitSize,
7734 unsigned MinSplatBits,
7735 bool IsBigEndian) const {
7736 EVT VT = getValueType(0);
7737 assert(VT.isVector() && "Expected a vector type");
7738 unsigned VecWidth = VT.getSizeInBits();
7739 if (MinSplatBits > VecWidth)
7742 // FIXME: The widths are based on this node's type, but build vectors can
7743 // truncate their operands.
7744 SplatValue = APInt(VecWidth, 0);
7745 SplatUndef = APInt(VecWidth, 0);
7747 // Get the bits. Bits with undefined values (when the corresponding element
7748 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7749 // in SplatValue. If any of the values are not constant, give up and return
7751 unsigned int NumOps = getNumOperands();
7752 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
7753 unsigned EltWidth = VT.getScalarSizeInBits();
7755 for (unsigned j = 0; j < NumOps; ++j) {
7756 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
7757 SDValue OpVal = getOperand(i);
7758 unsigned BitPos = j * EltWidth;
7760 if (OpVal.isUndef())
7761 SplatUndef.setBits(BitPos, BitPos + EltWidth);
7762 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
7763 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
7764 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7765 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
7770 // The build_vector is all constants or undefs. Find the smallest element
7771 // size that splats the vector.
7772 HasAnyUndefs = (SplatUndef != 0);
7774 // FIXME: This does not work for vectors with elements less than 8 bits.
7775 while (VecWidth > 8) {
7776 unsigned HalfSize = VecWidth / 2;
7777 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7778 APInt LowValue = SplatValue.trunc(HalfSize);
7779 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7780 APInt LowUndef = SplatUndef.trunc(HalfSize);
7782 // If the two halves do not match (ignoring undef bits), stop here.
7783 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7784 MinSplatBits > HalfSize)
7787 SplatValue = HighValue | LowValue;
7788 SplatUndef = HighUndef & LowUndef;
7790 VecWidth = HalfSize;
7793 SplatBitSize = VecWidth;
7797 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7798 if (UndefElements) {
7799 UndefElements->clear();
7800 UndefElements->resize(getNumOperands());
7803 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7804 SDValue Op = getOperand(i);
7807 (*UndefElements)[i] = true;
7808 } else if (!Splatted) {
7810 } else if (Splatted != Op) {
7816 assert(getOperand(0).isUndef() &&
7817 "Can only have a splat without a constant for all undefs.");
7818 return getOperand(0);
7825 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7826 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7830 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7831 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7835 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7836 uint32_t BitWidth) const {
7837 if (ConstantFPSDNode *CN =
7838 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7840 APSInt IntVal(BitWidth);
7841 const APFloat &APF = CN->getValueAPF();
7842 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7847 return IntVal.exactLogBase2();
7852 bool BuildVectorSDNode::isConstant() const {
7853 for (const SDValue &Op : op_values()) {
7854 unsigned Opc = Op.getOpcode();
7855 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7861 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7862 // Find the first non-undef value in the shuffle mask.
7864 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7867 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7869 // Make sure all remaining elements are either undef or the same as the first
7871 for (int Idx = Mask[i]; i != e; ++i)
7872 if (Mask[i] >= 0 && Mask[i] != Idx)
7877 // \brief Returns the SDNode if it is a constant integer BuildVector
7878 // or constant integer.
7879 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7880 if (isa<ConstantSDNode>(N))
7882 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7884 // Treat a GlobalAddress supporting constant offset folding as a
7885 // constant integer.
7886 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7887 if (GA->getOpcode() == ISD::GlobalAddress &&
7888 TLI->isOffsetFoldingLegal(GA))
7893 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
7894 if (isa<ConstantFPSDNode>(N))
7897 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
7904 static void checkForCyclesHelper(const SDNode *N,
7905 SmallPtrSetImpl<const SDNode*> &Visited,
7906 SmallPtrSetImpl<const SDNode*> &Checked,
7907 const llvm::SelectionDAG *DAG) {
7908 // If this node has already been checked, don't check it again.
7909 if (Checked.count(N))
7912 // If a node has already been visited on this depth-first walk, reject it as
7914 if (!Visited.insert(N).second) {
7915 errs() << "Detected cycle in SelectionDAG\n";
7916 dbgs() << "Offending node:\n";
7917 N->dumprFull(DAG); dbgs() << "\n";
7921 for (const SDValue &Op : N->op_values())
7922 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7929 void llvm::checkForCycles(const llvm::SDNode *N,
7930 const llvm::SelectionDAG *DAG,
7934 #ifdef EXPENSIVE_CHECKS
7936 #endif // EXPENSIVE_CHECKS
7938 assert(N && "Checking nonexistent SDNode");
7939 SmallPtrSet<const SDNode*, 32> visited;
7940 SmallPtrSet<const SDNode*, 32> checked;
7941 checkForCyclesHelper(N, visited, checked, DAG);
7946 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7947 checkForCycles(DAG->getRoot().getNode(), DAG, force);