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 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Function.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetFrameInfo.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetIntrinsicInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/System/Mutex.h"
42 #include "llvm/ADT/SetVector.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/ADT/StringExtras.h"
51 extern cl::opt<bool> DisableInstScheduling;
53 /// makeVTList - Return an instance of the SDVTList struct initialized with the
54 /// specified members.
55 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
56 SDVTList Res = {VTs, NumVTs};
60 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
61 switch (VT.getSimpleVT().SimpleTy) {
62 default: llvm_unreachable("Unknown FP format");
63 case MVT::f32: return &APFloat::IEEEsingle;
64 case MVT::f64: return &APFloat::IEEEdouble;
65 case MVT::f80: return &APFloat::x87DoubleExtended;
66 case MVT::f128: return &APFloat::IEEEquad;
67 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
71 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
73 //===----------------------------------------------------------------------===//
74 // ConstantFPSDNode Class
75 //===----------------------------------------------------------------------===//
77 /// isExactlyValue - We don't rely on operator== working on double values, as
78 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
79 /// As such, this method can be used to do an exact bit-for-bit comparison of
80 /// two floating point values.
81 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
82 return getValueAPF().bitwiseIsEqual(V);
85 bool ConstantFPSDNode::isValueValidForType(EVT VT,
87 assert(VT.isFloatingPoint() && "Can only convert between FP types");
89 // PPC long double cannot be converted to any other type.
90 if (VT == MVT::ppcf128 ||
91 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
94 // convert modifies in place, so make a copy.
95 APFloat Val2 = APFloat(Val);
97 (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
102 //===----------------------------------------------------------------------===//
104 //===----------------------------------------------------------------------===//
106 /// isBuildVectorAllOnes - Return true if the specified node is a
107 /// BUILD_VECTOR where all of the elements are ~0 or undef.
108 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
109 // Look through a bit convert.
110 if (N->getOpcode() == ISD::BIT_CONVERT)
111 N = N->getOperand(0).getNode();
113 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
115 unsigned i = 0, e = N->getNumOperands();
117 // Skip over all of the undef values.
118 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
121 // Do not accept an all-undef vector.
122 if (i == e) return false;
124 // Do not accept build_vectors that aren't all constants or which have non-~0
126 SDValue NotZero = N->getOperand(i);
127 if (isa<ConstantSDNode>(NotZero)) {
128 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
130 } else if (isa<ConstantFPSDNode>(NotZero)) {
131 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
132 bitcastToAPInt().isAllOnesValue())
137 // Okay, we have at least one ~0 value, check to see if the rest match or are
139 for (++i; i != e; ++i)
140 if (N->getOperand(i) != NotZero &&
141 N->getOperand(i).getOpcode() != ISD::UNDEF)
147 /// isBuildVectorAllZeros - Return true if the specified node is a
148 /// BUILD_VECTOR where all of the elements are 0 or undef.
149 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
150 // Look through a bit convert.
151 if (N->getOpcode() == ISD::BIT_CONVERT)
152 N = N->getOperand(0).getNode();
154 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
156 unsigned i = 0, e = N->getNumOperands();
158 // Skip over all of the undef values.
159 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
162 // Do not accept an all-undef vector.
163 if (i == e) return false;
165 // Do not accept build_vectors that aren't all constants or which have non-0
167 SDValue Zero = N->getOperand(i);
168 if (isa<ConstantSDNode>(Zero)) {
169 if (!cast<ConstantSDNode>(Zero)->isNullValue())
171 } else if (isa<ConstantFPSDNode>(Zero)) {
172 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
177 // Okay, we have at least one 0 value, check to see if the rest match or are
179 for (++i; i != e; ++i)
180 if (N->getOperand(i) != Zero &&
181 N->getOperand(i).getOpcode() != ISD::UNDEF)
186 /// isScalarToVector - Return true if the specified node is a
187 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
188 /// element is not an undef.
189 bool ISD::isScalarToVector(const SDNode *N) {
190 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
193 if (N->getOpcode() != ISD::BUILD_VECTOR)
195 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
197 unsigned NumElems = N->getNumOperands();
198 for (unsigned i = 1; i < NumElems; ++i) {
199 SDValue V = N->getOperand(i);
200 if (V.getOpcode() != ISD::UNDEF)
206 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
207 /// when given the operation for (X op Y).
208 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
209 // To perform this operation, we just need to swap the L and G bits of the
211 unsigned OldL = (Operation >> 2) & 1;
212 unsigned OldG = (Operation >> 1) & 1;
213 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
214 (OldL << 1) | // New G bit
215 (OldG << 2)); // New L bit.
218 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
219 /// 'op' is a valid SetCC operation.
220 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
221 unsigned Operation = Op;
223 Operation ^= 7; // Flip L, G, E bits, but not U.
225 Operation ^= 15; // Flip all of the condition bits.
227 if (Operation > ISD::SETTRUE2)
228 Operation &= ~8; // Don't let N and U bits get set.
230 return ISD::CondCode(Operation);
234 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
235 /// signed operation and 2 if the result is an unsigned comparison. Return zero
236 /// if the operation does not depend on the sign of the input (setne and seteq).
237 static int isSignedOp(ISD::CondCode Opcode) {
239 default: llvm_unreachable("Illegal integer setcc operation!");
241 case ISD::SETNE: return 0;
245 case ISD::SETGE: return 1;
249 case ISD::SETUGE: return 2;
253 /// getSetCCOrOperation - Return the result of a logical OR between different
254 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
255 /// returns SETCC_INVALID if it is not possible to represent the resultant
257 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
259 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
260 // Cannot fold a signed integer setcc with an unsigned integer setcc.
261 return ISD::SETCC_INVALID;
263 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
265 // If the N and U bits get set then the resultant comparison DOES suddenly
266 // care about orderedness, and is true when ordered.
267 if (Op > ISD::SETTRUE2)
268 Op &= ~16; // Clear the U bit if the N bit is set.
270 // Canonicalize illegal integer setcc's.
271 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
274 return ISD::CondCode(Op);
277 /// getSetCCAndOperation - Return the result of a logical AND between different
278 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
279 /// function returns zero if it is not possible to represent the resultant
281 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
283 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
284 // Cannot fold a signed setcc with an unsigned setcc.
285 return ISD::SETCC_INVALID;
287 // Combine all of the condition bits.
288 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
290 // Canonicalize illegal integer setcc's.
294 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
295 case ISD::SETOEQ: // SETEQ & SETU[LG]E
296 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
297 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
298 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
305 const TargetMachine &SelectionDAG::getTarget() const {
306 return MF->getTarget();
309 //===----------------------------------------------------------------------===//
310 // SDNode Profile Support
311 //===----------------------------------------------------------------------===//
313 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
315 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
319 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
320 /// solely with their pointer.
321 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
322 ID.AddPointer(VTList.VTs);
325 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
327 static void AddNodeIDOperands(FoldingSetNodeID &ID,
328 const SDValue *Ops, unsigned NumOps) {
329 for (; NumOps; --NumOps, ++Ops) {
330 ID.AddPointer(Ops->getNode());
331 ID.AddInteger(Ops->getResNo());
335 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
337 static void AddNodeIDOperands(FoldingSetNodeID &ID,
338 const SDUse *Ops, unsigned NumOps) {
339 for (; NumOps; --NumOps, ++Ops) {
340 ID.AddPointer(Ops->getNode());
341 ID.AddInteger(Ops->getResNo());
345 static void AddNodeIDNode(FoldingSetNodeID &ID,
346 unsigned short OpC, SDVTList VTList,
347 const SDValue *OpList, unsigned N) {
348 AddNodeIDOpcode(ID, OpC);
349 AddNodeIDValueTypes(ID, VTList);
350 AddNodeIDOperands(ID, OpList, N);
353 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
355 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
356 switch (N->getOpcode()) {
357 case ISD::TargetExternalSymbol:
358 case ISD::ExternalSymbol:
359 llvm_unreachable("Should only be used on nodes with operands");
360 default: break; // Normal nodes don't need extra info.
361 case ISD::TargetConstant:
363 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
365 case ISD::TargetConstantFP:
366 case ISD::ConstantFP: {
367 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
370 case ISD::TargetGlobalAddress:
371 case ISD::GlobalAddress:
372 case ISD::TargetGlobalTLSAddress:
373 case ISD::GlobalTLSAddress: {
374 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
375 ID.AddPointer(GA->getGlobal());
376 ID.AddInteger(GA->getOffset());
377 ID.AddInteger(GA->getTargetFlags());
380 case ISD::BasicBlock:
381 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
384 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
388 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
390 case ISD::FrameIndex:
391 case ISD::TargetFrameIndex:
392 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
395 case ISD::TargetJumpTable:
396 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
397 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
399 case ISD::ConstantPool:
400 case ISD::TargetConstantPool: {
401 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
402 ID.AddInteger(CP->getAlignment());
403 ID.AddInteger(CP->getOffset());
404 if (CP->isMachineConstantPoolEntry())
405 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
407 ID.AddPointer(CP->getConstVal());
408 ID.AddInteger(CP->getTargetFlags());
412 const LoadSDNode *LD = cast<LoadSDNode>(N);
413 ID.AddInteger(LD->getMemoryVT().getRawBits());
414 ID.AddInteger(LD->getRawSubclassData());
418 const StoreSDNode *ST = cast<StoreSDNode>(N);
419 ID.AddInteger(ST->getMemoryVT().getRawBits());
420 ID.AddInteger(ST->getRawSubclassData());
423 case ISD::ATOMIC_CMP_SWAP:
424 case ISD::ATOMIC_SWAP:
425 case ISD::ATOMIC_LOAD_ADD:
426 case ISD::ATOMIC_LOAD_SUB:
427 case ISD::ATOMIC_LOAD_AND:
428 case ISD::ATOMIC_LOAD_OR:
429 case ISD::ATOMIC_LOAD_XOR:
430 case ISD::ATOMIC_LOAD_NAND:
431 case ISD::ATOMIC_LOAD_MIN:
432 case ISD::ATOMIC_LOAD_MAX:
433 case ISD::ATOMIC_LOAD_UMIN:
434 case ISD::ATOMIC_LOAD_UMAX: {
435 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
436 ID.AddInteger(AT->getMemoryVT().getRawBits());
437 ID.AddInteger(AT->getRawSubclassData());
440 case ISD::VECTOR_SHUFFLE: {
441 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
442 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
444 ID.AddInteger(SVN->getMaskElt(i));
447 case ISD::TargetBlockAddress:
448 case ISD::BlockAddress: {
449 ID.AddPointer(cast<BlockAddressSDNode>(N)->getBlockAddress());
450 ID.AddInteger(cast<BlockAddressSDNode>(N)->getTargetFlags());
453 } // end switch (N->getOpcode())
456 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
458 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
459 AddNodeIDOpcode(ID, N->getOpcode());
460 // Add the return value info.
461 AddNodeIDValueTypes(ID, N->getVTList());
462 // Add the operand info.
463 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
465 // Handle SDNode leafs with special info.
466 AddNodeIDCustom(ID, N);
469 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
470 /// the CSE map that carries volatility, indexing mode, and
471 /// extension/truncation information.
473 static inline unsigned
474 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile) {
475 assert((ConvType & 3) == ConvType &&
476 "ConvType may not require more than 2 bits!");
477 assert((AM & 7) == AM &&
478 "AM may not require more than 3 bits!");
484 //===----------------------------------------------------------------------===//
485 // SelectionDAG Class
486 //===----------------------------------------------------------------------===//
488 /// doNotCSE - Return true if CSE should not be performed for this node.
489 static bool doNotCSE(SDNode *N) {
490 if (N->getValueType(0) == MVT::Flag)
491 return true; // Never CSE anything that produces a flag.
493 switch (N->getOpcode()) {
495 case ISD::HANDLENODE:
497 return true; // Never CSE these nodes.
500 // Check that remaining values produced are not flags.
501 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
502 if (N->getValueType(i) == MVT::Flag)
503 return true; // Never CSE anything that produces a flag.
508 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
510 void SelectionDAG::RemoveDeadNodes() {
511 // Create a dummy node (which is not added to allnodes), that adds a reference
512 // to the root node, preventing it from being deleted.
513 HandleSDNode Dummy(getRoot());
515 SmallVector<SDNode*, 128> DeadNodes;
517 // Add all obviously-dead nodes to the DeadNodes worklist.
518 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
520 DeadNodes.push_back(I);
522 RemoveDeadNodes(DeadNodes);
524 // If the root changed (e.g. it was a dead load, update the root).
525 setRoot(Dummy.getValue());
528 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
529 /// given list, and any nodes that become unreachable as a result.
530 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
531 DAGUpdateListener *UpdateListener) {
533 // Process the worklist, deleting the nodes and adding their uses to the
535 while (!DeadNodes.empty()) {
536 SDNode *N = DeadNodes.pop_back_val();
539 UpdateListener->NodeDeleted(N, 0);
541 // Take the node out of the appropriate CSE map.
542 RemoveNodeFromCSEMaps(N);
544 // Next, brutally remove the operand list. This is safe to do, as there are
545 // no cycles in the graph.
546 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
548 SDNode *Operand = Use.getNode();
551 // Now that we removed this operand, see if there are no uses of it left.
552 if (Operand->use_empty())
553 DeadNodes.push_back(Operand);
558 // Remove the ordering of this node.
559 if (Ordering) Ordering->remove(N);
563 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
564 SmallVector<SDNode*, 16> DeadNodes(1, N);
565 RemoveDeadNodes(DeadNodes, UpdateListener);
568 void SelectionDAG::DeleteNode(SDNode *N) {
569 // First take this out of the appropriate CSE map.
570 RemoveNodeFromCSEMaps(N);
572 // Finally, remove uses due to operands of this node, remove from the
573 // AllNodes list, and delete the node.
574 DeleteNodeNotInCSEMaps(N);
577 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
578 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
579 assert(N->use_empty() && "Cannot delete a node that is not dead!");
581 // Drop all of the operands and decrement used node's use counts.
586 // Remove the ordering of this node.
587 if (Ordering) Ordering->remove(N);
590 void SelectionDAG::DeallocateNode(SDNode *N) {
591 if (N->OperandsNeedDelete)
592 delete[] N->OperandList;
594 // Set the opcode to DELETED_NODE to help catch bugs when node
595 // memory is reallocated.
596 N->NodeType = ISD::DELETED_NODE;
598 NodeAllocator.Deallocate(AllNodes.remove(N));
600 // Remove the ordering of this node.
601 if (Ordering) Ordering->remove(N);
604 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
605 /// correspond to it. This is useful when we're about to delete or repurpose
606 /// the node. We don't want future request for structurally identical nodes
607 /// to return N anymore.
608 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
610 switch (N->getOpcode()) {
611 case ISD::EntryToken:
612 llvm_unreachable("EntryToken should not be in CSEMaps!");
614 case ISD::HANDLENODE: return false; // noop.
616 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
617 "Cond code doesn't exist!");
618 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
619 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
621 case ISD::ExternalSymbol:
622 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
624 case ISD::TargetExternalSymbol: {
625 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
626 Erased = TargetExternalSymbols.erase(
627 std::pair<std::string,unsigned char>(ESN->getSymbol(),
628 ESN->getTargetFlags()));
631 case ISD::VALUETYPE: {
632 EVT VT = cast<VTSDNode>(N)->getVT();
633 if (VT.isExtended()) {
634 Erased = ExtendedValueTypeNodes.erase(VT);
636 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
637 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
642 // Remove it from the CSE Map.
643 Erased = CSEMap.RemoveNode(N);
647 // Verify that the node was actually in one of the CSE maps, unless it has a
648 // flag result (which cannot be CSE'd) or is one of the special cases that are
649 // not subject to CSE.
650 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
651 !N->isMachineOpcode() && !doNotCSE(N)) {
654 llvm_unreachable("Node is not in map!");
660 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
661 /// maps and modified in place. Add it back to the CSE maps, unless an identical
662 /// node already exists, in which case transfer all its users to the existing
663 /// node. This transfer can potentially trigger recursive merging.
666 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
667 DAGUpdateListener *UpdateListener) {
668 // For node types that aren't CSE'd, just act as if no identical node
671 SDNode *Existing = CSEMap.GetOrInsertNode(N);
673 // If there was already an existing matching node, use ReplaceAllUsesWith
674 // to replace the dead one with the existing one. This can cause
675 // recursive merging of other unrelated nodes down the line.
676 ReplaceAllUsesWith(N, Existing, UpdateListener);
678 // N is now dead. Inform the listener if it exists and delete it.
680 UpdateListener->NodeDeleted(N, Existing);
681 DeleteNodeNotInCSEMaps(N);
686 // If the node doesn't already exist, we updated it. Inform a listener if
689 UpdateListener->NodeUpdated(N);
692 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
693 /// were replaced with those specified. If this node is never memoized,
694 /// return null, otherwise return a pointer to the slot it would take. If a
695 /// node already exists with these operands, the slot will be non-null.
696 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
701 SDValue Ops[] = { Op };
703 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
704 AddNodeIDCustom(ID, N);
705 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
706 if (Ordering) Ordering->remove(Node);
710 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
711 /// were replaced with those specified. If this node is never memoized,
712 /// return null, otherwise return a pointer to the slot it would take. If a
713 /// node already exists with these operands, the slot will be non-null.
714 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
715 SDValue Op1, SDValue Op2,
720 SDValue Ops[] = { Op1, Op2 };
722 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
723 AddNodeIDCustom(ID, N);
724 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
725 if (Ordering) Ordering->remove(Node);
730 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
731 /// were replaced with those specified. If this node is never memoized,
732 /// return null, otherwise return a pointer to the slot it would take. If a
733 /// node already exists with these operands, the slot will be non-null.
734 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
735 const SDValue *Ops,unsigned NumOps,
741 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
742 AddNodeIDCustom(ID, N);
743 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
744 if (Ordering) Ordering->remove(Node);
748 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
749 void SelectionDAG::VerifyNode(SDNode *N) {
750 switch (N->getOpcode()) {
753 case ISD::BUILD_PAIR: {
754 EVT VT = N->getValueType(0);
755 assert(N->getNumValues() == 1 && "Too many results!");
756 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
757 "Wrong return type!");
758 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
759 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
760 "Mismatched operand types!");
761 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
762 "Wrong operand type!");
763 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
764 "Wrong return type size");
767 case ISD::BUILD_VECTOR: {
768 assert(N->getNumValues() == 1 && "Too many results!");
769 assert(N->getValueType(0).isVector() && "Wrong return type!");
770 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
771 "Wrong number of operands!");
772 EVT EltVT = N->getValueType(0).getVectorElementType();
773 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
774 assert((I->getValueType() == EltVT ||
775 (EltVT.isInteger() && I->getValueType().isInteger() &&
776 EltVT.bitsLE(I->getValueType()))) &&
777 "Wrong operand type!");
783 /// getEVTAlignment - Compute the default alignment value for the
786 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
787 const Type *Ty = VT == MVT::iPTR ?
788 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
789 VT.getTypeForEVT(*getContext());
791 return TLI.getTargetData()->getABITypeAlignment(Ty);
794 // EntryNode could meaningfully have debug info if we can find it...
795 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
796 : TLI(tli), FLI(fli), DW(0),
797 EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
798 getVTList(MVT::Other)),
799 Root(getEntryNode()), Ordering(0) {
800 AllNodes.push_back(&EntryNode);
801 if (DisableInstScheduling) {
802 Ordering = new NodeOrdering();
803 Ordering->add(&EntryNode);
807 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
812 Context = &mf.getFunction()->getContext();
815 SelectionDAG::~SelectionDAG() {
820 void SelectionDAG::allnodes_clear() {
821 assert(&*AllNodes.begin() == &EntryNode);
822 AllNodes.remove(AllNodes.begin());
823 while (!AllNodes.empty())
824 DeallocateNode(AllNodes.begin());
827 void SelectionDAG::clear() {
829 OperandAllocator.Reset();
832 ExtendedValueTypeNodes.clear();
833 ExternalSymbols.clear();
834 TargetExternalSymbols.clear();
835 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
836 static_cast<CondCodeSDNode*>(0));
837 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
838 static_cast<SDNode*>(0));
840 EntryNode.UseList = 0;
841 AllNodes.push_back(&EntryNode);
842 Root = getEntryNode();
843 if (DisableInstScheduling) {
844 Ordering = new NodeOrdering();
845 Ordering->add(&EntryNode);
849 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
850 return VT.bitsGT(Op.getValueType()) ?
851 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
852 getNode(ISD::TRUNCATE, DL, VT, Op);
855 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
856 return VT.bitsGT(Op.getValueType()) ?
857 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
858 getNode(ISD::TRUNCATE, DL, VT, Op);
861 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
862 assert(!VT.isVector() &&
863 "getZeroExtendInReg should use the vector element type instead of "
865 if (Op.getValueType() == VT) return Op;
866 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
867 APInt Imm = APInt::getLowBitsSet(BitWidth,
869 return getNode(ISD::AND, DL, Op.getValueType(), Op,
870 getConstant(Imm, Op.getValueType()));
873 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
875 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
876 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
878 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
879 return getNode(ISD::XOR, DL, VT, Val, NegOne);
882 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
883 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
884 assert((EltVT.getSizeInBits() >= 64 ||
885 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
886 "getConstant with a uint64_t value that doesn't fit in the type!");
887 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
890 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
891 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
894 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
895 assert(VT.isInteger() && "Cannot create FP integer constant!");
897 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
898 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
899 "APInt size does not match type size!");
901 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
903 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
907 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP))) {
908 if (Ordering) Ordering->add(N);
910 return SDValue(N, 0);
913 N = NodeAllocator.Allocate<ConstantSDNode>();
914 new (N) ConstantSDNode(isT, &Val, EltVT);
915 CSEMap.InsertNode(N, IP);
916 AllNodes.push_back(N);
917 if (Ordering) Ordering->add(N);
920 SDValue Result(N, 0);
922 SmallVector<SDValue, 8> Ops;
923 Ops.assign(VT.getVectorNumElements(), Result);
924 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
925 VT, &Ops[0], Ops.size());
930 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
931 return getConstant(Val, TLI.getPointerTy(), isTarget);
935 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
936 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
939 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
940 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
943 VT.isVector() ? VT.getVectorElementType() : VT;
945 // Do the map lookup using the actual bit pattern for the floating point
946 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
947 // we don't have issues with SNANs.
948 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
950 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
954 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP))) {
955 if (Ordering) Ordering->add(N);
957 return SDValue(N, 0);
960 N = NodeAllocator.Allocate<ConstantFPSDNode>();
961 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
962 CSEMap.InsertNode(N, IP);
963 AllNodes.push_back(N);
964 if (Ordering) Ordering->add(N);
967 SDValue Result(N, 0);
969 SmallVector<SDValue, 8> Ops;
970 Ops.assign(VT.getVectorNumElements(), Result);
971 // FIXME DebugLoc info might be appropriate here
972 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
973 VT, &Ops[0], Ops.size());
978 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
980 VT.isVector() ? VT.getVectorElementType() : VT;
982 return getConstantFP(APFloat((float)Val), VT, isTarget);
984 return getConstantFP(APFloat(Val), VT, isTarget);
987 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
988 EVT VT, int64_t Offset,
990 unsigned char TargetFlags) {
991 assert((TargetFlags == 0 || isTargetGA) &&
992 "Cannot set target flags on target-independent globals");
994 // Truncate (with sign-extension) the offset value to the pointer size.
995 EVT PTy = TLI.getPointerTy();
996 unsigned BitWidth = PTy.getSizeInBits();
998 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
1000 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1002 // If GV is an alias then use the aliasee for determining thread-localness.
1003 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1004 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1008 if (GVar && GVar->isThreadLocal())
1009 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1011 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1013 FoldingSetNodeID ID;
1014 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1016 ID.AddInteger(Offset);
1017 ID.AddInteger(TargetFlags);
1019 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1020 if (Ordering) Ordering->add(E);
1021 return SDValue(E, 0);
1023 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
1024 new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags);
1025 CSEMap.InsertNode(N, IP);
1026 AllNodes.push_back(N);
1027 if (Ordering) Ordering->add(N);
1028 return SDValue(N, 0);
1031 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1032 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1033 FoldingSetNodeID ID;
1034 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1037 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1038 if (Ordering) Ordering->add(E);
1039 return SDValue(E, 0);
1041 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
1042 new (N) FrameIndexSDNode(FI, VT, isTarget);
1043 CSEMap.InsertNode(N, IP);
1044 AllNodes.push_back(N);
1045 if (Ordering) Ordering->add(N);
1046 return SDValue(N, 0);
1049 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1050 unsigned char TargetFlags) {
1051 assert((TargetFlags == 0 || isTarget) &&
1052 "Cannot set target flags on target-independent jump tables");
1053 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1054 FoldingSetNodeID ID;
1055 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1057 ID.AddInteger(TargetFlags);
1059 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1060 if (Ordering) Ordering->add(E);
1061 return SDValue(E, 0);
1063 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1064 new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags);
1065 CSEMap.InsertNode(N, IP);
1066 AllNodes.push_back(N);
1067 if (Ordering) Ordering->add(N);
1068 return SDValue(N, 0);
1071 SDValue SelectionDAG::getConstantPool(Constant *C, EVT VT,
1072 unsigned Alignment, int Offset,
1074 unsigned char TargetFlags) {
1075 assert((TargetFlags == 0 || isTarget) &&
1076 "Cannot set target flags on target-independent globals");
1078 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1079 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1080 FoldingSetNodeID ID;
1081 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1082 ID.AddInteger(Alignment);
1083 ID.AddInteger(Offset);
1085 ID.AddInteger(TargetFlags);
1087 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1088 if (Ordering) Ordering->add(E);
1089 return SDValue(E, 0);
1091 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1092 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1093 CSEMap.InsertNode(N, IP);
1094 AllNodes.push_back(N);
1095 if (Ordering) Ordering->add(N);
1096 return SDValue(N, 0);
1100 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1101 unsigned Alignment, int Offset,
1103 unsigned char TargetFlags) {
1104 assert((TargetFlags == 0 || isTarget) &&
1105 "Cannot set target flags on target-independent globals");
1107 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1108 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1109 FoldingSetNodeID ID;
1110 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1111 ID.AddInteger(Alignment);
1112 ID.AddInteger(Offset);
1113 C->AddSelectionDAGCSEId(ID);
1114 ID.AddInteger(TargetFlags);
1116 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1117 if (Ordering) Ordering->add(E);
1118 return SDValue(E, 0);
1120 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1121 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1122 CSEMap.InsertNode(N, IP);
1123 AllNodes.push_back(N);
1124 if (Ordering) Ordering->add(N);
1125 return SDValue(N, 0);
1128 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1129 FoldingSetNodeID ID;
1130 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1133 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1134 if (Ordering) Ordering->add(E);
1135 return SDValue(E, 0);
1137 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1138 new (N) BasicBlockSDNode(MBB);
1139 CSEMap.InsertNode(N, IP);
1140 AllNodes.push_back(N);
1141 if (Ordering) Ordering->add(N);
1142 return SDValue(N, 0);
1145 SDValue SelectionDAG::getValueType(EVT VT) {
1146 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1147 ValueTypeNodes.size())
1148 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1150 SDNode *&N = VT.isExtended() ?
1151 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1153 if (N) return SDValue(N, 0);
1154 N = NodeAllocator.Allocate<VTSDNode>();
1155 new (N) VTSDNode(VT);
1156 AllNodes.push_back(N);
1157 if (Ordering) Ordering->add(N);
1158 return SDValue(N, 0);
1161 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1162 SDNode *&N = ExternalSymbols[Sym];
1163 if (N) return SDValue(N, 0);
1164 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1165 new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
1166 AllNodes.push_back(N);
1167 if (Ordering) Ordering->add(N);
1168 return SDValue(N, 0);
1171 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1172 unsigned char TargetFlags) {
1174 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1176 if (N) return SDValue(N, 0);
1177 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1178 new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1179 AllNodes.push_back(N);
1180 if (Ordering) Ordering->add(N);
1181 return SDValue(N, 0);
1184 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1185 if ((unsigned)Cond >= CondCodeNodes.size())
1186 CondCodeNodes.resize(Cond+1);
1188 if (CondCodeNodes[Cond] == 0) {
1189 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1190 new (N) CondCodeSDNode(Cond);
1191 CondCodeNodes[Cond] = N;
1192 AllNodes.push_back(N);
1193 if (Ordering) Ordering->add(N);
1195 return SDValue(CondCodeNodes[Cond], 0);
1198 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1199 // the shuffle mask M that point at N1 to point at N2, and indices that point
1200 // N2 to point at N1.
1201 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1203 int NElts = M.size();
1204 for (int i = 0; i != NElts; ++i) {
1212 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1213 SDValue N2, const int *Mask) {
1214 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1215 assert(VT.isVector() && N1.getValueType().isVector() &&
1216 "Vector Shuffle VTs must be a vectors");
1217 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1218 && "Vector Shuffle VTs must have same element type");
1220 // Canonicalize shuffle undef, undef -> undef
1221 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1222 return getUNDEF(VT);
1224 // Validate that all indices in Mask are within the range of the elements
1225 // input to the shuffle.
1226 unsigned NElts = VT.getVectorNumElements();
1227 SmallVector<int, 8> MaskVec;
1228 for (unsigned i = 0; i != NElts; ++i) {
1229 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1230 MaskVec.push_back(Mask[i]);
1233 // Canonicalize shuffle v, v -> v, undef
1236 for (unsigned i = 0; i != NElts; ++i)
1237 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1240 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1241 if (N1.getOpcode() == ISD::UNDEF)
1242 commuteShuffle(N1, N2, MaskVec);
1244 // Canonicalize all index into lhs, -> shuffle lhs, undef
1245 // Canonicalize all index into rhs, -> shuffle rhs, undef
1246 bool AllLHS = true, AllRHS = true;
1247 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1248 for (unsigned i = 0; i != NElts; ++i) {
1249 if (MaskVec[i] >= (int)NElts) {
1254 } else if (MaskVec[i] >= 0) {
1258 if (AllLHS && AllRHS)
1259 return getUNDEF(VT);
1260 if (AllLHS && !N2Undef)
1264 commuteShuffle(N1, N2, MaskVec);
1267 // If Identity shuffle, or all shuffle in to undef, return that node.
1268 bool AllUndef = true;
1269 bool Identity = true;
1270 for (unsigned i = 0; i != NElts; ++i) {
1271 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1272 if (MaskVec[i] >= 0) AllUndef = false;
1274 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1277 return getUNDEF(VT);
1279 FoldingSetNodeID ID;
1280 SDValue Ops[2] = { N1, N2 };
1281 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1282 for (unsigned i = 0; i != NElts; ++i)
1283 ID.AddInteger(MaskVec[i]);
1286 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1287 if (Ordering) Ordering->add(E);
1288 return SDValue(E, 0);
1291 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1292 // SDNode doesn't have access to it. This memory will be "leaked" when
1293 // the node is deallocated, but recovered when the NodeAllocator is released.
1294 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1295 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1297 ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
1298 new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1299 CSEMap.InsertNode(N, IP);
1300 AllNodes.push_back(N);
1301 if (Ordering) Ordering->add(N);
1302 return SDValue(N, 0);
1305 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1306 SDValue Val, SDValue DTy,
1307 SDValue STy, SDValue Rnd, SDValue Sat,
1308 ISD::CvtCode Code) {
1309 // If the src and dest types are the same and the conversion is between
1310 // integer types of the same sign or two floats, no conversion is necessary.
1312 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1315 FoldingSetNodeID ID;
1316 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1317 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1319 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1320 if (Ordering) Ordering->add(E);
1321 return SDValue(E, 0);
1323 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1324 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
1325 CSEMap.InsertNode(N, IP);
1326 AllNodes.push_back(N);
1327 if (Ordering) Ordering->add(N);
1328 return SDValue(N, 0);
1331 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1332 FoldingSetNodeID ID;
1333 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1334 ID.AddInteger(RegNo);
1336 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1337 if (Ordering) Ordering->add(E);
1338 return SDValue(E, 0);
1340 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1341 new (N) RegisterSDNode(RegNo, VT);
1342 CSEMap.InsertNode(N, IP);
1343 AllNodes.push_back(N);
1344 if (Ordering) Ordering->add(N);
1345 return SDValue(N, 0);
1348 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1351 FoldingSetNodeID ID;
1352 SDValue Ops[] = { Root };
1353 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1354 ID.AddInteger(LabelID);
1356 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1357 if (Ordering) Ordering->add(E);
1358 return SDValue(E, 0);
1360 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1361 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1362 CSEMap.InsertNode(N, IP);
1363 AllNodes.push_back(N);
1364 if (Ordering) Ordering->add(N);
1365 return SDValue(N, 0);
1368 SDValue SelectionDAG::getBlockAddress(BlockAddress *BA, EVT VT,
1370 unsigned char TargetFlags) {
1371 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1373 FoldingSetNodeID ID;
1374 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1376 ID.AddInteger(TargetFlags);
1378 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1379 if (Ordering) Ordering->add(E);
1380 return SDValue(E, 0);
1382 SDNode *N = NodeAllocator.Allocate<BlockAddressSDNode>();
1383 new (N) BlockAddressSDNode(Opc, VT, BA, TargetFlags);
1384 CSEMap.InsertNode(N, IP);
1385 AllNodes.push_back(N);
1386 if (Ordering) Ordering->add(N);
1387 return SDValue(N, 0);
1390 SDValue SelectionDAG::getSrcValue(const Value *V) {
1391 assert((!V || isa<PointerType>(V->getType())) &&
1392 "SrcValue is not a pointer?");
1394 FoldingSetNodeID ID;
1395 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1399 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
1400 if (Ordering) Ordering->add(E);
1401 return SDValue(E, 0);
1404 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1405 new (N) SrcValueSDNode(V);
1406 CSEMap.InsertNode(N, IP);
1407 AllNodes.push_back(N);
1408 if (Ordering) Ordering->add(N);
1409 return SDValue(N, 0);
1412 /// getShiftAmountOperand - Return the specified value casted to
1413 /// the target's desired shift amount type.
1414 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1415 EVT OpTy = Op.getValueType();
1416 MVT ShTy = TLI.getShiftAmountTy();
1417 if (OpTy == ShTy || OpTy.isVector()) return Op;
1419 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1420 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1423 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1424 /// specified value type.
1425 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1426 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1427 unsigned ByteSize = VT.getStoreSize();
1428 const Type *Ty = VT.getTypeForEVT(*getContext());
1429 unsigned StackAlign =
1430 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1432 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1433 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1436 /// CreateStackTemporary - Create a stack temporary suitable for holding
1437 /// either of the specified value types.
1438 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1439 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1440 VT2.getStoreSizeInBits())/8;
1441 const Type *Ty1 = VT1.getTypeForEVT(*getContext());
1442 const Type *Ty2 = VT2.getTypeForEVT(*getContext());
1443 const TargetData *TD = TLI.getTargetData();
1444 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1445 TD->getPrefTypeAlignment(Ty2));
1447 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1448 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1449 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1452 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1453 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1454 // These setcc operations always fold.
1458 case ISD::SETFALSE2: return getConstant(0, VT);
1460 case ISD::SETTRUE2: return getConstant(1, VT);
1472 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1476 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1477 const APInt &C2 = N2C->getAPIntValue();
1478 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1479 const APInt &C1 = N1C->getAPIntValue();
1482 default: llvm_unreachable("Unknown integer setcc!");
1483 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1484 case ISD::SETNE: return getConstant(C1 != C2, VT);
1485 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1486 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1487 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1488 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1489 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1490 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1491 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1492 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1496 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1497 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1498 // No compile time operations on this type yet.
1499 if (N1C->getValueType(0) == MVT::ppcf128)
1502 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1505 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1506 return getUNDEF(VT);
1508 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1509 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1510 return getUNDEF(VT);
1512 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1513 R==APFloat::cmpLessThan, VT);
1514 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1515 return getUNDEF(VT);
1517 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1518 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1519 return getUNDEF(VT);
1521 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1522 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1523 return getUNDEF(VT);
1525 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1526 R==APFloat::cmpEqual, VT);
1527 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1528 return getUNDEF(VT);
1530 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1531 R==APFloat::cmpEqual, VT);
1532 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1533 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1534 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1535 R==APFloat::cmpEqual, VT);
1536 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1537 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1538 R==APFloat::cmpLessThan, VT);
1539 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1540 R==APFloat::cmpUnordered, VT);
1541 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1542 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1545 // Ensure that the constant occurs on the RHS.
1546 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1550 // Could not fold it.
1554 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1555 /// use this predicate to simplify operations downstream.
1556 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1557 // This predicate is not safe for vector operations.
1558 if (Op.getValueType().isVector())
1561 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1562 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1565 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1566 /// this predicate to simplify operations downstream. Mask is known to be zero
1567 /// for bits that V cannot have.
1568 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1569 unsigned Depth) const {
1570 APInt KnownZero, KnownOne;
1571 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1572 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1573 return (KnownZero & Mask) == Mask;
1576 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1577 /// known to be either zero or one and return them in the KnownZero/KnownOne
1578 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1580 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1581 APInt &KnownZero, APInt &KnownOne,
1582 unsigned Depth) const {
1583 unsigned BitWidth = Mask.getBitWidth();
1584 assert(BitWidth == Op.getValueType().getScalarType().getSizeInBits() &&
1585 "Mask size mismatches value type size!");
1587 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1588 if (Depth == 6 || Mask == 0)
1589 return; // Limit search depth.
1591 APInt KnownZero2, KnownOne2;
1593 switch (Op.getOpcode()) {
1595 // We know all of the bits for a constant!
1596 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1597 KnownZero = ~KnownOne & Mask;
1600 // If either the LHS or the RHS are Zero, the result is zero.
1601 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1602 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1603 KnownZero2, KnownOne2, Depth+1);
1604 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1605 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1607 // Output known-1 bits are only known if set in both the LHS & RHS.
1608 KnownOne &= KnownOne2;
1609 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1610 KnownZero |= KnownZero2;
1613 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1614 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1615 KnownZero2, KnownOne2, Depth+1);
1616 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1617 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1619 // Output known-0 bits are only known if clear in both the LHS & RHS.
1620 KnownZero &= KnownZero2;
1621 // Output known-1 are known to be set if set in either the LHS | RHS.
1622 KnownOne |= KnownOne2;
1625 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1626 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1628 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1630 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1631 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1632 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1633 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1634 KnownZero = KnownZeroOut;
1638 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1639 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1640 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1642 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1644 // If low bits are zero in either operand, output low known-0 bits.
1645 // Also compute a conserative estimate for high known-0 bits.
1646 // More trickiness is possible, but this is sufficient for the
1647 // interesting case of alignment computation.
1649 unsigned TrailZ = KnownZero.countTrailingOnes() +
1650 KnownZero2.countTrailingOnes();
1651 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1652 KnownZero2.countLeadingOnes(),
1653 BitWidth) - BitWidth;
1655 TrailZ = std::min(TrailZ, BitWidth);
1656 LeadZ = std::min(LeadZ, BitWidth);
1657 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1658 APInt::getHighBitsSet(BitWidth, LeadZ);
1663 // For the purposes of computing leading zeros we can conservatively
1664 // treat a udiv as a logical right shift by the power of 2 known to
1665 // be less than the denominator.
1666 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1667 ComputeMaskedBits(Op.getOperand(0),
1668 AllOnes, KnownZero2, KnownOne2, Depth+1);
1669 unsigned LeadZ = KnownZero2.countLeadingOnes();
1673 ComputeMaskedBits(Op.getOperand(1),
1674 AllOnes, KnownZero2, KnownOne2, Depth+1);
1675 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1676 if (RHSUnknownLeadingOnes != BitWidth)
1677 LeadZ = std::min(BitWidth,
1678 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1680 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1684 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1685 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1686 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1687 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1689 // Only known if known in both the LHS and RHS.
1690 KnownOne &= KnownOne2;
1691 KnownZero &= KnownZero2;
1693 case ISD::SELECT_CC:
1694 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1695 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1697 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1699 // Only known if known in both the LHS and RHS.
1700 KnownOne &= KnownOne2;
1701 KnownZero &= KnownZero2;
1709 if (Op.getResNo() != 1)
1711 // The boolean result conforms to getBooleanContents. Fall through.
1713 // If we know the result of a setcc has the top bits zero, use this info.
1714 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1716 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1719 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1720 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1721 unsigned ShAmt = SA->getZExtValue();
1723 // If the shift count is an invalid immediate, don't do anything.
1724 if (ShAmt >= BitWidth)
1727 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1728 KnownZero, KnownOne, Depth+1);
1729 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1730 KnownZero <<= ShAmt;
1732 // low bits known zero.
1733 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1737 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1738 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1739 unsigned ShAmt = SA->getZExtValue();
1741 // If the shift count is an invalid immediate, don't do anything.
1742 if (ShAmt >= BitWidth)
1745 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1746 KnownZero, KnownOne, Depth+1);
1747 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1748 KnownZero = KnownZero.lshr(ShAmt);
1749 KnownOne = KnownOne.lshr(ShAmt);
1751 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1752 KnownZero |= HighBits; // High bits known zero.
1756 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1757 unsigned ShAmt = SA->getZExtValue();
1759 // If the shift count is an invalid immediate, don't do anything.
1760 if (ShAmt >= BitWidth)
1763 APInt InDemandedMask = (Mask << ShAmt);
1764 // If any of the demanded bits are produced by the sign extension, we also
1765 // demand the input sign bit.
1766 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1767 if (HighBits.getBoolValue())
1768 InDemandedMask |= APInt::getSignBit(BitWidth);
1770 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1772 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1773 KnownZero = KnownZero.lshr(ShAmt);
1774 KnownOne = KnownOne.lshr(ShAmt);
1776 // Handle the sign bits.
1777 APInt SignBit = APInt::getSignBit(BitWidth);
1778 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1780 if (KnownZero.intersects(SignBit)) {
1781 KnownZero |= HighBits; // New bits are known zero.
1782 } else if (KnownOne.intersects(SignBit)) {
1783 KnownOne |= HighBits; // New bits are known one.
1787 case ISD::SIGN_EXTEND_INREG: {
1788 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1789 unsigned EBits = EVT.getSizeInBits();
1791 // Sign extension. Compute the demanded bits in the result that are not
1792 // present in the input.
1793 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1795 APInt InSignBit = APInt::getSignBit(EBits);
1796 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1798 // If the sign extended bits are demanded, we know that the sign
1800 InSignBit.zext(BitWidth);
1801 if (NewBits.getBoolValue())
1802 InputDemandedBits |= InSignBit;
1804 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1805 KnownZero, KnownOne, Depth+1);
1806 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1808 // If the sign bit of the input is known set or clear, then we know the
1809 // top bits of the result.
1810 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1811 KnownZero |= NewBits;
1812 KnownOne &= ~NewBits;
1813 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1814 KnownOne |= NewBits;
1815 KnownZero &= ~NewBits;
1816 } else { // Input sign bit unknown
1817 KnownZero &= ~NewBits;
1818 KnownOne &= ~NewBits;
1825 unsigned LowBits = Log2_32(BitWidth)+1;
1826 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1831 if (ISD::isZEXTLoad(Op.getNode())) {
1832 LoadSDNode *LD = cast<LoadSDNode>(Op);
1833 EVT VT = LD->getMemoryVT();
1834 unsigned MemBits = VT.getSizeInBits();
1835 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1839 case ISD::ZERO_EXTEND: {
1840 EVT InVT = Op.getOperand(0).getValueType();
1841 unsigned InBits = InVT.getScalarType().getSizeInBits();
1842 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1843 APInt InMask = Mask;
1844 InMask.trunc(InBits);
1845 KnownZero.trunc(InBits);
1846 KnownOne.trunc(InBits);
1847 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1848 KnownZero.zext(BitWidth);
1849 KnownOne.zext(BitWidth);
1850 KnownZero |= NewBits;
1853 case ISD::SIGN_EXTEND: {
1854 EVT InVT = Op.getOperand(0).getValueType();
1855 unsigned InBits = InVT.getScalarType().getSizeInBits();
1856 APInt InSignBit = APInt::getSignBit(InBits);
1857 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1858 APInt InMask = Mask;
1859 InMask.trunc(InBits);
1861 // If any of the sign extended bits are demanded, we know that the sign
1862 // bit is demanded. Temporarily set this bit in the mask for our callee.
1863 if (NewBits.getBoolValue())
1864 InMask |= InSignBit;
1866 KnownZero.trunc(InBits);
1867 KnownOne.trunc(InBits);
1868 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1870 // Note if the sign bit is known to be zero or one.
1871 bool SignBitKnownZero = KnownZero.isNegative();
1872 bool SignBitKnownOne = KnownOne.isNegative();
1873 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1874 "Sign bit can't be known to be both zero and one!");
1876 // If the sign bit wasn't actually demanded by our caller, we don't
1877 // want it set in the KnownZero and KnownOne result values. Reset the
1878 // mask and reapply it to the result values.
1880 InMask.trunc(InBits);
1881 KnownZero &= InMask;
1884 KnownZero.zext(BitWidth);
1885 KnownOne.zext(BitWidth);
1887 // If the sign bit is known zero or one, the top bits match.
1888 if (SignBitKnownZero)
1889 KnownZero |= NewBits;
1890 else if (SignBitKnownOne)
1891 KnownOne |= NewBits;
1894 case ISD::ANY_EXTEND: {
1895 EVT InVT = Op.getOperand(0).getValueType();
1896 unsigned InBits = InVT.getScalarType().getSizeInBits();
1897 APInt InMask = Mask;
1898 InMask.trunc(InBits);
1899 KnownZero.trunc(InBits);
1900 KnownOne.trunc(InBits);
1901 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1902 KnownZero.zext(BitWidth);
1903 KnownOne.zext(BitWidth);
1906 case ISD::TRUNCATE: {
1907 EVT InVT = Op.getOperand(0).getValueType();
1908 unsigned InBits = InVT.getScalarType().getSizeInBits();
1909 APInt InMask = Mask;
1910 InMask.zext(InBits);
1911 KnownZero.zext(InBits);
1912 KnownOne.zext(InBits);
1913 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1914 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1915 KnownZero.trunc(BitWidth);
1916 KnownOne.trunc(BitWidth);
1919 case ISD::AssertZext: {
1920 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1921 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1922 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1924 KnownZero |= (~InMask) & Mask;
1928 // All bits are zero except the low bit.
1929 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1933 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1934 // We know that the top bits of C-X are clear if X contains less bits
1935 // than C (i.e. no wrap-around can happen). For example, 20-X is
1936 // positive if we can prove that X is >= 0 and < 16.
1937 if (CLHS->getAPIntValue().isNonNegative()) {
1938 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1939 // NLZ can't be BitWidth with no sign bit
1940 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1941 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1944 // If all of the MaskV bits are known to be zero, then we know the
1945 // output top bits are zero, because we now know that the output is
1947 if ((KnownZero2 & MaskV) == MaskV) {
1948 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1949 // Top bits known zero.
1950 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1957 // Output known-0 bits are known if clear or set in both the low clear bits
1958 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1959 // low 3 bits clear.
1960 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1961 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1962 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1963 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1965 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1966 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1967 KnownZeroOut = std::min(KnownZeroOut,
1968 KnownZero2.countTrailingOnes());
1970 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1974 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1975 const APInt &RA = Rem->getAPIntValue();
1976 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1977 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1978 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1979 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1981 // If the sign bit of the first operand is zero, the sign bit of
1982 // the result is zero. If the first operand has no one bits below
1983 // the second operand's single 1 bit, its sign will be zero.
1984 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1985 KnownZero2 |= ~LowBits;
1987 KnownZero |= KnownZero2 & Mask;
1989 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1994 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1995 const APInt &RA = Rem->getAPIntValue();
1996 if (RA.isPowerOf2()) {
1997 APInt LowBits = (RA - 1);
1998 APInt Mask2 = LowBits & Mask;
1999 KnownZero |= ~LowBits & Mask;
2000 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
2001 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2006 // Since the result is less than or equal to either operand, any leading
2007 // zero bits in either operand must also exist in the result.
2008 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2009 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
2011 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
2014 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2015 KnownZero2.countLeadingOnes());
2017 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
2021 // Allow the target to implement this method for its nodes.
2022 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2023 case ISD::INTRINSIC_WO_CHAIN:
2024 case ISD::INTRINSIC_W_CHAIN:
2025 case ISD::INTRINSIC_VOID:
2026 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
2033 /// ComputeNumSignBits - Return the number of times the sign bit of the
2034 /// register is replicated into the other bits. We know that at least 1 bit
2035 /// is always equal to the sign bit (itself), but other cases can give us
2036 /// information. For example, immediately after an "SRA X, 2", we know that
2037 /// the top 3 bits are all equal to each other, so we return 3.
2038 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2039 EVT VT = Op.getValueType();
2040 assert(VT.isInteger() && "Invalid VT!");
2041 unsigned VTBits = VT.getScalarType().getSizeInBits();
2043 unsigned FirstAnswer = 1;
2046 return 1; // Limit search depth.
2048 switch (Op.getOpcode()) {
2050 case ISD::AssertSext:
2051 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2052 return VTBits-Tmp+1;
2053 case ISD::AssertZext:
2054 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2057 case ISD::Constant: {
2058 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2059 // If negative, return # leading ones.
2060 if (Val.isNegative())
2061 return Val.countLeadingOnes();
2063 // Return # leading zeros.
2064 return Val.countLeadingZeros();
2067 case ISD::SIGN_EXTEND:
2068 Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2069 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2071 case ISD::SIGN_EXTEND_INREG:
2072 // Max of the input and what this extends.
2073 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2076 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2077 return std::max(Tmp, Tmp2);
2080 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2081 // SRA X, C -> adds C sign bits.
2082 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2083 Tmp += C->getZExtValue();
2084 if (Tmp > VTBits) Tmp = VTBits;
2088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2089 // shl destroys sign bits.
2090 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2091 if (C->getZExtValue() >= VTBits || // Bad shift.
2092 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2093 return Tmp - C->getZExtValue();
2098 case ISD::XOR: // NOT is handled here.
2099 // Logical binary ops preserve the number of sign bits at the worst.
2100 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2102 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2103 FirstAnswer = std::min(Tmp, Tmp2);
2104 // We computed what we know about the sign bits as our first
2105 // answer. Now proceed to the generic code that uses
2106 // ComputeMaskedBits, and pick whichever answer is better.
2111 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2112 if (Tmp == 1) return 1; // Early out.
2113 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2114 return std::min(Tmp, Tmp2);
2122 if (Op.getResNo() != 1)
2124 // The boolean result conforms to getBooleanContents. Fall through.
2126 // If setcc returns 0/-1, all bits are sign bits.
2127 if (TLI.getBooleanContents() ==
2128 TargetLowering::ZeroOrNegativeOneBooleanContent)
2133 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2134 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2136 // Handle rotate right by N like a rotate left by 32-N.
2137 if (Op.getOpcode() == ISD::ROTR)
2138 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2140 // If we aren't rotating out all of the known-in sign bits, return the
2141 // number that are left. This handles rotl(sext(x), 1) for example.
2142 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2143 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2147 // Add can have at most one carry bit. Thus we know that the output
2148 // is, at worst, one more bit than the inputs.
2149 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2150 if (Tmp == 1) return 1; // Early out.
2152 // Special case decrementing a value (ADD X, -1):
2153 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2154 if (CRHS->isAllOnesValue()) {
2155 APInt KnownZero, KnownOne;
2156 APInt Mask = APInt::getAllOnesValue(VTBits);
2157 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2159 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2161 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2164 // If we are subtracting one from a positive number, there is no carry
2165 // out of the result.
2166 if (KnownZero.isNegative())
2170 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2171 if (Tmp2 == 1) return 1;
2172 return std::min(Tmp, Tmp2)-1;
2176 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2177 if (Tmp2 == 1) return 1;
2180 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2181 if (CLHS->isNullValue()) {
2182 APInt KnownZero, KnownOne;
2183 APInt Mask = APInt::getAllOnesValue(VTBits);
2184 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2185 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2187 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2190 // If the input is known to be positive (the sign bit is known clear),
2191 // the output of the NEG has the same number of sign bits as the input.
2192 if (KnownZero.isNegative())
2195 // Otherwise, we treat this like a SUB.
2198 // Sub can have at most one carry bit. Thus we know that the output
2199 // is, at worst, one more bit than the inputs.
2200 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2201 if (Tmp == 1) return 1; // Early out.
2202 return std::min(Tmp, Tmp2)-1;
2205 // FIXME: it's tricky to do anything useful for this, but it is an important
2206 // case for targets like X86.
2210 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2211 if (Op.getOpcode() == ISD::LOAD) {
2212 LoadSDNode *LD = cast<LoadSDNode>(Op);
2213 unsigned ExtType = LD->getExtensionType();
2216 case ISD::SEXTLOAD: // '17' bits known
2217 Tmp = LD->getMemoryVT().getSizeInBits();
2218 return VTBits-Tmp+1;
2219 case ISD::ZEXTLOAD: // '16' bits known
2220 Tmp = LD->getMemoryVT().getSizeInBits();
2225 // Allow the target to implement this method for its nodes.
2226 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2227 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2228 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2229 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2230 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2231 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2234 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2235 // use this information.
2236 APInt KnownZero, KnownOne;
2237 APInt Mask = APInt::getAllOnesValue(VTBits);
2238 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2240 if (KnownZero.isNegative()) { // sign bit is 0
2242 } else if (KnownOne.isNegative()) { // sign bit is 1;
2249 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2250 // the number of identical bits in the top of the input value.
2252 Mask <<= Mask.getBitWidth()-VTBits;
2253 // Return # leading zeros. We use 'min' here in case Val was zero before
2254 // shifting. We don't want to return '64' as for an i32 "0".
2255 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2258 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2259 // If we're told that NaNs won't happen, assume they won't.
2260 if (FiniteOnlyFPMath())
2263 // If the value is a constant, we can obviously see if it is a NaN or not.
2264 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2265 return !C->getValueAPF().isNaN();
2267 // TODO: Recognize more cases here.
2272 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2273 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2274 if (!GA) return false;
2275 if (GA->getOffset() != 0) return false;
2276 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2277 if (!GV) return false;
2278 MachineModuleInfo *MMI = getMachineModuleInfo();
2279 return MMI && MMI->hasDebugInfo();
2283 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2284 /// element of the result of the vector shuffle.
2285 SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
2287 EVT VT = N->getValueType(0);
2288 DebugLoc dl = N->getDebugLoc();
2289 if (N->getMaskElt(i) < 0)
2290 return getUNDEF(VT.getVectorElementType());
2291 unsigned Index = N->getMaskElt(i);
2292 unsigned NumElems = VT.getVectorNumElements();
2293 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2296 if (V.getOpcode() == ISD::BIT_CONVERT) {
2297 V = V.getOperand(0);
2298 EVT VVT = V.getValueType();
2299 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
2302 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2303 return (Index == 0) ? V.getOperand(0)
2304 : getUNDEF(VT.getVectorElementType());
2305 if (V.getOpcode() == ISD::BUILD_VECTOR)
2306 return V.getOperand(Index);
2307 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
2308 return getShuffleScalarElt(SVN, Index);
2313 /// getNode - Gets or creates the specified node.
2315 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2316 FoldingSetNodeID ID;
2317 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2319 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
2320 if (Ordering) Ordering->add(E);
2321 return SDValue(E, 0);
2323 SDNode *N = NodeAllocator.Allocate<SDNode>();
2324 new (N) SDNode(Opcode, DL, getVTList(VT));
2325 CSEMap.InsertNode(N, IP);
2327 AllNodes.push_back(N);
2328 if (Ordering) Ordering->add(N);
2332 return SDValue(N, 0);
2335 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2336 EVT VT, SDValue Operand) {
2337 // Constant fold unary operations with an integer constant operand.
2338 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2339 const APInt &Val = C->getAPIntValue();
2340 unsigned BitWidth = VT.getSizeInBits();
2343 case ISD::SIGN_EXTEND:
2344 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2345 case ISD::ANY_EXTEND:
2346 case ISD::ZERO_EXTEND:
2348 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2349 case ISD::UINT_TO_FP:
2350 case ISD::SINT_TO_FP: {
2351 const uint64_t zero[] = {0, 0};
2352 // No compile time operations on this type.
2353 if (VT==MVT::ppcf128)
2355 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2356 (void)apf.convertFromAPInt(Val,
2357 Opcode==ISD::SINT_TO_FP,
2358 APFloat::rmNearestTiesToEven);
2359 return getConstantFP(apf, VT);
2361 case ISD::BIT_CONVERT:
2362 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2363 return getConstantFP(Val.bitsToFloat(), VT);
2364 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2365 return getConstantFP(Val.bitsToDouble(), VT);
2368 return getConstant(Val.byteSwap(), VT);
2370 return getConstant(Val.countPopulation(), VT);
2372 return getConstant(Val.countLeadingZeros(), VT);
2374 return getConstant(Val.countTrailingZeros(), VT);
2378 // Constant fold unary operations with a floating point constant operand.
2379 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2380 APFloat V = C->getValueAPF(); // make copy
2381 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2385 return getConstantFP(V, VT);
2388 return getConstantFP(V, VT);
2390 case ISD::FP_EXTEND: {
2392 // This can return overflow, underflow, or inexact; we don't care.
2393 // FIXME need to be more flexible about rounding mode.
2394 (void)V.convert(*EVTToAPFloatSemantics(VT),
2395 APFloat::rmNearestTiesToEven, &ignored);
2396 return getConstantFP(V, VT);
2398 case ISD::FP_TO_SINT:
2399 case ISD::FP_TO_UINT: {
2402 assert(integerPartWidth >= 64);
2403 // FIXME need to be more flexible about rounding mode.
2404 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2405 Opcode==ISD::FP_TO_SINT,
2406 APFloat::rmTowardZero, &ignored);
2407 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2409 APInt api(VT.getSizeInBits(), 2, x);
2410 return getConstant(api, VT);
2412 case ISD::BIT_CONVERT:
2413 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2414 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2415 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2416 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2422 unsigned OpOpcode = Operand.getNode()->getOpcode();
2424 case ISD::TokenFactor:
2425 case ISD::MERGE_VALUES:
2426 case ISD::CONCAT_VECTORS:
2427 return Operand; // Factor, merge or concat of one node? No need.
2428 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2429 case ISD::FP_EXTEND:
2430 assert(VT.isFloatingPoint() &&
2431 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2432 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2433 assert((!VT.isVector() ||
2434 VT.getVectorNumElements() ==
2435 Operand.getValueType().getVectorNumElements()) &&
2436 "Vector element count mismatch!");
2437 if (Operand.getOpcode() == ISD::UNDEF)
2438 return getUNDEF(VT);
2440 case ISD::SIGN_EXTEND:
2441 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2442 "Invalid SIGN_EXTEND!");
2443 if (Operand.getValueType() == VT) return Operand; // noop extension
2444 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2445 "Invalid sext node, dst < src!");
2446 assert((!VT.isVector() ||
2447 VT.getVectorNumElements() ==
2448 Operand.getValueType().getVectorNumElements()) &&
2449 "Vector element count mismatch!");
2450 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2451 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2453 case ISD::ZERO_EXTEND:
2454 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2455 "Invalid ZERO_EXTEND!");
2456 if (Operand.getValueType() == VT) return Operand; // noop extension
2457 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2458 "Invalid zext node, dst < src!");
2459 assert((!VT.isVector() ||
2460 VT.getVectorNumElements() ==
2461 Operand.getValueType().getVectorNumElements()) &&
2462 "Vector element count mismatch!");
2463 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2464 return getNode(ISD::ZERO_EXTEND, DL, VT,
2465 Operand.getNode()->getOperand(0));
2467 case ISD::ANY_EXTEND:
2468 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2469 "Invalid ANY_EXTEND!");
2470 if (Operand.getValueType() == VT) return Operand; // noop extension
2471 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2472 "Invalid anyext node, dst < src!");
2473 assert((!VT.isVector() ||
2474 VT.getVectorNumElements() ==
2475 Operand.getValueType().getVectorNumElements()) &&
2476 "Vector element count mismatch!");
2477 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2478 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2479 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2482 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2483 "Invalid TRUNCATE!");
2484 if (Operand.getValueType() == VT) return Operand; // noop truncate
2485 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2486 "Invalid truncate node, src < dst!");
2487 assert((!VT.isVector() ||
2488 VT.getVectorNumElements() ==
2489 Operand.getValueType().getVectorNumElements()) &&
2490 "Vector element count mismatch!");
2491 if (OpOpcode == ISD::TRUNCATE)
2492 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2493 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2494 OpOpcode == ISD::ANY_EXTEND) {
2495 // If the source is smaller than the dest, we still need an extend.
2496 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2497 .bitsLT(VT.getScalarType()))
2498 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2499 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2500 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2502 return Operand.getNode()->getOperand(0);
2505 case ISD::BIT_CONVERT:
2506 // Basic sanity checking.
2507 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2508 && "Cannot BIT_CONVERT between types of different sizes!");
2509 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2510 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2511 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2512 if (OpOpcode == ISD::UNDEF)
2513 return getUNDEF(VT);
2515 case ISD::SCALAR_TO_VECTOR:
2516 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2517 (VT.getVectorElementType() == Operand.getValueType() ||
2518 (VT.getVectorElementType().isInteger() &&
2519 Operand.getValueType().isInteger() &&
2520 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2521 "Illegal SCALAR_TO_VECTOR node!");
2522 if (OpOpcode == ISD::UNDEF)
2523 return getUNDEF(VT);
2524 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2525 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2526 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2527 Operand.getConstantOperandVal(1) == 0 &&
2528 Operand.getOperand(0).getValueType() == VT)
2529 return Operand.getOperand(0);
2532 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2533 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2534 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2535 Operand.getNode()->getOperand(0));
2536 if (OpOpcode == ISD::FNEG) // --X -> X
2537 return Operand.getNode()->getOperand(0);
2540 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2541 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2546 SDVTList VTs = getVTList(VT);
2547 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2548 FoldingSetNodeID ID;
2549 SDValue Ops[1] = { Operand };
2550 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2552 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
2553 if (Ordering) Ordering->add(E);
2554 return SDValue(E, 0);
2556 N = NodeAllocator.Allocate<UnarySDNode>();
2557 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2558 CSEMap.InsertNode(N, IP);
2560 N = NodeAllocator.Allocate<UnarySDNode>();
2561 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2564 AllNodes.push_back(N);
2565 if (Ordering) Ordering->add(N);
2569 return SDValue(N, 0);
2572 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2574 ConstantSDNode *Cst1,
2575 ConstantSDNode *Cst2) {
2576 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2579 case ISD::ADD: return getConstant(C1 + C2, VT);
2580 case ISD::SUB: return getConstant(C1 - C2, VT);
2581 case ISD::MUL: return getConstant(C1 * C2, VT);
2583 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2586 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2589 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2592 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2594 case ISD::AND: return getConstant(C1 & C2, VT);
2595 case ISD::OR: return getConstant(C1 | C2, VT);
2596 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2597 case ISD::SHL: return getConstant(C1 << C2, VT);
2598 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2599 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2600 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2601 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2608 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2609 SDValue N1, SDValue N2) {
2610 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2611 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2614 case ISD::TokenFactor:
2615 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2616 N2.getValueType() == MVT::Other && "Invalid token factor!");
2617 // Fold trivial token factors.
2618 if (N1.getOpcode() == ISD::EntryToken) return N2;
2619 if (N2.getOpcode() == ISD::EntryToken) return N1;
2620 if (N1 == N2) return N1;
2622 case ISD::CONCAT_VECTORS:
2623 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2624 // one big BUILD_VECTOR.
2625 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2626 N2.getOpcode() == ISD::BUILD_VECTOR) {
2627 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2628 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2629 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2633 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2634 N1.getValueType() == VT && "Binary operator types must match!");
2635 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2636 // worth handling here.
2637 if (N2C && N2C->isNullValue())
2639 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2646 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2647 N1.getValueType() == VT && "Binary operator types must match!");
2648 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2649 // it's worth handling here.
2650 if (N2C && N2C->isNullValue())
2660 assert(VT.isInteger() && "This operator does not apply to FP types!");
2668 if (Opcode == ISD::FADD) {
2670 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2671 if (CFP->getValueAPF().isZero())
2674 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2675 if (CFP->getValueAPF().isZero())
2677 } else if (Opcode == ISD::FSUB) {
2679 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2680 if (CFP->getValueAPF().isZero())
2684 assert(N1.getValueType() == N2.getValueType() &&
2685 N1.getValueType() == VT && "Binary operator types must match!");
2687 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2688 assert(N1.getValueType() == VT &&
2689 N1.getValueType().isFloatingPoint() &&
2690 N2.getValueType().isFloatingPoint() &&
2691 "Invalid FCOPYSIGN!");
2698 assert(VT == N1.getValueType() &&
2699 "Shift operators return type must be the same as their first arg");
2700 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2701 "Shifts only work on integers");
2703 // Always fold shifts of i1 values so the code generator doesn't need to
2704 // handle them. Since we know the size of the shift has to be less than the
2705 // size of the value, the shift/rotate count is guaranteed to be zero.
2709 case ISD::FP_ROUND_INREG: {
2710 EVT EVT = cast<VTSDNode>(N2)->getVT();
2711 assert(VT == N1.getValueType() && "Not an inreg round!");
2712 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2713 "Cannot FP_ROUND_INREG integer types");
2714 assert(EVT.bitsLE(VT) && "Not rounding down!");
2715 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2719 assert(VT.isFloatingPoint() &&
2720 N1.getValueType().isFloatingPoint() &&
2721 VT.bitsLE(N1.getValueType()) &&
2722 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2723 if (N1.getValueType() == VT) return N1; // noop conversion.
2725 case ISD::AssertSext:
2726 case ISD::AssertZext: {
2727 EVT EVT = cast<VTSDNode>(N2)->getVT();
2728 assert(VT == N1.getValueType() && "Not an inreg extend!");
2729 assert(VT.isInteger() && EVT.isInteger() &&
2730 "Cannot *_EXTEND_INREG FP types");
2731 assert(!EVT.isVector() &&
2732 "AssertSExt/AssertZExt type should be the vector element type "
2733 "rather than the vector type!");
2734 assert(EVT.bitsLE(VT) && "Not extending!");
2735 if (VT == EVT) return N1; // noop assertion.
2738 case ISD::SIGN_EXTEND_INREG: {
2739 EVT EVT = cast<VTSDNode>(N2)->getVT();
2740 assert(VT == N1.getValueType() && "Not an inreg extend!");
2741 assert(VT.isInteger() && EVT.isInteger() &&
2742 "Cannot *_EXTEND_INREG FP types");
2743 assert(!EVT.isVector() &&
2744 "SIGN_EXTEND_INREG type should be the vector element type rather "
2745 "than the vector type!");
2746 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
2747 if (EVT == VT) return N1; // Not actually extending
2750 APInt Val = N1C->getAPIntValue();
2751 unsigned FromBits = EVT.getSizeInBits();
2752 Val <<= Val.getBitWidth()-FromBits;
2753 Val = Val.ashr(Val.getBitWidth()-FromBits);
2754 return getConstant(Val, VT);
2758 case ISD::EXTRACT_VECTOR_ELT:
2759 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2760 if (N1.getOpcode() == ISD::UNDEF)
2761 return getUNDEF(VT);
2763 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2764 // expanding copies of large vectors from registers.
2766 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2767 N1.getNumOperands() > 0) {
2769 N1.getOperand(0).getValueType().getVectorNumElements();
2770 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2771 N1.getOperand(N2C->getZExtValue() / Factor),
2772 getConstant(N2C->getZExtValue() % Factor,
2773 N2.getValueType()));
2776 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2777 // expanding large vector constants.
2778 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2779 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2780 EVT VEltTy = N1.getValueType().getVectorElementType();
2781 if (Elt.getValueType() != VEltTy) {
2782 // If the vector element type is not legal, the BUILD_VECTOR operands
2783 // are promoted and implicitly truncated. Make that explicit here.
2784 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2787 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2788 // result is implicitly extended.
2789 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2794 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2795 // operations are lowered to scalars.
2796 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2797 // If the indices are the same, return the inserted element.
2798 if (N1.getOperand(2) == N2)
2799 return N1.getOperand(1);
2800 // If the indices are known different, extract the element from
2801 // the original vector.
2802 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2803 isa<ConstantSDNode>(N2))
2804 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2807 case ISD::EXTRACT_ELEMENT:
2808 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2809 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2810 (N1.getValueType().isInteger() == VT.isInteger()) &&
2811 "Wrong types for EXTRACT_ELEMENT!");
2813 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2814 // 64-bit integers into 32-bit parts. Instead of building the extract of
2815 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2816 if (N1.getOpcode() == ISD::BUILD_PAIR)
2817 return N1.getOperand(N2C->getZExtValue());
2819 // EXTRACT_ELEMENT of a constant int is also very common.
2820 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2821 unsigned ElementSize = VT.getSizeInBits();
2822 unsigned Shift = ElementSize * N2C->getZExtValue();
2823 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2824 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2827 case ISD::EXTRACT_SUBVECTOR:
2828 if (N1.getValueType() == VT) // Trivial extraction.
2835 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2836 if (SV.getNode()) return SV;
2837 } else { // Cannonicalize constant to RHS if commutative
2838 if (isCommutativeBinOp(Opcode)) {
2839 std::swap(N1C, N2C);
2845 // Constant fold FP operations.
2846 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2847 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2849 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2850 // Cannonicalize constant to RHS if commutative
2851 std::swap(N1CFP, N2CFP);
2853 } else if (N2CFP && VT != MVT::ppcf128) {
2854 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2855 APFloat::opStatus s;
2858 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2859 if (s != APFloat::opInvalidOp)
2860 return getConstantFP(V1, VT);
2863 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2864 if (s!=APFloat::opInvalidOp)
2865 return getConstantFP(V1, VT);
2868 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2869 if (s!=APFloat::opInvalidOp)
2870 return getConstantFP(V1, VT);
2873 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2874 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2875 return getConstantFP(V1, VT);
2878 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2879 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2880 return getConstantFP(V1, VT);
2882 case ISD::FCOPYSIGN:
2884 return getConstantFP(V1, VT);
2890 // Canonicalize an UNDEF to the RHS, even over a constant.
2891 if (N1.getOpcode() == ISD::UNDEF) {
2892 if (isCommutativeBinOp(Opcode)) {
2896 case ISD::FP_ROUND_INREG:
2897 case ISD::SIGN_EXTEND_INREG:
2903 return N1; // fold op(undef, arg2) -> undef
2911 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2912 // For vectors, we can't easily build an all zero vector, just return
2919 // Fold a bunch of operators when the RHS is undef.
2920 if (N2.getOpcode() == ISD::UNDEF) {
2923 if (N1.getOpcode() == ISD::UNDEF)
2924 // Handle undef ^ undef -> 0 special case. This is a common
2926 return getConstant(0, VT);
2936 return N2; // fold op(arg1, undef) -> undef
2950 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2951 // For vectors, we can't easily build an all zero vector, just return
2956 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2957 // For vectors, we can't easily build an all one vector, just return
2965 // Memoize this node if possible.
2967 SDVTList VTs = getVTList(VT);
2968 if (VT != MVT::Flag) {
2969 SDValue Ops[] = { N1, N2 };
2970 FoldingSetNodeID ID;
2971 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2973 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
2974 if (Ordering) Ordering->add(E);
2975 return SDValue(E, 0);
2977 N = NodeAllocator.Allocate<BinarySDNode>();
2978 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2979 CSEMap.InsertNode(N, IP);
2981 N = NodeAllocator.Allocate<BinarySDNode>();
2982 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2985 AllNodes.push_back(N);
2986 if (Ordering) Ordering->add(N);
2990 return SDValue(N, 0);
2993 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2994 SDValue N1, SDValue N2, SDValue N3) {
2995 // Perform various simplifications.
2996 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2997 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2999 case ISD::CONCAT_VECTORS:
3000 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3001 // one big BUILD_VECTOR.
3002 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3003 N2.getOpcode() == ISD::BUILD_VECTOR &&
3004 N3.getOpcode() == ISD::BUILD_VECTOR) {
3005 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
3006 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
3007 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
3008 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
3012 // Use FoldSetCC to simplify SETCC's.
3013 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3014 if (Simp.getNode()) return Simp;
3019 if (N1C->getZExtValue())
3020 return N2; // select true, X, Y -> X
3022 return N3; // select false, X, Y -> Y
3025 if (N2 == N3) return N2; // select C, X, X -> X
3029 if (N2C->getZExtValue()) // Unconditional branch
3030 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
3032 return N1; // Never-taken branch
3035 case ISD::VECTOR_SHUFFLE:
3036 llvm_unreachable("should use getVectorShuffle constructor!");
3038 case ISD::BIT_CONVERT:
3039 // Fold bit_convert nodes from a type to themselves.
3040 if (N1.getValueType() == VT)
3045 // Memoize node if it doesn't produce a flag.
3047 SDVTList VTs = getVTList(VT);
3048 if (VT != MVT::Flag) {
3049 SDValue Ops[] = { N1, N2, N3 };
3050 FoldingSetNodeID ID;
3051 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3053 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3054 if (Ordering) Ordering->add(E);
3055 return SDValue(E, 0);
3057 N = NodeAllocator.Allocate<TernarySDNode>();
3058 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3059 CSEMap.InsertNode(N, IP);
3061 N = NodeAllocator.Allocate<TernarySDNode>();
3062 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3065 AllNodes.push_back(N);
3066 if (Ordering) Ordering->add(N);
3070 return SDValue(N, 0);
3073 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3074 SDValue N1, SDValue N2, SDValue N3,
3076 SDValue Ops[] = { N1, N2, N3, N4 };
3077 return getNode(Opcode, DL, VT, Ops, 4);
3080 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3081 SDValue N1, SDValue N2, SDValue N3,
3082 SDValue N4, SDValue N5) {
3083 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3084 return getNode(Opcode, DL, VT, Ops, 5);
3087 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3088 /// the incoming stack arguments to be loaded from the stack.
3089 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3090 SmallVector<SDValue, 8> ArgChains;
3092 // Include the original chain at the beginning of the list. When this is
3093 // used by target LowerCall hooks, this helps legalize find the
3094 // CALLSEQ_BEGIN node.
3095 ArgChains.push_back(Chain);
3097 // Add a chain value for each stack argument.
3098 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3099 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3100 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3101 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3102 if (FI->getIndex() < 0)
3103 ArgChains.push_back(SDValue(L, 1));
3105 // Build a tokenfactor for all the chains.
3106 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3107 &ArgChains[0], ArgChains.size());
3110 /// getMemsetValue - Vectorized representation of the memset value
3112 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3114 unsigned NumBits = VT.isVector() ?
3115 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
3116 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3117 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
3119 for (unsigned i = NumBits; i > 8; i >>= 1) {
3120 Val = (Val << Shift) | Val;
3124 return DAG.getConstant(Val, VT);
3125 return DAG.getConstantFP(APFloat(Val), VT);
3128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3129 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3131 for (unsigned i = NumBits; i > 8; i >>= 1) {
3132 Value = DAG.getNode(ISD::OR, dl, VT,
3133 DAG.getNode(ISD::SHL, dl, VT, Value,
3134 DAG.getConstant(Shift,
3135 TLI.getShiftAmountTy())),
3143 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3144 /// used when a memcpy is turned into a memset when the source is a constant
3146 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3147 const TargetLowering &TLI,
3148 std::string &Str, unsigned Offset) {
3149 // Handle vector with all elements zero.
3152 return DAG.getConstant(0, VT);
3153 unsigned NumElts = VT.getVectorNumElements();
3154 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3155 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3157 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
3160 assert(!VT.isVector() && "Can't handle vector type here!");
3161 unsigned NumBits = VT.getSizeInBits();
3162 unsigned MSB = NumBits / 8;
3164 if (TLI.isLittleEndian())
3165 Offset = Offset + MSB - 1;
3166 for (unsigned i = 0; i != MSB; ++i) {
3167 Val = (Val << 8) | (unsigned char)Str[Offset];
3168 Offset += TLI.isLittleEndian() ? -1 : 1;
3170 return DAG.getConstant(Val, VT);
3173 /// getMemBasePlusOffset - Returns base and offset node for the
3175 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3176 SelectionDAG &DAG) {
3177 EVT VT = Base.getValueType();
3178 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3179 VT, Base, DAG.getConstant(Offset, VT));
3182 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3184 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3185 unsigned SrcDelta = 0;
3186 GlobalAddressSDNode *G = NULL;
3187 if (Src.getOpcode() == ISD::GlobalAddress)
3188 G = cast<GlobalAddressSDNode>(Src);
3189 else if (Src.getOpcode() == ISD::ADD &&
3190 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3191 Src.getOperand(1).getOpcode() == ISD::Constant) {
3192 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3193 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3198 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3199 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3205 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3206 /// to replace the memset / memcpy is below the threshold. It also returns the
3207 /// types of the sequence of memory ops to perform memset / memcpy.
3209 bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
3210 SDValue Dst, SDValue Src,
3211 unsigned Limit, uint64_t Size, unsigned &Align,
3212 std::string &Str, bool &isSrcStr,
3214 const TargetLowering &TLI) {
3215 isSrcStr = isMemSrcFromString(Src, Str);
3216 bool isSrcConst = isa<ConstantSDNode>(Src);
3217 EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3218 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
3219 if (VT != MVT::iAny) {
3220 const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3221 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3222 // If source is a string constant, this will require an unaligned load.
3223 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3224 if (Dst.getOpcode() != ISD::FrameIndex) {
3225 // Can't change destination alignment. It requires a unaligned store.
3229 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3230 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3231 if (MFI->isFixedObjectIndex(FI)) {
3232 // Can't change destination alignment. It requires a unaligned store.
3236 // Give the stack frame object a larger alignment if needed.
3237 if (MFI->getObjectAlignment(FI) < NewAlign)
3238 MFI->setObjectAlignment(FI, NewAlign);
3245 if (VT == MVT::iAny) {
3246 if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
3249 switch (Align & 7) {
3250 case 0: VT = MVT::i64; break;
3251 case 4: VT = MVT::i32; break;
3252 case 2: VT = MVT::i16; break;
3253 default: VT = MVT::i8; break;
3258 while (!TLI.isTypeLegal(LVT))
3259 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3260 assert(LVT.isInteger());
3266 unsigned NumMemOps = 0;
3268 unsigned VTSize = VT.getSizeInBits() / 8;
3269 while (VTSize > Size) {
3270 // For now, only use non-vector load / store's for the left-over pieces.
3271 if (VT.isVector()) {
3273 while (!TLI.isTypeLegal(VT))
3274 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3275 VTSize = VT.getSizeInBits() / 8;
3277 // This can result in a type that is not legal on the target, e.g.
3278 // 1 or 2 bytes on PPC.
3279 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3284 if (++NumMemOps > Limit)
3286 MemOps.push_back(VT);
3293 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3294 SDValue Chain, SDValue Dst,
3295 SDValue Src, uint64_t Size,
3296 unsigned Align, bool AlwaysInline,
3297 const Value *DstSV, uint64_t DstSVOff,
3298 const Value *SrcSV, uint64_t SrcSVOff){
3299 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3301 // Expand memcpy to a series of load and store ops if the size operand falls
3302 // below a certain threshold.
3303 std::vector<EVT> MemOps;
3304 uint64_t Limit = -1ULL;
3306 Limit = TLI.getMaxStoresPerMemcpy();
3307 unsigned DstAlign = Align; // Destination alignment can change.
3310 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3311 Str, CopyFromStr, DAG, TLI))
3315 bool isZeroStr = CopyFromStr && Str.empty();
3316 SmallVector<SDValue, 8> OutChains;
3317 unsigned NumMemOps = MemOps.size();
3318 uint64_t SrcOff = 0, DstOff = 0;
3319 for (unsigned i = 0; i != NumMemOps; ++i) {
3321 unsigned VTSize = VT.getSizeInBits() / 8;
3322 SDValue Value, Store;
3324 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3325 // It's unlikely a store of a vector immediate can be done in a single
3326 // instruction. It would require a load from a constantpool first.
3327 // We also handle store a vector with all zero's.
3328 // FIXME: Handle other cases where store of vector immediate is done in
3329 // a single instruction.
3330 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3331 Store = DAG.getStore(Chain, dl, Value,
3332 getMemBasePlusOffset(Dst, DstOff, DAG),
3333 DstSV, DstSVOff + DstOff, false, DstAlign);
3335 // The type might not be legal for the target. This should only happen
3336 // if the type is smaller than a legal type, as on PPC, so the right
3337 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3338 // to Load/Store if NVT==VT.
3339 // FIXME does the case above also need this?
3340 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3341 assert(NVT.bitsGE(VT));
3342 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3343 getMemBasePlusOffset(Src, SrcOff, DAG),
3344 SrcSV, SrcSVOff + SrcOff, VT, false, Align);
3345 Store = DAG.getTruncStore(Chain, dl, Value,
3346 getMemBasePlusOffset(Dst, DstOff, DAG),
3347 DstSV, DstSVOff + DstOff, VT, false, DstAlign);
3349 OutChains.push_back(Store);
3354 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3355 &OutChains[0], OutChains.size());
3358 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3359 SDValue Chain, SDValue Dst,
3360 SDValue Src, uint64_t Size,
3361 unsigned Align, bool AlwaysInline,
3362 const Value *DstSV, uint64_t DstSVOff,
3363 const Value *SrcSV, uint64_t SrcSVOff){
3364 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3366 // Expand memmove to a series of load and store ops if the size operand falls
3367 // below a certain threshold.
3368 std::vector<EVT> MemOps;
3369 uint64_t Limit = -1ULL;
3371 Limit = TLI.getMaxStoresPerMemmove();
3372 unsigned DstAlign = Align; // Destination alignment can change.
3375 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3376 Str, CopyFromStr, DAG, TLI))
3379 uint64_t SrcOff = 0, DstOff = 0;
3381 SmallVector<SDValue, 8> LoadValues;
3382 SmallVector<SDValue, 8> LoadChains;
3383 SmallVector<SDValue, 8> OutChains;
3384 unsigned NumMemOps = MemOps.size();
3385 for (unsigned i = 0; i < NumMemOps; i++) {
3387 unsigned VTSize = VT.getSizeInBits() / 8;
3388 SDValue Value, Store;
3390 Value = DAG.getLoad(VT, dl, Chain,
3391 getMemBasePlusOffset(Src, SrcOff, DAG),
3392 SrcSV, SrcSVOff + SrcOff, false, Align);
3393 LoadValues.push_back(Value);
3394 LoadChains.push_back(Value.getValue(1));
3397 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3398 &LoadChains[0], LoadChains.size());
3400 for (unsigned i = 0; i < NumMemOps; i++) {
3402 unsigned VTSize = VT.getSizeInBits() / 8;
3403 SDValue Value, Store;
3405 Store = DAG.getStore(Chain, dl, LoadValues[i],
3406 getMemBasePlusOffset(Dst, DstOff, DAG),
3407 DstSV, DstSVOff + DstOff, false, DstAlign);
3408 OutChains.push_back(Store);
3412 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3413 &OutChains[0], OutChains.size());
3416 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3417 SDValue Chain, SDValue Dst,
3418 SDValue Src, uint64_t Size,
3420 const Value *DstSV, uint64_t DstSVOff) {
3421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3423 // Expand memset to a series of load/store ops if the size operand
3424 // falls below a certain threshold.
3425 std::vector<EVT> MemOps;
3428 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3429 Size, Align, Str, CopyFromStr, DAG, TLI))
3432 SmallVector<SDValue, 8> OutChains;
3433 uint64_t DstOff = 0;
3435 unsigned NumMemOps = MemOps.size();
3436 for (unsigned i = 0; i < NumMemOps; i++) {
3438 unsigned VTSize = VT.getSizeInBits() / 8;
3439 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3440 SDValue Store = DAG.getStore(Chain, dl, Value,
3441 getMemBasePlusOffset(Dst, DstOff, DAG),
3442 DstSV, DstSVOff + DstOff);
3443 OutChains.push_back(Store);
3447 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3448 &OutChains[0], OutChains.size());
3451 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3452 SDValue Src, SDValue Size,
3453 unsigned Align, bool AlwaysInline,
3454 const Value *DstSV, uint64_t DstSVOff,
3455 const Value *SrcSV, uint64_t SrcSVOff) {
3457 // Check to see if we should lower the memcpy to loads and stores first.
3458 // For cases within the target-specified limits, this is the best choice.
3459 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3461 // Memcpy with size zero? Just return the original chain.
3462 if (ConstantSize->isNullValue())
3466 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3467 ConstantSize->getZExtValue(),
3468 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3469 if (Result.getNode())
3473 // Then check to see if we should lower the memcpy with target-specific
3474 // code. If the target chooses to do this, this is the next best.
3476 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3478 DstSV, DstSVOff, SrcSV, SrcSVOff);
3479 if (Result.getNode())
3482 // If we really need inline code and the target declined to provide it,
3483 // use a (potentially long) sequence of loads and stores.
3485 assert(ConstantSize && "AlwaysInline requires a constant size!");
3486 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3487 ConstantSize->getZExtValue(), Align, true,
3488 DstSV, DstSVOff, SrcSV, SrcSVOff);
3491 // Emit a library call.
3492 TargetLowering::ArgListTy Args;
3493 TargetLowering::ArgListEntry Entry;
3494 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3495 Entry.Node = Dst; Args.push_back(Entry);
3496 Entry.Node = Src; Args.push_back(Entry);
3497 Entry.Node = Size; Args.push_back(Entry);
3498 // FIXME: pass in DebugLoc
3499 std::pair<SDValue,SDValue> CallResult =
3500 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3501 false, false, false, false, 0,
3502 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3503 /*isReturnValueUsed=*/false,
3504 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3505 TLI.getPointerTy()),
3507 return CallResult.second;
3510 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3511 SDValue Src, SDValue Size,
3513 const Value *DstSV, uint64_t DstSVOff,
3514 const Value *SrcSV, uint64_t SrcSVOff) {
3516 // Check to see if we should lower the memmove to loads and stores first.
3517 // For cases within the target-specified limits, this is the best choice.
3518 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3520 // Memmove with size zero? Just return the original chain.
3521 if (ConstantSize->isNullValue())
3525 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3526 ConstantSize->getZExtValue(),
3527 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3528 if (Result.getNode())
3532 // Then check to see if we should lower the memmove with target-specific
3533 // code. If the target chooses to do this, this is the next best.
3535 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3536 DstSV, DstSVOff, SrcSV, SrcSVOff);
3537 if (Result.getNode())
3540 // Emit a library call.
3541 TargetLowering::ArgListTy Args;
3542 TargetLowering::ArgListEntry Entry;
3543 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3544 Entry.Node = Dst; Args.push_back(Entry);
3545 Entry.Node = Src; Args.push_back(Entry);
3546 Entry.Node = Size; Args.push_back(Entry);
3547 // FIXME: pass in DebugLoc
3548 std::pair<SDValue,SDValue> CallResult =
3549 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3550 false, false, false, false, 0,
3551 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3552 /*isReturnValueUsed=*/false,
3553 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3554 TLI.getPointerTy()),
3556 return CallResult.second;
3559 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3560 SDValue Src, SDValue Size,
3562 const Value *DstSV, uint64_t DstSVOff) {
3564 // Check to see if we should lower the memset to stores first.
3565 // For cases within the target-specified limits, this is the best choice.
3566 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3568 // Memset with size zero? Just return the original chain.
3569 if (ConstantSize->isNullValue())
3573 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3574 Align, DstSV, DstSVOff);
3575 if (Result.getNode())
3579 // Then check to see if we should lower the memset with target-specific
3580 // code. If the target chooses to do this, this is the next best.
3582 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3584 if (Result.getNode())
3587 // Emit a library call.
3588 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3589 TargetLowering::ArgListTy Args;
3590 TargetLowering::ArgListEntry Entry;
3591 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3592 Args.push_back(Entry);
3593 // Extend or truncate the argument to be an i32 value for the call.
3594 if (Src.getValueType().bitsGT(MVT::i32))
3595 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3597 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3599 Entry.Ty = Type::getInt32Ty(*getContext());
3600 Entry.isSExt = true;
3601 Args.push_back(Entry);
3603 Entry.Ty = IntPtrTy;
3604 Entry.isSExt = false;
3605 Args.push_back(Entry);
3606 // FIXME: pass in DebugLoc
3607 std::pair<SDValue,SDValue> CallResult =
3608 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3609 false, false, false, false, 0,
3610 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3611 /*isReturnValueUsed=*/false,
3612 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3613 TLI.getPointerTy()),
3615 return CallResult.second;
3618 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3620 SDValue Ptr, SDValue Cmp,
3621 SDValue Swp, const Value* PtrVal,
3622 unsigned Alignment) {
3623 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3624 Alignment = getEVTAlignment(MemVT);
3626 // Check if the memory reference references a frame index
3628 if (const FrameIndexSDNode *FI =
3629 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3630 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3632 MachineFunction &MF = getMachineFunction();
3633 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3635 // For now, atomics are considered to be volatile always.
3636 Flags |= MachineMemOperand::MOVolatile;
3638 MachineMemOperand *MMO =
3639 MF.getMachineMemOperand(PtrVal, Flags, 0,
3640 MemVT.getStoreSize(), Alignment);
3642 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3645 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3647 SDValue Ptr, SDValue Cmp,
3648 SDValue Swp, MachineMemOperand *MMO) {
3649 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3650 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3652 EVT VT = Cmp.getValueType();
3654 SDVTList VTs = getVTList(VT, MVT::Other);
3655 FoldingSetNodeID ID;
3656 ID.AddInteger(MemVT.getRawBits());
3657 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3658 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3660 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3661 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3662 if (Ordering) Ordering->add(E);
3663 return SDValue(E, 0);
3665 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3666 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3667 CSEMap.InsertNode(N, IP);
3668 AllNodes.push_back(N);
3669 if (Ordering) Ordering->add(N);
3670 return SDValue(N, 0);
3673 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3675 SDValue Ptr, SDValue Val,
3676 const Value* PtrVal,
3677 unsigned Alignment) {
3678 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3679 Alignment = getEVTAlignment(MemVT);
3681 // Check if the memory reference references a frame index
3683 if (const FrameIndexSDNode *FI =
3684 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3685 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3687 MachineFunction &MF = getMachineFunction();
3688 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3690 // For now, atomics are considered to be volatile always.
3691 Flags |= MachineMemOperand::MOVolatile;
3693 MachineMemOperand *MMO =
3694 MF.getMachineMemOperand(PtrVal, Flags, 0,
3695 MemVT.getStoreSize(), Alignment);
3697 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
3700 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3702 SDValue Ptr, SDValue Val,
3703 MachineMemOperand *MMO) {
3704 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3705 Opcode == ISD::ATOMIC_LOAD_SUB ||
3706 Opcode == ISD::ATOMIC_LOAD_AND ||
3707 Opcode == ISD::ATOMIC_LOAD_OR ||
3708 Opcode == ISD::ATOMIC_LOAD_XOR ||
3709 Opcode == ISD::ATOMIC_LOAD_NAND ||
3710 Opcode == ISD::ATOMIC_LOAD_MIN ||
3711 Opcode == ISD::ATOMIC_LOAD_MAX ||
3712 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3713 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3714 Opcode == ISD::ATOMIC_SWAP) &&
3715 "Invalid Atomic Op");
3717 EVT VT = Val.getValueType();
3719 SDVTList VTs = getVTList(VT, MVT::Other);
3720 FoldingSetNodeID ID;
3721 ID.AddInteger(MemVT.getRawBits());
3722 SDValue Ops[] = {Chain, Ptr, Val};
3723 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3725 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3726 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3727 if (Ordering) Ordering->add(E);
3728 return SDValue(E, 0);
3730 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3731 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Val, MMO);
3732 CSEMap.InsertNode(N, IP);
3733 AllNodes.push_back(N);
3734 if (Ordering) Ordering->add(N);
3735 return SDValue(N, 0);
3738 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3739 /// Allowed to return something different (and simpler) if Simplify is true.
3740 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3745 SmallVector<EVT, 4> VTs;
3746 VTs.reserve(NumOps);
3747 for (unsigned i = 0; i < NumOps; ++i)
3748 VTs.push_back(Ops[i].getValueType());
3749 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3754 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3755 const EVT *VTs, unsigned NumVTs,
3756 const SDValue *Ops, unsigned NumOps,
3757 EVT MemVT, const Value *srcValue, int SVOff,
3758 unsigned Align, bool Vol,
3759 bool ReadMem, bool WriteMem) {
3760 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3761 MemVT, srcValue, SVOff, Align, Vol,
3766 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3767 const SDValue *Ops, unsigned NumOps,
3768 EVT MemVT, const Value *srcValue, int SVOff,
3769 unsigned Align, bool Vol,
3770 bool ReadMem, bool WriteMem) {
3771 if (Align == 0) // Ensure that codegen never sees alignment 0
3772 Align = getEVTAlignment(MemVT);
3774 MachineFunction &MF = getMachineFunction();
3777 Flags |= MachineMemOperand::MOStore;
3779 Flags |= MachineMemOperand::MOLoad;
3781 Flags |= MachineMemOperand::MOVolatile;
3782 MachineMemOperand *MMO =
3783 MF.getMachineMemOperand(srcValue, Flags, SVOff,
3784 MemVT.getStoreSize(), Align);
3786 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3790 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3791 const SDValue *Ops, unsigned NumOps,
3792 EVT MemVT, MachineMemOperand *MMO) {
3793 assert((Opcode == ISD::INTRINSIC_VOID ||
3794 Opcode == ISD::INTRINSIC_W_CHAIN ||
3795 (Opcode <= INT_MAX &&
3796 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
3797 "Opcode is not a memory-accessing opcode!");
3799 // Memoize the node unless it returns a flag.
3800 MemIntrinsicSDNode *N;
3801 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3802 FoldingSetNodeID ID;
3803 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3805 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3806 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
3807 if (Ordering) Ordering->add(E);
3808 return SDValue(E, 0);
3811 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3812 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3813 CSEMap.InsertNode(N, IP);
3815 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3816 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3818 AllNodes.push_back(N);
3819 if (Ordering) Ordering->add(N);
3820 return SDValue(N, 0);
3824 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3825 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3826 SDValue Ptr, SDValue Offset,
3827 const Value *SV, int SVOffset, EVT MemVT,
3828 bool isVolatile, unsigned Alignment) {
3829 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3830 Alignment = getEVTAlignment(VT);
3832 // Check if the memory reference references a frame index
3834 if (const FrameIndexSDNode *FI =
3835 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3836 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3838 MachineFunction &MF = getMachineFunction();
3839 unsigned Flags = MachineMemOperand::MOLoad;
3841 Flags |= MachineMemOperand::MOVolatile;
3842 MachineMemOperand *MMO =
3843 MF.getMachineMemOperand(SV, Flags, SVOffset,
3844 MemVT.getStoreSize(), Alignment);
3845 return getLoad(AM, dl, ExtType, VT, Chain, Ptr, Offset, MemVT, MMO);
3849 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3850 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3851 SDValue Ptr, SDValue Offset, EVT MemVT,
3852 MachineMemOperand *MMO) {
3854 ExtType = ISD::NON_EXTLOAD;
3855 } else if (ExtType == ISD::NON_EXTLOAD) {
3856 assert(VT == MemVT && "Non-extending load from different memory type!");
3859 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
3860 "Should only be an extending load, not truncating!");
3861 assert(VT.isInteger() == MemVT.isInteger() &&
3862 "Cannot convert from FP to Int or Int -> FP!");
3863 assert(VT.isVector() == MemVT.isVector() &&
3864 "Cannot use trunc store to convert to or from a vector!");
3865 assert((!VT.isVector() ||
3866 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
3867 "Cannot use trunc store to change the number of vector elements!");
3870 bool Indexed = AM != ISD::UNINDEXED;
3871 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3872 "Unindexed load with an offset!");
3874 SDVTList VTs = Indexed ?
3875 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3876 SDValue Ops[] = { Chain, Ptr, Offset };
3877 FoldingSetNodeID ID;
3878 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3879 ID.AddInteger(MemVT.getRawBits());
3880 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile()));
3882 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3883 cast<LoadSDNode>(E)->refineAlignment(MMO);
3884 if (Ordering) Ordering->add(E);
3885 return SDValue(E, 0);
3887 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3888 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, MemVT, MMO);
3889 CSEMap.InsertNode(N, IP);
3890 AllNodes.push_back(N);
3891 if (Ordering) Ordering->add(N);
3892 return SDValue(N, 0);
3895 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
3896 SDValue Chain, SDValue Ptr,
3897 const Value *SV, int SVOffset,
3898 bool isVolatile, unsigned Alignment) {
3899 SDValue Undef = getUNDEF(Ptr.getValueType());
3900 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3901 SV, SVOffset, VT, isVolatile, Alignment);
3904 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
3905 SDValue Chain, SDValue Ptr,
3907 int SVOffset, EVT MemVT,
3908 bool isVolatile, unsigned Alignment) {
3909 SDValue Undef = getUNDEF(Ptr.getValueType());
3910 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3911 SV, SVOffset, MemVT, isVolatile, Alignment);
3915 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3916 SDValue Offset, ISD::MemIndexedMode AM) {
3917 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3918 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3919 "Load is already a indexed load!");
3920 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3921 LD->getChain(), Base, Offset, LD->getSrcValue(),
3922 LD->getSrcValueOffset(), LD->getMemoryVT(),
3923 LD->isVolatile(), LD->getAlignment());
3926 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3927 SDValue Ptr, const Value *SV, int SVOffset,
3928 bool isVolatile, unsigned Alignment) {
3929 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3930 Alignment = getEVTAlignment(Val.getValueType());
3932 // Check if the memory reference references a frame index
3934 if (const FrameIndexSDNode *FI =
3935 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3936 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3938 MachineFunction &MF = getMachineFunction();
3939 unsigned Flags = MachineMemOperand::MOStore;
3941 Flags |= MachineMemOperand::MOVolatile;
3942 MachineMemOperand *MMO =
3943 MF.getMachineMemOperand(SV, Flags, SVOffset,
3944 Val.getValueType().getStoreSize(), Alignment);
3946 return getStore(Chain, dl, Val, Ptr, MMO);
3949 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3950 SDValue Ptr, MachineMemOperand *MMO) {
3951 EVT VT = Val.getValueType();
3952 SDVTList VTs = getVTList(MVT::Other);
3953 SDValue Undef = getUNDEF(Ptr.getValueType());
3954 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3955 FoldingSetNodeID ID;
3956 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3957 ID.AddInteger(VT.getRawBits());
3958 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile()));
3960 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3961 cast<StoreSDNode>(E)->refineAlignment(MMO);
3962 if (Ordering) Ordering->add(E);
3963 return SDValue(E, 0);
3965 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3966 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false, VT, MMO);
3967 CSEMap.InsertNode(N, IP);
3968 AllNodes.push_back(N);
3969 if (Ordering) Ordering->add(N);
3970 return SDValue(N, 0);
3973 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3974 SDValue Ptr, const Value *SV,
3975 int SVOffset, EVT SVT,
3976 bool isVolatile, unsigned Alignment) {
3977 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3978 Alignment = getEVTAlignment(SVT);
3980 // Check if the memory reference references a frame index
3982 if (const FrameIndexSDNode *FI =
3983 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3984 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3986 MachineFunction &MF = getMachineFunction();
3987 unsigned Flags = MachineMemOperand::MOStore;
3989 Flags |= MachineMemOperand::MOVolatile;
3990 MachineMemOperand *MMO =
3991 MF.getMachineMemOperand(SV, Flags, SVOffset, SVT.getStoreSize(), Alignment);
3993 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
3996 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3997 SDValue Ptr, EVT SVT,
3998 MachineMemOperand *MMO) {
3999 EVT VT = Val.getValueType();
4002 return getStore(Chain, dl, Val, Ptr, MMO);
4004 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4005 "Should only be a truncating store, not extending!");
4006 assert(VT.isInteger() == SVT.isInteger() &&
4007 "Can't do FP-INT conversion!");
4008 assert(VT.isVector() == SVT.isVector() &&
4009 "Cannot use trunc store to convert to or from a vector!");
4010 assert((!VT.isVector() ||
4011 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4012 "Cannot use trunc store to change the number of vector elements!");
4014 SDVTList VTs = getVTList(MVT::Other);
4015 SDValue Undef = getUNDEF(Ptr.getValueType());
4016 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4017 FoldingSetNodeID ID;
4018 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4019 ID.AddInteger(SVT.getRawBits());
4020 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile()));
4022 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4023 cast<StoreSDNode>(E)->refineAlignment(MMO);
4024 if (Ordering) Ordering->add(E);
4025 return SDValue(E, 0);
4027 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4028 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true, SVT, MMO);
4029 CSEMap.InsertNode(N, IP);
4030 AllNodes.push_back(N);
4031 if (Ordering) Ordering->add(N);
4032 return SDValue(N, 0);
4036 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
4037 SDValue Offset, ISD::MemIndexedMode AM) {
4038 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4039 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4040 "Store is already a indexed store!");
4041 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4042 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4043 FoldingSetNodeID ID;
4044 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4045 ID.AddInteger(ST->getMemoryVT().getRawBits());
4046 ID.AddInteger(ST->getRawSubclassData());
4048 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4049 if (Ordering) Ordering->add(E);
4050 return SDValue(E, 0);
4052 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4053 new (N) StoreSDNode(Ops, dl, VTs, AM,
4054 ST->isTruncatingStore(), ST->getMemoryVT(),
4055 ST->getMemOperand());
4056 CSEMap.InsertNode(N, IP);
4057 AllNodes.push_back(N);
4058 if (Ordering) Ordering->add(N);
4059 return SDValue(N, 0);
4062 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
4063 SDValue Chain, SDValue Ptr,
4065 SDValue Ops[] = { Chain, Ptr, SV };
4066 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
4069 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4070 const SDUse *Ops, unsigned NumOps) {
4072 case 0: return getNode(Opcode, DL, VT);
4073 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4074 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4075 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4079 // Copy from an SDUse array into an SDValue array for use with
4080 // the regular getNode logic.
4081 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4082 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4085 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4086 const SDValue *Ops, unsigned NumOps) {
4088 case 0: return getNode(Opcode, DL, VT);
4089 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4090 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4091 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4097 case ISD::SELECT_CC: {
4098 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4099 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4100 "LHS and RHS of condition must have same type!");
4101 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4102 "True and False arms of SelectCC must have same type!");
4103 assert(Ops[2].getValueType() == VT &&
4104 "select_cc node must be of same type as true and false value!");
4108 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4109 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4110 "LHS/RHS of comparison should match types!");
4117 SDVTList VTs = getVTList(VT);
4119 if (VT != MVT::Flag) {
4120 FoldingSetNodeID ID;
4121 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4124 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4125 if (Ordering) Ordering->add(E);
4126 return SDValue(E, 0);
4129 N = NodeAllocator.Allocate<SDNode>();
4130 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4131 CSEMap.InsertNode(N, IP);
4133 N = NodeAllocator.Allocate<SDNode>();
4134 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4137 AllNodes.push_back(N);
4138 if (Ordering) Ordering->add(N);
4142 return SDValue(N, 0);
4145 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4146 const std::vector<EVT> &ResultTys,
4147 const SDValue *Ops, unsigned NumOps) {
4148 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4152 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4153 const EVT *VTs, unsigned NumVTs,
4154 const SDValue *Ops, unsigned NumOps) {
4156 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4157 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4160 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4161 const SDValue *Ops, unsigned NumOps) {
4162 if (VTList.NumVTs == 1)
4163 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4167 // FIXME: figure out how to safely handle things like
4168 // int foo(int x) { return 1 << (x & 255); }
4169 // int bar() { return foo(256); }
4170 case ISD::SRA_PARTS:
4171 case ISD::SRL_PARTS:
4172 case ISD::SHL_PARTS:
4173 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4174 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4175 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4176 else if (N3.getOpcode() == ISD::AND)
4177 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4178 // If the and is only masking out bits that cannot effect the shift,
4179 // eliminate the and.
4180 unsigned NumBits = VT.getSizeInBits()*2;
4181 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4182 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4188 // Memoize the node unless it returns a flag.
4190 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4191 FoldingSetNodeID ID;
4192 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4194 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4195 if (Ordering) Ordering->add(E);
4196 return SDValue(E, 0);
4199 N = NodeAllocator.Allocate<UnarySDNode>();
4200 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4201 } else if (NumOps == 2) {
4202 N = NodeAllocator.Allocate<BinarySDNode>();
4203 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4204 } else if (NumOps == 3) {
4205 N = NodeAllocator.Allocate<TernarySDNode>();
4206 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4208 N = NodeAllocator.Allocate<SDNode>();
4209 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4211 CSEMap.InsertNode(N, IP);
4214 N = NodeAllocator.Allocate<UnarySDNode>();
4215 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4216 } else if (NumOps == 2) {
4217 N = NodeAllocator.Allocate<BinarySDNode>();
4218 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4219 } else if (NumOps == 3) {
4220 N = NodeAllocator.Allocate<TernarySDNode>();
4221 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4223 N = NodeAllocator.Allocate<SDNode>();
4224 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4227 AllNodes.push_back(N);
4228 if (Ordering) Ordering->add(N);
4232 return SDValue(N, 0);
4235 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4236 return getNode(Opcode, DL, VTList, 0, 0);
4239 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4241 SDValue Ops[] = { N1 };
4242 return getNode(Opcode, DL, VTList, Ops, 1);
4245 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4246 SDValue N1, SDValue N2) {
4247 SDValue Ops[] = { N1, N2 };
4248 return getNode(Opcode, DL, VTList, Ops, 2);
4251 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4252 SDValue N1, SDValue N2, SDValue N3) {
4253 SDValue Ops[] = { N1, N2, N3 };
4254 return getNode(Opcode, DL, VTList, Ops, 3);
4257 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4258 SDValue N1, SDValue N2, SDValue N3,
4260 SDValue Ops[] = { N1, N2, N3, N4 };
4261 return getNode(Opcode, DL, VTList, Ops, 4);
4264 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4265 SDValue N1, SDValue N2, SDValue N3,
4266 SDValue N4, SDValue N5) {
4267 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4268 return getNode(Opcode, DL, VTList, Ops, 5);
4271 SDVTList SelectionDAG::getVTList(EVT VT) {
4272 return makeVTList(SDNode::getValueTypeList(VT), 1);
4275 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4276 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4277 E = VTList.rend(); I != E; ++I)
4278 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4281 EVT *Array = Allocator.Allocate<EVT>(2);
4284 SDVTList Result = makeVTList(Array, 2);
4285 VTList.push_back(Result);
4289 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4290 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4291 E = VTList.rend(); I != E; ++I)
4292 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4296 EVT *Array = Allocator.Allocate<EVT>(3);
4300 SDVTList Result = makeVTList(Array, 3);
4301 VTList.push_back(Result);
4305 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4306 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4307 E = VTList.rend(); I != E; ++I)
4308 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4309 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4312 EVT *Array = Allocator.Allocate<EVT>(4);
4317 SDVTList Result = makeVTList(Array, 4);
4318 VTList.push_back(Result);
4322 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4324 case 0: llvm_unreachable("Cannot have nodes without results!");
4325 case 1: return getVTList(VTs[0]);
4326 case 2: return getVTList(VTs[0], VTs[1]);
4327 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4331 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4332 E = VTList.rend(); I != E; ++I) {
4333 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4336 bool NoMatch = false;
4337 for (unsigned i = 2; i != NumVTs; ++i)
4338 if (VTs[i] != I->VTs[i]) {
4346 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4347 std::copy(VTs, VTs+NumVTs, Array);
4348 SDVTList Result = makeVTList(Array, NumVTs);
4349 VTList.push_back(Result);
4354 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4355 /// specified operands. If the resultant node already exists in the DAG,
4356 /// this does not modify the specified node, instead it returns the node that
4357 /// already exists. If the resultant node does not exist in the DAG, the
4358 /// input node is returned. As a degenerate case, if you specify the same
4359 /// input operands as the node already has, the input node is returned.
4360 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4361 SDNode *N = InN.getNode();
4362 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4364 // Check to see if there is no change.
4365 if (Op == N->getOperand(0)) return InN;
4367 // See if the modified node already exists.
4368 void *InsertPos = 0;
4369 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4370 return SDValue(Existing, InN.getResNo());
4372 // Nope it doesn't. Remove the node from its current place in the maps.
4374 if (!RemoveNodeFromCSEMaps(N))
4377 // Now we update the operands.
4378 N->OperandList[0].set(Op);
4380 // If this gets put into a CSE map, add it.
4381 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4385 SDValue SelectionDAG::
4386 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4387 SDNode *N = InN.getNode();
4388 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4390 // Check to see if there is no change.
4391 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4392 return InN; // No operands changed, just return the input node.
4394 // See if the modified node already exists.
4395 void *InsertPos = 0;
4396 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4397 return SDValue(Existing, InN.getResNo());
4399 // Nope it doesn't. Remove the node from its current place in the maps.
4401 if (!RemoveNodeFromCSEMaps(N))
4404 // Now we update the operands.
4405 if (N->OperandList[0] != Op1)
4406 N->OperandList[0].set(Op1);
4407 if (N->OperandList[1] != Op2)
4408 N->OperandList[1].set(Op2);
4410 // If this gets put into a CSE map, add it.
4411 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4415 SDValue SelectionDAG::
4416 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4417 SDValue Ops[] = { Op1, Op2, Op3 };
4418 return UpdateNodeOperands(N, Ops, 3);
4421 SDValue SelectionDAG::
4422 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4423 SDValue Op3, SDValue Op4) {
4424 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4425 return UpdateNodeOperands(N, Ops, 4);
4428 SDValue SelectionDAG::
4429 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4430 SDValue Op3, SDValue Op4, SDValue Op5) {
4431 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4432 return UpdateNodeOperands(N, Ops, 5);
4435 SDValue SelectionDAG::
4436 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4437 SDNode *N = InN.getNode();
4438 assert(N->getNumOperands() == NumOps &&
4439 "Update with wrong number of operands");
4441 // Check to see if there is no change.
4442 bool AnyChange = false;
4443 for (unsigned i = 0; i != NumOps; ++i) {
4444 if (Ops[i] != N->getOperand(i)) {
4450 // No operands changed, just return the input node.
4451 if (!AnyChange) return InN;
4453 // See if the modified node already exists.
4454 void *InsertPos = 0;
4455 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4456 return SDValue(Existing, InN.getResNo());
4458 // Nope it doesn't. Remove the node from its current place in the maps.
4460 if (!RemoveNodeFromCSEMaps(N))
4463 // Now we update the operands.
4464 for (unsigned i = 0; i != NumOps; ++i)
4465 if (N->OperandList[i] != Ops[i])
4466 N->OperandList[i].set(Ops[i]);
4468 // If this gets put into a CSE map, add it.
4469 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4473 /// DropOperands - Release the operands and set this node to have
4475 void SDNode::DropOperands() {
4476 // Unlike the code in MorphNodeTo that does this, we don't need to
4477 // watch for dead nodes here.
4478 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4484 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4487 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4489 SDVTList VTs = getVTList(VT);
4490 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4493 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4494 EVT VT, SDValue Op1) {
4495 SDVTList VTs = getVTList(VT);
4496 SDValue Ops[] = { Op1 };
4497 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4500 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4501 EVT VT, SDValue Op1,
4503 SDVTList VTs = getVTList(VT);
4504 SDValue Ops[] = { Op1, Op2 };
4505 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4508 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4509 EVT VT, SDValue Op1,
4510 SDValue Op2, SDValue Op3) {
4511 SDVTList VTs = getVTList(VT);
4512 SDValue Ops[] = { Op1, Op2, Op3 };
4513 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4516 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4517 EVT VT, const SDValue *Ops,
4519 SDVTList VTs = getVTList(VT);
4520 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4523 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4524 EVT VT1, EVT VT2, const SDValue *Ops,
4526 SDVTList VTs = getVTList(VT1, VT2);
4527 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4530 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4532 SDVTList VTs = getVTList(VT1, VT2);
4533 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4536 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4537 EVT VT1, EVT VT2, EVT VT3,
4538 const SDValue *Ops, unsigned NumOps) {
4539 SDVTList VTs = getVTList(VT1, VT2, VT3);
4540 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4543 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4544 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4545 const SDValue *Ops, unsigned NumOps) {
4546 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4547 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4550 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4553 SDVTList VTs = getVTList(VT1, VT2);
4554 SDValue Ops[] = { Op1 };
4555 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4558 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4560 SDValue Op1, SDValue Op2) {
4561 SDVTList VTs = getVTList(VT1, VT2);
4562 SDValue Ops[] = { Op1, Op2 };
4563 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4566 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4568 SDValue Op1, SDValue Op2,
4570 SDVTList VTs = getVTList(VT1, VT2);
4571 SDValue Ops[] = { Op1, Op2, Op3 };
4572 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4575 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4576 EVT VT1, EVT VT2, EVT VT3,
4577 SDValue Op1, SDValue Op2,
4579 SDVTList VTs = getVTList(VT1, VT2, VT3);
4580 SDValue Ops[] = { Op1, Op2, Op3 };
4581 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4584 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4585 SDVTList VTs, const SDValue *Ops,
4587 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4590 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4592 SDVTList VTs = getVTList(VT);
4593 return MorphNodeTo(N, Opc, VTs, 0, 0);
4596 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4597 EVT VT, SDValue Op1) {
4598 SDVTList VTs = getVTList(VT);
4599 SDValue Ops[] = { Op1 };
4600 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4603 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4604 EVT VT, SDValue Op1,
4606 SDVTList VTs = getVTList(VT);
4607 SDValue Ops[] = { Op1, Op2 };
4608 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4611 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4612 EVT VT, SDValue Op1,
4613 SDValue Op2, SDValue Op3) {
4614 SDVTList VTs = getVTList(VT);
4615 SDValue Ops[] = { Op1, Op2, Op3 };
4616 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4619 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4620 EVT VT, const SDValue *Ops,
4622 SDVTList VTs = getVTList(VT);
4623 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4626 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4627 EVT VT1, EVT VT2, const SDValue *Ops,
4629 SDVTList VTs = getVTList(VT1, VT2);
4630 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4633 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4635 SDVTList VTs = getVTList(VT1, VT2);
4636 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4639 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4640 EVT VT1, EVT VT2, EVT VT3,
4641 const SDValue *Ops, unsigned NumOps) {
4642 SDVTList VTs = getVTList(VT1, VT2, VT3);
4643 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4646 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4649 SDVTList VTs = getVTList(VT1, VT2);
4650 SDValue Ops[] = { Op1 };
4651 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4654 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4656 SDValue Op1, SDValue Op2) {
4657 SDVTList VTs = getVTList(VT1, VT2);
4658 SDValue Ops[] = { Op1, Op2 };
4659 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4662 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4664 SDValue Op1, SDValue Op2,
4666 SDVTList VTs = getVTList(VT1, VT2);
4667 SDValue Ops[] = { Op1, Op2, Op3 };
4668 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4671 /// MorphNodeTo - These *mutate* the specified node to have the specified
4672 /// return type, opcode, and operands.
4674 /// Note that MorphNodeTo returns the resultant node. If there is already a
4675 /// node of the specified opcode and operands, it returns that node instead of
4676 /// the current one. Note that the DebugLoc need not be the same.
4678 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4679 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4680 /// node, and because it doesn't require CSE recalculation for any of
4681 /// the node's users.
4683 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4684 SDVTList VTs, const SDValue *Ops,
4686 // If an identical node already exists, use it.
4688 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4689 FoldingSetNodeID ID;
4690 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4691 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4692 if (Ordering) Ordering->add(ON);
4697 if (!RemoveNodeFromCSEMaps(N))
4700 // Start the morphing.
4702 N->ValueList = VTs.VTs;
4703 N->NumValues = VTs.NumVTs;
4705 // Clear the operands list, updating used nodes to remove this from their
4706 // use list. Keep track of any operands that become dead as a result.
4707 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4708 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4710 SDNode *Used = Use.getNode();
4712 if (Used->use_empty())
4713 DeadNodeSet.insert(Used);
4716 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4717 // Initialize the memory references information.
4718 MN->setMemRefs(0, 0);
4719 // If NumOps is larger than the # of operands we can have in a
4720 // MachineSDNode, reallocate the operand list.
4721 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4722 if (MN->OperandsNeedDelete)
4723 delete[] MN->OperandList;
4724 if (NumOps > array_lengthof(MN->LocalOperands))
4725 // We're creating a final node that will live unmorphed for the
4726 // remainder of the current SelectionDAG iteration, so we can allocate
4727 // the operands directly out of a pool with no recycling metadata.
4728 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4731 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4732 MN->OperandsNeedDelete = false;
4734 MN->InitOperands(MN->OperandList, Ops, NumOps);
4736 // If NumOps is larger than the # of operands we currently have, reallocate
4737 // the operand list.
4738 if (NumOps > N->NumOperands) {
4739 if (N->OperandsNeedDelete)
4740 delete[] N->OperandList;
4741 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4742 N->OperandsNeedDelete = true;
4744 N->InitOperands(N->OperandList, Ops, NumOps);
4747 // Delete any nodes that are still dead after adding the uses for the
4749 SmallVector<SDNode *, 16> DeadNodes;
4750 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4751 E = DeadNodeSet.end(); I != E; ++I)
4752 if ((*I)->use_empty())
4753 DeadNodes.push_back(*I);
4754 RemoveDeadNodes(DeadNodes);
4757 CSEMap.InsertNode(N, IP); // Memoize the new node.
4758 if (Ordering) Ordering->add(N);
4763 /// getMachineNode - These are used for target selectors to create a new node
4764 /// with specified return type(s), MachineInstr opcode, and operands.
4766 /// Note that getMachineNode returns the resultant node. If there is already a
4767 /// node of the specified opcode and operands, it returns that node instead of
4768 /// the current one.
4770 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4771 SDVTList VTs = getVTList(VT);
4772 return getMachineNode(Opcode, dl, VTs, 0, 0);
4776 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
4777 SDVTList VTs = getVTList(VT);
4778 SDValue Ops[] = { Op1 };
4779 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4783 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4784 SDValue Op1, SDValue Op2) {
4785 SDVTList VTs = getVTList(VT);
4786 SDValue Ops[] = { Op1, Op2 };
4787 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4791 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4792 SDValue Op1, SDValue Op2, SDValue Op3) {
4793 SDVTList VTs = getVTList(VT);
4794 SDValue Ops[] = { Op1, Op2, Op3 };
4795 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4799 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4800 const SDValue *Ops, unsigned NumOps) {
4801 SDVTList VTs = getVTList(VT);
4802 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4806 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
4807 SDVTList VTs = getVTList(VT1, VT2);
4808 return getMachineNode(Opcode, dl, VTs, 0, 0);
4812 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4813 EVT VT1, EVT VT2, SDValue Op1) {
4814 SDVTList VTs = getVTList(VT1, VT2);
4815 SDValue Ops[] = { Op1 };
4816 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4820 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4821 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
4822 SDVTList VTs = getVTList(VT1, VT2);
4823 SDValue Ops[] = { Op1, Op2 };
4824 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4828 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4829 EVT VT1, EVT VT2, SDValue Op1,
4830 SDValue Op2, SDValue Op3) {
4831 SDVTList VTs = getVTList(VT1, VT2);
4832 SDValue Ops[] = { Op1, Op2, Op3 };
4833 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4837 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4839 const SDValue *Ops, unsigned NumOps) {
4840 SDVTList VTs = getVTList(VT1, VT2);
4841 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4845 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4846 EVT VT1, EVT VT2, EVT VT3,
4847 SDValue Op1, SDValue Op2) {
4848 SDVTList VTs = getVTList(VT1, VT2, VT3);
4849 SDValue Ops[] = { Op1, Op2 };
4850 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4854 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4855 EVT VT1, EVT VT2, EVT VT3,
4856 SDValue Op1, SDValue Op2, SDValue Op3) {
4857 SDVTList VTs = getVTList(VT1, VT2, VT3);
4858 SDValue Ops[] = { Op1, Op2, Op3 };
4859 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4863 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4864 EVT VT1, EVT VT2, EVT VT3,
4865 const SDValue *Ops, unsigned NumOps) {
4866 SDVTList VTs = getVTList(VT1, VT2, VT3);
4867 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4871 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4872 EVT VT2, EVT VT3, EVT VT4,
4873 const SDValue *Ops, unsigned NumOps) {
4874 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4875 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4879 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4880 const std::vector<EVT> &ResultTys,
4881 const SDValue *Ops, unsigned NumOps) {
4882 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
4883 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4887 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
4888 const SDValue *Ops, unsigned NumOps) {
4889 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Flag;
4894 FoldingSetNodeID ID;
4895 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
4897 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4898 if (Ordering) Ordering->add(E);
4899 return cast<MachineSDNode>(E);
4903 // Allocate a new MachineSDNode.
4904 N = NodeAllocator.Allocate<MachineSDNode>();
4905 new (N) MachineSDNode(~Opcode, DL, VTs);
4907 // Initialize the operands list.
4908 if (NumOps > array_lengthof(N->LocalOperands))
4909 // We're creating a final node that will live unmorphed for the
4910 // remainder of the current SelectionDAG iteration, so we can allocate
4911 // the operands directly out of a pool with no recycling metadata.
4912 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4915 N->InitOperands(N->LocalOperands, Ops, NumOps);
4916 N->OperandsNeedDelete = false;
4919 CSEMap.InsertNode(N, IP);
4921 AllNodes.push_back(N);
4922 if (Ordering) Ordering->add(N);
4929 /// getTargetExtractSubreg - A convenience function for creating
4930 /// TargetInstrInfo::EXTRACT_SUBREG nodes.
4932 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4934 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4935 SDNode *Subreg = getMachineNode(TargetInstrInfo::EXTRACT_SUBREG, DL,
4936 VT, Operand, SRIdxVal);
4937 return SDValue(Subreg, 0);
4940 /// getTargetInsertSubreg - A convenience function for creating
4941 /// TargetInstrInfo::INSERT_SUBREG nodes.
4943 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
4944 SDValue Operand, SDValue Subreg) {
4945 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4946 SDNode *Result = getMachineNode(TargetInstrInfo::INSERT_SUBREG, DL,
4947 VT, Operand, Subreg, SRIdxVal);
4948 return SDValue(Result, 0);
4951 /// getNodeIfExists - Get the specified node if it's already available, or
4952 /// else return NULL.
4953 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4954 const SDValue *Ops, unsigned NumOps) {
4955 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4956 FoldingSetNodeID ID;
4957 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4959 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4960 if (Ordering) Ordering->add(E);
4967 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4968 /// This can cause recursive merging of nodes in the DAG.
4970 /// This version assumes From has a single result value.
4972 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4973 DAGUpdateListener *UpdateListener) {
4974 SDNode *From = FromN.getNode();
4975 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4976 "Cannot replace with this method!");
4977 assert(From != To.getNode() && "Cannot replace uses of with self");
4979 // Iterate over all the existing uses of From. New uses will be added
4980 // to the beginning of the use list, which we avoid visiting.
4981 // This specifically avoids visiting uses of From that arise while the
4982 // replacement is happening, because any such uses would be the result
4983 // of CSE: If an existing node looks like From after one of its operands
4984 // is replaced by To, we don't want to replace of all its users with To
4985 // too. See PR3018 for more info.
4986 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4990 // This node is about to morph, remove its old self from the CSE maps.
4991 RemoveNodeFromCSEMaps(User);
4993 // A user can appear in a use list multiple times, and when this
4994 // happens the uses are usually next to each other in the list.
4995 // To help reduce the number of CSE recomputations, process all
4996 // the uses of this user that we can find this way.
4998 SDUse &Use = UI.getUse();
5001 } while (UI != UE && *UI == User);
5003 // Now that we have modified User, add it back to the CSE maps. If it
5004 // already exists there, recursively merge the results together.
5005 AddModifiedNodeToCSEMaps(User, UpdateListener);
5009 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5010 /// This can cause recursive merging of nodes in the DAG.
5012 /// This version assumes that for each value of From, there is a
5013 /// corresponding value in To in the same position with the same type.
5015 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
5016 DAGUpdateListener *UpdateListener) {
5018 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
5019 assert((!From->hasAnyUseOfValue(i) ||
5020 From->getValueType(i) == To->getValueType(i)) &&
5021 "Cannot use this version of ReplaceAllUsesWith!");
5024 // Handle the trivial case.
5028 // Iterate over just the existing users of From. See the comments in
5029 // the ReplaceAllUsesWith above.
5030 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5034 // This node is about to morph, remove its old self from the CSE maps.
5035 RemoveNodeFromCSEMaps(User);
5037 // A user can appear in a use list multiple times, and when this
5038 // happens the uses are usually next to each other in the list.
5039 // To help reduce the number of CSE recomputations, process all
5040 // the uses of this user that we can find this way.
5042 SDUse &Use = UI.getUse();
5045 } while (UI != UE && *UI == User);
5047 // Now that we have modified User, add it back to the CSE maps. If it
5048 // already exists there, recursively merge the results together.
5049 AddModifiedNodeToCSEMaps(User, UpdateListener);
5053 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5054 /// This can cause recursive merging of nodes in the DAG.
5056 /// This version can replace From with any result values. To must match the
5057 /// number and types of values returned by From.
5058 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
5060 DAGUpdateListener *UpdateListener) {
5061 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5062 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
5064 // Iterate over just the existing users of From. See the comments in
5065 // the ReplaceAllUsesWith above.
5066 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5070 // This node is about to morph, remove its old self from the CSE maps.
5071 RemoveNodeFromCSEMaps(User);
5073 // A user can appear in a use list multiple times, and when this
5074 // happens the uses are usually next to each other in the list.
5075 // To help reduce the number of CSE recomputations, process all
5076 // the uses of this user that we can find this way.
5078 SDUse &Use = UI.getUse();
5079 const SDValue &ToOp = To[Use.getResNo()];
5082 } while (UI != UE && *UI == User);
5084 // Now that we have modified User, add it back to the CSE maps. If it
5085 // already exists there, recursively merge the results together.
5086 AddModifiedNodeToCSEMaps(User, UpdateListener);
5090 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5091 /// uses of other values produced by From.getNode() alone. The Deleted
5092 /// vector is handled the same way as for ReplaceAllUsesWith.
5093 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5094 DAGUpdateListener *UpdateListener){
5095 // Handle the really simple, really trivial case efficiently.
5096 if (From == To) return;
5098 // Handle the simple, trivial, case efficiently.
5099 if (From.getNode()->getNumValues() == 1) {
5100 ReplaceAllUsesWith(From, To, UpdateListener);
5104 // Iterate over just the existing users of From. See the comments in
5105 // the ReplaceAllUsesWith above.
5106 SDNode::use_iterator UI = From.getNode()->use_begin(),
5107 UE = From.getNode()->use_end();
5110 bool UserRemovedFromCSEMaps = false;
5112 // A user can appear in a use list multiple times, and when this
5113 // happens the uses are usually next to each other in the list.
5114 // To help reduce the number of CSE recomputations, process all
5115 // the uses of this user that we can find this way.
5117 SDUse &Use = UI.getUse();
5119 // Skip uses of different values from the same node.
5120 if (Use.getResNo() != From.getResNo()) {
5125 // If this node hasn't been modified yet, it's still in the CSE maps,
5126 // so remove its old self from the CSE maps.
5127 if (!UserRemovedFromCSEMaps) {
5128 RemoveNodeFromCSEMaps(User);
5129 UserRemovedFromCSEMaps = true;
5134 } while (UI != UE && *UI == User);
5136 // We are iterating over all uses of the From node, so if a use
5137 // doesn't use the specific value, no changes are made.
5138 if (!UserRemovedFromCSEMaps)
5141 // Now that we have modified User, add it back to the CSE maps. If it
5142 // already exists there, recursively merge the results together.
5143 AddModifiedNodeToCSEMaps(User, UpdateListener);
5148 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5149 /// to record information about a use.
5156 /// operator< - Sort Memos by User.
5157 bool operator<(const UseMemo &L, const UseMemo &R) {
5158 return (intptr_t)L.User < (intptr_t)R.User;
5162 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5163 /// uses of other values produced by From.getNode() alone. The same value
5164 /// may appear in both the From and To list. The Deleted vector is
5165 /// handled the same way as for ReplaceAllUsesWith.
5166 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5169 DAGUpdateListener *UpdateListener){
5170 // Handle the simple, trivial case efficiently.
5172 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5174 // Read up all the uses and make records of them. This helps
5175 // processing new uses that are introduced during the
5176 // replacement process.
5177 SmallVector<UseMemo, 4> Uses;
5178 for (unsigned i = 0; i != Num; ++i) {
5179 unsigned FromResNo = From[i].getResNo();
5180 SDNode *FromNode = From[i].getNode();
5181 for (SDNode::use_iterator UI = FromNode->use_begin(),
5182 E = FromNode->use_end(); UI != E; ++UI) {
5183 SDUse &Use = UI.getUse();
5184 if (Use.getResNo() == FromResNo) {
5185 UseMemo Memo = { *UI, i, &Use };
5186 Uses.push_back(Memo);
5191 // Sort the uses, so that all the uses from a given User are together.
5192 std::sort(Uses.begin(), Uses.end());
5194 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5195 UseIndex != UseIndexEnd; ) {
5196 // We know that this user uses some value of From. If it is the right
5197 // value, update it.
5198 SDNode *User = Uses[UseIndex].User;
5200 // This node is about to morph, remove its old self from the CSE maps.
5201 RemoveNodeFromCSEMaps(User);
5203 // The Uses array is sorted, so all the uses for a given User
5204 // are next to each other in the list.
5205 // To help reduce the number of CSE recomputations, process all
5206 // the uses of this user that we can find this way.
5208 unsigned i = Uses[UseIndex].Index;
5209 SDUse &Use = *Uses[UseIndex].Use;
5213 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5215 // Now that we have modified User, add it back to the CSE maps. If it
5216 // already exists there, recursively merge the results together.
5217 AddModifiedNodeToCSEMaps(User, UpdateListener);
5221 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5222 /// based on their topological order. It returns the maximum id and a vector
5223 /// of the SDNodes* in assigned order by reference.
5224 unsigned SelectionDAG::AssignTopologicalOrder() {
5226 unsigned DAGSize = 0;
5228 // SortedPos tracks the progress of the algorithm. Nodes before it are
5229 // sorted, nodes after it are unsorted. When the algorithm completes
5230 // it is at the end of the list.
5231 allnodes_iterator SortedPos = allnodes_begin();
5233 // Visit all the nodes. Move nodes with no operands to the front of
5234 // the list immediately. Annotate nodes that do have operands with their
5235 // operand count. Before we do this, the Node Id fields of the nodes
5236 // may contain arbitrary values. After, the Node Id fields for nodes
5237 // before SortedPos will contain the topological sort index, and the
5238 // Node Id fields for nodes At SortedPos and after will contain the
5239 // count of outstanding operands.
5240 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5242 unsigned Degree = N->getNumOperands();
5244 // A node with no uses, add it to the result array immediately.
5245 N->setNodeId(DAGSize++);
5246 allnodes_iterator Q = N;
5248 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5251 // Temporarily use the Node Id as scratch space for the degree count.
5252 N->setNodeId(Degree);
5256 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5257 // such that by the time the end is reached all nodes will be sorted.
5258 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5260 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5263 unsigned Degree = P->getNodeId();
5266 // All of P's operands are sorted, so P may sorted now.
5267 P->setNodeId(DAGSize++);
5269 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5272 // Update P's outstanding operand count.
5273 P->setNodeId(Degree);
5278 assert(SortedPos == AllNodes.end() &&
5279 "Topological sort incomplete!");
5280 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5281 "First node in topological sort is not the entry token!");
5282 assert(AllNodes.front().getNodeId() == 0 &&
5283 "First node in topological sort has non-zero id!");
5284 assert(AllNodes.front().getNumOperands() == 0 &&
5285 "First node in topological sort has operands!");
5286 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5287 "Last node in topologic sort has unexpected id!");
5288 assert(AllNodes.back().use_empty() &&
5289 "Last node in topologic sort has users!");
5290 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5296 //===----------------------------------------------------------------------===//
5298 //===----------------------------------------------------------------------===//
5300 HandleSDNode::~HandleSDNode() {
5304 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
5305 EVT VT, int64_t o, unsigned char TF)
5306 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
5307 Offset(o), TargetFlags(TF) {
5308 TheGlobal = const_cast<GlobalValue*>(GA);
5311 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5312 MachineMemOperand *mmo)
5313 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5314 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile());
5315 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5316 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5319 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5320 const SDValue *Ops, unsigned NumOps, EVT memvt,
5321 MachineMemOperand *mmo)
5322 : SDNode(Opc, dl, VTs, Ops, NumOps),
5323 MemoryVT(memvt), MMO(mmo) {
5324 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile());
5325 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5326 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5329 /// Profile - Gather unique data for the node.
5331 void SDNode::Profile(FoldingSetNodeID &ID) const {
5332 AddNodeIDNode(ID, this);
5337 std::vector<EVT> VTs;
5340 VTs.reserve(MVT::LAST_VALUETYPE);
5341 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5342 VTs.push_back(MVT((MVT::SimpleValueType)i));
5347 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5348 static ManagedStatic<EVTArray> SimpleVTArray;
5349 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5351 /// getValueTypeList - Return a pointer to the specified value type.
5353 const EVT *SDNode::getValueTypeList(EVT VT) {
5354 if (VT.isExtended()) {
5355 sys::SmartScopedLock<true> Lock(*VTMutex);
5356 return &(*EVTs->insert(VT).first);
5358 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5362 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5363 /// indicated value. This method ignores uses of other values defined by this
5365 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5366 assert(Value < getNumValues() && "Bad value!");
5368 // TODO: Only iterate over uses of a given value of the node
5369 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5370 if (UI.getUse().getResNo() == Value) {
5377 // Found exactly the right number of uses?
5382 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5383 /// value. This method ignores uses of other values defined by this operation.
5384 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5385 assert(Value < getNumValues() && "Bad value!");
5387 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5388 if (UI.getUse().getResNo() == Value)
5395 /// isOnlyUserOf - Return true if this node is the only use of N.
5397 bool SDNode::isOnlyUserOf(SDNode *N) const {
5399 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5410 /// isOperand - Return true if this node is an operand of N.
5412 bool SDValue::isOperandOf(SDNode *N) const {
5413 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5414 if (*this == N->getOperand(i))
5419 bool SDNode::isOperandOf(SDNode *N) const {
5420 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5421 if (this == N->OperandList[i].getNode())
5426 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5427 /// be a chain) reaches the specified operand without crossing any
5428 /// side-effecting instructions. In practice, this looks through token
5429 /// factors and non-volatile loads. In order to remain efficient, this only
5430 /// looks a couple of nodes in, it does not do an exhaustive search.
5431 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5432 unsigned Depth) const {
5433 if (*this == Dest) return true;
5435 // Don't search too deeply, we just want to be able to see through
5436 // TokenFactor's etc.
5437 if (Depth == 0) return false;
5439 // If this is a token factor, all inputs to the TF happen in parallel. If any
5440 // of the operands of the TF reach dest, then we can do the xform.
5441 if (getOpcode() == ISD::TokenFactor) {
5442 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5443 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5448 // Loads don't have side effects, look through them.
5449 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5450 if (!Ld->isVolatile())
5451 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5456 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5457 /// is either an operand of N or it can be reached by traversing up the operands.
5458 /// NOTE: this is an expensive method. Use it carefully.
5459 bool SDNode::isPredecessorOf(SDNode *N) const {
5460 SmallPtrSet<SDNode *, 32> Visited;
5461 SmallVector<SDNode *, 16> Worklist;
5462 Worklist.push_back(N);
5465 N = Worklist.pop_back_val();
5466 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5467 SDNode *Op = N->getOperand(i).getNode();
5470 if (Visited.insert(Op))
5471 Worklist.push_back(Op);
5473 } while (!Worklist.empty());
5478 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5479 assert(Num < NumOperands && "Invalid child # of SDNode!");
5480 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5483 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5484 switch (getOpcode()) {
5486 if (getOpcode() < ISD::BUILTIN_OP_END)
5487 return "<<Unknown DAG Node>>";
5488 if (isMachineOpcode()) {
5490 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5491 if (getMachineOpcode() < TII->getNumOpcodes())
5492 return TII->get(getMachineOpcode()).getName();
5493 return "<<Unknown Machine Node>>";
5496 const TargetLowering &TLI = G->getTargetLoweringInfo();
5497 const char *Name = TLI.getTargetNodeName(getOpcode());
5498 if (Name) return Name;
5499 return "<<Unknown Target Node>>";
5501 return "<<Unknown Node>>";
5504 case ISD::DELETED_NODE:
5505 return "<<Deleted Node!>>";
5507 case ISD::PREFETCH: return "Prefetch";
5508 case ISD::MEMBARRIER: return "MemBarrier";
5509 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5510 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5511 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5512 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5513 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5514 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5515 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5516 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5517 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5518 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5519 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5520 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5521 case ISD::PCMARKER: return "PCMarker";
5522 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5523 case ISD::SRCVALUE: return "SrcValue";
5524 case ISD::EntryToken: return "EntryToken";
5525 case ISD::TokenFactor: return "TokenFactor";
5526 case ISD::AssertSext: return "AssertSext";
5527 case ISD::AssertZext: return "AssertZext";
5529 case ISD::BasicBlock: return "BasicBlock";
5530 case ISD::VALUETYPE: return "ValueType";
5531 case ISD::Register: return "Register";
5533 case ISD::Constant: return "Constant";
5534 case ISD::ConstantFP: return "ConstantFP";
5535 case ISD::GlobalAddress: return "GlobalAddress";
5536 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5537 case ISD::FrameIndex: return "FrameIndex";
5538 case ISD::JumpTable: return "JumpTable";
5539 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5540 case ISD::RETURNADDR: return "RETURNADDR";
5541 case ISD::FRAMEADDR: return "FRAMEADDR";
5542 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5543 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5544 case ISD::LSDAADDR: return "LSDAADDR";
5545 case ISD::EHSELECTION: return "EHSELECTION";
5546 case ISD::EH_RETURN: return "EH_RETURN";
5547 case ISD::ConstantPool: return "ConstantPool";
5548 case ISD::ExternalSymbol: return "ExternalSymbol";
5549 case ISD::BlockAddress: return "BlockAddress";
5550 case ISD::INTRINSIC_WO_CHAIN:
5551 case ISD::INTRINSIC_VOID:
5552 case ISD::INTRINSIC_W_CHAIN: {
5553 unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5554 unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5555 if (IID < Intrinsic::num_intrinsics)
5556 return Intrinsic::getName((Intrinsic::ID)IID);
5557 else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5558 return TII->getName(IID);
5559 llvm_unreachable("Invalid intrinsic ID");
5562 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5563 case ISD::TargetConstant: return "TargetConstant";
5564 case ISD::TargetConstantFP:return "TargetConstantFP";
5565 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5566 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5567 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5568 case ISD::TargetJumpTable: return "TargetJumpTable";
5569 case ISD::TargetConstantPool: return "TargetConstantPool";
5570 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5571 case ISD::TargetBlockAddress: return "TargetBlockAddress";
5573 case ISD::CopyToReg: return "CopyToReg";
5574 case ISD::CopyFromReg: return "CopyFromReg";
5575 case ISD::UNDEF: return "undef";
5576 case ISD::MERGE_VALUES: return "merge_values";
5577 case ISD::INLINEASM: return "inlineasm";
5578 case ISD::EH_LABEL: return "eh_label";
5579 case ISD::HANDLENODE: return "handlenode";
5582 case ISD::FABS: return "fabs";
5583 case ISD::FNEG: return "fneg";
5584 case ISD::FSQRT: return "fsqrt";
5585 case ISD::FSIN: return "fsin";
5586 case ISD::FCOS: return "fcos";
5587 case ISD::FPOWI: return "fpowi";
5588 case ISD::FPOW: return "fpow";
5589 case ISD::FTRUNC: return "ftrunc";
5590 case ISD::FFLOOR: return "ffloor";
5591 case ISD::FCEIL: return "fceil";
5592 case ISD::FRINT: return "frint";
5593 case ISD::FNEARBYINT: return "fnearbyint";
5596 case ISD::ADD: return "add";
5597 case ISD::SUB: return "sub";
5598 case ISD::MUL: return "mul";
5599 case ISD::MULHU: return "mulhu";
5600 case ISD::MULHS: return "mulhs";
5601 case ISD::SDIV: return "sdiv";
5602 case ISD::UDIV: return "udiv";
5603 case ISD::SREM: return "srem";
5604 case ISD::UREM: return "urem";
5605 case ISD::SMUL_LOHI: return "smul_lohi";
5606 case ISD::UMUL_LOHI: return "umul_lohi";
5607 case ISD::SDIVREM: return "sdivrem";
5608 case ISD::UDIVREM: return "udivrem";
5609 case ISD::AND: return "and";
5610 case ISD::OR: return "or";
5611 case ISD::XOR: return "xor";
5612 case ISD::SHL: return "shl";
5613 case ISD::SRA: return "sra";
5614 case ISD::SRL: return "srl";
5615 case ISD::ROTL: return "rotl";
5616 case ISD::ROTR: return "rotr";
5617 case ISD::FADD: return "fadd";
5618 case ISD::FSUB: return "fsub";
5619 case ISD::FMUL: return "fmul";
5620 case ISD::FDIV: return "fdiv";
5621 case ISD::FREM: return "frem";
5622 case ISD::FCOPYSIGN: return "fcopysign";
5623 case ISD::FGETSIGN: return "fgetsign";
5625 case ISD::SETCC: return "setcc";
5626 case ISD::VSETCC: return "vsetcc";
5627 case ISD::SELECT: return "select";
5628 case ISD::SELECT_CC: return "select_cc";
5629 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5630 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5631 case ISD::CONCAT_VECTORS: return "concat_vectors";
5632 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5633 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5634 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5635 case ISD::CARRY_FALSE: return "carry_false";
5636 case ISD::ADDC: return "addc";
5637 case ISD::ADDE: return "adde";
5638 case ISD::SADDO: return "saddo";
5639 case ISD::UADDO: return "uaddo";
5640 case ISD::SSUBO: return "ssubo";
5641 case ISD::USUBO: return "usubo";
5642 case ISD::SMULO: return "smulo";
5643 case ISD::UMULO: return "umulo";
5644 case ISD::SUBC: return "subc";
5645 case ISD::SUBE: return "sube";
5646 case ISD::SHL_PARTS: return "shl_parts";
5647 case ISD::SRA_PARTS: return "sra_parts";
5648 case ISD::SRL_PARTS: return "srl_parts";
5650 // Conversion operators.
5651 case ISD::SIGN_EXTEND: return "sign_extend";
5652 case ISD::ZERO_EXTEND: return "zero_extend";
5653 case ISD::ANY_EXTEND: return "any_extend";
5654 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5655 case ISD::TRUNCATE: return "truncate";
5656 case ISD::FP_ROUND: return "fp_round";
5657 case ISD::FLT_ROUNDS_: return "flt_rounds";
5658 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5659 case ISD::FP_EXTEND: return "fp_extend";
5661 case ISD::SINT_TO_FP: return "sint_to_fp";
5662 case ISD::UINT_TO_FP: return "uint_to_fp";
5663 case ISD::FP_TO_SINT: return "fp_to_sint";
5664 case ISD::FP_TO_UINT: return "fp_to_uint";
5665 case ISD::BIT_CONVERT: return "bit_convert";
5667 case ISD::CONVERT_RNDSAT: {
5668 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5669 default: llvm_unreachable("Unknown cvt code!");
5670 case ISD::CVT_FF: return "cvt_ff";
5671 case ISD::CVT_FS: return "cvt_fs";
5672 case ISD::CVT_FU: return "cvt_fu";
5673 case ISD::CVT_SF: return "cvt_sf";
5674 case ISD::CVT_UF: return "cvt_uf";
5675 case ISD::CVT_SS: return "cvt_ss";
5676 case ISD::CVT_SU: return "cvt_su";
5677 case ISD::CVT_US: return "cvt_us";
5678 case ISD::CVT_UU: return "cvt_uu";
5682 // Control flow instructions
5683 case ISD::BR: return "br";
5684 case ISD::BRIND: return "brind";
5685 case ISD::BR_JT: return "br_jt";
5686 case ISD::BRCOND: return "brcond";
5687 case ISD::BR_CC: return "br_cc";
5688 case ISD::CALLSEQ_START: return "callseq_start";
5689 case ISD::CALLSEQ_END: return "callseq_end";
5692 case ISD::LOAD: return "load";
5693 case ISD::STORE: return "store";
5694 case ISD::VAARG: return "vaarg";
5695 case ISD::VACOPY: return "vacopy";
5696 case ISD::VAEND: return "vaend";
5697 case ISD::VASTART: return "vastart";
5698 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5699 case ISD::EXTRACT_ELEMENT: return "extract_element";
5700 case ISD::BUILD_PAIR: return "build_pair";
5701 case ISD::STACKSAVE: return "stacksave";
5702 case ISD::STACKRESTORE: return "stackrestore";
5703 case ISD::TRAP: return "trap";
5706 case ISD::BSWAP: return "bswap";
5707 case ISD::CTPOP: return "ctpop";
5708 case ISD::CTTZ: return "cttz";
5709 case ISD::CTLZ: return "ctlz";
5712 case ISD::TRAMPOLINE: return "trampoline";
5715 switch (cast<CondCodeSDNode>(this)->get()) {
5716 default: llvm_unreachable("Unknown setcc condition!");
5717 case ISD::SETOEQ: return "setoeq";
5718 case ISD::SETOGT: return "setogt";
5719 case ISD::SETOGE: return "setoge";
5720 case ISD::SETOLT: return "setolt";
5721 case ISD::SETOLE: return "setole";
5722 case ISD::SETONE: return "setone";
5724 case ISD::SETO: return "seto";
5725 case ISD::SETUO: return "setuo";
5726 case ISD::SETUEQ: return "setue";
5727 case ISD::SETUGT: return "setugt";
5728 case ISD::SETUGE: return "setuge";
5729 case ISD::SETULT: return "setult";
5730 case ISD::SETULE: return "setule";
5731 case ISD::SETUNE: return "setune";
5733 case ISD::SETEQ: return "seteq";
5734 case ISD::SETGT: return "setgt";
5735 case ISD::SETGE: return "setge";
5736 case ISD::SETLT: return "setlt";
5737 case ISD::SETLE: return "setle";
5738 case ISD::SETNE: return "setne";
5743 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5752 return "<post-inc>";
5754 return "<post-dec>";
5758 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5759 std::string S = "< ";
5773 if (getByValAlign())
5774 S += "byval-align:" + utostr(getByValAlign()) + " ";
5776 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5778 S += "byval-size:" + utostr(getByValSize()) + " ";
5782 void SDNode::dump() const { dump(0); }
5783 void SDNode::dump(const SelectionDAG *G) const {
5787 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5788 OS << (void*)this << ": ";
5790 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5792 if (getValueType(i) == MVT::Other)
5795 OS << getValueType(i).getEVTString();
5797 OS << " = " << getOperationName(G);
5800 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5801 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
5802 if (!MN->memoperands_empty()) {
5805 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
5806 e = MN->memoperands_end(); i != e; ++i) {
5813 } else if (const ShuffleVectorSDNode *SVN =
5814 dyn_cast<ShuffleVectorSDNode>(this)) {
5816 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5817 int Idx = SVN->getMaskElt(i);
5825 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5826 OS << '<' << CSDN->getAPIntValue() << '>';
5827 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5828 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5829 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5830 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5831 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5834 CSDN->getValueAPF().bitcastToAPInt().dump();
5837 } else if (const GlobalAddressSDNode *GADN =
5838 dyn_cast<GlobalAddressSDNode>(this)) {
5839 int64_t offset = GADN->getOffset();
5841 WriteAsOperand(OS, GADN->getGlobal());
5844 OS << " + " << offset;
5846 OS << " " << offset;
5847 if (unsigned int TF = GADN->getTargetFlags())
5848 OS << " [TF=" << TF << ']';
5849 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5850 OS << "<" << FIDN->getIndex() << ">";
5851 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5852 OS << "<" << JTDN->getIndex() << ">";
5853 if (unsigned int TF = JTDN->getTargetFlags())
5854 OS << " [TF=" << TF << ']';
5855 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5856 int offset = CP->getOffset();
5857 if (CP->isMachineConstantPoolEntry())
5858 OS << "<" << *CP->getMachineCPVal() << ">";
5860 OS << "<" << *CP->getConstVal() << ">";
5862 OS << " + " << offset;
5864 OS << " " << offset;
5865 if (unsigned int TF = CP->getTargetFlags())
5866 OS << " [TF=" << TF << ']';
5867 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5869 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5871 OS << LBB->getName() << " ";
5872 OS << (const void*)BBDN->getBasicBlock() << ">";
5873 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5874 if (G && R->getReg() &&
5875 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5876 OS << " %" << G->getTarget().getRegisterInfo()->getName(R->getReg());
5878 OS << " %reg" << R->getReg();
5880 } else if (const ExternalSymbolSDNode *ES =
5881 dyn_cast<ExternalSymbolSDNode>(this)) {
5882 OS << "'" << ES->getSymbol() << "'";
5883 if (unsigned int TF = ES->getTargetFlags())
5884 OS << " [TF=" << TF << ']';
5885 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5887 OS << "<" << M->getValue() << ">";
5890 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5891 OS << ":" << N->getVT().getEVTString();
5893 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5894 OS << "<" << *LD->getMemOperand();
5897 switch (LD->getExtensionType()) {
5898 default: doExt = false; break;
5899 case ISD::EXTLOAD: OS << ", anyext"; break;
5900 case ISD::SEXTLOAD: OS << ", sext"; break;
5901 case ISD::ZEXTLOAD: OS << ", zext"; break;
5904 OS << " from " << LD->getMemoryVT().getEVTString();
5906 const char *AM = getIndexedModeName(LD->getAddressingMode());
5911 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5912 OS << "<" << *ST->getMemOperand();
5914 if (ST->isTruncatingStore())
5915 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
5917 const char *AM = getIndexedModeName(ST->getAddressingMode());
5922 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
5923 OS << "<" << *M->getMemOperand() << ">";
5924 } else if (const BlockAddressSDNode *BA =
5925 dyn_cast<BlockAddressSDNode>(this)) {
5927 WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
5929 WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
5931 if (unsigned int TF = BA->getTargetFlags())
5932 OS << " [TF=" << TF << ']';
5936 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5938 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5939 if (i) OS << ", "; else OS << " ";
5940 OS << (void*)getOperand(i).getNode();
5941 if (unsigned RN = getOperand(i).getResNo())
5944 print_details(OS, G);
5947 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5948 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5949 if (N->getOperand(i).getNode()->hasOneUse())
5950 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5952 errs() << "\n" << std::string(indent+2, ' ')
5953 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5957 errs().indent(indent);
5961 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
5962 assert(N->getNumValues() == 1 &&
5963 "Can't unroll a vector with multiple results!");
5965 EVT VT = N->getValueType(0);
5966 unsigned NE = VT.getVectorNumElements();
5967 EVT EltVT = VT.getVectorElementType();
5968 DebugLoc dl = N->getDebugLoc();
5970 SmallVector<SDValue, 8> Scalars;
5971 SmallVector<SDValue, 4> Operands(N->getNumOperands());
5973 // If ResNE is 0, fully unroll the vector op.
5976 else if (NE > ResNE)
5980 for (i= 0; i != NE; ++i) {
5981 for (unsigned j = 0; j != N->getNumOperands(); ++j) {
5982 SDValue Operand = N->getOperand(j);
5983 EVT OperandVT = Operand.getValueType();
5984 if (OperandVT.isVector()) {
5985 // A vector operand; extract a single element.
5986 EVT OperandEltVT = OperandVT.getVectorElementType();
5987 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
5990 getConstant(i, MVT::i32));
5992 // A scalar operand; just use it as is.
5993 Operands[j] = Operand;
5997 switch (N->getOpcode()) {
5999 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6000 &Operands[0], Operands.size()));
6007 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6008 getShiftAmountOperand(Operands[1])));
6013 for (; i < ResNE; ++i)
6014 Scalars.push_back(getUNDEF(EltVT));
6016 return getNode(ISD::BUILD_VECTOR, dl,
6017 EVT::getVectorVT(*getContext(), EltVT, ResNE),
6018 &Scalars[0], Scalars.size());
6022 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6023 /// location that is 'Dist' units away from the location that the 'Base' load
6024 /// is loading from.
6025 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6026 unsigned Bytes, int Dist) const {
6027 if (LD->getChain() != Base->getChain())
6029 EVT VT = LD->getValueType(0);
6030 if (VT.getSizeInBits() / 8 != Bytes)
6033 SDValue Loc = LD->getOperand(1);
6034 SDValue BaseLoc = Base->getOperand(1);
6035 if (Loc.getOpcode() == ISD::FrameIndex) {
6036 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6038 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6039 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6040 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6041 int FS = MFI->getObjectSize(FI);
6042 int BFS = MFI->getObjectSize(BFI);
6043 if (FS != BFS || FS != (int)Bytes) return false;
6044 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6046 if (Loc.getOpcode() == ISD::ADD && Loc.getOperand(0) == BaseLoc) {
6047 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Loc.getOperand(1));
6048 if (V && (V->getSExtValue() == Dist*Bytes))
6052 GlobalValue *GV1 = NULL;
6053 GlobalValue *GV2 = NULL;
6054 int64_t Offset1 = 0;
6055 int64_t Offset2 = 0;
6056 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6057 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6058 if (isGA1 && isGA2 && GV1 == GV2)
6059 return Offset1 == (Offset2 + Dist*Bytes);
6064 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6065 /// it cannot be inferred.
6066 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6067 // If this is a GlobalAddress + cst, return the alignment.
6069 int64_t GVOffset = 0;
6070 if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset))
6071 return MinAlign(GV->getAlignment(), GVOffset);
6073 // If this is a direct reference to a stack slot, use information about the
6074 // stack slot's alignment.
6075 int FrameIdx = 1 << 31;
6076 int64_t FrameOffset = 0;
6077 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6078 FrameIdx = FI->getIndex();
6079 } else if (Ptr.getOpcode() == ISD::ADD &&
6080 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
6081 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6082 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6083 FrameOffset = Ptr.getConstantOperandVal(1);
6086 if (FrameIdx != (1 << 31)) {
6087 // FIXME: Handle FI+CST.
6088 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6089 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6091 if (MFI.isFixedObjectIndex(FrameIdx)) {
6092 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
6094 // The alignment of the frame index can be determined from its offset from
6095 // the incoming frame position. If the frame object is at offset 32 and
6096 // the stack is guaranteed to be 16-byte aligned, then we know that the
6097 // object is 16-byte aligned.
6098 unsigned StackAlign = getTarget().getFrameInfo()->getStackAlignment();
6099 unsigned Align = MinAlign(ObjectOffset, StackAlign);
6101 // Finally, the frame object itself may have a known alignment. Factor
6102 // the alignment + offset into a new alignment. For example, if we know
6103 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
6104 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
6105 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
6106 return std::max(Align, FIInfoAlign);
6114 void SelectionDAG::dump() const {
6115 errs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
6117 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6119 const SDNode *N = I;
6120 if (!N->hasOneUse() && N != getRoot().getNode())
6121 DumpNodes(N, 2, this);
6124 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6129 void SelectionDAG::NodeOrdering::dump() const {
6132 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
6134 print_details(OS, G);
6137 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
6138 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
6139 const SelectionDAG *G, VisitedSDNodeSet &once) {
6140 if (!once.insert(N)) // If we've been here before, return now.
6142 // Dump the current SDNode, but don't end the line yet.
6143 OS << std::string(indent, ' ');
6145 // Having printed this SDNode, walk the children:
6146 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6147 const SDNode *child = N->getOperand(i).getNode();
6150 if (child->getNumOperands() == 0) {
6151 // This child has no grandchildren; print it inline right here.
6152 child->printr(OS, G);
6154 } else { // Just the address. FIXME: also print the child's opcode
6156 if (unsigned RN = N->getOperand(i).getResNo())
6161 // Dump children that have grandchildren on their own line(s).
6162 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6163 const SDNode *child = N->getOperand(i).getNode();
6164 DumpNodesr(OS, child, indent+2, G, once);
6168 void SDNode::dumpr() const {
6169 VisitedSDNodeSet once;
6170 DumpNodesr(errs(), this, 0, 0, once);
6173 void SDNode::dumpr(const SelectionDAG *G) const {
6174 VisitedSDNodeSet once;
6175 DumpNodesr(errs(), this, 0, G, once);
6179 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6180 unsigned GlobalAddressSDNode::getAddressSpace() const {
6181 return getGlobal()->getType()->getAddressSpace();
6185 const Type *ConstantPoolSDNode::getType() const {
6186 if (isMachineConstantPoolEntry())
6187 return Val.MachineCPVal->getType();
6188 return Val.ConstVal->getType();
6191 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6193 unsigned &SplatBitSize,
6195 unsigned MinSplatBits,
6197 EVT VT = getValueType(0);
6198 assert(VT.isVector() && "Expected a vector type");
6199 unsigned sz = VT.getSizeInBits();
6200 if (MinSplatBits > sz)
6203 SplatValue = APInt(sz, 0);
6204 SplatUndef = APInt(sz, 0);
6206 // Get the bits. Bits with undefined values (when the corresponding element
6207 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6208 // in SplatValue. If any of the values are not constant, give up and return
6210 unsigned int nOps = getNumOperands();
6211 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6212 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6214 for (unsigned j = 0; j < nOps; ++j) {
6215 unsigned i = isBigEndian ? nOps-1-j : j;
6216 SDValue OpVal = getOperand(i);
6217 unsigned BitPos = j * EltBitSize;
6219 if (OpVal.getOpcode() == ISD::UNDEF)
6220 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6221 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6222 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
6223 zextOrTrunc(sz) << BitPos);
6224 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6225 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6230 // The build_vector is all constants or undefs. Find the smallest element
6231 // size that splats the vector.
6233 HasAnyUndefs = (SplatUndef != 0);
6236 unsigned HalfSize = sz / 2;
6237 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
6238 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
6239 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
6240 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
6242 // If the two halves do not match (ignoring undef bits), stop here.
6243 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6244 MinSplatBits > HalfSize)
6247 SplatValue = HighValue | LowValue;
6248 SplatUndef = HighUndef & LowUndef;
6257 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6258 // Find the first non-undef value in the shuffle mask.
6260 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6263 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6265 // Make sure all remaining elements are either undef or the same as the first
6267 for (int Idx = Mask[i]; i != e; ++i)
6268 if (Mask[i] >= 0 && Mask[i] != Idx)