1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeOrdering.h"
16 #include "SDNodeDbgValue.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Analysis/DebugInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalAlias.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/PseudoSourceValue.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetSelectionDAGInfo.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetIntrinsicInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Support/Mutex.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/SmallPtrSet.h"
49 #include "llvm/ADT/SmallSet.h"
50 #include "llvm/ADT/SmallVector.h"
51 #include "llvm/ADT/StringExtras.h"
56 /// makeVTList - Return an instance of the SDVTList struct initialized with the
57 /// specified members.
58 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
59 SDVTList Res = {VTs, NumVTs};
63 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
64 switch (VT.getSimpleVT().SimpleTy) {
65 default: llvm_unreachable("Unknown FP format");
66 case MVT::f32: return &APFloat::IEEEsingle;
67 case MVT::f64: return &APFloat::IEEEdouble;
68 case MVT::f80: return &APFloat::x87DoubleExtended;
69 case MVT::f128: return &APFloat::IEEEquad;
70 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
74 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
76 //===----------------------------------------------------------------------===//
77 // ConstantFPSDNode Class
78 //===----------------------------------------------------------------------===//
80 /// isExactlyValue - We don't rely on operator== working on double values, as
81 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
82 /// As such, this method can be used to do an exact bit-for-bit comparison of
83 /// two floating point values.
84 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
85 return getValueAPF().bitwiseIsEqual(V);
88 bool ConstantFPSDNode::isValueValidForType(EVT VT,
90 assert(VT.isFloatingPoint() && "Can only convert between FP types");
92 // PPC long double cannot be converted to any other type.
93 if (VT == MVT::ppcf128 ||
94 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
97 // convert modifies in place, so make a copy.
98 APFloat Val2 = APFloat(Val);
100 (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
105 //===----------------------------------------------------------------------===//
107 //===----------------------------------------------------------------------===//
109 /// isBuildVectorAllOnes - Return true if the specified node is a
110 /// BUILD_VECTOR where all of the elements are ~0 or undef.
111 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
112 // Look through a bit convert.
113 if (N->getOpcode() == ISD::BITCAST)
114 N = N->getOperand(0).getNode();
116 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
118 unsigned i = 0, e = N->getNumOperands();
120 // Skip over all of the undef values.
121 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
124 // Do not accept an all-undef vector.
125 if (i == e) return false;
127 // Do not accept build_vectors that aren't all constants or which have non-~0
129 SDValue NotZero = N->getOperand(i);
130 if (isa<ConstantSDNode>(NotZero)) {
131 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
133 } else if (isa<ConstantFPSDNode>(NotZero)) {
134 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
135 bitcastToAPInt().isAllOnesValue())
140 // Okay, we have at least one ~0 value, check to see if the rest match or are
142 for (++i; i != e; ++i)
143 if (N->getOperand(i) != NotZero &&
144 N->getOperand(i).getOpcode() != ISD::UNDEF)
150 /// isBuildVectorAllZeros - Return true if the specified node is a
151 /// BUILD_VECTOR where all of the elements are 0 or undef.
152 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
153 // Look through a bit convert.
154 if (N->getOpcode() == ISD::BITCAST)
155 N = N->getOperand(0).getNode();
157 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
159 unsigned i = 0, e = N->getNumOperands();
161 // Skip over all of the undef values.
162 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
165 // Do not accept an all-undef vector.
166 if (i == e) return false;
168 // Do not accept build_vectors that aren't all constants or which have non-0
170 SDValue Zero = N->getOperand(i);
171 if (isa<ConstantSDNode>(Zero)) {
172 if (!cast<ConstantSDNode>(Zero)->isNullValue())
174 } else if (isa<ConstantFPSDNode>(Zero)) {
175 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
180 // Okay, we have at least one 0 value, check to see if the rest match or are
182 for (++i; i != e; ++i)
183 if (N->getOperand(i) != Zero &&
184 N->getOperand(i).getOpcode() != ISD::UNDEF)
189 /// isScalarToVector - Return true if the specified node is a
190 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
191 /// element is not an undef.
192 bool ISD::isScalarToVector(const SDNode *N) {
193 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
196 if (N->getOpcode() != ISD::BUILD_VECTOR)
198 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
200 unsigned NumElems = N->getNumOperands();
203 for (unsigned i = 1; i < NumElems; ++i) {
204 SDValue V = N->getOperand(i);
205 if (V.getOpcode() != ISD::UNDEF)
211 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
212 /// when given the operation for (X op Y).
213 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
214 // To perform this operation, we just need to swap the L and G bits of the
216 unsigned OldL = (Operation >> 2) & 1;
217 unsigned OldG = (Operation >> 1) & 1;
218 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
219 (OldL << 1) | // New G bit
220 (OldG << 2)); // New L bit.
223 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
224 /// 'op' is a valid SetCC operation.
225 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
226 unsigned Operation = Op;
228 Operation ^= 7; // Flip L, G, E bits, but not U.
230 Operation ^= 15; // Flip all of the condition bits.
232 if (Operation > ISD::SETTRUE2)
233 Operation &= ~8; // Don't let N and U bits get set.
235 return ISD::CondCode(Operation);
239 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
240 /// signed operation and 2 if the result is an unsigned comparison. Return zero
241 /// if the operation does not depend on the sign of the input (setne and seteq).
242 static int isSignedOp(ISD::CondCode Opcode) {
244 default: llvm_unreachable("Illegal integer setcc operation!");
246 case ISD::SETNE: return 0;
250 case ISD::SETGE: return 1;
254 case ISD::SETUGE: return 2;
258 /// getSetCCOrOperation - Return the result of a logical OR between different
259 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
260 /// returns SETCC_INVALID if it is not possible to represent the resultant
262 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
264 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
265 // Cannot fold a signed integer setcc with an unsigned integer setcc.
266 return ISD::SETCC_INVALID;
268 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
270 // If the N and U bits get set then the resultant comparison DOES suddenly
271 // care about orderedness, and is true when ordered.
272 if (Op > ISD::SETTRUE2)
273 Op &= ~16; // Clear the U bit if the N bit is set.
275 // Canonicalize illegal integer setcc's.
276 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
279 return ISD::CondCode(Op);
282 /// getSetCCAndOperation - Return the result of a logical AND between different
283 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
284 /// function returns zero if it is not possible to represent the resultant
286 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
288 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
289 // Cannot fold a signed setcc with an unsigned setcc.
290 return ISD::SETCC_INVALID;
292 // Combine all of the condition bits.
293 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
295 // Canonicalize illegal integer setcc's.
299 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
300 case ISD::SETOEQ: // SETEQ & SETU[LG]E
301 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
302 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
303 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
310 //===----------------------------------------------------------------------===//
311 // SDNode Profile Support
312 //===----------------------------------------------------------------------===//
314 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
316 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
320 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
321 /// solely with their pointer.
322 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
323 ID.AddPointer(VTList.VTs);
326 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
328 static void AddNodeIDOperands(FoldingSetNodeID &ID,
329 const SDValue *Ops, unsigned NumOps) {
330 for (; NumOps; --NumOps, ++Ops) {
331 ID.AddPointer(Ops->getNode());
332 ID.AddInteger(Ops->getResNo());
336 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
338 static void AddNodeIDOperands(FoldingSetNodeID &ID,
339 const SDUse *Ops, unsigned NumOps) {
340 for (; NumOps; --NumOps, ++Ops) {
341 ID.AddPointer(Ops->getNode());
342 ID.AddInteger(Ops->getResNo());
346 static void AddNodeIDNode(FoldingSetNodeID &ID,
347 unsigned short OpC, SDVTList VTList,
348 const SDValue *OpList, unsigned N) {
349 AddNodeIDOpcode(ID, OpC);
350 AddNodeIDValueTypes(ID, VTList);
351 AddNodeIDOperands(ID, OpList, N);
354 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
356 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
357 switch (N->getOpcode()) {
358 case ISD::TargetExternalSymbol:
359 case ISD::ExternalSymbol:
360 llvm_unreachable("Should only be used on nodes with operands");
361 default: break; // Normal nodes don't need extra info.
362 case ISD::TargetConstant:
364 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
366 case ISD::TargetConstantFP:
367 case ISD::ConstantFP: {
368 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
371 case ISD::TargetGlobalAddress:
372 case ISD::GlobalAddress:
373 case ISD::TargetGlobalTLSAddress:
374 case ISD::GlobalTLSAddress: {
375 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
376 ID.AddPointer(GA->getGlobal());
377 ID.AddInteger(GA->getOffset());
378 ID.AddInteger(GA->getTargetFlags());
381 case ISD::BasicBlock:
382 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
385 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
389 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
391 case ISD::FrameIndex:
392 case ISD::TargetFrameIndex:
393 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
396 case ISD::TargetJumpTable:
397 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
398 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
400 case ISD::ConstantPool:
401 case ISD::TargetConstantPool: {
402 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
403 ID.AddInteger(CP->getAlignment());
404 ID.AddInteger(CP->getOffset());
405 if (CP->isMachineConstantPoolEntry())
406 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
408 ID.AddPointer(CP->getConstVal());
409 ID.AddInteger(CP->getTargetFlags());
413 const LoadSDNode *LD = cast<LoadSDNode>(N);
414 ID.AddInteger(LD->getMemoryVT().getRawBits());
415 ID.AddInteger(LD->getRawSubclassData());
419 const StoreSDNode *ST = cast<StoreSDNode>(N);
420 ID.AddInteger(ST->getMemoryVT().getRawBits());
421 ID.AddInteger(ST->getRawSubclassData());
424 case ISD::ATOMIC_CMP_SWAP:
425 case ISD::ATOMIC_SWAP:
426 case ISD::ATOMIC_LOAD_ADD:
427 case ISD::ATOMIC_LOAD_SUB:
428 case ISD::ATOMIC_LOAD_AND:
429 case ISD::ATOMIC_LOAD_OR:
430 case ISD::ATOMIC_LOAD_XOR:
431 case ISD::ATOMIC_LOAD_NAND:
432 case ISD::ATOMIC_LOAD_MIN:
433 case ISD::ATOMIC_LOAD_MAX:
434 case ISD::ATOMIC_LOAD_UMIN:
435 case ISD::ATOMIC_LOAD_UMAX:
436 case ISD::ATOMIC_LOAD:
437 case ISD::ATOMIC_STORE: {
438 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
439 ID.AddInteger(AT->getMemoryVT().getRawBits());
440 ID.AddInteger(AT->getRawSubclassData());
443 case ISD::VECTOR_SHUFFLE: {
444 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
445 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
447 ID.AddInteger(SVN->getMaskElt(i));
450 case ISD::TargetBlockAddress:
451 case ISD::BlockAddress: {
452 ID.AddPointer(cast<BlockAddressSDNode>(N)->getBlockAddress());
453 ID.AddInteger(cast<BlockAddressSDNode>(N)->getTargetFlags());
456 } // end switch (N->getOpcode())
459 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
461 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
462 AddNodeIDOpcode(ID, N->getOpcode());
463 // Add the return value info.
464 AddNodeIDValueTypes(ID, N->getVTList());
465 // Add the operand info.
466 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
468 // Handle SDNode leafs with special info.
469 AddNodeIDCustom(ID, N);
472 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
473 /// the CSE map that carries volatility, temporalness, indexing mode, and
474 /// extension/truncation information.
476 static inline unsigned
477 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
478 bool isNonTemporal) {
479 assert((ConvType & 3) == ConvType &&
480 "ConvType may not require more than 2 bits!");
481 assert((AM & 7) == AM &&
482 "AM may not require more than 3 bits!");
486 (isNonTemporal << 6);
489 //===----------------------------------------------------------------------===//
490 // SelectionDAG Class
491 //===----------------------------------------------------------------------===//
493 /// doNotCSE - Return true if CSE should not be performed for this node.
494 static bool doNotCSE(SDNode *N) {
495 if (N->getValueType(0) == MVT::Glue)
496 return true; // Never CSE anything that produces a flag.
498 switch (N->getOpcode()) {
500 case ISD::HANDLENODE:
502 return true; // Never CSE these nodes.
505 // Check that remaining values produced are not flags.
506 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
507 if (N->getValueType(i) == MVT::Glue)
508 return true; // Never CSE anything that produces a flag.
513 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
515 void SelectionDAG::RemoveDeadNodes() {
516 // Create a dummy node (which is not added to allnodes), that adds a reference
517 // to the root node, preventing it from being deleted.
518 HandleSDNode Dummy(getRoot());
520 SmallVector<SDNode*, 128> DeadNodes;
522 // Add all obviously-dead nodes to the DeadNodes worklist.
523 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
525 DeadNodes.push_back(I);
527 RemoveDeadNodes(DeadNodes);
529 // If the root changed (e.g. it was a dead load, update the root).
530 setRoot(Dummy.getValue());
533 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
534 /// given list, and any nodes that become unreachable as a result.
535 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
536 DAGUpdateListener *UpdateListener) {
538 // Process the worklist, deleting the nodes and adding their uses to the
540 while (!DeadNodes.empty()) {
541 SDNode *N = DeadNodes.pop_back_val();
544 UpdateListener->NodeDeleted(N, 0);
546 // Take the node out of the appropriate CSE map.
547 RemoveNodeFromCSEMaps(N);
549 // Next, brutally remove the operand list. This is safe to do, as there are
550 // no cycles in the graph.
551 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
553 SDNode *Operand = Use.getNode();
556 // Now that we removed this operand, see if there are no uses of it left.
557 if (Operand->use_empty())
558 DeadNodes.push_back(Operand);
565 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
566 SmallVector<SDNode*, 16> DeadNodes(1, N);
567 RemoveDeadNodes(DeadNodes, UpdateListener);
570 void SelectionDAG::DeleteNode(SDNode *N) {
571 // First take this out of the appropriate CSE map.
572 RemoveNodeFromCSEMaps(N);
574 // Finally, remove uses due to operands of this node, remove from the
575 // AllNodes list, and delete the node.
576 DeleteNodeNotInCSEMaps(N);
579 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
580 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
581 assert(N->use_empty() && "Cannot delete a node that is not dead!");
583 // Drop all of the operands and decrement used node's use counts.
589 void SelectionDAG::DeallocateNode(SDNode *N) {
590 if (N->OperandsNeedDelete)
591 delete[] N->OperandList;
593 // Set the opcode to DELETED_NODE to help catch bugs when node
594 // memory is reallocated.
595 N->NodeType = ISD::DELETED_NODE;
597 NodeAllocator.Deallocate(AllNodes.remove(N));
599 // Remove the ordering of this node.
602 // If any of the SDDbgValue nodes refer to this SDNode, invalidate them.
603 ArrayRef<SDDbgValue*> DbgVals = DbgInfo->getSDDbgValues(N);
604 for (unsigned i = 0, e = DbgVals.size(); i != e; ++i)
605 DbgVals[i]->setIsInvalidated();
608 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
609 /// correspond to it. This is useful when we're about to delete or repurpose
610 /// the node. We don't want future request for structurally identical nodes
611 /// to return N anymore.
612 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
614 switch (N->getOpcode()) {
615 case ISD::HANDLENODE: return false; // noop.
617 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
618 "Cond code doesn't exist!");
619 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
620 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
622 case ISD::ExternalSymbol:
623 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
625 case ISD::TargetExternalSymbol: {
626 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
627 Erased = TargetExternalSymbols.erase(
628 std::pair<std::string,unsigned char>(ESN->getSymbol(),
629 ESN->getTargetFlags()));
632 case ISD::VALUETYPE: {
633 EVT VT = cast<VTSDNode>(N)->getVT();
634 if (VT.isExtended()) {
635 Erased = ExtendedValueTypeNodes.erase(VT);
637 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
638 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
643 // Remove it from the CSE Map.
644 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
645 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
646 Erased = CSEMap.RemoveNode(N);
650 // Verify that the node was actually in one of the CSE maps, unless it has a
651 // flag result (which cannot be CSE'd) or is one of the special cases that are
652 // not subject to CSE.
653 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
654 !N->isMachineOpcode() && !doNotCSE(N)) {
657 llvm_unreachable("Node is not in map!");
663 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
664 /// maps and modified in place. Add it back to the CSE maps, unless an identical
665 /// node already exists, in which case transfer all its users to the existing
666 /// node. This transfer can potentially trigger recursive merging.
669 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
670 DAGUpdateListener *UpdateListener) {
671 // For node types that aren't CSE'd, just act as if no identical node
674 SDNode *Existing = CSEMap.GetOrInsertNode(N);
676 // If there was already an existing matching node, use ReplaceAllUsesWith
677 // to replace the dead one with the existing one. This can cause
678 // recursive merging of other unrelated nodes down the line.
679 ReplaceAllUsesWith(N, Existing, UpdateListener);
681 // N is now dead. Inform the listener if it exists and delete it.
683 UpdateListener->NodeDeleted(N, Existing);
684 DeleteNodeNotInCSEMaps(N);
689 // If the node doesn't already exist, we updated it. Inform a listener if
692 UpdateListener->NodeUpdated(N);
695 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
696 /// were replaced with those specified. If this node is never memoized,
697 /// return null, otherwise return a pointer to the slot it would take. If a
698 /// node already exists with these operands, the slot will be non-null.
699 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
704 SDValue Ops[] = { Op };
706 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
707 AddNodeIDCustom(ID, N);
708 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
712 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
713 /// were replaced with those specified. If this node is never memoized,
714 /// return null, otherwise return a pointer to the slot it would take. If a
715 /// node already exists with these operands, the slot will be non-null.
716 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
717 SDValue Op1, SDValue Op2,
722 SDValue Ops[] = { Op1, Op2 };
724 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
725 AddNodeIDCustom(ID, N);
726 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
731 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
732 /// were replaced with those specified. If this node is never memoized,
733 /// return null, otherwise return a pointer to the slot it would take. If a
734 /// node already exists with these operands, the slot will be non-null.
735 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
736 const SDValue *Ops,unsigned NumOps,
742 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
743 AddNodeIDCustom(ID, N);
744 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
749 /// VerifyNodeCommon - Sanity check the given node. Aborts if it is invalid.
750 static void VerifyNodeCommon(SDNode *N) {
751 switch (N->getOpcode()) {
754 case ISD::BUILD_PAIR: {
755 EVT VT = N->getValueType(0);
756 assert(N->getNumValues() == 1 && "Too many results!");
757 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
758 "Wrong return type!");
759 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
760 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
761 "Mismatched operand types!");
762 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
763 "Wrong operand type!");
764 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
765 "Wrong return type size");
768 case ISD::BUILD_VECTOR: {
769 assert(N->getNumValues() == 1 && "Too many results!");
770 assert(N->getValueType(0).isVector() && "Wrong return type!");
771 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
772 "Wrong number of operands!");
773 EVT EltVT = N->getValueType(0).getVectorElementType();
774 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
775 assert((I->getValueType() == EltVT ||
776 (EltVT.isInteger() && I->getValueType().isInteger() &&
777 EltVT.bitsLE(I->getValueType()))) &&
778 "Wrong operand type!");
779 assert(I->getValueType() == N->getOperand(0).getValueType() &&
780 "Operands must all have the same type");
787 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
788 static void VerifySDNode(SDNode *N) {
789 // The SDNode allocators cannot be used to allocate nodes with fields that are
790 // not present in an SDNode!
791 assert(!isa<MemSDNode>(N) && "Bad MemSDNode!");
792 assert(!isa<ShuffleVectorSDNode>(N) && "Bad ShuffleVectorSDNode!");
793 assert(!isa<ConstantSDNode>(N) && "Bad ConstantSDNode!");
794 assert(!isa<ConstantFPSDNode>(N) && "Bad ConstantFPSDNode!");
795 assert(!isa<GlobalAddressSDNode>(N) && "Bad GlobalAddressSDNode!");
796 assert(!isa<FrameIndexSDNode>(N) && "Bad FrameIndexSDNode!");
797 assert(!isa<JumpTableSDNode>(N) && "Bad JumpTableSDNode!");
798 assert(!isa<ConstantPoolSDNode>(N) && "Bad ConstantPoolSDNode!");
799 assert(!isa<BasicBlockSDNode>(N) && "Bad BasicBlockSDNode!");
800 assert(!isa<SrcValueSDNode>(N) && "Bad SrcValueSDNode!");
801 assert(!isa<MDNodeSDNode>(N) && "Bad MDNodeSDNode!");
802 assert(!isa<RegisterSDNode>(N) && "Bad RegisterSDNode!");
803 assert(!isa<BlockAddressSDNode>(N) && "Bad BlockAddressSDNode!");
804 assert(!isa<EHLabelSDNode>(N) && "Bad EHLabelSDNode!");
805 assert(!isa<ExternalSymbolSDNode>(N) && "Bad ExternalSymbolSDNode!");
806 assert(!isa<CondCodeSDNode>(N) && "Bad CondCodeSDNode!");
807 assert(!isa<CvtRndSatSDNode>(N) && "Bad CvtRndSatSDNode!");
808 assert(!isa<VTSDNode>(N) && "Bad VTSDNode!");
809 assert(!isa<MachineSDNode>(N) && "Bad MachineSDNode!");
814 /// VerifyMachineNode - Sanity check the given MachineNode. Aborts if it is
816 static void VerifyMachineNode(SDNode *N) {
817 // The MachineNode allocators cannot be used to allocate nodes with fields
818 // that are not present in a MachineNode!
819 // Currently there are no such nodes.
825 /// getEVTAlignment - Compute the default alignment value for the
828 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
829 Type *Ty = VT == MVT::iPTR ?
830 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
831 VT.getTypeForEVT(*getContext());
833 return TLI.getTargetData()->getABITypeAlignment(Ty);
836 // EntryNode could meaningfully have debug info if we can find it...
837 SelectionDAG::SelectionDAG(const TargetMachine &tm)
838 : TM(tm), TLI(*tm.getTargetLowering()), TSI(*tm.getSelectionDAGInfo()),
839 EntryNode(ISD::EntryToken, DebugLoc(), getVTList(MVT::Other)),
840 Root(getEntryNode()), Ordering(0) {
841 AllNodes.push_back(&EntryNode);
842 Ordering = new SDNodeOrdering();
843 DbgInfo = new SDDbgInfo();
846 void SelectionDAG::init(MachineFunction &mf) {
848 Context = &mf.getFunction()->getContext();
851 SelectionDAG::~SelectionDAG() {
857 void SelectionDAG::allnodes_clear() {
858 assert(&*AllNodes.begin() == &EntryNode);
859 AllNodes.remove(AllNodes.begin());
860 while (!AllNodes.empty())
861 DeallocateNode(AllNodes.begin());
864 void SelectionDAG::clear() {
866 OperandAllocator.Reset();
869 ExtendedValueTypeNodes.clear();
870 ExternalSymbols.clear();
871 TargetExternalSymbols.clear();
872 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
873 static_cast<CondCodeSDNode*>(0));
874 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
875 static_cast<SDNode*>(0));
877 EntryNode.UseList = 0;
878 AllNodes.push_back(&EntryNode);
879 Root = getEntryNode();
884 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
885 return VT.bitsGT(Op.getValueType()) ?
886 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
887 getNode(ISD::TRUNCATE, DL, VT, Op);
890 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
891 return VT.bitsGT(Op.getValueType()) ?
892 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
893 getNode(ISD::TRUNCATE, DL, VT, Op);
896 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
897 assert(!VT.isVector() &&
898 "getZeroExtendInReg should use the vector element type instead of "
900 if (Op.getValueType() == VT) return Op;
901 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
902 APInt Imm = APInt::getLowBitsSet(BitWidth,
904 return getNode(ISD::AND, DL, Op.getValueType(), Op,
905 getConstant(Imm, Op.getValueType()));
908 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
910 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
911 EVT EltVT = VT.getScalarType();
913 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
914 return getNode(ISD::XOR, DL, VT, Val, NegOne);
917 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
918 EVT EltVT = VT.getScalarType();
919 assert((EltVT.getSizeInBits() >= 64 ||
920 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
921 "getConstant with a uint64_t value that doesn't fit in the type!");
922 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
925 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
926 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
929 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
930 assert(VT.isInteger() && "Cannot create FP integer constant!");
932 EVT EltVT = VT.getScalarType();
933 const ConstantInt *Elt = &Val;
935 // In some cases the vector type is legal but the element type is illegal and
936 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
937 // inserted value (the type does not need to match the vector element type).
938 // Any extra bits introduced will be truncated away.
939 if (VT.isVector() && TLI.getTypeAction(*getContext(), EltVT) ==
940 TargetLowering::TypePromoteInteger) {
941 EltVT = TLI.getTypeToTransformTo(*getContext(), EltVT);
942 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits());
943 Elt = ConstantInt::get(*getContext(), NewVal);
946 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
947 "APInt size does not match type size!");
948 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
950 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
954 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
956 return SDValue(N, 0);
959 N = new (NodeAllocator) ConstantSDNode(isT, Elt, EltVT);
960 CSEMap.InsertNode(N, IP);
961 AllNodes.push_back(N);
964 SDValue Result(N, 0);
966 SmallVector<SDValue, 8> Ops;
967 Ops.assign(VT.getVectorNumElements(), Result);
968 Result = getNode(ISD::BUILD_VECTOR, DebugLoc(), VT, &Ops[0], Ops.size());
973 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
974 return getConstant(Val, TLI.getPointerTy(), isTarget);
978 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
979 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
982 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
983 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
985 EVT EltVT = VT.getScalarType();
987 // Do the map lookup using the actual bit pattern for the floating point
988 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
989 // we don't have issues with SNANs.
990 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
992 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
996 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
998 return SDValue(N, 0);
1001 N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT);
1002 CSEMap.InsertNode(N, IP);
1003 AllNodes.push_back(N);
1006 SDValue Result(N, 0);
1007 if (VT.isVector()) {
1008 SmallVector<SDValue, 8> Ops;
1009 Ops.assign(VT.getVectorNumElements(), Result);
1010 // FIXME DebugLoc info might be appropriate here
1011 Result = getNode(ISD::BUILD_VECTOR, DebugLoc(), VT, &Ops[0], Ops.size());
1016 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
1017 EVT EltVT = VT.getScalarType();
1018 if (EltVT==MVT::f32)
1019 return getConstantFP(APFloat((float)Val), VT, isTarget);
1020 else if (EltVT==MVT::f64)
1021 return getConstantFP(APFloat(Val), VT, isTarget);
1022 else if (EltVT==MVT::f80 || EltVT==MVT::f128) {
1024 APFloat apf = APFloat(Val);
1025 apf.convert(*EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1027 return getConstantFP(apf, VT, isTarget);
1029 assert(0 && "Unsupported type in getConstantFP");
1034 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, DebugLoc DL,
1035 EVT VT, int64_t Offset,
1037 unsigned char TargetFlags) {
1038 assert((TargetFlags == 0 || isTargetGA) &&
1039 "Cannot set target flags on target-independent globals");
1041 // Truncate (with sign-extension) the offset value to the pointer size.
1042 EVT PTy = TLI.getPointerTy();
1043 unsigned BitWidth = PTy.getSizeInBits();
1045 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
1047 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1049 // If GV is an alias then use the aliasee for determining thread-localness.
1050 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1051 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1055 if (GVar && GVar->isThreadLocal())
1056 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1058 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1060 FoldingSetNodeID ID;
1061 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1063 ID.AddInteger(Offset);
1064 ID.AddInteger(TargetFlags);
1066 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1067 return SDValue(E, 0);
1069 SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL, GV, VT,
1070 Offset, TargetFlags);
1071 CSEMap.InsertNode(N, IP);
1072 AllNodes.push_back(N);
1073 return SDValue(N, 0);
1076 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1077 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1078 FoldingSetNodeID ID;
1079 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1082 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1083 return SDValue(E, 0);
1085 SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget);
1086 CSEMap.InsertNode(N, IP);
1087 AllNodes.push_back(N);
1088 return SDValue(N, 0);
1091 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1092 unsigned char TargetFlags) {
1093 assert((TargetFlags == 0 || isTarget) &&
1094 "Cannot set target flags on target-independent jump tables");
1095 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1096 FoldingSetNodeID ID;
1097 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1099 ID.AddInteger(TargetFlags);
1101 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1102 return SDValue(E, 0);
1104 SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget,
1106 CSEMap.InsertNode(N, IP);
1107 AllNodes.push_back(N);
1108 return SDValue(N, 0);
1111 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1112 unsigned Alignment, int Offset,
1114 unsigned char TargetFlags) {
1115 assert((TargetFlags == 0 || isTarget) &&
1116 "Cannot set target flags on target-independent globals");
1118 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1119 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1120 FoldingSetNodeID ID;
1121 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1122 ID.AddInteger(Alignment);
1123 ID.AddInteger(Offset);
1125 ID.AddInteger(TargetFlags);
1127 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1128 return SDValue(E, 0);
1130 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1131 Alignment, TargetFlags);
1132 CSEMap.InsertNode(N, IP);
1133 AllNodes.push_back(N);
1134 return SDValue(N, 0);
1138 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1139 unsigned Alignment, int Offset,
1141 unsigned char TargetFlags) {
1142 assert((TargetFlags == 0 || isTarget) &&
1143 "Cannot set target flags on target-independent globals");
1145 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1146 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1147 FoldingSetNodeID ID;
1148 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1149 ID.AddInteger(Alignment);
1150 ID.AddInteger(Offset);
1151 C->AddSelectionDAGCSEId(ID);
1152 ID.AddInteger(TargetFlags);
1154 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1155 return SDValue(E, 0);
1157 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1158 Alignment, TargetFlags);
1159 CSEMap.InsertNode(N, IP);
1160 AllNodes.push_back(N);
1161 return SDValue(N, 0);
1164 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1165 FoldingSetNodeID ID;
1166 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1169 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1170 return SDValue(E, 0);
1172 SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB);
1173 CSEMap.InsertNode(N, IP);
1174 AllNodes.push_back(N);
1175 return SDValue(N, 0);
1178 SDValue SelectionDAG::getValueType(EVT VT) {
1179 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1180 ValueTypeNodes.size())
1181 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1183 SDNode *&N = VT.isExtended() ?
1184 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1186 if (N) return SDValue(N, 0);
1187 N = new (NodeAllocator) VTSDNode(VT);
1188 AllNodes.push_back(N);
1189 return SDValue(N, 0);
1192 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1193 SDNode *&N = ExternalSymbols[Sym];
1194 if (N) return SDValue(N, 0);
1195 N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT);
1196 AllNodes.push_back(N);
1197 return SDValue(N, 0);
1200 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1201 unsigned char TargetFlags) {
1203 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1205 if (N) return SDValue(N, 0);
1206 N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1207 AllNodes.push_back(N);
1208 return SDValue(N, 0);
1211 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1212 if ((unsigned)Cond >= CondCodeNodes.size())
1213 CondCodeNodes.resize(Cond+1);
1215 if (CondCodeNodes[Cond] == 0) {
1216 CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond);
1217 CondCodeNodes[Cond] = N;
1218 AllNodes.push_back(N);
1221 return SDValue(CondCodeNodes[Cond], 0);
1224 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1225 // the shuffle mask M that point at N1 to point at N2, and indices that point
1226 // N2 to point at N1.
1227 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1229 int NElts = M.size();
1230 for (int i = 0; i != NElts; ++i) {
1238 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1239 SDValue N2, const int *Mask) {
1240 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1241 assert(VT.isVector() && N1.getValueType().isVector() &&
1242 "Vector Shuffle VTs must be a vectors");
1243 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1244 && "Vector Shuffle VTs must have same element type");
1246 // Canonicalize shuffle undef, undef -> undef
1247 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1248 return getUNDEF(VT);
1250 // Validate that all indices in Mask are within the range of the elements
1251 // input to the shuffle.
1252 unsigned NElts = VT.getVectorNumElements();
1253 SmallVector<int, 8> MaskVec;
1254 for (unsigned i = 0; i != NElts; ++i) {
1255 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1256 MaskVec.push_back(Mask[i]);
1259 // Canonicalize shuffle v, v -> v, undef
1262 for (unsigned i = 0; i != NElts; ++i)
1263 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1266 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1267 if (N1.getOpcode() == ISD::UNDEF)
1268 commuteShuffle(N1, N2, MaskVec);
1270 // Canonicalize all index into lhs, -> shuffle lhs, undef
1271 // Canonicalize all index into rhs, -> shuffle rhs, undef
1272 bool AllLHS = true, AllRHS = true;
1273 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1274 for (unsigned i = 0; i != NElts; ++i) {
1275 if (MaskVec[i] >= (int)NElts) {
1280 } else if (MaskVec[i] >= 0) {
1284 if (AllLHS && AllRHS)
1285 return getUNDEF(VT);
1286 if (AllLHS && !N2Undef)
1290 commuteShuffle(N1, N2, MaskVec);
1293 // If Identity shuffle, or all shuffle in to undef, return that node.
1294 bool AllUndef = true;
1295 bool Identity = true;
1296 for (unsigned i = 0; i != NElts; ++i) {
1297 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1298 if (MaskVec[i] >= 0) AllUndef = false;
1300 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1303 return getUNDEF(VT);
1305 FoldingSetNodeID ID;
1306 SDValue Ops[2] = { N1, N2 };
1307 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1308 for (unsigned i = 0; i != NElts; ++i)
1309 ID.AddInteger(MaskVec[i]);
1312 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1313 return SDValue(E, 0);
1315 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1316 // SDNode doesn't have access to it. This memory will be "leaked" when
1317 // the node is deallocated, but recovered when the NodeAllocator is released.
1318 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1319 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1321 ShuffleVectorSDNode *N =
1322 new (NodeAllocator) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1323 CSEMap.InsertNode(N, IP);
1324 AllNodes.push_back(N);
1325 return SDValue(N, 0);
1328 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1329 SDValue Val, SDValue DTy,
1330 SDValue STy, SDValue Rnd, SDValue Sat,
1331 ISD::CvtCode Code) {
1332 // If the src and dest types are the same and the conversion is between
1333 // integer types of the same sign or two floats, no conversion is necessary.
1335 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1338 FoldingSetNodeID ID;
1339 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1340 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1342 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1343 return SDValue(E, 0);
1345 CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl, Ops, 5,
1347 CSEMap.InsertNode(N, IP);
1348 AllNodes.push_back(N);
1349 return SDValue(N, 0);
1352 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1353 FoldingSetNodeID ID;
1354 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1355 ID.AddInteger(RegNo);
1357 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1358 return SDValue(E, 0);
1360 SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT);
1361 CSEMap.InsertNode(N, IP);
1362 AllNodes.push_back(N);
1363 return SDValue(N, 0);
1366 SDValue SelectionDAG::getEHLabel(DebugLoc dl, SDValue Root, MCSymbol *Label) {
1367 FoldingSetNodeID ID;
1368 SDValue Ops[] = { Root };
1369 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), &Ops[0], 1);
1370 ID.AddPointer(Label);
1372 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1373 return SDValue(E, 0);
1375 SDNode *N = new (NodeAllocator) EHLabelSDNode(dl, Root, Label);
1376 CSEMap.InsertNode(N, IP);
1377 AllNodes.push_back(N);
1378 return SDValue(N, 0);
1382 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1384 unsigned char TargetFlags) {
1385 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1387 FoldingSetNodeID ID;
1388 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1390 ID.AddInteger(TargetFlags);
1392 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1393 return SDValue(E, 0);
1395 SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, TargetFlags);
1396 CSEMap.InsertNode(N, IP);
1397 AllNodes.push_back(N);
1398 return SDValue(N, 0);
1401 SDValue SelectionDAG::getSrcValue(const Value *V) {
1402 assert((!V || V->getType()->isPointerTy()) &&
1403 "SrcValue is not a pointer?");
1405 FoldingSetNodeID ID;
1406 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1410 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1411 return SDValue(E, 0);
1413 SDNode *N = new (NodeAllocator) SrcValueSDNode(V);
1414 CSEMap.InsertNode(N, IP);
1415 AllNodes.push_back(N);
1416 return SDValue(N, 0);
1419 /// getMDNode - Return an MDNodeSDNode which holds an MDNode.
1420 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1421 FoldingSetNodeID ID;
1422 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), 0, 0);
1426 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1427 return SDValue(E, 0);
1429 SDNode *N = new (NodeAllocator) MDNodeSDNode(MD);
1430 CSEMap.InsertNode(N, IP);
1431 AllNodes.push_back(N);
1432 return SDValue(N, 0);
1436 /// getShiftAmountOperand - Return the specified value casted to
1437 /// the target's desired shift amount type.
1438 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1439 EVT OpTy = Op.getValueType();
1440 MVT ShTy = TLI.getShiftAmountTy(LHSTy);
1441 if (OpTy == ShTy || OpTy.isVector()) return Op;
1443 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1444 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1447 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1448 /// specified value type.
1449 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1450 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1451 unsigned ByteSize = VT.getStoreSize();
1452 Type *Ty = VT.getTypeForEVT(*getContext());
1453 unsigned StackAlign =
1454 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1456 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1457 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1460 /// CreateStackTemporary - Create a stack temporary suitable for holding
1461 /// either of the specified value types.
1462 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1463 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1464 VT2.getStoreSizeInBits())/8;
1465 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1466 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1467 const TargetData *TD = TLI.getTargetData();
1468 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1469 TD->getPrefTypeAlignment(Ty2));
1471 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1472 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1473 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1476 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1477 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1478 // These setcc operations always fold.
1482 case ISD::SETFALSE2: return getConstant(0, VT);
1484 case ISD::SETTRUE2: return getConstant(1, VT);
1496 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1500 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1501 const APInt &C2 = N2C->getAPIntValue();
1502 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1503 const APInt &C1 = N1C->getAPIntValue();
1506 default: llvm_unreachable("Unknown integer setcc!");
1507 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1508 case ISD::SETNE: return getConstant(C1 != C2, VT);
1509 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1510 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1511 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1512 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1513 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1514 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1515 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1516 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1520 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1521 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1522 // No compile time operations on this type yet.
1523 if (N1C->getValueType(0) == MVT::ppcf128)
1526 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1529 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1530 return getUNDEF(VT);
1532 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1533 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1534 return getUNDEF(VT);
1536 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1537 R==APFloat::cmpLessThan, VT);
1538 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1539 return getUNDEF(VT);
1541 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1542 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1543 return getUNDEF(VT);
1545 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1546 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1547 return getUNDEF(VT);
1549 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1550 R==APFloat::cmpEqual, VT);
1551 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1552 return getUNDEF(VT);
1554 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1555 R==APFloat::cmpEqual, VT);
1556 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1557 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1558 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1559 R==APFloat::cmpEqual, VT);
1560 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1561 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1562 R==APFloat::cmpLessThan, VT);
1563 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1564 R==APFloat::cmpUnordered, VT);
1565 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1566 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1569 // Ensure that the constant occurs on the RHS.
1570 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1574 // Could not fold it.
1578 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1579 /// use this predicate to simplify operations downstream.
1580 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1581 // This predicate is not safe for vector operations.
1582 if (Op.getValueType().isVector())
1585 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1586 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1589 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1590 /// this predicate to simplify operations downstream. Mask is known to be zero
1591 /// for bits that V cannot have.
1592 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1593 unsigned Depth) const {
1594 APInt KnownZero, KnownOne;
1595 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1596 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1597 return (KnownZero & Mask) == Mask;
1600 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1601 /// known to be either zero or one and return them in the KnownZero/KnownOne
1602 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1604 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1605 APInt &KnownZero, APInt &KnownOne,
1606 unsigned Depth) const {
1607 unsigned BitWidth = Mask.getBitWidth();
1608 assert(BitWidth == Op.getValueType().getScalarType().getSizeInBits() &&
1609 "Mask size mismatches value type size!");
1611 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1612 if (Depth == 6 || Mask == 0)
1613 return; // Limit search depth.
1615 APInt KnownZero2, KnownOne2;
1617 switch (Op.getOpcode()) {
1619 // We know all of the bits for a constant!
1620 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1621 KnownZero = ~KnownOne & Mask;
1624 // If either the LHS or the RHS are Zero, the result is zero.
1625 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1626 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1627 KnownZero2, KnownOne2, Depth+1);
1628 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1629 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1631 // Output known-1 bits are only known if set in both the LHS & RHS.
1632 KnownOne &= KnownOne2;
1633 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1634 KnownZero |= KnownZero2;
1637 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1638 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1639 KnownZero2, KnownOne2, Depth+1);
1640 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1641 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1643 // Output known-0 bits are only known if clear in both the LHS & RHS.
1644 KnownZero &= KnownZero2;
1645 // Output known-1 are known to be set if set in either the LHS | RHS.
1646 KnownOne |= KnownOne2;
1649 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1650 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1651 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1652 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1654 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1655 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1656 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1657 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1658 KnownZero = KnownZeroOut;
1662 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1663 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1664 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1665 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1666 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1668 // If low bits are zero in either operand, output low known-0 bits.
1669 // Also compute a conserative estimate for high known-0 bits.
1670 // More trickiness is possible, but this is sufficient for the
1671 // interesting case of alignment computation.
1672 KnownOne.clearAllBits();
1673 unsigned TrailZ = KnownZero.countTrailingOnes() +
1674 KnownZero2.countTrailingOnes();
1675 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1676 KnownZero2.countLeadingOnes(),
1677 BitWidth) - BitWidth;
1679 TrailZ = std::min(TrailZ, BitWidth);
1680 LeadZ = std::min(LeadZ, BitWidth);
1681 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1682 APInt::getHighBitsSet(BitWidth, LeadZ);
1687 // For the purposes of computing leading zeros we can conservatively
1688 // treat a udiv as a logical right shift by the power of 2 known to
1689 // be less than the denominator.
1690 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1691 ComputeMaskedBits(Op.getOperand(0),
1692 AllOnes, KnownZero2, KnownOne2, Depth+1);
1693 unsigned LeadZ = KnownZero2.countLeadingOnes();
1695 KnownOne2.clearAllBits();
1696 KnownZero2.clearAllBits();
1697 ComputeMaskedBits(Op.getOperand(1),
1698 AllOnes, KnownZero2, KnownOne2, Depth+1);
1699 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1700 if (RHSUnknownLeadingOnes != BitWidth)
1701 LeadZ = std::min(BitWidth,
1702 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1704 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1708 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1709 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1710 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1711 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1713 // Only known if known in both the LHS and RHS.
1714 KnownOne &= KnownOne2;
1715 KnownZero &= KnownZero2;
1717 case ISD::SELECT_CC:
1718 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1719 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1720 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1721 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1723 // Only known if known in both the LHS and RHS.
1724 KnownOne &= KnownOne2;
1725 KnownZero &= KnownZero2;
1733 if (Op.getResNo() != 1)
1735 // The boolean result conforms to getBooleanContents. Fall through.
1737 // If we know the result of a setcc has the top bits zero, use this info.
1738 if (TLI.getBooleanContents(Op.getValueType().isVector()) ==
1739 TargetLowering::ZeroOrOneBooleanContent && BitWidth > 1)
1740 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1743 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1744 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1745 unsigned ShAmt = SA->getZExtValue();
1747 // If the shift count is an invalid immediate, don't do anything.
1748 if (ShAmt >= BitWidth)
1751 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1752 KnownZero, KnownOne, Depth+1);
1753 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1754 KnownZero <<= ShAmt;
1756 // low bits known zero.
1757 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1761 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1762 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1763 unsigned ShAmt = SA->getZExtValue();
1765 // If the shift count is an invalid immediate, don't do anything.
1766 if (ShAmt >= BitWidth)
1769 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1770 KnownZero, KnownOne, Depth+1);
1771 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1772 KnownZero = KnownZero.lshr(ShAmt);
1773 KnownOne = KnownOne.lshr(ShAmt);
1775 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1776 KnownZero |= HighBits; // High bits known zero.
1780 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1781 unsigned ShAmt = SA->getZExtValue();
1783 // If the shift count is an invalid immediate, don't do anything.
1784 if (ShAmt >= BitWidth)
1787 APInt InDemandedMask = (Mask << ShAmt);
1788 // If any of the demanded bits are produced by the sign extension, we also
1789 // demand the input sign bit.
1790 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1791 if (HighBits.getBoolValue())
1792 InDemandedMask |= APInt::getSignBit(BitWidth);
1794 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1796 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1797 KnownZero = KnownZero.lshr(ShAmt);
1798 KnownOne = KnownOne.lshr(ShAmt);
1800 // Handle the sign bits.
1801 APInt SignBit = APInt::getSignBit(BitWidth);
1802 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1804 if (KnownZero.intersects(SignBit)) {
1805 KnownZero |= HighBits; // New bits are known zero.
1806 } else if (KnownOne.intersects(SignBit)) {
1807 KnownOne |= HighBits; // New bits are known one.
1811 case ISD::SIGN_EXTEND_INREG: {
1812 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1813 unsigned EBits = EVT.getScalarType().getSizeInBits();
1815 // Sign extension. Compute the demanded bits in the result that are not
1816 // present in the input.
1817 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1819 APInt InSignBit = APInt::getSignBit(EBits);
1820 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1822 // If the sign extended bits are demanded, we know that the sign
1824 InSignBit = InSignBit.zext(BitWidth);
1825 if (NewBits.getBoolValue())
1826 InputDemandedBits |= InSignBit;
1828 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1829 KnownZero, KnownOne, Depth+1);
1830 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1832 // If the sign bit of the input is known set or clear, then we know the
1833 // top bits of the result.
1834 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1835 KnownZero |= NewBits;
1836 KnownOne &= ~NewBits;
1837 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1838 KnownOne |= NewBits;
1839 KnownZero &= ~NewBits;
1840 } else { // Input sign bit unknown
1841 KnownZero &= ~NewBits;
1842 KnownOne &= ~NewBits;
1849 unsigned LowBits = Log2_32(BitWidth)+1;
1850 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1851 KnownOne.clearAllBits();
1855 if (ISD::isZEXTLoad(Op.getNode())) {
1856 LoadSDNode *LD = cast<LoadSDNode>(Op);
1857 EVT VT = LD->getMemoryVT();
1858 unsigned MemBits = VT.getScalarType().getSizeInBits();
1859 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1863 case ISD::ZERO_EXTEND: {
1864 EVT InVT = Op.getOperand(0).getValueType();
1865 unsigned InBits = InVT.getScalarType().getSizeInBits();
1866 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1867 APInt InMask = Mask.trunc(InBits);
1868 KnownZero = KnownZero.trunc(InBits);
1869 KnownOne = KnownOne.trunc(InBits);
1870 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1871 KnownZero = KnownZero.zext(BitWidth);
1872 KnownOne = KnownOne.zext(BitWidth);
1873 KnownZero |= NewBits;
1876 case ISD::SIGN_EXTEND: {
1877 EVT InVT = Op.getOperand(0).getValueType();
1878 unsigned InBits = InVT.getScalarType().getSizeInBits();
1879 APInt InSignBit = APInt::getSignBit(InBits);
1880 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1881 APInt InMask = Mask.trunc(InBits);
1883 // If any of the sign extended bits are demanded, we know that the sign
1884 // bit is demanded. Temporarily set this bit in the mask for our callee.
1885 if (NewBits.getBoolValue())
1886 InMask |= InSignBit;
1888 KnownZero = KnownZero.trunc(InBits);
1889 KnownOne = KnownOne.trunc(InBits);
1890 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1892 // Note if the sign bit is known to be zero or one.
1893 bool SignBitKnownZero = KnownZero.isNegative();
1894 bool SignBitKnownOne = KnownOne.isNegative();
1895 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1896 "Sign bit can't be known to be both zero and one!");
1898 // If the sign bit wasn't actually demanded by our caller, we don't
1899 // want it set in the KnownZero and KnownOne result values. Reset the
1900 // mask and reapply it to the result values.
1901 InMask = Mask.trunc(InBits);
1902 KnownZero &= InMask;
1905 KnownZero = KnownZero.zext(BitWidth);
1906 KnownOne = KnownOne.zext(BitWidth);
1908 // If the sign bit is known zero or one, the top bits match.
1909 if (SignBitKnownZero)
1910 KnownZero |= NewBits;
1911 else if (SignBitKnownOne)
1912 KnownOne |= NewBits;
1915 case ISD::ANY_EXTEND: {
1916 EVT InVT = Op.getOperand(0).getValueType();
1917 unsigned InBits = InVT.getScalarType().getSizeInBits();
1918 APInt InMask = Mask.trunc(InBits);
1919 KnownZero = KnownZero.trunc(InBits);
1920 KnownOne = KnownOne.trunc(InBits);
1921 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1922 KnownZero = KnownZero.zext(BitWidth);
1923 KnownOne = KnownOne.zext(BitWidth);
1926 case ISD::TRUNCATE: {
1927 EVT InVT = Op.getOperand(0).getValueType();
1928 unsigned InBits = InVT.getScalarType().getSizeInBits();
1929 APInt InMask = Mask.zext(InBits);
1930 KnownZero = KnownZero.zext(InBits);
1931 KnownOne = KnownOne.zext(InBits);
1932 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1933 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1934 KnownZero = KnownZero.trunc(BitWidth);
1935 KnownOne = KnownOne.trunc(BitWidth);
1938 case ISD::AssertZext: {
1939 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1940 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1941 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1943 KnownZero |= (~InMask) & Mask;
1947 // All bits are zero except the low bit.
1948 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1952 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1953 // We know that the top bits of C-X are clear if X contains less bits
1954 // than C (i.e. no wrap-around can happen). For example, 20-X is
1955 // positive if we can prove that X is >= 0 and < 16.
1956 if (CLHS->getAPIntValue().isNonNegative()) {
1957 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1958 // NLZ can't be BitWidth with no sign bit
1959 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1960 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1963 // If all of the MaskV bits are known to be zero, then we know the
1964 // output top bits are zero, because we now know that the output is
1966 if ((KnownZero2 & MaskV) == MaskV) {
1967 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1968 // Top bits known zero.
1969 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1977 // Output known-0 bits are known if clear or set in both the low clear bits
1978 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1979 // low 3 bits clear.
1980 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
1981 BitWidth - Mask.countLeadingZeros());
1982 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1983 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1984 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1986 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1987 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1988 KnownZeroOut = std::min(KnownZeroOut,
1989 KnownZero2.countTrailingOnes());
1991 if (Op.getOpcode() == ISD::ADD) {
1992 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1996 // With ADDE, a carry bit may be added in, so we can only use this
1997 // information if we know (at least) that the low two bits are clear. We
1998 // then return to the caller that the low bit is unknown but that other bits
2000 if (KnownZeroOut >= 2) // ADDE
2001 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut);
2005 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2006 const APInt &RA = Rem->getAPIntValue().abs();
2007 if (RA.isPowerOf2()) {
2008 APInt LowBits = RA - 1;
2009 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
2010 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
2012 // The low bits of the first operand are unchanged by the srem.
2013 KnownZero = KnownZero2 & LowBits;
2014 KnownOne = KnownOne2 & LowBits;
2016 // If the first operand is non-negative or has all low bits zero, then
2017 // the upper bits are all zero.
2018 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2019 KnownZero |= ~LowBits;
2021 // If the first operand is negative and not all low bits are zero, then
2022 // the upper bits are all one.
2023 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2024 KnownOne |= ~LowBits;
2029 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2034 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2035 const APInt &RA = Rem->getAPIntValue();
2036 if (RA.isPowerOf2()) {
2037 APInt LowBits = (RA - 1);
2038 APInt Mask2 = LowBits & Mask;
2039 KnownZero |= ~LowBits & Mask;
2040 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
2041 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2046 // Since the result is less than or equal to either operand, any leading
2047 // zero bits in either operand must also exist in the result.
2048 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2049 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
2051 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
2054 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2055 KnownZero2.countLeadingOnes());
2056 KnownOne.clearAllBits();
2057 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
2060 case ISD::FrameIndex:
2061 case ISD::TargetFrameIndex:
2062 if (unsigned Align = InferPtrAlignment(Op)) {
2063 // The low bits are known zero if the pointer is aligned.
2064 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align));
2070 if (Op.getOpcode() < ISD::BUILTIN_OP_END)
2073 case ISD::INTRINSIC_WO_CHAIN:
2074 case ISD::INTRINSIC_W_CHAIN:
2075 case ISD::INTRINSIC_VOID:
2076 // Allow the target to implement this method for its nodes.
2077 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
2083 /// ComputeNumSignBits - Return the number of times the sign bit of the
2084 /// register is replicated into the other bits. We know that at least 1 bit
2085 /// is always equal to the sign bit (itself), but other cases can give us
2086 /// information. For example, immediately after an "SRA X, 2", we know that
2087 /// the top 3 bits are all equal to each other, so we return 3.
2088 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2089 EVT VT = Op.getValueType();
2090 assert(VT.isInteger() && "Invalid VT!");
2091 unsigned VTBits = VT.getScalarType().getSizeInBits();
2093 unsigned FirstAnswer = 1;
2096 return 1; // Limit search depth.
2098 switch (Op.getOpcode()) {
2100 case ISD::AssertSext:
2101 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2102 return VTBits-Tmp+1;
2103 case ISD::AssertZext:
2104 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2107 case ISD::Constant: {
2108 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2109 return Val.getNumSignBits();
2112 case ISD::SIGN_EXTEND:
2113 Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2114 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2116 case ISD::SIGN_EXTEND_INREG:
2117 // Max of the input and what this extends.
2119 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2122 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2123 return std::max(Tmp, Tmp2);
2126 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2127 // SRA X, C -> adds C sign bits.
2128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2129 Tmp += C->getZExtValue();
2130 if (Tmp > VTBits) Tmp = VTBits;
2134 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2135 // shl destroys sign bits.
2136 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2137 if (C->getZExtValue() >= VTBits || // Bad shift.
2138 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2139 return Tmp - C->getZExtValue();
2144 case ISD::XOR: // NOT is handled here.
2145 // Logical binary ops preserve the number of sign bits at the worst.
2146 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2148 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2149 FirstAnswer = std::min(Tmp, Tmp2);
2150 // We computed what we know about the sign bits as our first
2151 // answer. Now proceed to the generic code that uses
2152 // ComputeMaskedBits, and pick whichever answer is better.
2157 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2158 if (Tmp == 1) return 1; // Early out.
2159 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2160 return std::min(Tmp, Tmp2);
2168 if (Op.getResNo() != 1)
2170 // The boolean result conforms to getBooleanContents. Fall through.
2172 // If setcc returns 0/-1, all bits are sign bits.
2173 if (TLI.getBooleanContents(Op.getValueType().isVector()) ==
2174 TargetLowering::ZeroOrNegativeOneBooleanContent)
2179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2180 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2182 // Handle rotate right by N like a rotate left by 32-N.
2183 if (Op.getOpcode() == ISD::ROTR)
2184 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2186 // If we aren't rotating out all of the known-in sign bits, return the
2187 // number that are left. This handles rotl(sext(x), 1) for example.
2188 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2189 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2193 // Add can have at most one carry bit. Thus we know that the output
2194 // is, at worst, one more bit than the inputs.
2195 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2196 if (Tmp == 1) return 1; // Early out.
2198 // Special case decrementing a value (ADD X, -1):
2199 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2200 if (CRHS->isAllOnesValue()) {
2201 APInt KnownZero, KnownOne;
2202 APInt Mask = APInt::getAllOnesValue(VTBits);
2203 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2205 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2207 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2210 // If we are subtracting one from a positive number, there is no carry
2211 // out of the result.
2212 if (KnownZero.isNegative())
2216 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2217 if (Tmp2 == 1) return 1;
2218 return std::min(Tmp, Tmp2)-1;
2222 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2223 if (Tmp2 == 1) return 1;
2226 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2227 if (CLHS->isNullValue()) {
2228 APInt KnownZero, KnownOne;
2229 APInt Mask = APInt::getAllOnesValue(VTBits);
2230 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2231 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2233 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2236 // If the input is known to be positive (the sign bit is known clear),
2237 // the output of the NEG has the same number of sign bits as the input.
2238 if (KnownZero.isNegative())
2241 // Otherwise, we treat this like a SUB.
2244 // Sub can have at most one carry bit. Thus we know that the output
2245 // is, at worst, one more bit than the inputs.
2246 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2247 if (Tmp == 1) return 1; // Early out.
2248 return std::min(Tmp, Tmp2)-1;
2251 // FIXME: it's tricky to do anything useful for this, but it is an important
2252 // case for targets like X86.
2256 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2257 if (Op.getOpcode() == ISD::LOAD) {
2258 LoadSDNode *LD = cast<LoadSDNode>(Op);
2259 unsigned ExtType = LD->getExtensionType();
2262 case ISD::SEXTLOAD: // '17' bits known
2263 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2264 return VTBits-Tmp+1;
2265 case ISD::ZEXTLOAD: // '16' bits known
2266 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2271 // Allow the target to implement this method for its nodes.
2272 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2273 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2274 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2275 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2276 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2277 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2280 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2281 // use this information.
2282 APInt KnownZero, KnownOne;
2283 APInt Mask = APInt::getAllOnesValue(VTBits);
2284 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2286 if (KnownZero.isNegative()) { // sign bit is 0
2288 } else if (KnownOne.isNegative()) { // sign bit is 1;
2295 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2296 // the number of identical bits in the top of the input value.
2298 Mask <<= Mask.getBitWidth()-VTBits;
2299 // Return # leading zeros. We use 'min' here in case Val was zero before
2300 // shifting. We don't want to return '64' as for an i32 "0".
2301 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2304 /// isBaseWithConstantOffset - Return true if the specified operand is an
2305 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an
2306 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same
2307 /// semantics as an ADD. This handles the equivalence:
2308 /// X|Cst == X+Cst iff X&Cst = 0.
2309 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
2310 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
2311 !isa<ConstantSDNode>(Op.getOperand(1)))
2314 if (Op.getOpcode() == ISD::OR &&
2315 !MaskedValueIsZero(Op.getOperand(0),
2316 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
2323 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2324 // If we're told that NaNs won't happen, assume they won't.
2328 // If the value is a constant, we can obviously see if it is a NaN or not.
2329 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2330 return !C->getValueAPF().isNaN();
2332 // TODO: Recognize more cases here.
2337 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2338 // If the value is a constant, we can obviously see if it is a zero or not.
2339 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2340 return !C->isZero();
2342 // TODO: Recognize more cases here.
2343 switch (Op.getOpcode()) {
2346 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2347 return !C->isNullValue();
2354 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2355 // Check the obvious case.
2356 if (A == B) return true;
2358 // For for negative and positive zero.
2359 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2360 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2361 if (CA->isZero() && CB->isZero()) return true;
2363 // Otherwise they may not be equal.
2367 /// getNode - Gets or creates the specified node.
2369 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2370 FoldingSetNodeID ID;
2371 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2373 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2374 return SDValue(E, 0);
2376 SDNode *N = new (NodeAllocator) SDNode(Opcode, DL, getVTList(VT));
2377 CSEMap.InsertNode(N, IP);
2379 AllNodes.push_back(N);
2383 return SDValue(N, 0);
2386 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2387 EVT VT, SDValue Operand) {
2388 // Constant fold unary operations with an integer constant operand.
2389 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2390 const APInt &Val = C->getAPIntValue();
2393 case ISD::SIGN_EXTEND:
2394 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT);
2395 case ISD::ANY_EXTEND:
2396 case ISD::ZERO_EXTEND:
2398 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT);
2399 case ISD::UINT_TO_FP:
2400 case ISD::SINT_TO_FP: {
2401 // No compile time operations on ppcf128.
2402 if (VT == MVT::ppcf128) break;
2403 APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
2404 (void)apf.convertFromAPInt(Val,
2405 Opcode==ISD::SINT_TO_FP,
2406 APFloat::rmNearestTiesToEven);
2407 return getConstantFP(apf, VT);
2410 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2411 return getConstantFP(Val.bitsToFloat(), VT);
2412 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2413 return getConstantFP(Val.bitsToDouble(), VT);
2416 return getConstant(Val.byteSwap(), VT);
2418 return getConstant(Val.countPopulation(), VT);
2420 return getConstant(Val.countLeadingZeros(), VT);
2422 return getConstant(Val.countTrailingZeros(), VT);
2426 // Constant fold unary operations with a floating point constant operand.
2427 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2428 APFloat V = C->getValueAPF(); // make copy
2429 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2433 return getConstantFP(V, VT);
2436 return getConstantFP(V, VT);
2438 case ISD::FP_EXTEND: {
2440 // This can return overflow, underflow, or inexact; we don't care.
2441 // FIXME need to be more flexible about rounding mode.
2442 (void)V.convert(*EVTToAPFloatSemantics(VT),
2443 APFloat::rmNearestTiesToEven, &ignored);
2444 return getConstantFP(V, VT);
2446 case ISD::FP_TO_SINT:
2447 case ISD::FP_TO_UINT: {
2450 assert(integerPartWidth >= 64);
2451 // FIXME need to be more flexible about rounding mode.
2452 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2453 Opcode==ISD::FP_TO_SINT,
2454 APFloat::rmTowardZero, &ignored);
2455 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2457 APInt api(VT.getSizeInBits(), x);
2458 return getConstant(api, VT);
2461 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2462 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2463 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2464 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2470 unsigned OpOpcode = Operand.getNode()->getOpcode();
2472 case ISD::TokenFactor:
2473 case ISD::MERGE_VALUES:
2474 case ISD::CONCAT_VECTORS:
2475 return Operand; // Factor, merge or concat of one node? No need.
2476 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2477 case ISD::FP_EXTEND:
2478 assert(VT.isFloatingPoint() &&
2479 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2480 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2481 assert((!VT.isVector() ||
2482 VT.getVectorNumElements() ==
2483 Operand.getValueType().getVectorNumElements()) &&
2484 "Vector element count mismatch!");
2485 if (Operand.getOpcode() == ISD::UNDEF)
2486 return getUNDEF(VT);
2488 case ISD::SIGN_EXTEND:
2489 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2490 "Invalid SIGN_EXTEND!");
2491 if (Operand.getValueType() == VT) return Operand; // noop extension
2492 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2493 "Invalid sext node, dst < src!");
2494 assert((!VT.isVector() ||
2495 VT.getVectorNumElements() ==
2496 Operand.getValueType().getVectorNumElements()) &&
2497 "Vector element count mismatch!");
2498 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2499 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2500 else if (OpOpcode == ISD::UNDEF)
2501 // sext(undef) = 0, because the top bits will all be the same.
2502 return getConstant(0, VT);
2504 case ISD::ZERO_EXTEND:
2505 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2506 "Invalid ZERO_EXTEND!");
2507 if (Operand.getValueType() == VT) return Operand; // noop extension
2508 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2509 "Invalid zext node, dst < src!");
2510 assert((!VT.isVector() ||
2511 VT.getVectorNumElements() ==
2512 Operand.getValueType().getVectorNumElements()) &&
2513 "Vector element count mismatch!");
2514 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2515 return getNode(ISD::ZERO_EXTEND, DL, VT,
2516 Operand.getNode()->getOperand(0));
2517 else if (OpOpcode == ISD::UNDEF)
2518 // zext(undef) = 0, because the top bits will be zero.
2519 return getConstant(0, VT);
2521 case ISD::ANY_EXTEND:
2522 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2523 "Invalid ANY_EXTEND!");
2524 if (Operand.getValueType() == VT) return Operand; // noop extension
2525 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2526 "Invalid anyext node, dst < src!");
2527 assert((!VT.isVector() ||
2528 VT.getVectorNumElements() ==
2529 Operand.getValueType().getVectorNumElements()) &&
2530 "Vector element count mismatch!");
2532 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2533 OpOpcode == ISD::ANY_EXTEND)
2534 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2535 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2536 else if (OpOpcode == ISD::UNDEF)
2537 return getUNDEF(VT);
2539 // (ext (trunx x)) -> x
2540 if (OpOpcode == ISD::TRUNCATE) {
2541 SDValue OpOp = Operand.getNode()->getOperand(0);
2542 if (OpOp.getValueType() == VT)
2547 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2548 "Invalid TRUNCATE!");
2549 if (Operand.getValueType() == VT) return Operand; // noop truncate
2550 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2551 "Invalid truncate node, src < dst!");
2552 assert((!VT.isVector() ||
2553 VT.getVectorNumElements() ==
2554 Operand.getValueType().getVectorNumElements()) &&
2555 "Vector element count mismatch!");
2556 if (OpOpcode == ISD::TRUNCATE)
2557 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2558 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2559 OpOpcode == ISD::ANY_EXTEND) {
2560 // If the source is smaller than the dest, we still need an extend.
2561 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2562 .bitsLT(VT.getScalarType()))
2563 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2564 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2565 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2567 return Operand.getNode()->getOperand(0);
2571 // Basic sanity checking.
2572 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2573 && "Cannot BITCAST between types of different sizes!");
2574 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2575 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
2576 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
2577 if (OpOpcode == ISD::UNDEF)
2578 return getUNDEF(VT);
2580 case ISD::SCALAR_TO_VECTOR:
2581 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2582 (VT.getVectorElementType() == Operand.getValueType() ||
2583 (VT.getVectorElementType().isInteger() &&
2584 Operand.getValueType().isInteger() &&
2585 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2586 "Illegal SCALAR_TO_VECTOR node!");
2587 if (OpOpcode == ISD::UNDEF)
2588 return getUNDEF(VT);
2589 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2590 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2591 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2592 Operand.getConstantOperandVal(1) == 0 &&
2593 Operand.getOperand(0).getValueType() == VT)
2594 return Operand.getOperand(0);
2597 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2598 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2599 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2600 Operand.getNode()->getOperand(0));
2601 if (OpOpcode == ISD::FNEG) // --X -> X
2602 return Operand.getNode()->getOperand(0);
2605 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2606 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2611 SDVTList VTs = getVTList(VT);
2612 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
2613 FoldingSetNodeID ID;
2614 SDValue Ops[1] = { Operand };
2615 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2617 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2618 return SDValue(E, 0);
2620 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTs, Operand);
2621 CSEMap.InsertNode(N, IP);
2623 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTs, Operand);
2626 AllNodes.push_back(N);
2630 return SDValue(N, 0);
2633 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2635 ConstantSDNode *Cst1,
2636 ConstantSDNode *Cst2) {
2637 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2640 case ISD::ADD: return getConstant(C1 + C2, VT);
2641 case ISD::SUB: return getConstant(C1 - C2, VT);
2642 case ISD::MUL: return getConstant(C1 * C2, VT);
2644 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2647 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2650 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2653 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2655 case ISD::AND: return getConstant(C1 & C2, VT);
2656 case ISD::OR: return getConstant(C1 | C2, VT);
2657 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2658 case ISD::SHL: return getConstant(C1 << C2, VT);
2659 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2660 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2661 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2662 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2669 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2670 SDValue N1, SDValue N2) {
2671 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2672 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2675 case ISD::TokenFactor:
2676 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2677 N2.getValueType() == MVT::Other && "Invalid token factor!");
2678 // Fold trivial token factors.
2679 if (N1.getOpcode() == ISD::EntryToken) return N2;
2680 if (N2.getOpcode() == ISD::EntryToken) return N1;
2681 if (N1 == N2) return N1;
2683 case ISD::CONCAT_VECTORS:
2684 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2685 // one big BUILD_VECTOR.
2686 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2687 N2.getOpcode() == ISD::BUILD_VECTOR) {
2688 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
2689 N1.getNode()->op_end());
2690 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
2691 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2695 assert(VT.isInteger() && "This operator does not apply to FP types!");
2696 assert(N1.getValueType() == N2.getValueType() &&
2697 N1.getValueType() == VT && "Binary operator types must match!");
2698 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2699 // worth handling here.
2700 if (N2C && N2C->isNullValue())
2702 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2709 assert(VT.isInteger() && "This operator does not apply to FP types!");
2710 assert(N1.getValueType() == N2.getValueType() &&
2711 N1.getValueType() == VT && "Binary operator types must match!");
2712 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2713 // it's worth handling here.
2714 if (N2C && N2C->isNullValue())
2724 assert(VT.isInteger() && "This operator does not apply to FP types!");
2725 assert(N1.getValueType() == N2.getValueType() &&
2726 N1.getValueType() == VT && "Binary operator types must match!");
2734 if (Opcode == ISD::FADD) {
2736 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2737 if (CFP->getValueAPF().isZero())
2740 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2741 if (CFP->getValueAPF().isZero())
2743 } else if (Opcode == ISD::FSUB) {
2745 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2746 if (CFP->getValueAPF().isZero())
2750 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
2751 assert(N1.getValueType() == N2.getValueType() &&
2752 N1.getValueType() == VT && "Binary operator types must match!");
2754 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2755 assert(N1.getValueType() == VT &&
2756 N1.getValueType().isFloatingPoint() &&
2757 N2.getValueType().isFloatingPoint() &&
2758 "Invalid FCOPYSIGN!");
2765 assert(VT == N1.getValueType() &&
2766 "Shift operators return type must be the same as their first arg");
2767 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2768 "Shifts only work on integers");
2769 // Verify that the shift amount VT is bit enough to hold valid shift
2770 // amounts. This catches things like trying to shift an i1024 value by an
2771 // i8, which is easy to fall into in generic code that uses
2772 // TLI.getShiftAmount().
2773 assert(N2.getValueType().getSizeInBits() >=
2774 Log2_32_Ceil(N1.getValueType().getSizeInBits()) &&
2775 "Invalid use of small shift amount with oversized value!");
2777 // Always fold shifts of i1 values so the code generator doesn't need to
2778 // handle them. Since we know the size of the shift has to be less than the
2779 // size of the value, the shift/rotate count is guaranteed to be zero.
2782 if (N2C && N2C->isNullValue())
2785 case ISD::FP_ROUND_INREG: {
2786 EVT EVT = cast<VTSDNode>(N2)->getVT();
2787 assert(VT == N1.getValueType() && "Not an inreg round!");
2788 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2789 "Cannot FP_ROUND_INREG integer types");
2790 assert(EVT.isVector() == VT.isVector() &&
2791 "FP_ROUND_INREG type should be vector iff the operand "
2793 assert((!EVT.isVector() ||
2794 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2795 "Vector element counts must match in FP_ROUND_INREG");
2796 assert(EVT.bitsLE(VT) && "Not rounding down!");
2797 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2801 assert(VT.isFloatingPoint() &&
2802 N1.getValueType().isFloatingPoint() &&
2803 VT.bitsLE(N1.getValueType()) &&
2804 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2805 if (N1.getValueType() == VT) return N1; // noop conversion.
2807 case ISD::AssertSext:
2808 case ISD::AssertZext: {
2809 EVT EVT = cast<VTSDNode>(N2)->getVT();
2810 assert(VT == N1.getValueType() && "Not an inreg extend!");
2811 assert(VT.isInteger() && EVT.isInteger() &&
2812 "Cannot *_EXTEND_INREG FP types");
2813 assert(!EVT.isVector() &&
2814 "AssertSExt/AssertZExt type should be the vector element type "
2815 "rather than the vector type!");
2816 assert(EVT.bitsLE(VT) && "Not extending!");
2817 if (VT == EVT) return N1; // noop assertion.
2820 case ISD::SIGN_EXTEND_INREG: {
2821 EVT EVT = cast<VTSDNode>(N2)->getVT();
2822 assert(VT == N1.getValueType() && "Not an inreg extend!");
2823 assert(VT.isInteger() && EVT.isInteger() &&
2824 "Cannot *_EXTEND_INREG FP types");
2825 assert(EVT.isVector() == VT.isVector() &&
2826 "SIGN_EXTEND_INREG type should be vector iff the operand "
2828 assert((!EVT.isVector() ||
2829 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2830 "Vector element counts must match in SIGN_EXTEND_INREG");
2831 assert(EVT.bitsLE(VT) && "Not extending!");
2832 if (EVT == VT) return N1; // Not actually extending
2835 APInt Val = N1C->getAPIntValue();
2836 unsigned FromBits = EVT.getScalarType().getSizeInBits();
2837 Val <<= Val.getBitWidth()-FromBits;
2838 Val = Val.ashr(Val.getBitWidth()-FromBits);
2839 return getConstant(Val, VT);
2843 case ISD::EXTRACT_VECTOR_ELT:
2844 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2845 if (N1.getOpcode() == ISD::UNDEF)
2846 return getUNDEF(VT);
2848 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2849 // expanding copies of large vectors from registers.
2851 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2852 N1.getNumOperands() > 0) {
2854 N1.getOperand(0).getValueType().getVectorNumElements();
2855 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2856 N1.getOperand(N2C->getZExtValue() / Factor),
2857 getConstant(N2C->getZExtValue() % Factor,
2858 N2.getValueType()));
2861 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2862 // expanding large vector constants.
2863 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2864 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2865 EVT VEltTy = N1.getValueType().getVectorElementType();
2866 if (Elt.getValueType() != VEltTy) {
2867 // If the vector element type is not legal, the BUILD_VECTOR operands
2868 // are promoted and implicitly truncated. Make that explicit here.
2869 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2872 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2873 // result is implicitly extended.
2874 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2879 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2880 // operations are lowered to scalars.
2881 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2882 // If the indices are the same, return the inserted element else
2883 // if the indices are known different, extract the element from
2884 // the original vector.
2885 SDValue N1Op2 = N1.getOperand(2);
2886 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode());
2888 if (N1Op2C && N2C) {
2889 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
2890 if (VT == N1.getOperand(1).getValueType())
2891 return N1.getOperand(1);
2893 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
2896 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2900 case ISD::EXTRACT_ELEMENT:
2901 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2902 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2903 (N1.getValueType().isInteger() == VT.isInteger()) &&
2904 N1.getValueType() != VT &&
2905 "Wrong types for EXTRACT_ELEMENT!");
2907 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2908 // 64-bit integers into 32-bit parts. Instead of building the extract of
2909 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2910 if (N1.getOpcode() == ISD::BUILD_PAIR)
2911 return N1.getOperand(N2C->getZExtValue());
2913 // EXTRACT_ELEMENT of a constant int is also very common.
2914 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2915 unsigned ElementSize = VT.getSizeInBits();
2916 unsigned Shift = ElementSize * N2C->getZExtValue();
2917 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2918 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2921 case ISD::EXTRACT_SUBVECTOR: {
2923 if (VT.isSimple() && N1.getValueType().isSimple()) {
2924 assert(VT.isVector() && N1.getValueType().isVector() &&
2925 "Extract subvector VTs must be a vectors!");
2926 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType() &&
2927 "Extract subvector VTs must have the same element type!");
2928 assert(VT.getSimpleVT() <= N1.getValueType().getSimpleVT() &&
2929 "Extract subvector must be from larger vector to smaller vector!");
2931 if (isa<ConstantSDNode>(Index.getNode())) {
2932 assert((VT.getVectorNumElements() +
2933 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
2934 <= N1.getValueType().getVectorNumElements())
2935 && "Extract subvector overflow!");
2938 // Trivial extraction.
2939 if (VT.getSimpleVT() == N1.getValueType().getSimpleVT())
2948 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2949 if (SV.getNode()) return SV;
2950 } else { // Cannonicalize constant to RHS if commutative
2951 if (isCommutativeBinOp(Opcode)) {
2952 std::swap(N1C, N2C);
2958 // Constant fold FP operations.
2959 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2960 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2962 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2963 // Cannonicalize constant to RHS if commutative
2964 std::swap(N1CFP, N2CFP);
2966 } else if (N2CFP && VT != MVT::ppcf128) {
2967 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2968 APFloat::opStatus s;
2971 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2972 if (s != APFloat::opInvalidOp)
2973 return getConstantFP(V1, VT);
2976 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2977 if (s!=APFloat::opInvalidOp)
2978 return getConstantFP(V1, VT);
2981 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2982 if (s!=APFloat::opInvalidOp)
2983 return getConstantFP(V1, VT);
2986 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2987 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2988 return getConstantFP(V1, VT);
2991 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2992 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2993 return getConstantFP(V1, VT);
2995 case ISD::FCOPYSIGN:
2997 return getConstantFP(V1, VT);
3003 // Canonicalize an UNDEF to the RHS, even over a constant.
3004 if (N1.getOpcode() == ISD::UNDEF) {
3005 if (isCommutativeBinOp(Opcode)) {
3009 case ISD::FP_ROUND_INREG:
3010 case ISD::SIGN_EXTEND_INREG:
3016 return N1; // fold op(undef, arg2) -> undef
3024 return getConstant(0, VT); // fold op(undef, arg2) -> 0
3025 // For vectors, we can't easily build an all zero vector, just return
3032 // Fold a bunch of operators when the RHS is undef.
3033 if (N2.getOpcode() == ISD::UNDEF) {
3036 if (N1.getOpcode() == ISD::UNDEF)
3037 // Handle undef ^ undef -> 0 special case. This is a common
3039 return getConstant(0, VT);
3049 return N2; // fold op(arg1, undef) -> undef
3063 return getConstant(0, VT); // fold op(arg1, undef) -> 0
3064 // For vectors, we can't easily build an all zero vector, just return
3069 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3070 // For vectors, we can't easily build an all one vector, just return
3078 // Memoize this node if possible.
3080 SDVTList VTs = getVTList(VT);
3081 if (VT != MVT::Glue) {
3082 SDValue Ops[] = { N1, N2 };
3083 FoldingSetNodeID ID;
3084 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
3086 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3087 return SDValue(E, 0);
3089 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTs, N1, N2);
3090 CSEMap.InsertNode(N, IP);
3092 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTs, N1, N2);
3095 AllNodes.push_back(N);
3099 return SDValue(N, 0);
3102 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3103 SDValue N1, SDValue N2, SDValue N3) {
3104 // Perform various simplifications.
3105 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3107 case ISD::CONCAT_VECTORS:
3108 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3109 // one big BUILD_VECTOR.
3110 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3111 N2.getOpcode() == ISD::BUILD_VECTOR &&
3112 N3.getOpcode() == ISD::BUILD_VECTOR) {
3113 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3114 N1.getNode()->op_end());
3115 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3116 Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end());
3117 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
3121 // Use FoldSetCC to simplify SETCC's.
3122 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3123 if (Simp.getNode()) return Simp;
3128 if (N1C->getZExtValue())
3129 return N2; // select true, X, Y -> X
3131 return N3; // select false, X, Y -> Y
3134 if (N2 == N3) return N2; // select C, X, X -> X
3136 case ISD::VECTOR_SHUFFLE:
3137 llvm_unreachable("should use getVectorShuffle constructor!");
3139 case ISD::INSERT_SUBVECTOR: {
3141 if (VT.isSimple() && N1.getValueType().isSimple()
3142 && N2.getValueType().isSimple()) {
3143 assert(VT.isVector() && N1.getValueType().isVector() &&
3144 N2.getValueType().isVector() &&
3145 "Insert subvector VTs must be a vectors");
3146 assert(VT == N1.getValueType() &&
3147 "Dest and insert subvector source types must match!");
3148 assert(N2.getValueType().getSimpleVT() <= N1.getValueType().getSimpleVT() &&
3149 "Insert subvector must be from smaller vector to larger vector!");
3150 if (isa<ConstantSDNode>(Index.getNode())) {
3151 assert((N2.getValueType().getVectorNumElements() +
3152 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3153 <= VT.getVectorNumElements())
3154 && "Insert subvector overflow!");
3157 // Trivial insertion.
3158 if (VT.getSimpleVT() == N2.getValueType().getSimpleVT())
3164 // Fold bit_convert nodes from a type to themselves.
3165 if (N1.getValueType() == VT)
3170 // Memoize node if it doesn't produce a flag.
3172 SDVTList VTs = getVTList(VT);
3173 if (VT != MVT::Glue) {
3174 SDValue Ops[] = { N1, N2, N3 };
3175 FoldingSetNodeID ID;
3176 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3178 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3179 return SDValue(E, 0);
3181 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3182 CSEMap.InsertNode(N, IP);
3184 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3187 AllNodes.push_back(N);
3191 return SDValue(N, 0);
3194 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3195 SDValue N1, SDValue N2, SDValue N3,
3197 SDValue Ops[] = { N1, N2, N3, N4 };
3198 return getNode(Opcode, DL, VT, Ops, 4);
3201 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3202 SDValue N1, SDValue N2, SDValue N3,
3203 SDValue N4, SDValue N5) {
3204 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3205 return getNode(Opcode, DL, VT, Ops, 5);
3208 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3209 /// the incoming stack arguments to be loaded from the stack.
3210 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3211 SmallVector<SDValue, 8> ArgChains;
3213 // Include the original chain at the beginning of the list. When this is
3214 // used by target LowerCall hooks, this helps legalize find the
3215 // CALLSEQ_BEGIN node.
3216 ArgChains.push_back(Chain);
3218 // Add a chain value for each stack argument.
3219 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3220 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3221 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3222 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3223 if (FI->getIndex() < 0)
3224 ArgChains.push_back(SDValue(L, 1));
3226 // Build a tokenfactor for all the chains.
3227 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3228 &ArgChains[0], ArgChains.size());
3231 /// SplatByte - Distribute ByteVal over NumBits bits.
3232 static APInt SplatByte(unsigned NumBits, uint8_t ByteVal) {
3233 APInt Val = APInt(NumBits, ByteVal);
3235 for (unsigned i = NumBits; i > 8; i >>= 1) {
3236 Val = (Val << Shift) | Val;
3242 /// getMemsetValue - Vectorized representation of the memset value
3244 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3246 assert(Value.getOpcode() != ISD::UNDEF);
3248 unsigned NumBits = VT.getScalarType().getSizeInBits();
3249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3250 APInt Val = SplatByte(NumBits, C->getZExtValue() & 255);
3252 return DAG.getConstant(Val, VT);
3253 return DAG.getConstantFP(APFloat(Val), VT);
3256 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3258 // Use a multiplication with 0x010101... to extend the input to the
3260 APInt Magic = SplatByte(NumBits, 0x01);
3261 Value = DAG.getNode(ISD::MUL, dl, VT, Value, DAG.getConstant(Magic, VT));
3267 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3268 /// used when a memcpy is turned into a memset when the source is a constant
3270 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3271 const TargetLowering &TLI,
3272 std::string &Str, unsigned Offset) {
3273 // Handle vector with all elements zero.
3276 return DAG.getConstant(0, VT);
3277 else if (VT == MVT::f32 || VT == MVT::f64)
3278 return DAG.getConstantFP(0.0, VT);
3279 else if (VT.isVector()) {
3280 unsigned NumElts = VT.getVectorNumElements();
3281 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3282 return DAG.getNode(ISD::BITCAST, dl, VT,
3283 DAG.getConstant(0, EVT::getVectorVT(*DAG.getContext(),
3286 llvm_unreachable("Expected type!");
3289 assert(!VT.isVector() && "Can't handle vector type here!");
3290 unsigned NumBits = VT.getSizeInBits();
3291 unsigned MSB = NumBits / 8;
3293 if (TLI.isLittleEndian())
3294 Offset = Offset + MSB - 1;
3295 for (unsigned i = 0; i != MSB; ++i) {
3296 Val = (Val << 8) | (unsigned char)Str[Offset];
3297 Offset += TLI.isLittleEndian() ? -1 : 1;
3299 return DAG.getConstant(Val, VT);
3302 /// getMemBasePlusOffset - Returns base and offset node for the
3304 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3305 SelectionDAG &DAG) {
3306 EVT VT = Base.getValueType();
3307 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3308 VT, Base, DAG.getConstant(Offset, VT));
3311 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3313 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3314 unsigned SrcDelta = 0;
3315 GlobalAddressSDNode *G = NULL;
3316 if (Src.getOpcode() == ISD::GlobalAddress)
3317 G = cast<GlobalAddressSDNode>(Src);
3318 else if (Src.getOpcode() == ISD::ADD &&
3319 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3320 Src.getOperand(1).getOpcode() == ISD::Constant) {
3321 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3322 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3327 const GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3328 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3334 /// FindOptimalMemOpLowering - Determines the optimial series memory ops
3335 /// to replace the memset / memcpy. Return true if the number of memory ops
3336 /// is below the threshold. It returns the types of the sequence of
3337 /// memory ops to perform memset / memcpy by reference.
3338 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
3339 unsigned Limit, uint64_t Size,
3340 unsigned DstAlign, unsigned SrcAlign,
3341 bool NonScalarIntSafe,
3344 const TargetLowering &TLI) {
3345 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
3346 "Expecting memcpy / memset source to meet alignment requirement!");
3347 // If 'SrcAlign' is zero, that means the memory operation does not need to
3348 // load the value, i.e. memset or memcpy from constant string. Otherwise,
3349 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
3350 // is the specified alignment of the memory operation. If it is zero, that
3351 // means it's possible to change the alignment of the destination.
3352 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
3353 // not need to be loaded.
3354 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
3355 NonScalarIntSafe, MemcpyStrSrc,
3356 DAG.getMachineFunction());
3358 if (VT == MVT::Other) {
3359 if (DstAlign >= TLI.getTargetData()->getPointerPrefAlignment() ||
3360 TLI.allowsUnalignedMemoryAccesses(VT)) {
3361 VT = TLI.getPointerTy();
3363 switch (DstAlign & 7) {
3364 case 0: VT = MVT::i64; break;
3365 case 4: VT = MVT::i32; break;
3366 case 2: VT = MVT::i16; break;
3367 default: VT = MVT::i8; break;
3372 while (!TLI.isTypeLegal(LVT))
3373 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3374 assert(LVT.isInteger());
3380 unsigned NumMemOps = 0;
3382 unsigned VTSize = VT.getSizeInBits() / 8;
3383 while (VTSize > Size) {
3384 // For now, only use non-vector load / store's for the left-over pieces.
3385 if (VT.isVector() || VT.isFloatingPoint()) {
3387 while (!TLI.isTypeLegal(VT))
3388 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3389 VTSize = VT.getSizeInBits() / 8;
3391 // This can result in a type that is not legal on the target, e.g.
3392 // 1 or 2 bytes on PPC.
3393 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3398 if (++NumMemOps > Limit)
3400 MemOps.push_back(VT);
3407 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3408 SDValue Chain, SDValue Dst,
3409 SDValue Src, uint64_t Size,
3410 unsigned Align, bool isVol,
3412 MachinePointerInfo DstPtrInfo,
3413 MachinePointerInfo SrcPtrInfo) {
3414 // Turn a memcpy of undef to nop.
3415 if (Src.getOpcode() == ISD::UNDEF)
3418 // Expand memcpy to a series of load and store ops if the size operand falls
3419 // below a certain threshold.
3420 // TODO: In the AlwaysInline case, if the size is big then generate a loop
3421 // rather than maybe a humongous number of loads and stores.
3422 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3423 std::vector<EVT> MemOps;
3424 bool DstAlignCanChange = false;
3425 MachineFunction &MF = DAG.getMachineFunction();
3426 MachineFrameInfo *MFI = MF.getFrameInfo();
3427 bool OptSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
3428 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3429 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3430 DstAlignCanChange = true;
3431 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3432 if (Align > SrcAlign)
3435 bool CopyFromStr = isMemSrcFromString(Src, Str);
3436 bool isZeroStr = CopyFromStr && Str.empty();
3437 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
3439 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3440 (DstAlignCanChange ? 0 : Align),
3441 (isZeroStr ? 0 : SrcAlign),
3442 true, CopyFromStr, DAG, TLI))
3445 if (DstAlignCanChange) {
3446 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3447 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3448 if (NewAlign > Align) {
3449 // Give the stack frame object a larger alignment if needed.
3450 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3451 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3456 SmallVector<SDValue, 8> OutChains;
3457 unsigned NumMemOps = MemOps.size();
3458 uint64_t SrcOff = 0, DstOff = 0;
3459 for (unsigned i = 0; i != NumMemOps; ++i) {
3461 unsigned VTSize = VT.getSizeInBits() / 8;
3462 SDValue Value, Store;
3465 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
3466 // It's unlikely a store of a vector immediate can be done in a single
3467 // instruction. It would require a load from a constantpool first.
3468 // We only handle zero vectors here.
3469 // FIXME: Handle other cases where store of vector immediate is done in
3470 // a single instruction.
3471 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3472 Store = DAG.getStore(Chain, dl, Value,
3473 getMemBasePlusOffset(Dst, DstOff, DAG),
3474 DstPtrInfo.getWithOffset(DstOff), isVol,
3477 // The type might not be legal for the target. This should only happen
3478 // if the type is smaller than a legal type, as on PPC, so the right
3479 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3480 // to Load/Store if NVT==VT.
3481 // FIXME does the case above also need this?
3482 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3483 assert(NVT.bitsGE(VT));
3484 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3485 getMemBasePlusOffset(Src, SrcOff, DAG),
3486 SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false,
3487 MinAlign(SrcAlign, SrcOff));
3488 Store = DAG.getTruncStore(Chain, dl, Value,
3489 getMemBasePlusOffset(Dst, DstOff, DAG),
3490 DstPtrInfo.getWithOffset(DstOff), VT, isVol,
3493 OutChains.push_back(Store);
3498 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3499 &OutChains[0], OutChains.size());
3502 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3503 SDValue Chain, SDValue Dst,
3504 SDValue Src, uint64_t Size,
3505 unsigned Align, bool isVol,
3507 MachinePointerInfo DstPtrInfo,
3508 MachinePointerInfo SrcPtrInfo) {
3509 // Turn a memmove of undef to nop.
3510 if (Src.getOpcode() == ISD::UNDEF)
3513 // Expand memmove to a series of load and store ops if the size operand falls
3514 // below a certain threshold.
3515 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3516 std::vector<EVT> MemOps;
3517 bool DstAlignCanChange = false;
3518 MachineFunction &MF = DAG.getMachineFunction();
3519 MachineFrameInfo *MFI = MF.getFrameInfo();
3520 bool OptSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
3521 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3522 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3523 DstAlignCanChange = true;
3524 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3525 if (Align > SrcAlign)
3527 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
3529 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3530 (DstAlignCanChange ? 0 : Align),
3531 SrcAlign, true, false, DAG, TLI))
3534 if (DstAlignCanChange) {
3535 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3536 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3537 if (NewAlign > Align) {
3538 // Give the stack frame object a larger alignment if needed.
3539 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3540 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3545 uint64_t SrcOff = 0, DstOff = 0;
3546 SmallVector<SDValue, 8> LoadValues;
3547 SmallVector<SDValue, 8> LoadChains;
3548 SmallVector<SDValue, 8> OutChains;
3549 unsigned NumMemOps = MemOps.size();
3550 for (unsigned i = 0; i < NumMemOps; i++) {
3552 unsigned VTSize = VT.getSizeInBits() / 8;
3553 SDValue Value, Store;
3555 Value = DAG.getLoad(VT, dl, Chain,
3556 getMemBasePlusOffset(Src, SrcOff, DAG),
3557 SrcPtrInfo.getWithOffset(SrcOff), isVol,
3559 LoadValues.push_back(Value);
3560 LoadChains.push_back(Value.getValue(1));
3563 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3564 &LoadChains[0], LoadChains.size());
3566 for (unsigned i = 0; i < NumMemOps; i++) {
3568 unsigned VTSize = VT.getSizeInBits() / 8;
3569 SDValue Value, Store;
3571 Store = DAG.getStore(Chain, dl, LoadValues[i],
3572 getMemBasePlusOffset(Dst, DstOff, DAG),
3573 DstPtrInfo.getWithOffset(DstOff), isVol, false, Align);
3574 OutChains.push_back(Store);
3578 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3579 &OutChains[0], OutChains.size());
3582 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3583 SDValue Chain, SDValue Dst,
3584 SDValue Src, uint64_t Size,
3585 unsigned Align, bool isVol,
3586 MachinePointerInfo DstPtrInfo) {
3587 // Turn a memset of undef to nop.
3588 if (Src.getOpcode() == ISD::UNDEF)
3591 // Expand memset to a series of load/store ops if the size operand
3592 // falls below a certain threshold.
3593 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3594 std::vector<EVT> MemOps;
3595 bool DstAlignCanChange = false;
3596 MachineFunction &MF = DAG.getMachineFunction();
3597 MachineFrameInfo *MFI = MF.getFrameInfo();
3598 bool OptSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
3599 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3600 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3601 DstAlignCanChange = true;
3602 bool NonScalarIntSafe =
3603 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
3604 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
3605 Size, (DstAlignCanChange ? 0 : Align), 0,
3606 NonScalarIntSafe, false, DAG, TLI))
3609 if (DstAlignCanChange) {
3610 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3611 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3612 if (NewAlign > Align) {
3613 // Give the stack frame object a larger alignment if needed.
3614 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3615 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3620 SmallVector<SDValue, 8> OutChains;
3621 uint64_t DstOff = 0;
3622 unsigned NumMemOps = MemOps.size();
3624 // Find the largest store and generate the bit pattern for it.
3625 EVT LargestVT = MemOps[0];
3626 for (unsigned i = 1; i < NumMemOps; i++)
3627 if (MemOps[i].bitsGT(LargestVT))
3628 LargestVT = MemOps[i];
3629 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
3631 for (unsigned i = 0; i < NumMemOps; i++) {
3634 // If this store is smaller than the largest store see whether we can get
3635 // the smaller value for free with a truncate.
3636 SDValue Value = MemSetValue;
3637 if (VT.bitsLT(LargestVT)) {
3638 if (!LargestVT.isVector() && !VT.isVector() &&
3639 TLI.isTruncateFree(LargestVT, VT))
3640 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
3642 Value = getMemsetValue(Src, VT, DAG, dl);
3644 assert(Value.getValueType() == VT && "Value with wrong type.");
3645 SDValue Store = DAG.getStore(Chain, dl, Value,
3646 getMemBasePlusOffset(Dst, DstOff, DAG),
3647 DstPtrInfo.getWithOffset(DstOff),
3648 isVol, false, Align);
3649 OutChains.push_back(Store);
3650 DstOff += VT.getSizeInBits() / 8;
3653 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3654 &OutChains[0], OutChains.size());
3657 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3658 SDValue Src, SDValue Size,
3659 unsigned Align, bool isVol, bool AlwaysInline,
3660 MachinePointerInfo DstPtrInfo,
3661 MachinePointerInfo SrcPtrInfo) {
3663 // Check to see if we should lower the memcpy to loads and stores first.
3664 // For cases within the target-specified limits, this is the best choice.
3665 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3667 // Memcpy with size zero? Just return the original chain.
3668 if (ConstantSize->isNullValue())
3671 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3672 ConstantSize->getZExtValue(),Align,
3673 isVol, false, DstPtrInfo, SrcPtrInfo);
3674 if (Result.getNode())
3678 // Then check to see if we should lower the memcpy with target-specific
3679 // code. If the target chooses to do this, this is the next best.
3681 TSI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3682 isVol, AlwaysInline,
3683 DstPtrInfo, SrcPtrInfo);
3684 if (Result.getNode())
3687 // If we really need inline code and the target declined to provide it,
3688 // use a (potentially long) sequence of loads and stores.
3690 assert(ConstantSize && "AlwaysInline requires a constant size!");
3691 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3692 ConstantSize->getZExtValue(), Align, isVol,
3693 true, DstPtrInfo, SrcPtrInfo);
3696 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
3697 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
3698 // respect volatile, so they may do things like read or write memory
3699 // beyond the given memory regions. But fixing this isn't easy, and most
3700 // people don't care.
3702 // Emit a library call.
3703 TargetLowering::ArgListTy Args;
3704 TargetLowering::ArgListEntry Entry;
3705 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3706 Entry.Node = Dst; Args.push_back(Entry);
3707 Entry.Node = Src; Args.push_back(Entry);
3708 Entry.Node = Size; Args.push_back(Entry);
3709 // FIXME: pass in DebugLoc
3710 std::pair<SDValue,SDValue> CallResult =
3711 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3712 false, false, false, false, 0,
3713 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3714 /*isReturnValueUsed=*/false,
3715 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3716 TLI.getPointerTy()),
3718 return CallResult.second;
3721 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3722 SDValue Src, SDValue Size,
3723 unsigned Align, bool isVol,
3724 MachinePointerInfo DstPtrInfo,
3725 MachinePointerInfo SrcPtrInfo) {
3727 // Check to see if we should lower the memmove to loads and stores first.
3728 // For cases within the target-specified limits, this is the best choice.
3729 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3731 // Memmove with size zero? Just return the original chain.
3732 if (ConstantSize->isNullValue())
3736 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3737 ConstantSize->getZExtValue(), Align, isVol,
3738 false, DstPtrInfo, SrcPtrInfo);
3739 if (Result.getNode())
3743 // Then check to see if we should lower the memmove with target-specific
3744 // code. If the target chooses to do this, this is the next best.
3746 TSI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align, isVol,
3747 DstPtrInfo, SrcPtrInfo);
3748 if (Result.getNode())
3751 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
3752 // not be safe. See memcpy above for more details.
3754 // Emit a library call.
3755 TargetLowering::ArgListTy Args;
3756 TargetLowering::ArgListEntry Entry;
3757 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3758 Entry.Node = Dst; Args.push_back(Entry);
3759 Entry.Node = Src; Args.push_back(Entry);
3760 Entry.Node = Size; Args.push_back(Entry);
3761 // FIXME: pass in DebugLoc
3762 std::pair<SDValue,SDValue> CallResult =
3763 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3764 false, false, false, false, 0,
3765 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3766 /*isReturnValueUsed=*/false,
3767 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3768 TLI.getPointerTy()),
3770 return CallResult.second;
3773 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3774 SDValue Src, SDValue Size,
3775 unsigned Align, bool isVol,
3776 MachinePointerInfo DstPtrInfo) {
3778 // Check to see if we should lower the memset to stores first.
3779 // For cases within the target-specified limits, this is the best choice.
3780 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3782 // Memset with size zero? Just return the original chain.
3783 if (ConstantSize->isNullValue())
3787 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3788 Align, isVol, DstPtrInfo);
3790 if (Result.getNode())
3794 // Then check to see if we should lower the memset with target-specific
3795 // code. If the target chooses to do this, this is the next best.
3797 TSI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align, isVol,
3799 if (Result.getNode())
3802 // Emit a library call.
3803 Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3804 TargetLowering::ArgListTy Args;
3805 TargetLowering::ArgListEntry Entry;
3806 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3807 Args.push_back(Entry);
3808 // Extend or truncate the argument to be an i32 value for the call.
3809 if (Src.getValueType().bitsGT(MVT::i32))
3810 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3812 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3814 Entry.Ty = Type::getInt32Ty(*getContext());
3815 Entry.isSExt = true;
3816 Args.push_back(Entry);
3818 Entry.Ty = IntPtrTy;
3819 Entry.isSExt = false;
3820 Args.push_back(Entry);
3821 // FIXME: pass in DebugLoc
3822 std::pair<SDValue,SDValue> CallResult =
3823 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3824 false, false, false, false, 0,
3825 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3826 /*isReturnValueUsed=*/false,
3827 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3828 TLI.getPointerTy()),
3830 return CallResult.second;
3833 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3834 SDValue Chain, SDValue Ptr, SDValue Cmp,
3835 SDValue Swp, MachinePointerInfo PtrInfo,
3837 AtomicOrdering Ordering,
3838 SynchronizationScope SynchScope) {
3839 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3840 Alignment = getEVTAlignment(MemVT);
3842 MachineFunction &MF = getMachineFunction();
3843 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3845 // For now, atomics are considered to be volatile always.
3846 // FIXME: Volatile isn't really correct; we should keep track of atomic
3847 // orderings in the memoperand.
3848 Flags |= MachineMemOperand::MOVolatile;
3850 MachineMemOperand *MMO =
3851 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
3853 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO,
3854 Ordering, SynchScope);
3857 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3859 SDValue Ptr, SDValue Cmp,
3860 SDValue Swp, MachineMemOperand *MMO,
3861 AtomicOrdering Ordering,
3862 SynchronizationScope SynchScope) {
3863 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3864 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3866 EVT VT = Cmp.getValueType();
3868 SDVTList VTs = getVTList(VT, MVT::Other);
3869 FoldingSetNodeID ID;
3870 ID.AddInteger(MemVT.getRawBits());
3871 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3872 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3874 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3875 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3876 return SDValue(E, 0);
3878 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
3879 Ptr, Cmp, Swp, MMO, Ordering,
3881 CSEMap.InsertNode(N, IP);
3882 AllNodes.push_back(N);
3883 return SDValue(N, 0);
3886 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3888 SDValue Ptr, SDValue Val,
3889 const Value* PtrVal,
3891 AtomicOrdering Ordering,
3892 SynchronizationScope SynchScope) {
3893 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3894 Alignment = getEVTAlignment(MemVT);
3896 MachineFunction &MF = getMachineFunction();
3897 // A monotonic store does not load; a release store "loads" in the sense
3898 // that other stores cannot be sunk past it.
3899 // (An atomicrmw obviously both loads and stores.)
3900 unsigned Flags = MachineMemOperand::MOStore;
3901 if (Opcode != ISD::ATOMIC_STORE || Ordering > Monotonic)
3902 Flags |= MachineMemOperand::MOLoad;
3904 // For now, atomics are considered to be volatile always.
3905 // FIXME: Volatile isn't really correct; we should keep track of atomic
3906 // orderings in the memoperand.
3907 Flags |= MachineMemOperand::MOVolatile;
3909 MachineMemOperand *MMO =
3910 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
3911 MemVT.getStoreSize(), Alignment);
3913 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO,
3914 Ordering, SynchScope);
3917 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3919 SDValue Ptr, SDValue Val,
3920 MachineMemOperand *MMO,
3921 AtomicOrdering Ordering,
3922 SynchronizationScope SynchScope) {
3923 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3924 Opcode == ISD::ATOMIC_LOAD_SUB ||
3925 Opcode == ISD::ATOMIC_LOAD_AND ||
3926 Opcode == ISD::ATOMIC_LOAD_OR ||
3927 Opcode == ISD::ATOMIC_LOAD_XOR ||
3928 Opcode == ISD::ATOMIC_LOAD_NAND ||
3929 Opcode == ISD::ATOMIC_LOAD_MIN ||
3930 Opcode == ISD::ATOMIC_LOAD_MAX ||
3931 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3932 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3933 Opcode == ISD::ATOMIC_SWAP ||
3934 Opcode == ISD::ATOMIC_STORE) &&
3935 "Invalid Atomic Op");
3937 EVT VT = Val.getValueType();
3939 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
3940 getVTList(VT, MVT::Other);
3941 FoldingSetNodeID ID;
3942 ID.AddInteger(MemVT.getRawBits());
3943 SDValue Ops[] = {Chain, Ptr, Val};
3944 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3946 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3947 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3948 return SDValue(E, 0);
3950 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
3952 Ordering, SynchScope);
3953 CSEMap.InsertNode(N, IP);
3954 AllNodes.push_back(N);
3955 return SDValue(N, 0);
3958 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3959 EVT VT, SDValue Chain,
3961 const Value* PtrVal,
3963 AtomicOrdering Ordering,
3964 SynchronizationScope SynchScope) {
3965 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3966 Alignment = getEVTAlignment(MemVT);
3968 MachineFunction &MF = getMachineFunction();
3969 // A monotonic load does not store; an acquire load "stores" in the sense
3970 // that other loads cannot be hoisted past it.
3971 unsigned Flags = MachineMemOperand::MOLoad;
3972 if (Ordering > Monotonic)
3973 Flags |= MachineMemOperand::MOStore;
3975 // For now, atomics are considered to be volatile always.
3976 // FIXME: Volatile isn't really correct; we should keep track of atomic
3977 // orderings in the memoperand.
3978 Flags |= MachineMemOperand::MOVolatile;
3980 MachineMemOperand *MMO =
3981 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
3982 MemVT.getStoreSize(), Alignment);
3984 return getAtomic(Opcode, dl, MemVT, VT, Chain, Ptr, MMO,
3985 Ordering, SynchScope);
3988 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3989 EVT VT, SDValue Chain,
3991 MachineMemOperand *MMO,
3992 AtomicOrdering Ordering,
3993 SynchronizationScope SynchScope) {
3994 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
3996 SDVTList VTs = getVTList(VT, MVT::Other);
3997 FoldingSetNodeID ID;
3998 ID.AddInteger(MemVT.getRawBits());
3999 SDValue Ops[] = {Chain, Ptr};
4000 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
4002 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4003 cast<AtomicSDNode>(E)->refineAlignment(MMO);
4004 return SDValue(E, 0);
4006 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
4007 Ptr, MMO, Ordering, SynchScope);
4008 CSEMap.InsertNode(N, IP);
4009 AllNodes.push_back(N);
4010 return SDValue(N, 0);
4013 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4014 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
4019 SmallVector<EVT, 4> VTs;
4020 VTs.reserve(NumOps);
4021 for (unsigned i = 0; i < NumOps; ++i)
4022 VTs.push_back(Ops[i].getValueType());
4023 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
4028 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
4029 const EVT *VTs, unsigned NumVTs,
4030 const SDValue *Ops, unsigned NumOps,
4031 EVT MemVT, MachinePointerInfo PtrInfo,
4032 unsigned Align, bool Vol,
4033 bool ReadMem, bool WriteMem) {
4034 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
4035 MemVT, PtrInfo, Align, Vol,
4040 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
4041 const SDValue *Ops, unsigned NumOps,
4042 EVT MemVT, MachinePointerInfo PtrInfo,
4043 unsigned Align, bool Vol,
4044 bool ReadMem, bool WriteMem) {
4045 if (Align == 0) // Ensure that codegen never sees alignment 0
4046 Align = getEVTAlignment(MemVT);
4048 MachineFunction &MF = getMachineFunction();
4051 Flags |= MachineMemOperand::MOStore;
4053 Flags |= MachineMemOperand::MOLoad;
4055 Flags |= MachineMemOperand::MOVolatile;
4056 MachineMemOperand *MMO =
4057 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Align);
4059 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
4063 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
4064 const SDValue *Ops, unsigned NumOps,
4065 EVT MemVT, MachineMemOperand *MMO) {
4066 assert((Opcode == ISD::INTRINSIC_VOID ||
4067 Opcode == ISD::INTRINSIC_W_CHAIN ||
4068 Opcode == ISD::PREFETCH ||
4069 (Opcode <= INT_MAX &&
4070 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4071 "Opcode is not a memory-accessing opcode!");
4073 // Memoize the node unless it returns a flag.
4074 MemIntrinsicSDNode *N;
4075 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4076 FoldingSetNodeID ID;
4077 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4079 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4080 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
4081 return SDValue(E, 0);
4084 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps,
4086 CSEMap.InsertNode(N, IP);
4088 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps,
4091 AllNodes.push_back(N);
4092 return SDValue(N, 0);
4095 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4096 /// MachinePointerInfo record from it. This is particularly useful because the
4097 /// code generator has many cases where it doesn't bother passing in a
4098 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4099 static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) {
4100 // If this is FI+Offset, we can model it.
4101 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
4102 return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset);
4104 // If this is (FI+Offset1)+Offset2, we can model it.
4105 if (Ptr.getOpcode() != ISD::ADD ||
4106 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
4107 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
4108 return MachinePointerInfo();
4110 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4111 return MachinePointerInfo::getFixedStack(FI, Offset+
4112 cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
4115 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4116 /// MachinePointerInfo record from it. This is particularly useful because the
4117 /// code generator has many cases where it doesn't bother passing in a
4118 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4119 static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) {
4120 // If the 'Offset' value isn't a constant, we can't handle this.
4121 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
4122 return InferPointerInfo(Ptr, OffsetNode->getSExtValue());
4123 if (OffsetOp.getOpcode() == ISD::UNDEF)
4124 return InferPointerInfo(Ptr);
4125 return MachinePointerInfo();
4130 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4131 EVT VT, DebugLoc dl, SDValue Chain,
4132 SDValue Ptr, SDValue Offset,
4133 MachinePointerInfo PtrInfo, EVT MemVT,
4134 bool isVolatile, bool isNonTemporal,
4135 unsigned Alignment, const MDNode *TBAAInfo) {
4136 assert(Chain.getValueType() == MVT::Other &&
4137 "Invalid chain type");
4138 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4139 Alignment = getEVTAlignment(VT);
4141 unsigned Flags = MachineMemOperand::MOLoad;
4143 Flags |= MachineMemOperand::MOVolatile;
4145 Flags |= MachineMemOperand::MONonTemporal;
4147 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
4150 PtrInfo = InferPointerInfo(Ptr, Offset);
4152 MachineFunction &MF = getMachineFunction();
4153 MachineMemOperand *MMO =
4154 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
4156 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
4160 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4161 EVT VT, DebugLoc dl, SDValue Chain,
4162 SDValue Ptr, SDValue Offset, EVT MemVT,
4163 MachineMemOperand *MMO) {
4165 ExtType = ISD::NON_EXTLOAD;
4166 } else if (ExtType == ISD::NON_EXTLOAD) {
4167 assert(VT == MemVT && "Non-extending load from different memory type!");
4170 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
4171 "Should only be an extending load, not truncating!");
4172 assert(VT.isInteger() == MemVT.isInteger() &&
4173 "Cannot convert from FP to Int or Int -> FP!");
4174 assert(VT.isVector() == MemVT.isVector() &&
4175 "Cannot use trunc store to convert to or from a vector!");
4176 assert((!VT.isVector() ||
4177 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
4178 "Cannot use trunc store to change the number of vector elements!");
4181 bool Indexed = AM != ISD::UNINDEXED;
4182 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
4183 "Unindexed load with an offset!");
4185 SDVTList VTs = Indexed ?
4186 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
4187 SDValue Ops[] = { Chain, Ptr, Offset };
4188 FoldingSetNodeID ID;
4189 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
4190 ID.AddInteger(MemVT.getRawBits());
4191 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
4192 MMO->isNonTemporal()));
4194 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4195 cast<LoadSDNode>(E)->refineAlignment(MMO);
4196 return SDValue(E, 0);
4198 SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl, VTs, AM, ExtType,
4200 CSEMap.InsertNode(N, IP);
4201 AllNodes.push_back(N);
4202 return SDValue(N, 0);
4205 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
4206 SDValue Chain, SDValue Ptr,
4207 MachinePointerInfo PtrInfo,
4208 bool isVolatile, bool isNonTemporal,
4209 unsigned Alignment, const MDNode *TBAAInfo) {
4210 SDValue Undef = getUNDEF(Ptr.getValueType());
4211 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4212 PtrInfo, VT, isVolatile, isNonTemporal, Alignment, TBAAInfo);
4215 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
4216 SDValue Chain, SDValue Ptr,
4217 MachinePointerInfo PtrInfo, EVT MemVT,
4218 bool isVolatile, bool isNonTemporal,
4219 unsigned Alignment, const MDNode *TBAAInfo) {
4220 SDValue Undef = getUNDEF(Ptr.getValueType());
4221 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4222 PtrInfo, MemVT, isVolatile, isNonTemporal, Alignment,
4228 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
4229 SDValue Offset, ISD::MemIndexedMode AM) {
4230 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
4231 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
4232 "Load is already a indexed load!");
4233 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
4234 LD->getChain(), Base, Offset, LD->getPointerInfo(),
4236 LD->isVolatile(), LD->isNonTemporal(), LD->getAlignment());
4239 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
4240 SDValue Ptr, MachinePointerInfo PtrInfo,
4241 bool isVolatile, bool isNonTemporal,
4242 unsigned Alignment, const MDNode *TBAAInfo) {
4243 assert(Chain.getValueType() == MVT::Other &&
4244 "Invalid chain type");
4245 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4246 Alignment = getEVTAlignment(Val.getValueType());
4248 unsigned Flags = MachineMemOperand::MOStore;
4250 Flags |= MachineMemOperand::MOVolatile;
4252 Flags |= MachineMemOperand::MONonTemporal;
4255 PtrInfo = InferPointerInfo(Ptr);
4257 MachineFunction &MF = getMachineFunction();
4258 MachineMemOperand *MMO =
4259 MF.getMachineMemOperand(PtrInfo, Flags,
4260 Val.getValueType().getStoreSize(), Alignment,
4263 return getStore(Chain, dl, Val, Ptr, MMO);
4266 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
4267 SDValue Ptr, MachineMemOperand *MMO) {
4268 assert(Chain.getValueType() == MVT::Other &&
4269 "Invalid chain type");
4270 EVT VT = Val.getValueType();
4271 SDVTList VTs = getVTList(MVT::Other);
4272 SDValue Undef = getUNDEF(Ptr.getValueType());
4273 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4274 FoldingSetNodeID ID;
4275 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4276 ID.AddInteger(VT.getRawBits());
4277 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4278 MMO->isNonTemporal()));
4280 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4281 cast<StoreSDNode>(E)->refineAlignment(MMO);
4282 return SDValue(E, 0);
4284 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED,
4286 CSEMap.InsertNode(N, IP);
4287 AllNodes.push_back(N);
4288 return SDValue(N, 0);
4291 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
4292 SDValue Ptr, MachinePointerInfo PtrInfo,
4293 EVT SVT,bool isVolatile, bool isNonTemporal,
4295 const MDNode *TBAAInfo) {
4296 assert(Chain.getValueType() == MVT::Other &&
4297 "Invalid chain type");
4298 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4299 Alignment = getEVTAlignment(SVT);
4301 unsigned Flags = MachineMemOperand::MOStore;
4303 Flags |= MachineMemOperand::MOVolatile;
4305 Flags |= MachineMemOperand::MONonTemporal;
4308 PtrInfo = InferPointerInfo(Ptr);
4310 MachineFunction &MF = getMachineFunction();
4311 MachineMemOperand *MMO =
4312 MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment,
4315 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
4318 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
4319 SDValue Ptr, EVT SVT,
4320 MachineMemOperand *MMO) {
4321 EVT VT = Val.getValueType();
4323 assert(Chain.getValueType() == MVT::Other &&
4324 "Invalid chain type");
4326 return getStore(Chain, dl, Val, Ptr, MMO);
4328 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4329 "Should only be a truncating store, not extending!");
4330 assert(VT.isInteger() == SVT.isInteger() &&
4331 "Can't do FP-INT conversion!");
4332 assert(VT.isVector() == SVT.isVector() &&
4333 "Cannot use trunc store to convert to or from a vector!");
4334 assert((!VT.isVector() ||
4335 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4336 "Cannot use trunc store to change the number of vector elements!");
4338 SDVTList VTs = getVTList(MVT::Other);
4339 SDValue Undef = getUNDEF(Ptr.getValueType());
4340 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4341 FoldingSetNodeID ID;
4342 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4343 ID.AddInteger(SVT.getRawBits());
4344 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4345 MMO->isNonTemporal()));
4347 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4348 cast<StoreSDNode>(E)->refineAlignment(MMO);
4349 return SDValue(E, 0);
4351 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED,
4353 CSEMap.InsertNode(N, IP);
4354 AllNodes.push_back(N);
4355 return SDValue(N, 0);
4359 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
4360 SDValue Offset, ISD::MemIndexedMode AM) {
4361 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4362 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4363 "Store is already a indexed store!");
4364 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4365 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4366 FoldingSetNodeID ID;
4367 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4368 ID.AddInteger(ST->getMemoryVT().getRawBits());
4369 ID.AddInteger(ST->getRawSubclassData());
4371 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4372 return SDValue(E, 0);
4374 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, AM,
4375 ST->isTruncatingStore(),
4377 ST->getMemOperand());
4378 CSEMap.InsertNode(N, IP);
4379 AllNodes.push_back(N);
4380 return SDValue(N, 0);
4383 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
4384 SDValue Chain, SDValue Ptr,
4387 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, MVT::i32) };
4388 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 4);
4391 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4392 const SDUse *Ops, unsigned NumOps) {
4394 case 0: return getNode(Opcode, DL, VT);
4395 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4396 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4397 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4401 // Copy from an SDUse array into an SDValue array for use with
4402 // the regular getNode logic.
4403 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4404 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4407 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4408 const SDValue *Ops, unsigned NumOps) {
4410 case 0: return getNode(Opcode, DL, VT);
4411 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4412 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4413 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4419 case ISD::SELECT_CC: {
4420 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4421 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4422 "LHS and RHS of condition must have same type!");
4423 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4424 "True and False arms of SelectCC must have same type!");
4425 assert(Ops[2].getValueType() == VT &&
4426 "select_cc node must be of same type as true and false value!");
4430 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4431 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4432 "LHS/RHS of comparison should match types!");
4439 SDVTList VTs = getVTList(VT);
4441 if (VT != MVT::Glue) {
4442 FoldingSetNodeID ID;
4443 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4446 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4447 return SDValue(E, 0);
4449 N = new (NodeAllocator) SDNode(Opcode, DL, VTs, Ops, NumOps);
4450 CSEMap.InsertNode(N, IP);
4452 N = new (NodeAllocator) SDNode(Opcode, DL, VTs, Ops, NumOps);
4455 AllNodes.push_back(N);
4459 return SDValue(N, 0);
4462 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4463 const std::vector<EVT> &ResultTys,
4464 const SDValue *Ops, unsigned NumOps) {
4465 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4469 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4470 const EVT *VTs, unsigned NumVTs,
4471 const SDValue *Ops, unsigned NumOps) {
4473 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4474 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4477 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4478 const SDValue *Ops, unsigned NumOps) {
4479 if (VTList.NumVTs == 1)
4480 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4484 // FIXME: figure out how to safely handle things like
4485 // int foo(int x) { return 1 << (x & 255); }
4486 // int bar() { return foo(256); }
4487 case ISD::SRA_PARTS:
4488 case ISD::SRL_PARTS:
4489 case ISD::SHL_PARTS:
4490 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4491 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4492 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4493 else if (N3.getOpcode() == ISD::AND)
4494 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4495 // If the and is only masking out bits that cannot effect the shift,
4496 // eliminate the and.
4497 unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4498 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4499 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4505 // Memoize the node unless it returns a flag.
4507 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4508 FoldingSetNodeID ID;
4509 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4511 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4512 return SDValue(E, 0);
4515 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4516 } else if (NumOps == 2) {
4517 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4518 } else if (NumOps == 3) {
4519 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1],
4522 N = new (NodeAllocator) SDNode(Opcode, DL, VTList, Ops, NumOps);
4524 CSEMap.InsertNode(N, IP);
4527 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4528 } else if (NumOps == 2) {
4529 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4530 } else if (NumOps == 3) {
4531 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1],
4534 N = new (NodeAllocator) SDNode(Opcode, DL, VTList, Ops, NumOps);
4537 AllNodes.push_back(N);
4541 return SDValue(N, 0);
4544 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4545 return getNode(Opcode, DL, VTList, 0, 0);
4548 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4550 SDValue Ops[] = { N1 };
4551 return getNode(Opcode, DL, VTList, Ops, 1);
4554 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4555 SDValue N1, SDValue N2) {
4556 SDValue Ops[] = { N1, N2 };
4557 return getNode(Opcode, DL, VTList, Ops, 2);
4560 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4561 SDValue N1, SDValue N2, SDValue N3) {
4562 SDValue Ops[] = { N1, N2, N3 };
4563 return getNode(Opcode, DL, VTList, Ops, 3);
4566 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4567 SDValue N1, SDValue N2, SDValue N3,
4569 SDValue Ops[] = { N1, N2, N3, N4 };
4570 return getNode(Opcode, DL, VTList, Ops, 4);
4573 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4574 SDValue N1, SDValue N2, SDValue N3,
4575 SDValue N4, SDValue N5) {
4576 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4577 return getNode(Opcode, DL, VTList, Ops, 5);
4580 SDVTList SelectionDAG::getVTList(EVT VT) {
4581 return makeVTList(SDNode::getValueTypeList(VT), 1);
4584 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4585 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4586 E = VTList.rend(); I != E; ++I)
4587 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4590 EVT *Array = Allocator.Allocate<EVT>(2);
4593 SDVTList Result = makeVTList(Array, 2);
4594 VTList.push_back(Result);
4598 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4599 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4600 E = VTList.rend(); I != E; ++I)
4601 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4605 EVT *Array = Allocator.Allocate<EVT>(3);
4609 SDVTList Result = makeVTList(Array, 3);
4610 VTList.push_back(Result);
4614 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4615 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4616 E = VTList.rend(); I != E; ++I)
4617 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4618 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4621 EVT *Array = Allocator.Allocate<EVT>(4);
4626 SDVTList Result = makeVTList(Array, 4);
4627 VTList.push_back(Result);
4631 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4633 case 0: llvm_unreachable("Cannot have nodes without results!");
4634 case 1: return getVTList(VTs[0]);
4635 case 2: return getVTList(VTs[0], VTs[1]);
4636 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4637 case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
4641 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4642 E = VTList.rend(); I != E; ++I) {
4643 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4646 bool NoMatch = false;
4647 for (unsigned i = 2; i != NumVTs; ++i)
4648 if (VTs[i] != I->VTs[i]) {
4656 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4657 std::copy(VTs, VTs+NumVTs, Array);
4658 SDVTList Result = makeVTList(Array, NumVTs);
4659 VTList.push_back(Result);
4664 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4665 /// specified operands. If the resultant node already exists in the DAG,
4666 /// this does not modify the specified node, instead it returns the node that
4667 /// already exists. If the resultant node does not exist in the DAG, the
4668 /// input node is returned. As a degenerate case, if you specify the same
4669 /// input operands as the node already has, the input node is returned.
4670 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
4671 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4673 // Check to see if there is no change.
4674 if (Op == N->getOperand(0)) return N;
4676 // See if the modified node already exists.
4677 void *InsertPos = 0;
4678 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4681 // Nope it doesn't. Remove the node from its current place in the maps.
4683 if (!RemoveNodeFromCSEMaps(N))
4686 // Now we update the operands.
4687 N->OperandList[0].set(Op);
4689 // If this gets put into a CSE map, add it.
4690 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4694 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
4695 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4697 // Check to see if there is no change.
4698 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4699 return N; // No operands changed, just return the input node.
4701 // See if the modified node already exists.
4702 void *InsertPos = 0;
4703 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4706 // Nope it doesn't. Remove the node from its current place in the maps.
4708 if (!RemoveNodeFromCSEMaps(N))
4711 // Now we update the operands.
4712 if (N->OperandList[0] != Op1)
4713 N->OperandList[0].set(Op1);
4714 if (N->OperandList[1] != Op2)
4715 N->OperandList[1].set(Op2);
4717 // If this gets put into a CSE map, add it.
4718 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4722 SDNode *SelectionDAG::
4723 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
4724 SDValue Ops[] = { Op1, Op2, Op3 };
4725 return UpdateNodeOperands(N, Ops, 3);
4728 SDNode *SelectionDAG::
4729 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4730 SDValue Op3, SDValue Op4) {
4731 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4732 return UpdateNodeOperands(N, Ops, 4);
4735 SDNode *SelectionDAG::
4736 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4737 SDValue Op3, SDValue Op4, SDValue Op5) {
4738 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4739 return UpdateNodeOperands(N, Ops, 5);
4742 SDNode *SelectionDAG::
4743 UpdateNodeOperands(SDNode *N, const SDValue *Ops, unsigned NumOps) {
4744 assert(N->getNumOperands() == NumOps &&
4745 "Update with wrong number of operands");
4747 // Check to see if there is no change.
4748 bool AnyChange = false;
4749 for (unsigned i = 0; i != NumOps; ++i) {
4750 if (Ops[i] != N->getOperand(i)) {
4756 // No operands changed, just return the input node.
4757 if (!AnyChange) return N;
4759 // See if the modified node already exists.
4760 void *InsertPos = 0;
4761 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4764 // Nope it doesn't. Remove the node from its current place in the maps.
4766 if (!RemoveNodeFromCSEMaps(N))
4769 // Now we update the operands.
4770 for (unsigned i = 0; i != NumOps; ++i)
4771 if (N->OperandList[i] != Ops[i])
4772 N->OperandList[i].set(Ops[i]);
4774 // If this gets put into a CSE map, add it.
4775 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4779 /// DropOperands - Release the operands and set this node to have
4781 void SDNode::DropOperands() {
4782 // Unlike the code in MorphNodeTo that does this, we don't need to
4783 // watch for dead nodes here.
4784 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4790 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4793 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4795 SDVTList VTs = getVTList(VT);
4796 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4799 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4800 EVT VT, SDValue Op1) {
4801 SDVTList VTs = getVTList(VT);
4802 SDValue Ops[] = { Op1 };
4803 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4806 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4807 EVT VT, SDValue Op1,
4809 SDVTList VTs = getVTList(VT);
4810 SDValue Ops[] = { Op1, Op2 };
4811 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4814 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4815 EVT VT, SDValue Op1,
4816 SDValue Op2, SDValue Op3) {
4817 SDVTList VTs = getVTList(VT);
4818 SDValue Ops[] = { Op1, Op2, Op3 };
4819 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4822 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4823 EVT VT, const SDValue *Ops,
4825 SDVTList VTs = getVTList(VT);
4826 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4829 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4830 EVT VT1, EVT VT2, const SDValue *Ops,
4832 SDVTList VTs = getVTList(VT1, VT2);
4833 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4836 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4838 SDVTList VTs = getVTList(VT1, VT2);
4839 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4842 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4843 EVT VT1, EVT VT2, EVT VT3,
4844 const SDValue *Ops, unsigned NumOps) {
4845 SDVTList VTs = getVTList(VT1, VT2, VT3);
4846 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4849 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4850 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4851 const SDValue *Ops, unsigned NumOps) {
4852 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4853 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4856 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4859 SDVTList VTs = getVTList(VT1, VT2);
4860 SDValue Ops[] = { Op1 };
4861 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4864 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4866 SDValue Op1, SDValue Op2) {
4867 SDVTList VTs = getVTList(VT1, VT2);
4868 SDValue Ops[] = { Op1, Op2 };
4869 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4872 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4874 SDValue Op1, SDValue Op2,
4876 SDVTList VTs = getVTList(VT1, VT2);
4877 SDValue Ops[] = { Op1, Op2, Op3 };
4878 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4881 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4882 EVT VT1, EVT VT2, EVT VT3,
4883 SDValue Op1, SDValue Op2,
4885 SDVTList VTs = getVTList(VT1, VT2, VT3);
4886 SDValue Ops[] = { Op1, Op2, Op3 };
4887 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4890 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4891 SDVTList VTs, const SDValue *Ops,
4893 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4894 // Reset the NodeID to -1.
4899 /// MorphNodeTo - This *mutates* the specified node to have the specified
4900 /// return type, opcode, and operands.
4902 /// Note that MorphNodeTo returns the resultant node. If there is already a
4903 /// node of the specified opcode and operands, it returns that node instead of
4904 /// the current one. Note that the DebugLoc need not be the same.
4906 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4907 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4908 /// node, and because it doesn't require CSE recalculation for any of
4909 /// the node's users.
4911 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4912 SDVTList VTs, const SDValue *Ops,
4914 // If an identical node already exists, use it.
4916 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
4917 FoldingSetNodeID ID;
4918 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4919 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4923 if (!RemoveNodeFromCSEMaps(N))
4926 // Start the morphing.
4928 N->ValueList = VTs.VTs;
4929 N->NumValues = VTs.NumVTs;
4931 // Clear the operands list, updating used nodes to remove this from their
4932 // use list. Keep track of any operands that become dead as a result.
4933 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4934 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4936 SDNode *Used = Use.getNode();
4938 if (Used->use_empty())
4939 DeadNodeSet.insert(Used);
4942 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4943 // Initialize the memory references information.
4944 MN->setMemRefs(0, 0);
4945 // If NumOps is larger than the # of operands we can have in a
4946 // MachineSDNode, reallocate the operand list.
4947 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4948 if (MN->OperandsNeedDelete)
4949 delete[] MN->OperandList;
4950 if (NumOps > array_lengthof(MN->LocalOperands))
4951 // We're creating a final node that will live unmorphed for the
4952 // remainder of the current SelectionDAG iteration, so we can allocate
4953 // the operands directly out of a pool with no recycling metadata.
4954 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4957 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4958 MN->OperandsNeedDelete = false;
4960 MN->InitOperands(MN->OperandList, Ops, NumOps);
4962 // If NumOps is larger than the # of operands we currently have, reallocate
4963 // the operand list.
4964 if (NumOps > N->NumOperands) {
4965 if (N->OperandsNeedDelete)
4966 delete[] N->OperandList;
4967 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4968 N->OperandsNeedDelete = true;
4970 N->InitOperands(N->OperandList, Ops, NumOps);
4973 // Delete any nodes that are still dead after adding the uses for the
4975 if (!DeadNodeSet.empty()) {
4976 SmallVector<SDNode *, 16> DeadNodes;
4977 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4978 E = DeadNodeSet.end(); I != E; ++I)
4979 if ((*I)->use_empty())
4980 DeadNodes.push_back(*I);
4981 RemoveDeadNodes(DeadNodes);
4985 CSEMap.InsertNode(N, IP); // Memoize the new node.
4990 /// getMachineNode - These are used for target selectors to create a new node
4991 /// with specified return type(s), MachineInstr opcode, and operands.
4993 /// Note that getMachineNode returns the resultant node. If there is already a
4994 /// node of the specified opcode and operands, it returns that node instead of
4995 /// the current one.
4997 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4998 SDVTList VTs = getVTList(VT);
4999 return getMachineNode(Opcode, dl, VTs, 0, 0);
5003 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
5004 SDVTList VTs = getVTList(VT);
5005 SDValue Ops[] = { Op1 };
5006 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5010 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
5011 SDValue Op1, SDValue Op2) {
5012 SDVTList VTs = getVTList(VT);
5013 SDValue Ops[] = { Op1, Op2 };
5014 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5018 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
5019 SDValue Op1, SDValue Op2, SDValue Op3) {
5020 SDVTList VTs = getVTList(VT);
5021 SDValue Ops[] = { Op1, Op2, Op3 };
5022 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5026 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
5027 const SDValue *Ops, unsigned NumOps) {
5028 SDVTList VTs = getVTList(VT);
5029 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5033 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
5034 SDVTList VTs = getVTList(VT1, VT2);
5035 return getMachineNode(Opcode, dl, VTs, 0, 0);
5039 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5040 EVT VT1, EVT VT2, SDValue Op1) {
5041 SDVTList VTs = getVTList(VT1, VT2);
5042 SDValue Ops[] = { Op1 };
5043 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5047 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5048 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
5049 SDVTList VTs = getVTList(VT1, VT2);
5050 SDValue Ops[] = { Op1, Op2 };
5051 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5055 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5056 EVT VT1, EVT VT2, SDValue Op1,
5057 SDValue Op2, SDValue Op3) {
5058 SDVTList VTs = getVTList(VT1, VT2);
5059 SDValue Ops[] = { Op1, Op2, Op3 };
5060 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5064 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5066 const SDValue *Ops, unsigned NumOps) {
5067 SDVTList VTs = getVTList(VT1, VT2);
5068 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5072 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5073 EVT VT1, EVT VT2, EVT VT3,
5074 SDValue Op1, SDValue Op2) {
5075 SDVTList VTs = getVTList(VT1, VT2, VT3);
5076 SDValue Ops[] = { Op1, Op2 };
5077 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5081 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5082 EVT VT1, EVT VT2, EVT VT3,
5083 SDValue Op1, SDValue Op2, SDValue Op3) {
5084 SDVTList VTs = getVTList(VT1, VT2, VT3);
5085 SDValue Ops[] = { Op1, Op2, Op3 };
5086 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5090 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5091 EVT VT1, EVT VT2, EVT VT3,
5092 const SDValue *Ops, unsigned NumOps) {
5093 SDVTList VTs = getVTList(VT1, VT2, VT3);
5094 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5098 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
5099 EVT VT2, EVT VT3, EVT VT4,
5100 const SDValue *Ops, unsigned NumOps) {
5101 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5102 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5106 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5107 const std::vector<EVT> &ResultTys,
5108 const SDValue *Ops, unsigned NumOps) {
5109 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
5110 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5114 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
5115 const SDValue *Ops, unsigned NumOps) {
5116 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
5121 FoldingSetNodeID ID;
5122 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
5124 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5125 return cast<MachineSDNode>(E);
5128 // Allocate a new MachineSDNode.
5129 N = new (NodeAllocator) MachineSDNode(~Opcode, DL, VTs);
5131 // Initialize the operands list.
5132 if (NumOps > array_lengthof(N->LocalOperands))
5133 // We're creating a final node that will live unmorphed for the
5134 // remainder of the current SelectionDAG iteration, so we can allocate
5135 // the operands directly out of a pool with no recycling metadata.
5136 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5139 N->InitOperands(N->LocalOperands, Ops, NumOps);
5140 N->OperandsNeedDelete = false;
5143 CSEMap.InsertNode(N, IP);
5145 AllNodes.push_back(N);
5147 VerifyMachineNode(N);
5152 /// getTargetExtractSubreg - A convenience function for creating
5153 /// TargetOpcode::EXTRACT_SUBREG nodes.
5155 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
5157 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5158 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
5159 VT, Operand, SRIdxVal);
5160 return SDValue(Subreg, 0);
5163 /// getTargetInsertSubreg - A convenience function for creating
5164 /// TargetOpcode::INSERT_SUBREG nodes.
5166 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
5167 SDValue Operand, SDValue Subreg) {
5168 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5169 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
5170 VT, Operand, Subreg, SRIdxVal);
5171 return SDValue(Result, 0);
5174 /// getNodeIfExists - Get the specified node if it's already available, or
5175 /// else return NULL.
5176 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
5177 const SDValue *Ops, unsigned NumOps) {
5178 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5179 FoldingSetNodeID ID;
5180 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
5182 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5188 /// getDbgValue - Creates a SDDbgValue node.
5191 SelectionDAG::getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R, uint64_t Off,
5192 DebugLoc DL, unsigned O) {
5193 return new (Allocator) SDDbgValue(MDPtr, N, R, Off, DL, O);
5197 SelectionDAG::getDbgValue(MDNode *MDPtr, const Value *C, uint64_t Off,
5198 DebugLoc DL, unsigned O) {
5199 return new (Allocator) SDDbgValue(MDPtr, C, Off, DL, O);
5203 SelectionDAG::getDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off,
5204 DebugLoc DL, unsigned O) {
5205 return new (Allocator) SDDbgValue(MDPtr, FI, Off, DL, O);
5210 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
5211 /// pointed to by a use iterator is deleted, increment the use iterator
5212 /// so that it doesn't dangle.
5214 /// This class also manages a "downlink" DAGUpdateListener, to forward
5215 /// messages to ReplaceAllUsesWith's callers.
5217 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
5218 SelectionDAG::DAGUpdateListener *DownLink;
5219 SDNode::use_iterator &UI;
5220 SDNode::use_iterator &UE;
5222 virtual void NodeDeleted(SDNode *N, SDNode *E) {
5223 // Increment the iterator as needed.
5224 while (UI != UE && N == *UI)
5227 // Then forward the message.
5228 if (DownLink) DownLink->NodeDeleted(N, E);
5231 virtual void NodeUpdated(SDNode *N) {
5232 // Just forward the message.
5233 if (DownLink) DownLink->NodeUpdated(N);
5237 RAUWUpdateListener(SelectionDAG::DAGUpdateListener *dl,
5238 SDNode::use_iterator &ui,
5239 SDNode::use_iterator &ue)
5240 : DownLink(dl), UI(ui), UE(ue) {}
5245 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5246 /// This can cause recursive merging of nodes in the DAG.
5248 /// This version assumes From has a single result value.
5250 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
5251 DAGUpdateListener *UpdateListener) {
5252 SDNode *From = FromN.getNode();
5253 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
5254 "Cannot replace with this method!");
5255 assert(From != To.getNode() && "Cannot replace uses of with self");
5257 // Iterate over all the existing uses of From. New uses will be added
5258 // to the beginning of the use list, which we avoid visiting.
5259 // This specifically avoids visiting uses of From that arise while the
5260 // replacement is happening, because any such uses would be the result
5261 // of CSE: If an existing node looks like From after one of its operands
5262 // is replaced by To, we don't want to replace of all its users with To
5263 // too. See PR3018 for more info.
5264 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5265 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5269 // This node is about to morph, remove its old self from the CSE maps.
5270 RemoveNodeFromCSEMaps(User);
5272 // A user can appear in a use list multiple times, and when this
5273 // happens the uses are usually next to each other in the list.
5274 // To help reduce the number of CSE recomputations, process all
5275 // the uses of this user that we can find this way.
5277 SDUse &Use = UI.getUse();
5280 } while (UI != UE && *UI == User);
5282 // Now that we have modified User, add it back to the CSE maps. If it
5283 // already exists there, recursively merge the results together.
5284 AddModifiedNodeToCSEMaps(User, &Listener);
5288 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5289 /// This can cause recursive merging of nodes in the DAG.
5291 /// This version assumes that for each value of From, there is a
5292 /// corresponding value in To in the same position with the same type.
5294 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
5295 DAGUpdateListener *UpdateListener) {
5297 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
5298 assert((!From->hasAnyUseOfValue(i) ||
5299 From->getValueType(i) == To->getValueType(i)) &&
5300 "Cannot use this version of ReplaceAllUsesWith!");
5303 // Handle the trivial case.
5307 // Iterate over just the existing users of From. See the comments in
5308 // the ReplaceAllUsesWith above.
5309 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5310 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5314 // This node is about to morph, remove its old self from the CSE maps.
5315 RemoveNodeFromCSEMaps(User);
5317 // A user can appear in a use list multiple times, and when this
5318 // happens the uses are usually next to each other in the list.
5319 // To help reduce the number of CSE recomputations, process all
5320 // the uses of this user that we can find this way.
5322 SDUse &Use = UI.getUse();
5325 } while (UI != UE && *UI == User);
5327 // Now that we have modified User, add it back to the CSE maps. If it
5328 // already exists there, recursively merge the results together.
5329 AddModifiedNodeToCSEMaps(User, &Listener);
5333 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5334 /// This can cause recursive merging of nodes in the DAG.
5336 /// This version can replace From with any result values. To must match the
5337 /// number and types of values returned by From.
5338 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
5340 DAGUpdateListener *UpdateListener) {
5341 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5342 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
5344 // Iterate over just the existing users of From. See the comments in
5345 // the ReplaceAllUsesWith above.
5346 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5347 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5351 // This node is about to morph, remove its old self from the CSE maps.
5352 RemoveNodeFromCSEMaps(User);
5354 // A user can appear in a use list multiple times, and when this
5355 // happens the uses are usually next to each other in the list.
5356 // To help reduce the number of CSE recomputations, process all
5357 // the uses of this user that we can find this way.
5359 SDUse &Use = UI.getUse();
5360 const SDValue &ToOp = To[Use.getResNo()];
5363 } while (UI != UE && *UI == User);
5365 // Now that we have modified User, add it back to the CSE maps. If it
5366 // already exists there, recursively merge the results together.
5367 AddModifiedNodeToCSEMaps(User, &Listener);
5371 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5372 /// uses of other values produced by From.getNode() alone. The Deleted
5373 /// vector is handled the same way as for ReplaceAllUsesWith.
5374 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5375 DAGUpdateListener *UpdateListener){
5376 // Handle the really simple, really trivial case efficiently.
5377 if (From == To) return;
5379 // Handle the simple, trivial, case efficiently.
5380 if (From.getNode()->getNumValues() == 1) {
5381 ReplaceAllUsesWith(From, To, UpdateListener);
5385 // Iterate over just the existing users of From. See the comments in
5386 // the ReplaceAllUsesWith above.
5387 SDNode::use_iterator UI = From.getNode()->use_begin(),
5388 UE = From.getNode()->use_end();
5389 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5392 bool UserRemovedFromCSEMaps = false;
5394 // A user can appear in a use list multiple times, and when this
5395 // happens the uses are usually next to each other in the list.
5396 // To help reduce the number of CSE recomputations, process all
5397 // the uses of this user that we can find this way.
5399 SDUse &Use = UI.getUse();
5401 // Skip uses of different values from the same node.
5402 if (Use.getResNo() != From.getResNo()) {
5407 // If this node hasn't been modified yet, it's still in the CSE maps,
5408 // so remove its old self from the CSE maps.
5409 if (!UserRemovedFromCSEMaps) {
5410 RemoveNodeFromCSEMaps(User);
5411 UserRemovedFromCSEMaps = true;
5416 } while (UI != UE && *UI == User);
5418 // We are iterating over all uses of the From node, so if a use
5419 // doesn't use the specific value, no changes are made.
5420 if (!UserRemovedFromCSEMaps)
5423 // Now that we have modified User, add it back to the CSE maps. If it
5424 // already exists there, recursively merge the results together.
5425 AddModifiedNodeToCSEMaps(User, &Listener);
5430 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5431 /// to record information about a use.
5438 /// operator< - Sort Memos by User.
5439 bool operator<(const UseMemo &L, const UseMemo &R) {
5440 return (intptr_t)L.User < (intptr_t)R.User;
5444 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5445 /// uses of other values produced by From.getNode() alone. The same value
5446 /// may appear in both the From and To list. The Deleted vector is
5447 /// handled the same way as for ReplaceAllUsesWith.
5448 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5451 DAGUpdateListener *UpdateListener){
5452 // Handle the simple, trivial case efficiently.
5454 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5456 // Read up all the uses and make records of them. This helps
5457 // processing new uses that are introduced during the
5458 // replacement process.
5459 SmallVector<UseMemo, 4> Uses;
5460 for (unsigned i = 0; i != Num; ++i) {
5461 unsigned FromResNo = From[i].getResNo();
5462 SDNode *FromNode = From[i].getNode();
5463 for (SDNode::use_iterator UI = FromNode->use_begin(),
5464 E = FromNode->use_end(); UI != E; ++UI) {
5465 SDUse &Use = UI.getUse();
5466 if (Use.getResNo() == FromResNo) {
5467 UseMemo Memo = { *UI, i, &Use };
5468 Uses.push_back(Memo);
5473 // Sort the uses, so that all the uses from a given User are together.
5474 std::sort(Uses.begin(), Uses.end());
5476 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5477 UseIndex != UseIndexEnd; ) {
5478 // We know that this user uses some value of From. If it is the right
5479 // value, update it.
5480 SDNode *User = Uses[UseIndex].User;
5482 // This node is about to morph, remove its old self from the CSE maps.
5483 RemoveNodeFromCSEMaps(User);
5485 // The Uses array is sorted, so all the uses for a given User
5486 // are next to each other in the list.
5487 // To help reduce the number of CSE recomputations, process all
5488 // the uses of this user that we can find this way.
5490 unsigned i = Uses[UseIndex].Index;
5491 SDUse &Use = *Uses[UseIndex].Use;
5495 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5497 // Now that we have modified User, add it back to the CSE maps. If it
5498 // already exists there, recursively merge the results together.
5499 AddModifiedNodeToCSEMaps(User, UpdateListener);
5503 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5504 /// based on their topological order. It returns the maximum id and a vector
5505 /// of the SDNodes* in assigned order by reference.
5506 unsigned SelectionDAG::AssignTopologicalOrder() {
5508 unsigned DAGSize = 0;
5510 // SortedPos tracks the progress of the algorithm. Nodes before it are
5511 // sorted, nodes after it are unsorted. When the algorithm completes
5512 // it is at the end of the list.
5513 allnodes_iterator SortedPos = allnodes_begin();
5515 // Visit all the nodes. Move nodes with no operands to the front of
5516 // the list immediately. Annotate nodes that do have operands with their
5517 // operand count. Before we do this, the Node Id fields of the nodes
5518 // may contain arbitrary values. After, the Node Id fields for nodes
5519 // before SortedPos will contain the topological sort index, and the
5520 // Node Id fields for nodes At SortedPos and after will contain the
5521 // count of outstanding operands.
5522 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5525 unsigned Degree = N->getNumOperands();
5527 // A node with no uses, add it to the result array immediately.
5528 N->setNodeId(DAGSize++);
5529 allnodes_iterator Q = N;
5531 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5532 assert(SortedPos != AllNodes.end() && "Overran node list");
5535 // Temporarily use the Node Id as scratch space for the degree count.
5536 N->setNodeId(Degree);
5540 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5541 // such that by the time the end is reached all nodes will be sorted.
5542 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5545 // N is in sorted position, so all its uses have one less operand
5546 // that needs to be sorted.
5547 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5550 unsigned Degree = P->getNodeId();
5551 assert(Degree != 0 && "Invalid node degree");
5554 // All of P's operands are sorted, so P may sorted now.
5555 P->setNodeId(DAGSize++);
5557 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5558 assert(SortedPos != AllNodes.end() && "Overran node list");
5561 // Update P's outstanding operand count.
5562 P->setNodeId(Degree);
5565 if (I == SortedPos) {
5568 dbgs() << "Overran sorted position:\n";
5571 llvm_unreachable(0);
5575 assert(SortedPos == AllNodes.end() &&
5576 "Topological sort incomplete!");
5577 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5578 "First node in topological sort is not the entry token!");
5579 assert(AllNodes.front().getNodeId() == 0 &&
5580 "First node in topological sort has non-zero id!");
5581 assert(AllNodes.front().getNumOperands() == 0 &&
5582 "First node in topological sort has operands!");
5583 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5584 "Last node in topologic sort has unexpected id!");
5585 assert(AllNodes.back().use_empty() &&
5586 "Last node in topologic sort has users!");
5587 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5591 /// AssignOrdering - Assign an order to the SDNode.
5592 void SelectionDAG::AssignOrdering(const SDNode *SD, unsigned Order) {
5593 assert(SD && "Trying to assign an order to a null node!");
5594 Ordering->add(SD, Order);
5597 /// GetOrdering - Get the order for the SDNode.
5598 unsigned SelectionDAG::GetOrdering(const SDNode *SD) const {
5599 assert(SD && "Trying to get the order of a null node!");
5600 return Ordering->getOrder(SD);
5603 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
5604 /// value is produced by SD.
5605 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
5606 DbgInfo->add(DB, SD, isParameter);
5608 SD->setHasDebugValue(true);
5611 /// TransferDbgValues - Transfer SDDbgValues.
5612 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
5613 if (From == To || !From.getNode()->getHasDebugValue())
5615 SDNode *FromNode = From.getNode();
5616 SDNode *ToNode = To.getNode();
5617 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
5618 SmallVector<SDDbgValue *, 2> ClonedDVs;
5619 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
5621 SDDbgValue *Dbg = *I;
5622 if (Dbg->getKind() == SDDbgValue::SDNODE) {
5623 SDDbgValue *Clone = getDbgValue(Dbg->getMDPtr(), ToNode, To.getResNo(),
5624 Dbg->getOffset(), Dbg->getDebugLoc(),
5626 ClonedDVs.push_back(Clone);
5629 for (SmallVector<SDDbgValue *, 2>::iterator I = ClonedDVs.begin(),
5630 E = ClonedDVs.end(); I != E; ++I)
5631 AddDbgValue(*I, ToNode, false);
5634 //===----------------------------------------------------------------------===//
5636 //===----------------------------------------------------------------------===//
5638 HandleSDNode::~HandleSDNode() {
5642 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, DebugLoc DL,
5643 const GlobalValue *GA,
5644 EVT VT, int64_t o, unsigned char TF)
5645 : SDNode(Opc, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
5649 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5650 MachineMemOperand *mmo)
5651 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5652 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5653 MMO->isNonTemporal());
5654 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5655 assert(isNonTemporal() == MMO->isNonTemporal() &&
5656 "Non-temporal encoding error!");
5657 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5660 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5661 const SDValue *Ops, unsigned NumOps, EVT memvt,
5662 MachineMemOperand *mmo)
5663 : SDNode(Opc, dl, VTs, Ops, NumOps),
5664 MemoryVT(memvt), MMO(mmo) {
5665 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5666 MMO->isNonTemporal());
5667 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5668 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5671 /// Profile - Gather unique data for the node.
5673 void SDNode::Profile(FoldingSetNodeID &ID) const {
5674 AddNodeIDNode(ID, this);
5679 std::vector<EVT> VTs;
5682 VTs.reserve(MVT::LAST_VALUETYPE);
5683 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5684 VTs.push_back(MVT((MVT::SimpleValueType)i));
5689 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5690 static ManagedStatic<EVTArray> SimpleVTArray;
5691 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5693 /// getValueTypeList - Return a pointer to the specified value type.
5695 const EVT *SDNode::getValueTypeList(EVT VT) {
5696 if (VT.isExtended()) {
5697 sys::SmartScopedLock<true> Lock(*VTMutex);
5698 return &(*EVTs->insert(VT).first);
5700 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
5701 "Value type out of range!");
5702 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5706 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5707 /// indicated value. This method ignores uses of other values defined by this
5709 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5710 assert(Value < getNumValues() && "Bad value!");
5712 // TODO: Only iterate over uses of a given value of the node
5713 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5714 if (UI.getUse().getResNo() == Value) {
5721 // Found exactly the right number of uses?
5726 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5727 /// value. This method ignores uses of other values defined by this operation.
5728 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5729 assert(Value < getNumValues() && "Bad value!");
5731 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5732 if (UI.getUse().getResNo() == Value)
5739 /// isOnlyUserOf - Return true if this node is the only use of N.
5741 bool SDNode::isOnlyUserOf(SDNode *N) const {
5743 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5754 /// isOperand - Return true if this node is an operand of N.
5756 bool SDValue::isOperandOf(SDNode *N) const {
5757 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5758 if (*this == N->getOperand(i))
5763 bool SDNode::isOperandOf(SDNode *N) const {
5764 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5765 if (this == N->OperandList[i].getNode())
5770 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5771 /// be a chain) reaches the specified operand without crossing any
5772 /// side-effecting instructions on any chain path. In practice, this looks
5773 /// through token factors and non-volatile loads. In order to remain efficient,
5774 /// this only looks a couple of nodes in, it does not do an exhaustive search.
5775 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5776 unsigned Depth) const {
5777 if (*this == Dest) return true;
5779 // Don't search too deeply, we just want to be able to see through
5780 // TokenFactor's etc.
5781 if (Depth == 0) return false;
5783 // If this is a token factor, all inputs to the TF happen in parallel. If any
5784 // of the operands of the TF does not reach dest, then we cannot do the xform.
5785 if (getOpcode() == ISD::TokenFactor) {
5786 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5787 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5792 // Loads don't have side effects, look through them.
5793 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5794 if (!Ld->isVolatile())
5795 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5800 /// hasPredecessor - Return true if N is a predecessor of this node.
5801 /// N is either an operand of this node, or can be reached by recursively
5802 /// traversing up the operands.
5803 /// NOTE: This is an expensive method. Use it carefully.
5804 bool SDNode::hasPredecessor(const SDNode *N) const {
5805 SmallPtrSet<const SDNode *, 32> Visited;
5806 SmallVector<const SDNode *, 16> Worklist;
5807 return hasPredecessorHelper(N, Visited, Worklist);
5810 bool SDNode::hasPredecessorHelper(const SDNode *N,
5811 SmallPtrSet<const SDNode *, 32> &Visited,
5812 SmallVector<const SDNode *, 16> &Worklist) const {
5813 if (Visited.empty()) {
5814 Worklist.push_back(this);
5816 // Take a look in the visited set. If we've already encountered this node
5817 // we needn't search further.
5818 if (Visited.count(N))
5822 // Haven't visited N yet. Continue the search.
5823 while (!Worklist.empty()) {
5824 const SDNode *M = Worklist.pop_back_val();
5825 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
5826 SDNode *Op = M->getOperand(i).getNode();
5827 if (Visited.insert(Op))
5828 Worklist.push_back(Op);
5837 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5838 assert(Num < NumOperands && "Invalid child # of SDNode!");
5839 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5842 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5843 switch (getOpcode()) {
5845 if (getOpcode() < ISD::BUILTIN_OP_END)
5846 return "<<Unknown DAG Node>>";
5847 if (isMachineOpcode()) {
5849 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5850 if (getMachineOpcode() < TII->getNumOpcodes())
5851 return TII->get(getMachineOpcode()).getName();
5852 return "<<Unknown Machine Node #" + utostr(getOpcode()) + ">>";
5855 const TargetLowering &TLI = G->getTargetLoweringInfo();
5856 const char *Name = TLI.getTargetNodeName(getOpcode());
5857 if (Name) return Name;
5858 return "<<Unknown Target Node #" + utostr(getOpcode()) + ">>";
5860 return "<<Unknown Node #" + utostr(getOpcode()) + ">>";
5863 case ISD::DELETED_NODE:
5864 return "<<Deleted Node!>>";
5866 case ISD::PREFETCH: return "Prefetch";
5867 case ISD::MEMBARRIER: return "MemBarrier";
5868 case ISD::ATOMIC_FENCE: return "AtomicFence";
5869 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5870 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5871 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5872 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5873 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5874 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5875 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5876 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5877 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5878 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5879 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5880 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5881 case ISD::ATOMIC_LOAD: return "AtomicLoad";
5882 case ISD::ATOMIC_STORE: return "AtomicStore";
5883 case ISD::PCMARKER: return "PCMarker";
5884 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5885 case ISD::SRCVALUE: return "SrcValue";
5886 case ISD::MDNODE_SDNODE: return "MDNode";
5887 case ISD::EntryToken: return "EntryToken";
5888 case ISD::TokenFactor: return "TokenFactor";
5889 case ISD::AssertSext: return "AssertSext";
5890 case ISD::AssertZext: return "AssertZext";
5892 case ISD::BasicBlock: return "BasicBlock";
5893 case ISD::VALUETYPE: return "ValueType";
5894 case ISD::Register: return "Register";
5896 case ISD::Constant: return "Constant";
5897 case ISD::ConstantFP: return "ConstantFP";
5898 case ISD::GlobalAddress: return "GlobalAddress";
5899 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5900 case ISD::FrameIndex: return "FrameIndex";
5901 case ISD::JumpTable: return "JumpTable";
5902 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5903 case ISD::RETURNADDR: return "RETURNADDR";
5904 case ISD::FRAMEADDR: return "FRAMEADDR";
5905 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5906 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5907 case ISD::LSDAADDR: return "LSDAADDR";
5908 case ISD::EHSELECTION: return "EHSELECTION";
5909 case ISD::EH_RETURN: return "EH_RETURN";
5910 case ISD::EH_SJLJ_SETJMP: return "EH_SJLJ_SETJMP";
5911 case ISD::EH_SJLJ_LONGJMP: return "EH_SJLJ_LONGJMP";
5912 case ISD::EH_SJLJ_DISPATCHSETUP: return "EH_SJLJ_DISPATCHSETUP";
5913 case ISD::ConstantPool: return "ConstantPool";
5914 case ISD::ExternalSymbol: return "ExternalSymbol";
5915 case ISD::BlockAddress: return "BlockAddress";
5916 case ISD::INTRINSIC_WO_CHAIN:
5917 case ISD::INTRINSIC_VOID:
5918 case ISD::INTRINSIC_W_CHAIN: {
5919 unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5920 unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5921 if (IID < Intrinsic::num_intrinsics)
5922 return Intrinsic::getName((Intrinsic::ID)IID);
5923 else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5924 return TII->getName(IID);
5925 llvm_unreachable("Invalid intrinsic ID");
5928 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5929 case ISD::TargetConstant: return "TargetConstant";
5930 case ISD::TargetConstantFP:return "TargetConstantFP";
5931 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5932 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5933 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5934 case ISD::TargetJumpTable: return "TargetJumpTable";
5935 case ISD::TargetConstantPool: return "TargetConstantPool";
5936 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5937 case ISD::TargetBlockAddress: return "TargetBlockAddress";
5939 case ISD::CopyToReg: return "CopyToReg";
5940 case ISD::CopyFromReg: return "CopyFromReg";
5941 case ISD::UNDEF: return "undef";
5942 case ISD::MERGE_VALUES: return "merge_values";
5943 case ISD::INLINEASM: return "inlineasm";
5944 case ISD::EH_LABEL: return "eh_label";
5945 case ISD::HANDLENODE: return "handlenode";
5948 case ISD::FABS: return "fabs";
5949 case ISD::FNEG: return "fneg";
5950 case ISD::FSQRT: return "fsqrt";
5951 case ISD::FSIN: return "fsin";
5952 case ISD::FCOS: return "fcos";
5953 case ISD::FTRUNC: return "ftrunc";
5954 case ISD::FFLOOR: return "ffloor";
5955 case ISD::FCEIL: return "fceil";
5956 case ISD::FRINT: return "frint";
5957 case ISD::FNEARBYINT: return "fnearbyint";
5958 case ISD::FEXP: return "fexp";
5959 case ISD::FEXP2: return "fexp2";
5960 case ISD::FLOG: return "flog";
5961 case ISD::FLOG2: return "flog2";
5962 case ISD::FLOG10: return "flog10";
5965 case ISD::ADD: return "add";
5966 case ISD::SUB: return "sub";
5967 case ISD::MUL: return "mul";
5968 case ISD::MULHU: return "mulhu";
5969 case ISD::MULHS: return "mulhs";
5970 case ISD::SDIV: return "sdiv";
5971 case ISD::UDIV: return "udiv";
5972 case ISD::SREM: return "srem";
5973 case ISD::UREM: return "urem";
5974 case ISD::SMUL_LOHI: return "smul_lohi";
5975 case ISD::UMUL_LOHI: return "umul_lohi";
5976 case ISD::SDIVREM: return "sdivrem";
5977 case ISD::UDIVREM: return "udivrem";
5978 case ISD::AND: return "and";
5979 case ISD::OR: return "or";
5980 case ISD::XOR: return "xor";
5981 case ISD::SHL: return "shl";
5982 case ISD::SRA: return "sra";
5983 case ISD::SRL: return "srl";
5984 case ISD::ROTL: return "rotl";
5985 case ISD::ROTR: return "rotr";
5986 case ISD::FADD: return "fadd";
5987 case ISD::FSUB: return "fsub";
5988 case ISD::FMUL: return "fmul";
5989 case ISD::FDIV: return "fdiv";
5990 case ISD::FMA: return "fma";
5991 case ISD::FREM: return "frem";
5992 case ISD::FCOPYSIGN: return "fcopysign";
5993 case ISD::FGETSIGN: return "fgetsign";
5994 case ISD::FPOW: return "fpow";
5996 case ISD::FPOWI: return "fpowi";
5997 case ISD::SETCC: return "setcc";
5998 case ISD::SELECT: return "select";
5999 case ISD::VSELECT: return "vselect";
6000 case ISD::SELECT_CC: return "select_cc";
6001 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
6002 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
6003 case ISD::CONCAT_VECTORS: return "concat_vectors";
6004 case ISD::INSERT_SUBVECTOR: return "insert_subvector";
6005 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
6006 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
6007 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
6008 case ISD::CARRY_FALSE: return "carry_false";
6009 case ISD::ADDC: return "addc";
6010 case ISD::ADDE: return "adde";
6011 case ISD::SADDO: return "saddo";
6012 case ISD::UADDO: return "uaddo";
6013 case ISD::SSUBO: return "ssubo";
6014 case ISD::USUBO: return "usubo";
6015 case ISD::SMULO: return "smulo";
6016 case ISD::UMULO: return "umulo";
6017 case ISD::SUBC: return "subc";
6018 case ISD::SUBE: return "sube";
6019 case ISD::SHL_PARTS: return "shl_parts";
6020 case ISD::SRA_PARTS: return "sra_parts";
6021 case ISD::SRL_PARTS: return "srl_parts";
6023 // Conversion operators.
6024 case ISD::SIGN_EXTEND: return "sign_extend";
6025 case ISD::ZERO_EXTEND: return "zero_extend";
6026 case ISD::ANY_EXTEND: return "any_extend";
6027 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
6028 case ISD::TRUNCATE: return "truncate";
6029 case ISD::FP_ROUND: return "fp_round";
6030 case ISD::FLT_ROUNDS_: return "flt_rounds";
6031 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
6032 case ISD::FP_EXTEND: return "fp_extend";
6034 case ISD::SINT_TO_FP: return "sint_to_fp";
6035 case ISD::UINT_TO_FP: return "uint_to_fp";
6036 case ISD::FP_TO_SINT: return "fp_to_sint";
6037 case ISD::FP_TO_UINT: return "fp_to_uint";
6038 case ISD::BITCAST: return "bitcast";
6039 case ISD::FP16_TO_FP32: return "fp16_to_fp32";
6040 case ISD::FP32_TO_FP16: return "fp32_to_fp16";
6042 case ISD::CONVERT_RNDSAT: {
6043 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
6044 default: llvm_unreachable("Unknown cvt code!");
6045 case ISD::CVT_FF: return "cvt_ff";
6046 case ISD::CVT_FS: return "cvt_fs";
6047 case ISD::CVT_FU: return "cvt_fu";
6048 case ISD::CVT_SF: return "cvt_sf";
6049 case ISD::CVT_UF: return "cvt_uf";
6050 case ISD::CVT_SS: return "cvt_ss";
6051 case ISD::CVT_SU: return "cvt_su";
6052 case ISD::CVT_US: return "cvt_us";
6053 case ISD::CVT_UU: return "cvt_uu";
6057 // Control flow instructions
6058 case ISD::BR: return "br";
6059 case ISD::BRIND: return "brind";
6060 case ISD::BR_JT: return "br_jt";
6061 case ISD::BRCOND: return "brcond";
6062 case ISD::BR_CC: return "br_cc";
6063 case ISD::CALLSEQ_START: return "callseq_start";
6064 case ISD::CALLSEQ_END: return "callseq_end";
6067 case ISD::LOAD: return "load";
6068 case ISD::STORE: return "store";
6069 case ISD::VAARG: return "vaarg";
6070 case ISD::VACOPY: return "vacopy";
6071 case ISD::VAEND: return "vaend";
6072 case ISD::VASTART: return "vastart";
6073 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
6074 case ISD::EXTRACT_ELEMENT: return "extract_element";
6075 case ISD::BUILD_PAIR: return "build_pair";
6076 case ISD::STACKSAVE: return "stacksave";
6077 case ISD::STACKRESTORE: return "stackrestore";
6078 case ISD::TRAP: return "trap";
6081 case ISD::BSWAP: return "bswap";
6082 case ISD::CTPOP: return "ctpop";
6083 case ISD::CTTZ: return "cttz";
6084 case ISD::CTLZ: return "ctlz";
6087 case ISD::INIT_TRAMPOLINE: return "init_trampoline";
6088 case ISD::ADJUST_TRAMPOLINE: return "adjust_trampoline";
6091 switch (cast<CondCodeSDNode>(this)->get()) {
6092 default: llvm_unreachable("Unknown setcc condition!");
6093 case ISD::SETOEQ: return "setoeq";
6094 case ISD::SETOGT: return "setogt";
6095 case ISD::SETOGE: return "setoge";
6096 case ISD::SETOLT: return "setolt";
6097 case ISD::SETOLE: return "setole";
6098 case ISD::SETONE: return "setone";
6100 case ISD::SETO: return "seto";
6101 case ISD::SETUO: return "setuo";
6102 case ISD::SETUEQ: return "setue";
6103 case ISD::SETUGT: return "setugt";
6104 case ISD::SETUGE: return "setuge";
6105 case ISD::SETULT: return "setult";
6106 case ISD::SETULE: return "setule";
6107 case ISD::SETUNE: return "setune";
6109 case ISD::SETEQ: return "seteq";
6110 case ISD::SETGT: return "setgt";
6111 case ISD::SETGE: return "setge";
6112 case ISD::SETLT: return "setlt";
6113 case ISD::SETLE: return "setle";
6114 case ISD::SETNE: return "setne";
6119 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
6128 return "<post-inc>";
6130 return "<post-dec>";
6134 std::string ISD::ArgFlagsTy::getArgFlagsString() {
6135 std::string S = "< ";
6149 if (getByValAlign())
6150 S += "byval-align:" + utostr(getByValAlign()) + " ";
6152 S += "orig-align:" + utostr(getOrigAlign()) + " ";
6154 S += "byval-size:" + utostr(getByValSize()) + " ";
6158 void SDNode::dump() const { dump(0); }
6159 void SDNode::dump(const SelectionDAG *G) const {
6164 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
6165 OS << (void*)this << ": ";
6167 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
6169 if (getValueType(i) == MVT::Other)
6172 OS << getValueType(i).getEVTString();
6174 OS << " = " << getOperationName(G);
6177 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
6178 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
6179 if (!MN->memoperands_empty()) {
6182 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
6183 e = MN->memoperands_end(); i != e; ++i) {
6185 if (llvm::next(i) != e)
6190 } else if (const ShuffleVectorSDNode *SVN =
6191 dyn_cast<ShuffleVectorSDNode>(this)) {
6193 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
6194 int Idx = SVN->getMaskElt(i);
6202 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
6203 OS << '<' << CSDN->getAPIntValue() << '>';
6204 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
6205 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
6206 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
6207 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
6208 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
6211 CSDN->getValueAPF().bitcastToAPInt().dump();
6214 } else if (const GlobalAddressSDNode *GADN =
6215 dyn_cast<GlobalAddressSDNode>(this)) {
6216 int64_t offset = GADN->getOffset();
6218 WriteAsOperand(OS, GADN->getGlobal());
6221 OS << " + " << offset;
6223 OS << " " << offset;
6224 if (unsigned int TF = GADN->getTargetFlags())
6225 OS << " [TF=" << TF << ']';
6226 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
6227 OS << "<" << FIDN->getIndex() << ">";
6228 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
6229 OS << "<" << JTDN->getIndex() << ">";
6230 if (unsigned int TF = JTDN->getTargetFlags())
6231 OS << " [TF=" << TF << ']';
6232 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
6233 int offset = CP->getOffset();
6234 if (CP->isMachineConstantPoolEntry())
6235 OS << "<" << *CP->getMachineCPVal() << ">";
6237 OS << "<" << *CP->getConstVal() << ">";
6239 OS << " + " << offset;
6241 OS << " " << offset;
6242 if (unsigned int TF = CP->getTargetFlags())
6243 OS << " [TF=" << TF << ']';
6244 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
6246 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
6248 OS << LBB->getName() << " ";
6249 OS << (const void*)BBDN->getBasicBlock() << ">";
6250 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
6251 OS << ' ' << PrintReg(R->getReg(), G ? G->getTarget().getRegisterInfo() :0);
6252 } else if (const ExternalSymbolSDNode *ES =
6253 dyn_cast<ExternalSymbolSDNode>(this)) {
6254 OS << "'" << ES->getSymbol() << "'";
6255 if (unsigned int TF = ES->getTargetFlags())
6256 OS << " [TF=" << TF << ']';
6257 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
6259 OS << "<" << M->getValue() << ">";
6262 } else if (const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(this)) {
6264 OS << "<" << MD->getMD() << ">";
6267 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
6268 OS << ":" << N->getVT().getEVTString();
6270 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
6271 OS << "<" << *LD->getMemOperand();
6274 switch (LD->getExtensionType()) {
6275 default: doExt = false; break;
6276 case ISD::EXTLOAD: OS << ", anyext"; break;
6277 case ISD::SEXTLOAD: OS << ", sext"; break;
6278 case ISD::ZEXTLOAD: OS << ", zext"; break;
6281 OS << " from " << LD->getMemoryVT().getEVTString();
6283 const char *AM = getIndexedModeName(LD->getAddressingMode());
6288 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
6289 OS << "<" << *ST->getMemOperand();
6291 if (ST->isTruncatingStore())
6292 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
6294 const char *AM = getIndexedModeName(ST->getAddressingMode());
6299 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
6300 OS << "<" << *M->getMemOperand() << ">";
6301 } else if (const BlockAddressSDNode *BA =
6302 dyn_cast<BlockAddressSDNode>(this)) {
6304 WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
6306 WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
6308 if (unsigned int TF = BA->getTargetFlags())
6309 OS << " [TF=" << TF << ']';
6313 if (unsigned Order = G->GetOrdering(this))
6314 OS << " [ORD=" << Order << ']';
6316 if (getNodeId() != -1)
6317 OS << " [ID=" << getNodeId() << ']';
6319 DebugLoc dl = getDebugLoc();
6320 if (G && !dl.isUnknown()) {
6322 Scope(dl.getScope(G->getMachineFunction().getFunction()->getContext()));
6324 // Omit the directory, since it's usually long and uninteresting.
6326 OS << Scope.getFilename();
6329 OS << ':' << dl.getLine();
6330 if (dl.getCol() != 0)
6331 OS << ':' << dl.getCol();
6335 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
6337 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
6338 if (i) OS << ", "; else OS << " ";
6339 OS << (void*)getOperand(i).getNode();
6340 if (unsigned RN = getOperand(i).getResNo())
6343 print_details(OS, G);
6346 static void printrWithDepthHelper(raw_ostream &OS, const SDNode *N,
6347 const SelectionDAG *G, unsigned depth,
6360 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6361 // Don't follow chain operands.
6362 if (N->getOperand(i).getValueType() == MVT::Other)
6365 printrWithDepthHelper(OS, N->getOperand(i).getNode(), G, depth-1, indent+2);
6369 void SDNode::printrWithDepth(raw_ostream &OS, const SelectionDAG *G,
6370 unsigned depth) const {
6371 printrWithDepthHelper(OS, this, G, depth, 0);
6374 void SDNode::printrFull(raw_ostream &OS, const SelectionDAG *G) const {
6375 // Don't print impossibly deep things.
6376 printrWithDepth(OS, G, 10);
6379 void SDNode::dumprWithDepth(const SelectionDAG *G, unsigned depth) const {
6380 printrWithDepth(dbgs(), G, depth);
6383 void SDNode::dumprFull(const SelectionDAG *G) const {
6384 // Don't print impossibly deep things.
6385 dumprWithDepth(G, 10);
6388 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
6389 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6390 if (N->getOperand(i).getNode()->hasOneUse())
6391 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
6393 dbgs() << "\n" << std::string(indent+2, ' ')
6394 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
6398 dbgs().indent(indent);
6402 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6403 assert(N->getNumValues() == 1 &&
6404 "Can't unroll a vector with multiple results!");
6406 EVT VT = N->getValueType(0);
6407 unsigned NE = VT.getVectorNumElements();
6408 EVT EltVT = VT.getVectorElementType();
6409 DebugLoc dl = N->getDebugLoc();
6411 SmallVector<SDValue, 8> Scalars;
6412 SmallVector<SDValue, 4> Operands(N->getNumOperands());
6414 // If ResNE is 0, fully unroll the vector op.
6417 else if (NE > ResNE)
6421 for (i= 0; i != NE; ++i) {
6422 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6423 SDValue Operand = N->getOperand(j);
6424 EVT OperandVT = Operand.getValueType();
6425 if (OperandVT.isVector()) {
6426 // A vector operand; extract a single element.
6427 EVT OperandEltVT = OperandVT.getVectorElementType();
6428 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6431 getConstant(i, TLI.getPointerTy()));
6433 // A scalar operand; just use it as is.
6434 Operands[j] = Operand;
6438 switch (N->getOpcode()) {
6440 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6441 &Operands[0], Operands.size()));
6444 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT,
6445 &Operands[0], Operands.size()));
6452 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6453 getShiftAmountOperand(Operands[0].getValueType(),
6456 case ISD::SIGN_EXTEND_INREG:
6457 case ISD::FP_ROUND_INREG: {
6458 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6459 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6461 getValueType(ExtVT)));
6466 for (; i < ResNE; ++i)
6467 Scalars.push_back(getUNDEF(EltVT));
6469 return getNode(ISD::BUILD_VECTOR, dl,
6470 EVT::getVectorVT(*getContext(), EltVT, ResNE),
6471 &Scalars[0], Scalars.size());
6475 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6476 /// location that is 'Dist' units away from the location that the 'Base' load
6477 /// is loading from.
6478 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6479 unsigned Bytes, int Dist) const {
6480 if (LD->getChain() != Base->getChain())
6482 EVT VT = LD->getValueType(0);
6483 if (VT.getSizeInBits() / 8 != Bytes)
6486 SDValue Loc = LD->getOperand(1);
6487 SDValue BaseLoc = Base->getOperand(1);
6488 if (Loc.getOpcode() == ISD::FrameIndex) {
6489 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6491 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6492 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6493 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6494 int FS = MFI->getObjectSize(FI);
6495 int BFS = MFI->getObjectSize(BFI);
6496 if (FS != BFS || FS != (int)Bytes) return false;
6497 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6501 if (isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
6502 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
6505 const GlobalValue *GV1 = NULL;
6506 const GlobalValue *GV2 = NULL;
6507 int64_t Offset1 = 0;
6508 int64_t Offset2 = 0;
6509 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6510 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6511 if (isGA1 && isGA2 && GV1 == GV2)
6512 return Offset1 == (Offset2 + Dist*Bytes);
6517 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6518 /// it cannot be inferred.
6519 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6520 // If this is a GlobalAddress + cst, return the alignment.
6521 const GlobalValue *GV;
6522 int64_t GVOffset = 0;
6523 if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6524 // If GV has specified alignment, then use it. Otherwise, use the preferred
6526 unsigned Align = GV->getAlignment();
6528 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
6529 if (GVar->hasInitializer()) {
6530 const TargetData *TD = TLI.getTargetData();
6531 Align = TD->getPreferredAlignment(GVar);
6535 return MinAlign(Align, GVOffset);
6538 // If this is a direct reference to a stack slot, use information about the
6539 // stack slot's alignment.
6540 int FrameIdx = 1 << 31;
6541 int64_t FrameOffset = 0;
6542 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6543 FrameIdx = FI->getIndex();
6544 } else if (isBaseWithConstantOffset(Ptr) &&
6545 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6547 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6548 FrameOffset = Ptr.getConstantOperandVal(1);
6551 if (FrameIdx != (1 << 31)) {
6552 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6553 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6561 void SelectionDAG::dump() const {
6562 dbgs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
6564 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6566 const SDNode *N = I;
6567 if (!N->hasOneUse() && N != getRoot().getNode())
6568 DumpNodes(N, 2, this);
6571 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6576 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
6578 print_details(OS, G);
6581 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
6582 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
6583 const SelectionDAG *G, VisitedSDNodeSet &once) {
6584 if (!once.insert(N)) // If we've been here before, return now.
6587 // Dump the current SDNode, but don't end the line yet.
6588 OS << std::string(indent, ' ');
6591 // Having printed this SDNode, walk the children:
6592 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6593 const SDNode *child = N->getOperand(i).getNode();
6598 if (child->getNumOperands() == 0) {
6599 // This child has no grandchildren; print it inline right here.
6600 child->printr(OS, G);
6602 } else { // Just the address. FIXME: also print the child's opcode.
6604 if (unsigned RN = N->getOperand(i).getResNo())
6611 // Dump children that have grandchildren on their own line(s).
6612 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6613 const SDNode *child = N->getOperand(i).getNode();
6614 DumpNodesr(OS, child, indent+2, G, once);
6618 void SDNode::dumpr() const {
6619 VisitedSDNodeSet once;
6620 DumpNodesr(dbgs(), this, 0, 0, once);
6623 void SDNode::dumpr(const SelectionDAG *G) const {
6624 VisitedSDNodeSet once;
6625 DumpNodesr(dbgs(), this, 0, G, once);
6629 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6630 unsigned GlobalAddressSDNode::getAddressSpace() const {
6631 return getGlobal()->getType()->getAddressSpace();
6635 Type *ConstantPoolSDNode::getType() const {
6636 if (isMachineConstantPoolEntry())
6637 return Val.MachineCPVal->getType();
6638 return Val.ConstVal->getType();
6641 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6643 unsigned &SplatBitSize,
6645 unsigned MinSplatBits,
6647 EVT VT = getValueType(0);
6648 assert(VT.isVector() && "Expected a vector type");
6649 unsigned sz = VT.getSizeInBits();
6650 if (MinSplatBits > sz)
6653 SplatValue = APInt(sz, 0);
6654 SplatUndef = APInt(sz, 0);
6656 // Get the bits. Bits with undefined values (when the corresponding element
6657 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6658 // in SplatValue. If any of the values are not constant, give up and return
6660 unsigned int nOps = getNumOperands();
6661 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6662 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6664 for (unsigned j = 0; j < nOps; ++j) {
6665 unsigned i = isBigEndian ? nOps-1-j : j;
6666 SDValue OpVal = getOperand(i);
6667 unsigned BitPos = j * EltBitSize;
6669 if (OpVal.getOpcode() == ISD::UNDEF)
6670 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6671 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6672 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
6673 zextOrTrunc(sz) << BitPos;
6674 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6675 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6680 // The build_vector is all constants or undefs. Find the smallest element
6681 // size that splats the vector.
6683 HasAnyUndefs = (SplatUndef != 0);
6686 unsigned HalfSize = sz / 2;
6687 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
6688 APInt LowValue = SplatValue.trunc(HalfSize);
6689 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
6690 APInt LowUndef = SplatUndef.trunc(HalfSize);
6692 // If the two halves do not match (ignoring undef bits), stop here.
6693 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6694 MinSplatBits > HalfSize)
6697 SplatValue = HighValue | LowValue;
6698 SplatUndef = HighUndef & LowUndef;
6707 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6708 // Find the first non-undef value in the shuffle mask.
6710 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6713 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6715 // Make sure all remaining elements are either undef or the same as the first
6717 for (int Idx = Mask[i]; i != e; ++i)
6718 if (Mask[i] >= 0 && Mask[i] != Idx)
6724 static void checkForCyclesHelper(const SDNode *N,
6725 SmallPtrSet<const SDNode*, 32> &Visited,
6726 SmallPtrSet<const SDNode*, 32> &Checked) {
6727 // If this node has already been checked, don't check it again.
6728 if (Checked.count(N))
6731 // If a node has already been visited on this depth-first walk, reject it as
6733 if (!Visited.insert(N)) {
6734 dbgs() << "Offending node:\n";
6736 errs() << "Detected cycle in SelectionDAG\n";
6740 for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6741 checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
6748 void llvm::checkForCycles(const llvm::SDNode *N) {
6750 assert(N && "Checking nonexistant SDNode");
6751 SmallPtrSet<const SDNode*, 32> visited;
6752 SmallPtrSet<const SDNode*, 32> checked;
6753 checkForCyclesHelper(N, visited, checked);
6757 void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
6758 checkForCycles(DAG->getRoot().getNode());