1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Function.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/System/Mutex.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringExtras.h"
49 /// makeVTList - Return an instance of the SDVTList struct initialized with the
50 /// specified members.
51 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
52 SDVTList Res = {VTs, NumVTs};
56 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
57 switch (VT.getSimpleVT().SimpleTy) {
58 default: llvm_unreachable("Unknown FP format");
59 case MVT::f32: return &APFloat::IEEEsingle;
60 case MVT::f64: return &APFloat::IEEEdouble;
61 case MVT::f80: return &APFloat::x87DoubleExtended;
62 case MVT::f128: return &APFloat::IEEEquad;
63 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
67 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
69 //===----------------------------------------------------------------------===//
70 // ConstantFPSDNode Class
71 //===----------------------------------------------------------------------===//
73 /// isExactlyValue - We don't rely on operator== working on double values, as
74 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
75 /// As such, this method can be used to do an exact bit-for-bit comparison of
76 /// two floating point values.
77 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
78 return getValueAPF().bitwiseIsEqual(V);
81 bool ConstantFPSDNode::isValueValidForType(EVT VT,
83 assert(VT.isFloatingPoint() && "Can only convert between FP types");
85 // PPC long double cannot be converted to any other type.
86 if (VT == MVT::ppcf128 ||
87 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
90 // convert modifies in place, so make a copy.
91 APFloat Val2 = APFloat(Val);
93 (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
98 //===----------------------------------------------------------------------===//
100 //===----------------------------------------------------------------------===//
102 /// isBuildVectorAllOnes - Return true if the specified node is a
103 /// BUILD_VECTOR where all of the elements are ~0 or undef.
104 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
105 // Look through a bit convert.
106 if (N->getOpcode() == ISD::BIT_CONVERT)
107 N = N->getOperand(0).getNode();
109 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
111 unsigned i = 0, e = N->getNumOperands();
113 // Skip over all of the undef values.
114 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
117 // Do not accept an all-undef vector.
118 if (i == e) return false;
120 // Do not accept build_vectors that aren't all constants or which have non-~0
122 SDValue NotZero = N->getOperand(i);
123 if (isa<ConstantSDNode>(NotZero)) {
124 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
126 } else if (isa<ConstantFPSDNode>(NotZero)) {
127 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
128 bitcastToAPInt().isAllOnesValue())
133 // Okay, we have at least one ~0 value, check to see if the rest match or are
135 for (++i; i != e; ++i)
136 if (N->getOperand(i) != NotZero &&
137 N->getOperand(i).getOpcode() != ISD::UNDEF)
143 /// isBuildVectorAllZeros - Return true if the specified node is a
144 /// BUILD_VECTOR where all of the elements are 0 or undef.
145 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
146 // Look through a bit convert.
147 if (N->getOpcode() == ISD::BIT_CONVERT)
148 N = N->getOperand(0).getNode();
150 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
152 unsigned i = 0, e = N->getNumOperands();
154 // Skip over all of the undef values.
155 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
158 // Do not accept an all-undef vector.
159 if (i == e) return false;
161 // Do not accept build_vectors that aren't all constants or which have non-0
163 SDValue Zero = N->getOperand(i);
164 if (isa<ConstantSDNode>(Zero)) {
165 if (!cast<ConstantSDNode>(Zero)->isNullValue())
167 } else if (isa<ConstantFPSDNode>(Zero)) {
168 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
173 // Okay, we have at least one 0 value, check to see if the rest match or are
175 for (++i; i != e; ++i)
176 if (N->getOperand(i) != Zero &&
177 N->getOperand(i).getOpcode() != ISD::UNDEF)
182 /// isScalarToVector - Return true if the specified node is a
183 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
184 /// element is not an undef.
185 bool ISD::isScalarToVector(const SDNode *N) {
186 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
189 if (N->getOpcode() != ISD::BUILD_VECTOR)
191 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
193 unsigned NumElems = N->getNumOperands();
194 for (unsigned i = 1; i < NumElems; ++i) {
195 SDValue V = N->getOperand(i);
196 if (V.getOpcode() != ISD::UNDEF)
203 /// isDebugLabel - Return true if the specified node represents a debug
204 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
205 bool ISD::isDebugLabel(const SDNode *N) {
207 if (N->getOpcode() == ISD::DBG_LABEL)
209 if (N->isMachineOpcode() &&
210 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
215 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
216 /// when given the operation for (X op Y).
217 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
218 // To perform this operation, we just need to swap the L and G bits of the
220 unsigned OldL = (Operation >> 2) & 1;
221 unsigned OldG = (Operation >> 1) & 1;
222 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
223 (OldL << 1) | // New G bit
224 (OldG << 2)); // New L bit.
227 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
228 /// 'op' is a valid SetCC operation.
229 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
230 unsigned Operation = Op;
232 Operation ^= 7; // Flip L, G, E bits, but not U.
234 Operation ^= 15; // Flip all of the condition bits.
236 if (Operation > ISD::SETTRUE2)
237 Operation &= ~8; // Don't let N and U bits get set.
239 return ISD::CondCode(Operation);
243 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
244 /// signed operation and 2 if the result is an unsigned comparison. Return zero
245 /// if the operation does not depend on the sign of the input (setne and seteq).
246 static int isSignedOp(ISD::CondCode Opcode) {
248 default: llvm_unreachable("Illegal integer setcc operation!");
250 case ISD::SETNE: return 0;
254 case ISD::SETGE: return 1;
258 case ISD::SETUGE: return 2;
262 /// getSetCCOrOperation - Return the result of a logical OR between different
263 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
264 /// returns SETCC_INVALID if it is not possible to represent the resultant
266 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
268 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
269 // Cannot fold a signed integer setcc with an unsigned integer setcc.
270 return ISD::SETCC_INVALID;
272 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
274 // If the N and U bits get set then the resultant comparison DOES suddenly
275 // care about orderedness, and is true when ordered.
276 if (Op > ISD::SETTRUE2)
277 Op &= ~16; // Clear the U bit if the N bit is set.
279 // Canonicalize illegal integer setcc's.
280 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
283 return ISD::CondCode(Op);
286 /// getSetCCAndOperation - Return the result of a logical AND between different
287 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
288 /// function returns zero if it is not possible to represent the resultant
290 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
292 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
293 // Cannot fold a signed setcc with an unsigned setcc.
294 return ISD::SETCC_INVALID;
296 // Combine all of the condition bits.
297 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
299 // Canonicalize illegal integer setcc's.
303 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
304 case ISD::SETOEQ: // SETEQ & SETU[LG]E
305 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
306 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
307 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
314 const TargetMachine &SelectionDAG::getTarget() const {
315 return MF->getTarget();
318 //===----------------------------------------------------------------------===//
319 // SDNode Profile Support
320 //===----------------------------------------------------------------------===//
322 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
324 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
328 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
329 /// solely with their pointer.
330 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
331 ID.AddPointer(VTList.VTs);
334 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
336 static void AddNodeIDOperands(FoldingSetNodeID &ID,
337 const SDValue *Ops, unsigned NumOps) {
338 for (; NumOps; --NumOps, ++Ops) {
339 ID.AddPointer(Ops->getNode());
340 ID.AddInteger(Ops->getResNo());
344 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
346 static void AddNodeIDOperands(FoldingSetNodeID &ID,
347 const SDUse *Ops, unsigned NumOps) {
348 for (; NumOps; --NumOps, ++Ops) {
349 ID.AddPointer(Ops->getNode());
350 ID.AddInteger(Ops->getResNo());
354 static void AddNodeIDNode(FoldingSetNodeID &ID,
355 unsigned short OpC, SDVTList VTList,
356 const SDValue *OpList, unsigned N) {
357 AddNodeIDOpcode(ID, OpC);
358 AddNodeIDValueTypes(ID, VTList);
359 AddNodeIDOperands(ID, OpList, N);
362 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
364 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
365 switch (N->getOpcode()) {
366 case ISD::TargetExternalSymbol:
367 case ISD::ExternalSymbol:
368 llvm_unreachable("Should only be used on nodes with operands");
369 default: break; // Normal nodes don't need extra info.
370 case ISD::TargetConstant:
372 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
374 case ISD::TargetConstantFP:
375 case ISD::ConstantFP: {
376 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
379 case ISD::TargetGlobalAddress:
380 case ISD::GlobalAddress:
381 case ISD::TargetGlobalTLSAddress:
382 case ISD::GlobalTLSAddress: {
383 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
384 ID.AddPointer(GA->getGlobal());
385 ID.AddInteger(GA->getOffset());
386 ID.AddInteger(GA->getTargetFlags());
389 case ISD::BasicBlock:
390 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
393 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
395 case ISD::DBG_STOPPOINT: {
396 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
397 ID.AddInteger(DSP->getLine());
398 ID.AddInteger(DSP->getColumn());
399 ID.AddPointer(DSP->getCompileUnit());
403 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
405 case ISD::FrameIndex:
406 case ISD::TargetFrameIndex:
407 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
410 case ISD::TargetJumpTable:
411 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
412 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
414 case ISD::ConstantPool:
415 case ISD::TargetConstantPool: {
416 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
417 ID.AddInteger(CP->getAlignment());
418 ID.AddInteger(CP->getOffset());
419 if (CP->isMachineConstantPoolEntry())
420 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
422 ID.AddPointer(CP->getConstVal());
423 ID.AddInteger(CP->getTargetFlags());
427 const LoadSDNode *LD = cast<LoadSDNode>(N);
428 ID.AddInteger(LD->getMemoryVT().getRawBits());
429 ID.AddInteger(LD->getRawSubclassData());
433 const StoreSDNode *ST = cast<StoreSDNode>(N);
434 ID.AddInteger(ST->getMemoryVT().getRawBits());
435 ID.AddInteger(ST->getRawSubclassData());
438 case ISD::ATOMIC_CMP_SWAP:
439 case ISD::ATOMIC_SWAP:
440 case ISD::ATOMIC_LOAD_ADD:
441 case ISD::ATOMIC_LOAD_SUB:
442 case ISD::ATOMIC_LOAD_AND:
443 case ISD::ATOMIC_LOAD_OR:
444 case ISD::ATOMIC_LOAD_XOR:
445 case ISD::ATOMIC_LOAD_NAND:
446 case ISD::ATOMIC_LOAD_MIN:
447 case ISD::ATOMIC_LOAD_MAX:
448 case ISD::ATOMIC_LOAD_UMIN:
449 case ISD::ATOMIC_LOAD_UMAX: {
450 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
451 ID.AddInteger(AT->getMemoryVT().getRawBits());
452 ID.AddInteger(AT->getRawSubclassData());
455 case ISD::VECTOR_SHUFFLE: {
456 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
457 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
459 ID.AddInteger(SVN->getMaskElt(i));
462 } // end switch (N->getOpcode())
465 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
467 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
468 AddNodeIDOpcode(ID, N->getOpcode());
469 // Add the return value info.
470 AddNodeIDValueTypes(ID, N->getVTList());
471 // Add the operand info.
472 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
474 // Handle SDNode leafs with special info.
475 AddNodeIDCustom(ID, N);
478 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
479 /// the CSE map that carries volatility, indexing mode, and
480 /// extension/truncation information.
482 static inline unsigned
483 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile) {
484 assert((ConvType & 3) == ConvType &&
485 "ConvType may not require more than 2 bits!");
486 assert((AM & 7) == AM &&
487 "AM may not require more than 3 bits!");
493 //===----------------------------------------------------------------------===//
494 // SelectionDAG Class
495 //===----------------------------------------------------------------------===//
497 /// doNotCSE - Return true if CSE should not be performed for this node.
498 static bool doNotCSE(SDNode *N) {
499 if (N->getValueType(0) == MVT::Flag)
500 return true; // Never CSE anything that produces a flag.
502 switch (N->getOpcode()) {
504 case ISD::HANDLENODE:
506 case ISD::DBG_STOPPOINT:
508 return true; // Never CSE these nodes.
511 // Check that remaining values produced are not flags.
512 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
513 if (N->getValueType(i) == MVT::Flag)
514 return true; // Never CSE anything that produces a flag.
519 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
521 void SelectionDAG::RemoveDeadNodes() {
522 // Create a dummy node (which is not added to allnodes), that adds a reference
523 // to the root node, preventing it from being deleted.
524 HandleSDNode Dummy(getRoot());
526 SmallVector<SDNode*, 128> DeadNodes;
528 // Add all obviously-dead nodes to the DeadNodes worklist.
529 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
531 DeadNodes.push_back(I);
533 RemoveDeadNodes(DeadNodes);
535 // If the root changed (e.g. it was a dead load, update the root).
536 setRoot(Dummy.getValue());
539 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
540 /// given list, and any nodes that become unreachable as a result.
541 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
542 DAGUpdateListener *UpdateListener) {
544 // Process the worklist, deleting the nodes and adding their uses to the
546 while (!DeadNodes.empty()) {
547 SDNode *N = DeadNodes.pop_back_val();
550 UpdateListener->NodeDeleted(N, 0);
552 // Take the node out of the appropriate CSE map.
553 RemoveNodeFromCSEMaps(N);
555 // Next, brutally remove the operand list. This is safe to do, as there are
556 // no cycles in the graph.
557 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
559 SDNode *Operand = Use.getNode();
562 // Now that we removed this operand, see if there are no uses of it left.
563 if (Operand->use_empty())
564 DeadNodes.push_back(Operand);
571 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
572 SmallVector<SDNode*, 16> DeadNodes(1, N);
573 RemoveDeadNodes(DeadNodes, UpdateListener);
576 void SelectionDAG::DeleteNode(SDNode *N) {
577 // First take this out of the appropriate CSE map.
578 RemoveNodeFromCSEMaps(N);
580 // Finally, remove uses due to operands of this node, remove from the
581 // AllNodes list, and delete the node.
582 DeleteNodeNotInCSEMaps(N);
585 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
586 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
587 assert(N->use_empty() && "Cannot delete a node that is not dead!");
589 // Drop all of the operands and decrement used node's use counts.
595 void SelectionDAG::DeallocateNode(SDNode *N) {
596 if (N->OperandsNeedDelete)
597 delete[] N->OperandList;
599 // Set the opcode to DELETED_NODE to help catch bugs when node
600 // memory is reallocated.
601 N->NodeType = ISD::DELETED_NODE;
603 NodeAllocator.Deallocate(AllNodes.remove(N));
606 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
607 /// correspond to it. This is useful when we're about to delete or repurpose
608 /// the node. We don't want future request for structurally identical nodes
609 /// to return N anymore.
610 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
612 switch (N->getOpcode()) {
613 case ISD::EntryToken:
614 llvm_unreachable("EntryToken should not be in CSEMaps!");
616 case ISD::HANDLENODE: return false; // noop.
618 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
619 "Cond code doesn't exist!");
620 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
621 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
623 case ISD::ExternalSymbol:
624 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
626 case ISD::TargetExternalSymbol: {
627 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
628 Erased = TargetExternalSymbols.erase(
629 std::pair<std::string,unsigned char>(ESN->getSymbol(),
630 ESN->getTargetFlags()));
633 case ISD::VALUETYPE: {
634 EVT VT = cast<VTSDNode>(N)->getVT();
635 if (VT.isExtended()) {
636 Erased = ExtendedValueTypeNodes.erase(VT);
638 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
639 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
644 // Remove it from the CSE Map.
645 Erased = CSEMap.RemoveNode(N);
649 // Verify that the node was actually in one of the CSE maps, unless it has a
650 // flag result (which cannot be CSE'd) or is one of the special cases that are
651 // not subject to CSE.
652 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
653 !N->isMachineOpcode() && !doNotCSE(N)) {
656 llvm_unreachable("Node is not in map!");
662 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
663 /// maps and modified in place. Add it back to the CSE maps, unless an identical
664 /// node already exists, in which case transfer all its users to the existing
665 /// node. This transfer can potentially trigger recursive merging.
668 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
669 DAGUpdateListener *UpdateListener) {
670 // For node types that aren't CSE'd, just act as if no identical node
673 SDNode *Existing = CSEMap.GetOrInsertNode(N);
675 // If there was already an existing matching node, use ReplaceAllUsesWith
676 // to replace the dead one with the existing one. This can cause
677 // recursive merging of other unrelated nodes down the line.
678 ReplaceAllUsesWith(N, Existing, UpdateListener);
680 // N is now dead. Inform the listener if it exists and delete it.
682 UpdateListener->NodeDeleted(N, Existing);
683 DeleteNodeNotInCSEMaps(N);
688 // If the node doesn't already exist, we updated it. Inform a listener if
691 UpdateListener->NodeUpdated(N);
694 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
695 /// were replaced with those specified. If this node is never memoized,
696 /// return null, otherwise return a pointer to the slot it would take. If a
697 /// node already exists with these operands, the slot will be non-null.
698 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
703 SDValue Ops[] = { Op };
705 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
706 AddNodeIDCustom(ID, N);
707 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
710 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
711 /// were replaced with those specified. If this node is never memoized,
712 /// return null, otherwise return a pointer to the slot it would take. If a
713 /// node already exists with these operands, the slot will be non-null.
714 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
715 SDValue Op1, SDValue Op2,
720 SDValue Ops[] = { Op1, Op2 };
722 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
723 AddNodeIDCustom(ID, N);
724 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
728 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
729 /// were replaced with those specified. If this node is never memoized,
730 /// return null, otherwise return a pointer to the slot it would take. If a
731 /// node already exists with these operands, the slot will be non-null.
732 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
733 const SDValue *Ops,unsigned NumOps,
739 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
740 AddNodeIDCustom(ID, N);
741 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
744 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
745 void SelectionDAG::VerifyNode(SDNode *N) {
746 switch (N->getOpcode()) {
749 case ISD::BUILD_PAIR: {
750 EVT VT = N->getValueType(0);
751 assert(N->getNumValues() == 1 && "Too many results!");
752 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
753 "Wrong return type!");
754 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
755 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
756 "Mismatched operand types!");
757 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
758 "Wrong operand type!");
759 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
760 "Wrong return type size");
763 case ISD::BUILD_VECTOR: {
764 assert(N->getNumValues() == 1 && "Too many results!");
765 assert(N->getValueType(0).isVector() && "Wrong return type!");
766 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
767 "Wrong number of operands!");
768 EVT EltVT = N->getValueType(0).getVectorElementType();
769 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
770 assert((I->getValueType() == EltVT ||
771 (EltVT.isInteger() && I->getValueType().isInteger() &&
772 EltVT.bitsLE(I->getValueType()))) &&
773 "Wrong operand type!");
779 /// getEVTAlignment - Compute the default alignment value for the
782 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
783 const Type *Ty = VT == MVT::iPTR ?
784 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
785 VT.getTypeForEVT(*getContext());
787 return TLI.getTargetData()->getABITypeAlignment(Ty);
790 // EntryNode could meaningfully have debug info if we can find it...
791 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
792 : TLI(tli), FLI(fli), DW(0),
793 EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
794 getVTList(MVT::Other)), Root(getEntryNode()) {
795 AllNodes.push_back(&EntryNode);
798 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
803 Context = &mf.getFunction()->getContext();
806 SelectionDAG::~SelectionDAG() {
810 void SelectionDAG::allnodes_clear() {
811 assert(&*AllNodes.begin() == &EntryNode);
812 AllNodes.remove(AllNodes.begin());
813 while (!AllNodes.empty())
814 DeallocateNode(AllNodes.begin());
817 void SelectionDAG::clear() {
819 OperandAllocator.Reset();
822 ExtendedValueTypeNodes.clear();
823 ExternalSymbols.clear();
824 TargetExternalSymbols.clear();
825 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
826 static_cast<CondCodeSDNode*>(0));
827 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
828 static_cast<SDNode*>(0));
830 EntryNode.UseList = 0;
831 AllNodes.push_back(&EntryNode);
832 Root = getEntryNode();
835 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
836 return VT.bitsGT(Op.getValueType()) ?
837 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
838 getNode(ISD::TRUNCATE, DL, VT, Op);
841 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
842 return VT.bitsGT(Op.getValueType()) ?
843 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
844 getNode(ISD::TRUNCATE, DL, VT, Op);
847 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
848 if (Op.getValueType() == VT) return Op;
849 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
851 return getNode(ISD::AND, DL, Op.getValueType(), Op,
852 getConstant(Imm, Op.getValueType()));
855 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
857 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
858 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
860 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
861 return getNode(ISD::XOR, DL, VT, Val, NegOne);
864 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
865 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
866 assert((EltVT.getSizeInBits() >= 64 ||
867 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
868 "getConstant with a uint64_t value that doesn't fit in the type!");
869 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
872 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
873 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
876 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
877 assert(VT.isInteger() && "Cannot create FP integer constant!");
879 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
880 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
881 "APInt size does not match type size!");
883 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
885 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
889 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
891 return SDValue(N, 0);
893 N = NodeAllocator.Allocate<ConstantSDNode>();
894 new (N) ConstantSDNode(isT, &Val, EltVT);
895 CSEMap.InsertNode(N, IP);
896 AllNodes.push_back(N);
899 SDValue Result(N, 0);
901 SmallVector<SDValue, 8> Ops;
902 Ops.assign(VT.getVectorNumElements(), Result);
903 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
904 VT, &Ops[0], Ops.size());
909 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
910 return getConstant(Val, TLI.getPointerTy(), isTarget);
914 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
915 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
918 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
919 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
922 VT.isVector() ? VT.getVectorElementType() : VT;
924 // Do the map lookup using the actual bit pattern for the floating point
925 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
926 // we don't have issues with SNANs.
927 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
929 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
933 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
935 return SDValue(N, 0);
937 N = NodeAllocator.Allocate<ConstantFPSDNode>();
938 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
939 CSEMap.InsertNode(N, IP);
940 AllNodes.push_back(N);
943 SDValue Result(N, 0);
945 SmallVector<SDValue, 8> Ops;
946 Ops.assign(VT.getVectorNumElements(), Result);
947 // FIXME DebugLoc info might be appropriate here
948 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
949 VT, &Ops[0], Ops.size());
954 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
956 VT.isVector() ? VT.getVectorElementType() : VT;
958 return getConstantFP(APFloat((float)Val), VT, isTarget);
960 return getConstantFP(APFloat(Val), VT, isTarget);
963 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
964 EVT VT, int64_t Offset,
966 unsigned char TargetFlags) {
967 assert((TargetFlags == 0 || isTargetGA) &&
968 "Cannot set target flags on target-independent globals");
970 // Truncate (with sign-extension) the offset value to the pointer size.
971 EVT PTy = TLI.getPointerTy();
972 unsigned BitWidth = PTy.getSizeInBits();
974 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
976 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
978 // If GV is an alias then use the aliasee for determining thread-localness.
979 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
980 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
984 if (GVar && GVar->isThreadLocal())
985 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
987 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
990 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
992 ID.AddInteger(Offset);
993 ID.AddInteger(TargetFlags);
995 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
996 return SDValue(E, 0);
997 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
998 new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags);
999 CSEMap.InsertNode(N, IP);
1000 AllNodes.push_back(N);
1001 return SDValue(N, 0);
1004 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1005 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1006 FoldingSetNodeID ID;
1007 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1010 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1011 return SDValue(E, 0);
1012 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
1013 new (N) FrameIndexSDNode(FI, VT, isTarget);
1014 CSEMap.InsertNode(N, IP);
1015 AllNodes.push_back(N);
1016 return SDValue(N, 0);
1019 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1020 unsigned char TargetFlags) {
1021 assert((TargetFlags == 0 || isTarget) &&
1022 "Cannot set target flags on target-independent jump tables");
1023 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1024 FoldingSetNodeID ID;
1025 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1027 ID.AddInteger(TargetFlags);
1029 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1030 return SDValue(E, 0);
1031 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1032 new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags);
1033 CSEMap.InsertNode(N, IP);
1034 AllNodes.push_back(N);
1035 return SDValue(N, 0);
1038 SDValue SelectionDAG::getConstantPool(Constant *C, EVT VT,
1039 unsigned Alignment, int Offset,
1041 unsigned char TargetFlags) {
1042 assert((TargetFlags == 0 || isTarget) &&
1043 "Cannot set target flags on target-independent globals");
1045 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1046 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1047 FoldingSetNodeID ID;
1048 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1049 ID.AddInteger(Alignment);
1050 ID.AddInteger(Offset);
1052 ID.AddInteger(TargetFlags);
1054 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1055 return SDValue(E, 0);
1056 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1057 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1058 CSEMap.InsertNode(N, IP);
1059 AllNodes.push_back(N);
1060 return SDValue(N, 0);
1064 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1065 unsigned Alignment, int Offset,
1067 unsigned char TargetFlags) {
1068 assert((TargetFlags == 0 || isTarget) &&
1069 "Cannot set target flags on target-independent globals");
1071 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1072 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1073 FoldingSetNodeID ID;
1074 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1075 ID.AddInteger(Alignment);
1076 ID.AddInteger(Offset);
1077 C->AddSelectionDAGCSEId(ID);
1078 ID.AddInteger(TargetFlags);
1080 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1081 return SDValue(E, 0);
1082 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1083 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1084 CSEMap.InsertNode(N, IP);
1085 AllNodes.push_back(N);
1086 return SDValue(N, 0);
1089 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1090 FoldingSetNodeID ID;
1091 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1094 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1095 return SDValue(E, 0);
1096 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1097 new (N) BasicBlockSDNode(MBB);
1098 CSEMap.InsertNode(N, IP);
1099 AllNodes.push_back(N);
1100 return SDValue(N, 0);
1103 SDValue SelectionDAG::getValueType(EVT VT) {
1104 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1105 ValueTypeNodes.size())
1106 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1108 SDNode *&N = VT.isExtended() ?
1109 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1111 if (N) return SDValue(N, 0);
1112 N = NodeAllocator.Allocate<VTSDNode>();
1113 new (N) VTSDNode(VT);
1114 AllNodes.push_back(N);
1115 return SDValue(N, 0);
1118 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1119 SDNode *&N = ExternalSymbols[Sym];
1120 if (N) return SDValue(N, 0);
1121 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1122 new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
1123 AllNodes.push_back(N);
1124 return SDValue(N, 0);
1127 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1128 unsigned char TargetFlags) {
1130 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1132 if (N) return SDValue(N, 0);
1133 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1134 new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1135 AllNodes.push_back(N);
1136 return SDValue(N, 0);
1139 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1140 if ((unsigned)Cond >= CondCodeNodes.size())
1141 CondCodeNodes.resize(Cond+1);
1143 if (CondCodeNodes[Cond] == 0) {
1144 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1145 new (N) CondCodeSDNode(Cond);
1146 CondCodeNodes[Cond] = N;
1147 AllNodes.push_back(N);
1149 return SDValue(CondCodeNodes[Cond], 0);
1152 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1153 // the shuffle mask M that point at N1 to point at N2, and indices that point
1154 // N2 to point at N1.
1155 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1157 int NElts = M.size();
1158 for (int i = 0; i != NElts; ++i) {
1166 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1167 SDValue N2, const int *Mask) {
1168 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1169 assert(VT.isVector() && N1.getValueType().isVector() &&
1170 "Vector Shuffle VTs must be a vectors");
1171 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1172 && "Vector Shuffle VTs must have same element type");
1174 // Canonicalize shuffle undef, undef -> undef
1175 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1176 return getUNDEF(VT);
1178 // Validate that all indices in Mask are within the range of the elements
1179 // input to the shuffle.
1180 unsigned NElts = VT.getVectorNumElements();
1181 SmallVector<int, 8> MaskVec;
1182 for (unsigned i = 0; i != NElts; ++i) {
1183 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1184 MaskVec.push_back(Mask[i]);
1187 // Canonicalize shuffle v, v -> v, undef
1190 for (unsigned i = 0; i != NElts; ++i)
1191 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1194 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1195 if (N1.getOpcode() == ISD::UNDEF)
1196 commuteShuffle(N1, N2, MaskVec);
1198 // Canonicalize all index into lhs, -> shuffle lhs, undef
1199 // Canonicalize all index into rhs, -> shuffle rhs, undef
1200 bool AllLHS = true, AllRHS = true;
1201 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1202 for (unsigned i = 0; i != NElts; ++i) {
1203 if (MaskVec[i] >= (int)NElts) {
1208 } else if (MaskVec[i] >= 0) {
1212 if (AllLHS && AllRHS)
1213 return getUNDEF(VT);
1214 if (AllLHS && !N2Undef)
1218 commuteShuffle(N1, N2, MaskVec);
1221 // If Identity shuffle, or all shuffle in to undef, return that node.
1222 bool AllUndef = true;
1223 bool Identity = true;
1224 for (unsigned i = 0; i != NElts; ++i) {
1225 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1226 if (MaskVec[i] >= 0) AllUndef = false;
1228 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1231 return getUNDEF(VT);
1233 FoldingSetNodeID ID;
1234 SDValue Ops[2] = { N1, N2 };
1235 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1236 for (unsigned i = 0; i != NElts; ++i)
1237 ID.AddInteger(MaskVec[i]);
1240 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1241 return SDValue(E, 0);
1243 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1244 // SDNode doesn't have access to it. This memory will be "leaked" when
1245 // the node is deallocated, but recovered when the NodeAllocator is released.
1246 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1247 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1249 ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
1250 new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1251 CSEMap.InsertNode(N, IP);
1252 AllNodes.push_back(N);
1253 return SDValue(N, 0);
1256 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1257 SDValue Val, SDValue DTy,
1258 SDValue STy, SDValue Rnd, SDValue Sat,
1259 ISD::CvtCode Code) {
1260 // If the src and dest types are the same and the conversion is between
1261 // integer types of the same sign or two floats, no conversion is necessary.
1263 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1266 FoldingSetNodeID ID;
1268 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1269 return SDValue(E, 0);
1270 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1271 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1272 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
1273 CSEMap.InsertNode(N, IP);
1274 AllNodes.push_back(N);
1275 return SDValue(N, 0);
1278 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1279 FoldingSetNodeID ID;
1280 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1281 ID.AddInteger(RegNo);
1283 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1284 return SDValue(E, 0);
1285 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1286 new (N) RegisterSDNode(RegNo, VT);
1287 CSEMap.InsertNode(N, IP);
1288 AllNodes.push_back(N);
1289 return SDValue(N, 0);
1292 SDValue SelectionDAG::getDbgStopPoint(DebugLoc DL, SDValue Root,
1293 unsigned Line, unsigned Col,
1295 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1296 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1298 AllNodes.push_back(N);
1299 return SDValue(N, 0);
1302 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1305 FoldingSetNodeID ID;
1306 SDValue Ops[] = { Root };
1307 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1308 ID.AddInteger(LabelID);
1310 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1311 return SDValue(E, 0);
1312 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1313 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1314 CSEMap.InsertNode(N, IP);
1315 AllNodes.push_back(N);
1316 return SDValue(N, 0);
1319 SDValue SelectionDAG::getSrcValue(const Value *V) {
1320 assert((!V || isa<PointerType>(V->getType())) &&
1321 "SrcValue is not a pointer?");
1323 FoldingSetNodeID ID;
1324 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1328 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1329 return SDValue(E, 0);
1331 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1332 new (N) SrcValueSDNode(V);
1333 CSEMap.InsertNode(N, IP);
1334 AllNodes.push_back(N);
1335 return SDValue(N, 0);
1338 /// getShiftAmountOperand - Return the specified value casted to
1339 /// the target's desired shift amount type.
1340 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1341 EVT OpTy = Op.getValueType();
1342 MVT ShTy = TLI.getShiftAmountTy();
1343 if (OpTy == ShTy || OpTy.isVector()) return Op;
1345 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1346 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1349 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1350 /// specified value type.
1351 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1352 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1353 unsigned ByteSize = VT.getStoreSize();
1354 const Type *Ty = VT.getTypeForEVT(*getContext());
1355 unsigned StackAlign =
1356 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1358 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1359 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1362 /// CreateStackTemporary - Create a stack temporary suitable for holding
1363 /// either of the specified value types.
1364 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1365 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1366 VT2.getStoreSizeInBits())/8;
1367 const Type *Ty1 = VT1.getTypeForEVT(*getContext());
1368 const Type *Ty2 = VT2.getTypeForEVT(*getContext());
1369 const TargetData *TD = TLI.getTargetData();
1370 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1371 TD->getPrefTypeAlignment(Ty2));
1373 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1374 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
1375 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1378 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1379 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1380 // These setcc operations always fold.
1384 case ISD::SETFALSE2: return getConstant(0, VT);
1386 case ISD::SETTRUE2: return getConstant(1, VT);
1398 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1402 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1403 const APInt &C2 = N2C->getAPIntValue();
1404 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1405 const APInt &C1 = N1C->getAPIntValue();
1408 default: llvm_unreachable("Unknown integer setcc!");
1409 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1410 case ISD::SETNE: return getConstant(C1 != C2, VT);
1411 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1412 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1413 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1414 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1415 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1416 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1417 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1418 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1422 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1423 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1424 // No compile time operations on this type yet.
1425 if (N1C->getValueType(0) == MVT::ppcf128)
1428 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1431 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1432 return getUNDEF(VT);
1434 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1435 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1436 return getUNDEF(VT);
1438 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1439 R==APFloat::cmpLessThan, VT);
1440 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1441 return getUNDEF(VT);
1443 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1444 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1445 return getUNDEF(VT);
1447 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1448 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1449 return getUNDEF(VT);
1451 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1452 R==APFloat::cmpEqual, VT);
1453 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1454 return getUNDEF(VT);
1456 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1457 R==APFloat::cmpEqual, VT);
1458 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1459 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1460 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1461 R==APFloat::cmpEqual, VT);
1462 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1463 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1464 R==APFloat::cmpLessThan, VT);
1465 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1466 R==APFloat::cmpUnordered, VT);
1467 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1468 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1471 // Ensure that the constant occurs on the RHS.
1472 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1476 // Could not fold it.
1480 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1481 /// use this predicate to simplify operations downstream.
1482 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1483 // This predicate is not safe for vector operations.
1484 if (Op.getValueType().isVector())
1487 unsigned BitWidth = Op.getValueSizeInBits();
1488 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1491 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1492 /// this predicate to simplify operations downstream. Mask is known to be zero
1493 /// for bits that V cannot have.
1494 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1495 unsigned Depth) const {
1496 APInt KnownZero, KnownOne;
1497 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1498 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1499 return (KnownZero & Mask) == Mask;
1502 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1503 /// known to be either zero or one and return them in the KnownZero/KnownOne
1504 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1506 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1507 APInt &KnownZero, APInt &KnownOne,
1508 unsigned Depth) const {
1509 unsigned BitWidth = Mask.getBitWidth();
1510 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1511 "Mask size mismatches value type size!");
1513 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1514 if (Depth == 6 || Mask == 0)
1515 return; // Limit search depth.
1517 APInt KnownZero2, KnownOne2;
1519 switch (Op.getOpcode()) {
1521 // We know all of the bits for a constant!
1522 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1523 KnownZero = ~KnownOne & Mask;
1526 // If either the LHS or the RHS are Zero, the result is zero.
1527 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1528 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1529 KnownZero2, KnownOne2, Depth+1);
1530 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1531 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1533 // Output known-1 bits are only known if set in both the LHS & RHS.
1534 KnownOne &= KnownOne2;
1535 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1536 KnownZero |= KnownZero2;
1539 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1540 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1541 KnownZero2, KnownOne2, Depth+1);
1542 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1543 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1545 // Output known-0 bits are only known if clear in both the LHS & RHS.
1546 KnownZero &= KnownZero2;
1547 // Output known-1 are known to be set if set in either the LHS | RHS.
1548 KnownOne |= KnownOne2;
1551 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1552 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1553 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1554 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1556 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1557 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1558 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1559 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1560 KnownZero = KnownZeroOut;
1564 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1565 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1566 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1567 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1568 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1570 // If low bits are zero in either operand, output low known-0 bits.
1571 // Also compute a conserative estimate for high known-0 bits.
1572 // More trickiness is possible, but this is sufficient for the
1573 // interesting case of alignment computation.
1575 unsigned TrailZ = KnownZero.countTrailingOnes() +
1576 KnownZero2.countTrailingOnes();
1577 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1578 KnownZero2.countLeadingOnes(),
1579 BitWidth) - BitWidth;
1581 TrailZ = std::min(TrailZ, BitWidth);
1582 LeadZ = std::min(LeadZ, BitWidth);
1583 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1584 APInt::getHighBitsSet(BitWidth, LeadZ);
1589 // For the purposes of computing leading zeros we can conservatively
1590 // treat a udiv as a logical right shift by the power of 2 known to
1591 // be less than the denominator.
1592 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1593 ComputeMaskedBits(Op.getOperand(0),
1594 AllOnes, KnownZero2, KnownOne2, Depth+1);
1595 unsigned LeadZ = KnownZero2.countLeadingOnes();
1599 ComputeMaskedBits(Op.getOperand(1),
1600 AllOnes, KnownZero2, KnownOne2, Depth+1);
1601 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1602 if (RHSUnknownLeadingOnes != BitWidth)
1603 LeadZ = std::min(BitWidth,
1604 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1606 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1610 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1611 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1612 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1613 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1615 // Only known if known in both the LHS and RHS.
1616 KnownOne &= KnownOne2;
1617 KnownZero &= KnownZero2;
1619 case ISD::SELECT_CC:
1620 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1621 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1622 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1623 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1625 // Only known if known in both the LHS and RHS.
1626 KnownOne &= KnownOne2;
1627 KnownZero &= KnownZero2;
1635 if (Op.getResNo() != 1)
1637 // The boolean result conforms to getBooleanContents. Fall through.
1639 // If we know the result of a setcc has the top bits zero, use this info.
1640 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1642 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1645 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1646 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1647 unsigned ShAmt = SA->getZExtValue();
1649 // If the shift count is an invalid immediate, don't do anything.
1650 if (ShAmt >= BitWidth)
1653 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1654 KnownZero, KnownOne, Depth+1);
1655 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1656 KnownZero <<= ShAmt;
1658 // low bits known zero.
1659 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1663 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1664 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1665 unsigned ShAmt = SA->getZExtValue();
1667 // If the shift count is an invalid immediate, don't do anything.
1668 if (ShAmt >= BitWidth)
1671 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1672 KnownZero, KnownOne, Depth+1);
1673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1674 KnownZero = KnownZero.lshr(ShAmt);
1675 KnownOne = KnownOne.lshr(ShAmt);
1677 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1678 KnownZero |= HighBits; // High bits known zero.
1682 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1683 unsigned ShAmt = SA->getZExtValue();
1685 // If the shift count is an invalid immediate, don't do anything.
1686 if (ShAmt >= BitWidth)
1689 APInt InDemandedMask = (Mask << ShAmt);
1690 // If any of the demanded bits are produced by the sign extension, we also
1691 // demand the input sign bit.
1692 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1693 if (HighBits.getBoolValue())
1694 InDemandedMask |= APInt::getSignBit(BitWidth);
1696 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1698 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1699 KnownZero = KnownZero.lshr(ShAmt);
1700 KnownOne = KnownOne.lshr(ShAmt);
1702 // Handle the sign bits.
1703 APInt SignBit = APInt::getSignBit(BitWidth);
1704 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1706 if (KnownZero.intersects(SignBit)) {
1707 KnownZero |= HighBits; // New bits are known zero.
1708 } else if (KnownOne.intersects(SignBit)) {
1709 KnownOne |= HighBits; // New bits are known one.
1713 case ISD::SIGN_EXTEND_INREG: {
1714 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1715 unsigned EBits = EVT.getSizeInBits();
1717 // Sign extension. Compute the demanded bits in the result that are not
1718 // present in the input.
1719 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1721 APInt InSignBit = APInt::getSignBit(EBits);
1722 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1724 // If the sign extended bits are demanded, we know that the sign
1726 InSignBit.zext(BitWidth);
1727 if (NewBits.getBoolValue())
1728 InputDemandedBits |= InSignBit;
1730 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1731 KnownZero, KnownOne, Depth+1);
1732 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1734 // If the sign bit of the input is known set or clear, then we know the
1735 // top bits of the result.
1736 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1737 KnownZero |= NewBits;
1738 KnownOne &= ~NewBits;
1739 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1740 KnownOne |= NewBits;
1741 KnownZero &= ~NewBits;
1742 } else { // Input sign bit unknown
1743 KnownZero &= ~NewBits;
1744 KnownOne &= ~NewBits;
1751 unsigned LowBits = Log2_32(BitWidth)+1;
1752 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1757 if (ISD::isZEXTLoad(Op.getNode())) {
1758 LoadSDNode *LD = cast<LoadSDNode>(Op);
1759 EVT VT = LD->getMemoryVT();
1760 unsigned MemBits = VT.getSizeInBits();
1761 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1765 case ISD::ZERO_EXTEND: {
1766 EVT InVT = Op.getOperand(0).getValueType();
1767 unsigned InBits = InVT.getSizeInBits();
1768 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1769 APInt InMask = Mask;
1770 InMask.trunc(InBits);
1771 KnownZero.trunc(InBits);
1772 KnownOne.trunc(InBits);
1773 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1774 KnownZero.zext(BitWidth);
1775 KnownOne.zext(BitWidth);
1776 KnownZero |= NewBits;
1779 case ISD::SIGN_EXTEND: {
1780 EVT InVT = Op.getOperand(0).getValueType();
1781 unsigned InBits = InVT.getSizeInBits();
1782 APInt InSignBit = APInt::getSignBit(InBits);
1783 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1784 APInt InMask = Mask;
1785 InMask.trunc(InBits);
1787 // If any of the sign extended bits are demanded, we know that the sign
1788 // bit is demanded. Temporarily set this bit in the mask for our callee.
1789 if (NewBits.getBoolValue())
1790 InMask |= InSignBit;
1792 KnownZero.trunc(InBits);
1793 KnownOne.trunc(InBits);
1794 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1796 // Note if the sign bit is known to be zero or one.
1797 bool SignBitKnownZero = KnownZero.isNegative();
1798 bool SignBitKnownOne = KnownOne.isNegative();
1799 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1800 "Sign bit can't be known to be both zero and one!");
1802 // If the sign bit wasn't actually demanded by our caller, we don't
1803 // want it set in the KnownZero and KnownOne result values. Reset the
1804 // mask and reapply it to the result values.
1806 InMask.trunc(InBits);
1807 KnownZero &= InMask;
1810 KnownZero.zext(BitWidth);
1811 KnownOne.zext(BitWidth);
1813 // If the sign bit is known zero or one, the top bits match.
1814 if (SignBitKnownZero)
1815 KnownZero |= NewBits;
1816 else if (SignBitKnownOne)
1817 KnownOne |= NewBits;
1820 case ISD::ANY_EXTEND: {
1821 EVT InVT = Op.getOperand(0).getValueType();
1822 unsigned InBits = InVT.getSizeInBits();
1823 APInt InMask = Mask;
1824 InMask.trunc(InBits);
1825 KnownZero.trunc(InBits);
1826 KnownOne.trunc(InBits);
1827 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1828 KnownZero.zext(BitWidth);
1829 KnownOne.zext(BitWidth);
1832 case ISD::TRUNCATE: {
1833 EVT InVT = Op.getOperand(0).getValueType();
1834 unsigned InBits = InVT.getSizeInBits();
1835 APInt InMask = Mask;
1836 InMask.zext(InBits);
1837 KnownZero.zext(InBits);
1838 KnownOne.zext(InBits);
1839 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1840 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1841 KnownZero.trunc(BitWidth);
1842 KnownOne.trunc(BitWidth);
1845 case ISD::AssertZext: {
1846 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1847 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1848 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1850 KnownZero |= (~InMask) & Mask;
1854 // All bits are zero except the low bit.
1855 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1859 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1860 // We know that the top bits of C-X are clear if X contains less bits
1861 // than C (i.e. no wrap-around can happen). For example, 20-X is
1862 // positive if we can prove that X is >= 0 and < 16.
1863 if (CLHS->getAPIntValue().isNonNegative()) {
1864 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1865 // NLZ can't be BitWidth with no sign bit
1866 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1867 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1870 // If all of the MaskV bits are known to be zero, then we know the
1871 // output top bits are zero, because we now know that the output is
1873 if ((KnownZero2 & MaskV) == MaskV) {
1874 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1875 // Top bits known zero.
1876 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1883 // Output known-0 bits are known if clear or set in both the low clear bits
1884 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1885 // low 3 bits clear.
1886 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1887 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1888 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1889 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1891 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1892 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1893 KnownZeroOut = std::min(KnownZeroOut,
1894 KnownZero2.countTrailingOnes());
1896 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1900 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1901 const APInt &RA = Rem->getAPIntValue();
1902 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1903 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1904 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1905 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1907 // If the sign bit of the first operand is zero, the sign bit of
1908 // the result is zero. If the first operand has no one bits below
1909 // the second operand's single 1 bit, its sign will be zero.
1910 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1911 KnownZero2 |= ~LowBits;
1913 KnownZero |= KnownZero2 & Mask;
1915 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1920 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1921 const APInt &RA = Rem->getAPIntValue();
1922 if (RA.isPowerOf2()) {
1923 APInt LowBits = (RA - 1);
1924 APInt Mask2 = LowBits & Mask;
1925 KnownZero |= ~LowBits & Mask;
1926 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1927 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1932 // Since the result is less than or equal to either operand, any leading
1933 // zero bits in either operand must also exist in the result.
1934 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1935 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1937 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1940 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1941 KnownZero2.countLeadingOnes());
1943 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1947 // Allow the target to implement this method for its nodes.
1948 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1949 case ISD::INTRINSIC_WO_CHAIN:
1950 case ISD::INTRINSIC_W_CHAIN:
1951 case ISD::INTRINSIC_VOID:
1952 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
1959 /// ComputeNumSignBits - Return the number of times the sign bit of the
1960 /// register is replicated into the other bits. We know that at least 1 bit
1961 /// is always equal to the sign bit (itself), but other cases can give us
1962 /// information. For example, immediately after an "SRA X, 2", we know that
1963 /// the top 3 bits are all equal to each other, so we return 3.
1964 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1965 EVT VT = Op.getValueType();
1966 assert(VT.isInteger() && "Invalid VT!");
1967 unsigned VTBits = VT.getSizeInBits();
1969 unsigned FirstAnswer = 1;
1972 return 1; // Limit search depth.
1974 switch (Op.getOpcode()) {
1976 case ISD::AssertSext:
1977 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1978 return VTBits-Tmp+1;
1979 case ISD::AssertZext:
1980 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1983 case ISD::Constant: {
1984 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1985 // If negative, return # leading ones.
1986 if (Val.isNegative())
1987 return Val.countLeadingOnes();
1989 // Return # leading zeros.
1990 return Val.countLeadingZeros();
1993 case ISD::SIGN_EXTEND:
1994 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1995 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1997 case ISD::SIGN_EXTEND_INREG:
1998 // Max of the input and what this extends.
1999 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2002 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2003 return std::max(Tmp, Tmp2);
2006 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2007 // SRA X, C -> adds C sign bits.
2008 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2009 Tmp += C->getZExtValue();
2010 if (Tmp > VTBits) Tmp = VTBits;
2014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2015 // shl destroys sign bits.
2016 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2017 if (C->getZExtValue() >= VTBits || // Bad shift.
2018 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2019 return Tmp - C->getZExtValue();
2024 case ISD::XOR: // NOT is handled here.
2025 // Logical binary ops preserve the number of sign bits at the worst.
2026 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2028 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2029 FirstAnswer = std::min(Tmp, Tmp2);
2030 // We computed what we know about the sign bits as our first
2031 // answer. Now proceed to the generic code that uses
2032 // ComputeMaskedBits, and pick whichever answer is better.
2037 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2038 if (Tmp == 1) return 1; // Early out.
2039 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2040 return std::min(Tmp, Tmp2);
2048 if (Op.getResNo() != 1)
2050 // The boolean result conforms to getBooleanContents. Fall through.
2052 // If setcc returns 0/-1, all bits are sign bits.
2053 if (TLI.getBooleanContents() ==
2054 TargetLowering::ZeroOrNegativeOneBooleanContent)
2059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2060 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2062 // Handle rotate right by N like a rotate left by 32-N.
2063 if (Op.getOpcode() == ISD::ROTR)
2064 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2066 // If we aren't rotating out all of the known-in sign bits, return the
2067 // number that are left. This handles rotl(sext(x), 1) for example.
2068 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2069 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2073 // Add can have at most one carry bit. Thus we know that the output
2074 // is, at worst, one more bit than the inputs.
2075 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2076 if (Tmp == 1) return 1; // Early out.
2078 // Special case decrementing a value (ADD X, -1):
2079 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2080 if (CRHS->isAllOnesValue()) {
2081 APInt KnownZero, KnownOne;
2082 APInt Mask = APInt::getAllOnesValue(VTBits);
2083 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2085 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2087 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2090 // If we are subtracting one from a positive number, there is no carry
2091 // out of the result.
2092 if (KnownZero.isNegative())
2096 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2097 if (Tmp2 == 1) return 1;
2098 return std::min(Tmp, Tmp2)-1;
2102 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2103 if (Tmp2 == 1) return 1;
2106 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2107 if (CLHS->isNullValue()) {
2108 APInt KnownZero, KnownOne;
2109 APInt Mask = APInt::getAllOnesValue(VTBits);
2110 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2111 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2113 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2116 // If the input is known to be positive (the sign bit is known clear),
2117 // the output of the NEG has the same number of sign bits as the input.
2118 if (KnownZero.isNegative())
2121 // Otherwise, we treat this like a SUB.
2124 // Sub can have at most one carry bit. Thus we know that the output
2125 // is, at worst, one more bit than the inputs.
2126 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2127 if (Tmp == 1) return 1; // Early out.
2128 return std::min(Tmp, Tmp2)-1;
2131 // FIXME: it's tricky to do anything useful for this, but it is an important
2132 // case for targets like X86.
2136 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2137 if (Op.getOpcode() == ISD::LOAD) {
2138 LoadSDNode *LD = cast<LoadSDNode>(Op);
2139 unsigned ExtType = LD->getExtensionType();
2142 case ISD::SEXTLOAD: // '17' bits known
2143 Tmp = LD->getMemoryVT().getSizeInBits();
2144 return VTBits-Tmp+1;
2145 case ISD::ZEXTLOAD: // '16' bits known
2146 Tmp = LD->getMemoryVT().getSizeInBits();
2151 // Allow the target to implement this method for its nodes.
2152 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2153 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2154 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2155 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2156 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2157 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2160 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2161 // use this information.
2162 APInt KnownZero, KnownOne;
2163 APInt Mask = APInt::getAllOnesValue(VTBits);
2164 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2166 if (KnownZero.isNegative()) { // sign bit is 0
2168 } else if (KnownOne.isNegative()) { // sign bit is 1;
2175 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2176 // the number of identical bits in the top of the input value.
2178 Mask <<= Mask.getBitWidth()-VTBits;
2179 // Return # leading zeros. We use 'min' here in case Val was zero before
2180 // shifting. We don't want to return '64' as for an i32 "0".
2181 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2184 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2185 // If we're told that NaNs won't happen, assume they won't.
2186 if (FiniteOnlyFPMath())
2189 // If the value is a constant, we can obviously see if it is a NaN or not.
2190 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2191 return !C->getValueAPF().isNaN();
2193 // TODO: Recognize more cases here.
2198 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2199 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2200 if (!GA) return false;
2201 if (GA->getOffset() != 0) return false;
2202 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2203 if (!GV) return false;
2204 MachineModuleInfo *MMI = getMachineModuleInfo();
2205 return MMI && MMI->hasDebugInfo();
2209 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2210 /// element of the result of the vector shuffle.
2211 SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
2213 EVT VT = N->getValueType(0);
2214 DebugLoc dl = N->getDebugLoc();
2215 if (N->getMaskElt(i) < 0)
2216 return getUNDEF(VT.getVectorElementType());
2217 unsigned Index = N->getMaskElt(i);
2218 unsigned NumElems = VT.getVectorNumElements();
2219 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2222 if (V.getOpcode() == ISD::BIT_CONVERT) {
2223 V = V.getOperand(0);
2224 EVT VVT = V.getValueType();
2225 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
2228 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2229 return (Index == 0) ? V.getOperand(0)
2230 : getUNDEF(VT.getVectorElementType());
2231 if (V.getOpcode() == ISD::BUILD_VECTOR)
2232 return V.getOperand(Index);
2233 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
2234 return getShuffleScalarElt(SVN, Index);
2239 /// getNode - Gets or creates the specified node.
2241 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2242 FoldingSetNodeID ID;
2243 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2245 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2246 return SDValue(E, 0);
2247 SDNode *N = NodeAllocator.Allocate<SDNode>();
2248 new (N) SDNode(Opcode, DL, getVTList(VT));
2249 CSEMap.InsertNode(N, IP);
2251 AllNodes.push_back(N);
2255 return SDValue(N, 0);
2258 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2259 EVT VT, SDValue Operand) {
2260 // Constant fold unary operations with an integer constant operand.
2261 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2262 const APInt &Val = C->getAPIntValue();
2263 unsigned BitWidth = VT.getSizeInBits();
2266 case ISD::SIGN_EXTEND:
2267 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2268 case ISD::ANY_EXTEND:
2269 case ISD::ZERO_EXTEND:
2271 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2272 case ISD::UINT_TO_FP:
2273 case ISD::SINT_TO_FP: {
2274 const uint64_t zero[] = {0, 0};
2275 // No compile time operations on this type.
2276 if (VT==MVT::ppcf128)
2278 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2279 (void)apf.convertFromAPInt(Val,
2280 Opcode==ISD::SINT_TO_FP,
2281 APFloat::rmNearestTiesToEven);
2282 return getConstantFP(apf, VT);
2284 case ISD::BIT_CONVERT:
2285 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2286 return getConstantFP(Val.bitsToFloat(), VT);
2287 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2288 return getConstantFP(Val.bitsToDouble(), VT);
2291 return getConstant(Val.byteSwap(), VT);
2293 return getConstant(Val.countPopulation(), VT);
2295 return getConstant(Val.countLeadingZeros(), VT);
2297 return getConstant(Val.countTrailingZeros(), VT);
2301 // Constant fold unary operations with a floating point constant operand.
2302 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2303 APFloat V = C->getValueAPF(); // make copy
2304 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2308 return getConstantFP(V, VT);
2311 return getConstantFP(V, VT);
2313 case ISD::FP_EXTEND: {
2315 // This can return overflow, underflow, or inexact; we don't care.
2316 // FIXME need to be more flexible about rounding mode.
2317 (void)V.convert(*EVTToAPFloatSemantics(VT),
2318 APFloat::rmNearestTiesToEven, &ignored);
2319 return getConstantFP(V, VT);
2321 case ISD::FP_TO_SINT:
2322 case ISD::FP_TO_UINT: {
2325 assert(integerPartWidth >= 64);
2326 // FIXME need to be more flexible about rounding mode.
2327 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2328 Opcode==ISD::FP_TO_SINT,
2329 APFloat::rmTowardZero, &ignored);
2330 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2332 APInt api(VT.getSizeInBits(), 2, x);
2333 return getConstant(api, VT);
2335 case ISD::BIT_CONVERT:
2336 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2337 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2338 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2339 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2345 unsigned OpOpcode = Operand.getNode()->getOpcode();
2347 case ISD::TokenFactor:
2348 case ISD::MERGE_VALUES:
2349 case ISD::CONCAT_VECTORS:
2350 return Operand; // Factor, merge or concat of one node? No need.
2351 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2352 case ISD::FP_EXTEND:
2353 assert(VT.isFloatingPoint() &&
2354 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2355 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2356 if (Operand.getOpcode() == ISD::UNDEF)
2357 return getUNDEF(VT);
2359 case ISD::SIGN_EXTEND:
2360 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2361 "Invalid SIGN_EXTEND!");
2362 if (Operand.getValueType() == VT) return Operand; // noop extension
2363 assert(Operand.getValueType().bitsLT(VT)
2364 && "Invalid sext node, dst < src!");
2365 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2366 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2368 case ISD::ZERO_EXTEND:
2369 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2370 "Invalid ZERO_EXTEND!");
2371 if (Operand.getValueType() == VT) return Operand; // noop extension
2372 assert(Operand.getValueType().bitsLT(VT)
2373 && "Invalid zext node, dst < src!");
2374 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2375 return getNode(ISD::ZERO_EXTEND, DL, VT,
2376 Operand.getNode()->getOperand(0));
2378 case ISD::ANY_EXTEND:
2379 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2380 "Invalid ANY_EXTEND!");
2381 if (Operand.getValueType() == VT) return Operand; // noop extension
2382 assert(Operand.getValueType().bitsLT(VT)
2383 && "Invalid anyext node, dst < src!");
2384 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2385 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2386 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2389 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2390 "Invalid TRUNCATE!");
2391 if (Operand.getValueType() == VT) return Operand; // noop truncate
2392 assert(Operand.getValueType().bitsGT(VT)
2393 && "Invalid truncate node, src < dst!");
2394 if (OpOpcode == ISD::TRUNCATE)
2395 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2396 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2397 OpOpcode == ISD::ANY_EXTEND) {
2398 // If the source is smaller than the dest, we still need an extend.
2399 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2400 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2401 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2402 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2404 return Operand.getNode()->getOperand(0);
2407 case ISD::BIT_CONVERT:
2408 // Basic sanity checking.
2409 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2410 && "Cannot BIT_CONVERT between types of different sizes!");
2411 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2412 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2413 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2414 if (OpOpcode == ISD::UNDEF)
2415 return getUNDEF(VT);
2417 case ISD::SCALAR_TO_VECTOR:
2418 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2419 (VT.getVectorElementType() == Operand.getValueType() ||
2420 (VT.getVectorElementType().isInteger() &&
2421 Operand.getValueType().isInteger() &&
2422 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2423 "Illegal SCALAR_TO_VECTOR node!");
2424 if (OpOpcode == ISD::UNDEF)
2425 return getUNDEF(VT);
2426 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2427 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2428 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2429 Operand.getConstantOperandVal(1) == 0 &&
2430 Operand.getOperand(0).getValueType() == VT)
2431 return Operand.getOperand(0);
2434 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2435 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2436 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2437 Operand.getNode()->getOperand(0));
2438 if (OpOpcode == ISD::FNEG) // --X -> X
2439 return Operand.getNode()->getOperand(0);
2442 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2443 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2448 SDVTList VTs = getVTList(VT);
2449 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2450 FoldingSetNodeID ID;
2451 SDValue Ops[1] = { Operand };
2452 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2454 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2455 return SDValue(E, 0);
2456 N = NodeAllocator.Allocate<UnarySDNode>();
2457 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2458 CSEMap.InsertNode(N, IP);
2460 N = NodeAllocator.Allocate<UnarySDNode>();
2461 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2464 AllNodes.push_back(N);
2468 return SDValue(N, 0);
2471 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2473 ConstantSDNode *Cst1,
2474 ConstantSDNode *Cst2) {
2475 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2478 case ISD::ADD: return getConstant(C1 + C2, VT);
2479 case ISD::SUB: return getConstant(C1 - C2, VT);
2480 case ISD::MUL: return getConstant(C1 * C2, VT);
2482 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2485 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2488 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2491 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2493 case ISD::AND: return getConstant(C1 & C2, VT);
2494 case ISD::OR: return getConstant(C1 | C2, VT);
2495 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2496 case ISD::SHL: return getConstant(C1 << C2, VT);
2497 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2498 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2499 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2500 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2507 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2508 SDValue N1, SDValue N2) {
2509 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2510 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2513 case ISD::TokenFactor:
2514 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2515 N2.getValueType() == MVT::Other && "Invalid token factor!");
2516 // Fold trivial token factors.
2517 if (N1.getOpcode() == ISD::EntryToken) return N2;
2518 if (N2.getOpcode() == ISD::EntryToken) return N1;
2519 if (N1 == N2) return N1;
2521 case ISD::CONCAT_VECTORS:
2522 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2523 // one big BUILD_VECTOR.
2524 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2525 N2.getOpcode() == ISD::BUILD_VECTOR) {
2526 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2527 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2528 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2532 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2533 N1.getValueType() == VT && "Binary operator types must match!");
2534 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2535 // worth handling here.
2536 if (N2C && N2C->isNullValue())
2538 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2545 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2546 N1.getValueType() == VT && "Binary operator types must match!");
2547 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2548 // it's worth handling here.
2549 if (N2C && N2C->isNullValue())
2559 assert(VT.isInteger() && "This operator does not apply to FP types!");
2567 if (Opcode == ISD::FADD) {
2569 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2570 if (CFP->getValueAPF().isZero())
2573 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2574 if (CFP->getValueAPF().isZero())
2576 } else if (Opcode == ISD::FSUB) {
2578 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2579 if (CFP->getValueAPF().isZero())
2583 assert(N1.getValueType() == N2.getValueType() &&
2584 N1.getValueType() == VT && "Binary operator types must match!");
2586 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2587 assert(N1.getValueType() == VT &&
2588 N1.getValueType().isFloatingPoint() &&
2589 N2.getValueType().isFloatingPoint() &&
2590 "Invalid FCOPYSIGN!");
2597 assert(VT == N1.getValueType() &&
2598 "Shift operators return type must be the same as their first arg");
2599 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2600 "Shifts only work on integers");
2602 // Always fold shifts of i1 values so the code generator doesn't need to
2603 // handle them. Since we know the size of the shift has to be less than the
2604 // size of the value, the shift/rotate count is guaranteed to be zero.
2608 case ISD::FP_ROUND_INREG: {
2609 EVT EVT = cast<VTSDNode>(N2)->getVT();
2610 assert(VT == N1.getValueType() && "Not an inreg round!");
2611 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2612 "Cannot FP_ROUND_INREG integer types");
2613 assert(EVT.bitsLE(VT) && "Not rounding down!");
2614 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2618 assert(VT.isFloatingPoint() &&
2619 N1.getValueType().isFloatingPoint() &&
2620 VT.bitsLE(N1.getValueType()) &&
2621 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2622 if (N1.getValueType() == VT) return N1; // noop conversion.
2624 case ISD::AssertSext:
2625 case ISD::AssertZext: {
2626 EVT EVT = cast<VTSDNode>(N2)->getVT();
2627 assert(VT == N1.getValueType() && "Not an inreg extend!");
2628 assert(VT.isInteger() && EVT.isInteger() &&
2629 "Cannot *_EXTEND_INREG FP types");
2630 assert(EVT.bitsLE(VT) && "Not extending!");
2631 if (VT == EVT) return N1; // noop assertion.
2634 case ISD::SIGN_EXTEND_INREG: {
2635 EVT EVT = cast<VTSDNode>(N2)->getVT();
2636 assert(VT == N1.getValueType() && "Not an inreg extend!");
2637 assert(VT.isInteger() && EVT.isInteger() &&
2638 "Cannot *_EXTEND_INREG FP types");
2639 assert(EVT.bitsLE(VT) && "Not extending!");
2640 if (EVT == VT) return N1; // Not actually extending
2643 APInt Val = N1C->getAPIntValue();
2644 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2645 Val <<= Val.getBitWidth()-FromBits;
2646 Val = Val.ashr(Val.getBitWidth()-FromBits);
2647 return getConstant(Val, VT);
2651 case ISD::EXTRACT_VECTOR_ELT:
2652 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2653 if (N1.getOpcode() == ISD::UNDEF)
2654 return getUNDEF(VT);
2656 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2657 // expanding copies of large vectors from registers.
2659 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2660 N1.getNumOperands() > 0) {
2662 N1.getOperand(0).getValueType().getVectorNumElements();
2663 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2664 N1.getOperand(N2C->getZExtValue() / Factor),
2665 getConstant(N2C->getZExtValue() % Factor,
2666 N2.getValueType()));
2669 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2670 // expanding large vector constants.
2671 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2672 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2673 EVT VEltTy = N1.getValueType().getVectorElementType();
2674 if (Elt.getValueType() != VEltTy) {
2675 // If the vector element type is not legal, the BUILD_VECTOR operands
2676 // are promoted and implicitly truncated. Make that explicit here.
2677 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2680 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2681 // result is implicitly extended.
2682 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2687 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2688 // operations are lowered to scalars.
2689 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2690 // If the indices are the same, return the inserted element.
2691 if (N1.getOperand(2) == N2)
2692 return N1.getOperand(1);
2693 // If the indices are known different, extract the element from
2694 // the original vector.
2695 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2696 isa<ConstantSDNode>(N2))
2697 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2700 case ISD::EXTRACT_ELEMENT:
2701 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2702 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2703 (N1.getValueType().isInteger() == VT.isInteger()) &&
2704 "Wrong types for EXTRACT_ELEMENT!");
2706 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2707 // 64-bit integers into 32-bit parts. Instead of building the extract of
2708 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2709 if (N1.getOpcode() == ISD::BUILD_PAIR)
2710 return N1.getOperand(N2C->getZExtValue());
2712 // EXTRACT_ELEMENT of a constant int is also very common.
2713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2714 unsigned ElementSize = VT.getSizeInBits();
2715 unsigned Shift = ElementSize * N2C->getZExtValue();
2716 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2717 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2720 case ISD::EXTRACT_SUBVECTOR:
2721 if (N1.getValueType() == VT) // Trivial extraction.
2728 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2729 if (SV.getNode()) return SV;
2730 } else { // Cannonicalize constant to RHS if commutative
2731 if (isCommutativeBinOp(Opcode)) {
2732 std::swap(N1C, N2C);
2738 // Constant fold FP operations.
2739 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2740 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2742 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2743 // Cannonicalize constant to RHS if commutative
2744 std::swap(N1CFP, N2CFP);
2746 } else if (N2CFP && VT != MVT::ppcf128) {
2747 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2748 APFloat::opStatus s;
2751 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2752 if (s != APFloat::opInvalidOp)
2753 return getConstantFP(V1, VT);
2756 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2757 if (s!=APFloat::opInvalidOp)
2758 return getConstantFP(V1, VT);
2761 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2762 if (s!=APFloat::opInvalidOp)
2763 return getConstantFP(V1, VT);
2766 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2767 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2768 return getConstantFP(V1, VT);
2771 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2772 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2773 return getConstantFP(V1, VT);
2775 case ISD::FCOPYSIGN:
2777 return getConstantFP(V1, VT);
2783 // Canonicalize an UNDEF to the RHS, even over a constant.
2784 if (N1.getOpcode() == ISD::UNDEF) {
2785 if (isCommutativeBinOp(Opcode)) {
2789 case ISD::FP_ROUND_INREG:
2790 case ISD::SIGN_EXTEND_INREG:
2796 return N1; // fold op(undef, arg2) -> undef
2804 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2805 // For vectors, we can't easily build an all zero vector, just return
2812 // Fold a bunch of operators when the RHS is undef.
2813 if (N2.getOpcode() == ISD::UNDEF) {
2816 if (N1.getOpcode() == ISD::UNDEF)
2817 // Handle undef ^ undef -> 0 special case. This is a common
2819 return getConstant(0, VT);
2829 return N2; // fold op(arg1, undef) -> undef
2843 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2844 // For vectors, we can't easily build an all zero vector, just return
2849 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2850 // For vectors, we can't easily build an all one vector, just return
2858 // Memoize this node if possible.
2860 SDVTList VTs = getVTList(VT);
2861 if (VT != MVT::Flag) {
2862 SDValue Ops[] = { N1, N2 };
2863 FoldingSetNodeID ID;
2864 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2866 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2867 return SDValue(E, 0);
2868 N = NodeAllocator.Allocate<BinarySDNode>();
2869 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2870 CSEMap.InsertNode(N, IP);
2872 N = NodeAllocator.Allocate<BinarySDNode>();
2873 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2876 AllNodes.push_back(N);
2880 return SDValue(N, 0);
2883 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2884 SDValue N1, SDValue N2, SDValue N3) {
2885 // Perform various simplifications.
2886 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2887 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2889 case ISD::CONCAT_VECTORS:
2890 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2891 // one big BUILD_VECTOR.
2892 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2893 N2.getOpcode() == ISD::BUILD_VECTOR &&
2894 N3.getOpcode() == ISD::BUILD_VECTOR) {
2895 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2896 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2897 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2898 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2902 // Use FoldSetCC to simplify SETCC's.
2903 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
2904 if (Simp.getNode()) return Simp;
2909 if (N1C->getZExtValue())
2910 return N2; // select true, X, Y -> X
2912 return N3; // select false, X, Y -> Y
2915 if (N2 == N3) return N2; // select C, X, X -> X
2919 if (N2C->getZExtValue()) // Unconditional branch
2920 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
2922 return N1; // Never-taken branch
2925 case ISD::VECTOR_SHUFFLE:
2926 llvm_unreachable("should use getVectorShuffle constructor!");
2928 case ISD::BIT_CONVERT:
2929 // Fold bit_convert nodes from a type to themselves.
2930 if (N1.getValueType() == VT)
2935 // Memoize node if it doesn't produce a flag.
2937 SDVTList VTs = getVTList(VT);
2938 if (VT != MVT::Flag) {
2939 SDValue Ops[] = { N1, N2, N3 };
2940 FoldingSetNodeID ID;
2941 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2943 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2944 return SDValue(E, 0);
2945 N = NodeAllocator.Allocate<TernarySDNode>();
2946 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2947 CSEMap.InsertNode(N, IP);
2949 N = NodeAllocator.Allocate<TernarySDNode>();
2950 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2952 AllNodes.push_back(N);
2956 return SDValue(N, 0);
2959 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2960 SDValue N1, SDValue N2, SDValue N3,
2962 SDValue Ops[] = { N1, N2, N3, N4 };
2963 return getNode(Opcode, DL, VT, Ops, 4);
2966 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2967 SDValue N1, SDValue N2, SDValue N3,
2968 SDValue N4, SDValue N5) {
2969 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2970 return getNode(Opcode, DL, VT, Ops, 5);
2973 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
2974 /// the incoming stack arguments to be loaded from the stack.
2975 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
2976 SmallVector<SDValue, 8> ArgChains;
2978 // Include the original chain at the beginning of the list. When this is
2979 // used by target LowerCall hooks, this helps legalize find the
2980 // CALLSEQ_BEGIN node.
2981 ArgChains.push_back(Chain);
2983 // Add a chain value for each stack argument.
2984 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
2985 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
2986 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2987 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2988 if (FI->getIndex() < 0)
2989 ArgChains.push_back(SDValue(L, 1));
2991 // Build a tokenfactor for all the chains.
2992 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
2993 &ArgChains[0], ArgChains.size());
2996 /// getMemsetValue - Vectorized representation of the memset value
2998 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3000 unsigned NumBits = VT.isVector() ?
3001 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
3002 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3003 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
3005 for (unsigned i = NumBits; i > 8; i >>= 1) {
3006 Val = (Val << Shift) | Val;
3010 return DAG.getConstant(Val, VT);
3011 return DAG.getConstantFP(APFloat(Val), VT);
3014 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3015 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3017 for (unsigned i = NumBits; i > 8; i >>= 1) {
3018 Value = DAG.getNode(ISD::OR, dl, VT,
3019 DAG.getNode(ISD::SHL, dl, VT, Value,
3020 DAG.getConstant(Shift,
3021 TLI.getShiftAmountTy())),
3029 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3030 /// used when a memcpy is turned into a memset when the source is a constant
3032 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3033 const TargetLowering &TLI,
3034 std::string &Str, unsigned Offset) {
3035 // Handle vector with all elements zero.
3038 return DAG.getConstant(0, VT);
3039 unsigned NumElts = VT.getVectorNumElements();
3040 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3041 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3043 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
3046 assert(!VT.isVector() && "Can't handle vector type here!");
3047 unsigned NumBits = VT.getSizeInBits();
3048 unsigned MSB = NumBits / 8;
3050 if (TLI.isLittleEndian())
3051 Offset = Offset + MSB - 1;
3052 for (unsigned i = 0; i != MSB; ++i) {
3053 Val = (Val << 8) | (unsigned char)Str[Offset];
3054 Offset += TLI.isLittleEndian() ? -1 : 1;
3056 return DAG.getConstant(Val, VT);
3059 /// getMemBasePlusOffset - Returns base and offset node for the
3061 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3062 SelectionDAG &DAG) {
3063 EVT VT = Base.getValueType();
3064 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3065 VT, Base, DAG.getConstant(Offset, VT));
3068 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3070 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3071 unsigned SrcDelta = 0;
3072 GlobalAddressSDNode *G = NULL;
3073 if (Src.getOpcode() == ISD::GlobalAddress)
3074 G = cast<GlobalAddressSDNode>(Src);
3075 else if (Src.getOpcode() == ISD::ADD &&
3076 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3077 Src.getOperand(1).getOpcode() == ISD::Constant) {
3078 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3079 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3084 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3085 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3091 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3092 /// to replace the memset / memcpy is below the threshold. It also returns the
3093 /// types of the sequence of memory ops to perform memset / memcpy.
3095 bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
3096 SDValue Dst, SDValue Src,
3097 unsigned Limit, uint64_t Size, unsigned &Align,
3098 std::string &Str, bool &isSrcStr,
3100 const TargetLowering &TLI) {
3101 isSrcStr = isMemSrcFromString(Src, Str);
3102 bool isSrcConst = isa<ConstantSDNode>(Src);
3103 EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3104 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
3105 if (VT != MVT::iAny) {
3106 const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3107 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3108 // If source is a string constant, this will require an unaligned load.
3109 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3110 if (Dst.getOpcode() != ISD::FrameIndex) {
3111 // Can't change destination alignment. It requires a unaligned store.
3115 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3116 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3117 if (MFI->isFixedObjectIndex(FI)) {
3118 // Can't change destination alignment. It requires a unaligned store.
3122 // Give the stack frame object a larger alignment if needed.
3123 if (MFI->getObjectAlignment(FI) < NewAlign)
3124 MFI->setObjectAlignment(FI, NewAlign);
3131 if (VT == MVT::iAny) {
3132 if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
3135 switch (Align & 7) {
3136 case 0: VT = MVT::i64; break;
3137 case 4: VT = MVT::i32; break;
3138 case 2: VT = MVT::i16; break;
3139 default: VT = MVT::i8; break;
3144 while (!TLI.isTypeLegal(LVT))
3145 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3146 assert(LVT.isInteger());
3152 unsigned NumMemOps = 0;
3154 unsigned VTSize = VT.getSizeInBits() / 8;
3155 while (VTSize > Size) {
3156 // For now, only use non-vector load / store's for the left-over pieces.
3157 if (VT.isVector()) {
3159 while (!TLI.isTypeLegal(VT))
3160 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3161 VTSize = VT.getSizeInBits() / 8;
3163 // This can result in a type that is not legal on the target, e.g.
3164 // 1 or 2 bytes on PPC.
3165 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3170 if (++NumMemOps > Limit)
3172 MemOps.push_back(VT);
3179 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3180 SDValue Chain, SDValue Dst,
3181 SDValue Src, uint64_t Size,
3182 unsigned Align, bool AlwaysInline,
3183 const Value *DstSV, uint64_t DstSVOff,
3184 const Value *SrcSV, uint64_t SrcSVOff){
3185 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3187 // Expand memcpy to a series of load and store ops if the size operand falls
3188 // below a certain threshold.
3189 std::vector<EVT> MemOps;
3190 uint64_t Limit = -1ULL;
3192 Limit = TLI.getMaxStoresPerMemcpy();
3193 unsigned DstAlign = Align; // Destination alignment can change.
3196 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3197 Str, CopyFromStr, DAG, TLI))
3201 bool isZeroStr = CopyFromStr && Str.empty();
3202 SmallVector<SDValue, 8> OutChains;
3203 unsigned NumMemOps = MemOps.size();
3204 uint64_t SrcOff = 0, DstOff = 0;
3205 for (unsigned i = 0; i != NumMemOps; ++i) {
3207 unsigned VTSize = VT.getSizeInBits() / 8;
3208 SDValue Value, Store;
3210 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3211 // It's unlikely a store of a vector immediate can be done in a single
3212 // instruction. It would require a load from a constantpool first.
3213 // We also handle store a vector with all zero's.
3214 // FIXME: Handle other cases where store of vector immediate is done in
3215 // a single instruction.
3216 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3217 Store = DAG.getStore(Chain, dl, Value,
3218 getMemBasePlusOffset(Dst, DstOff, DAG),
3219 DstSV, DstSVOff + DstOff, false, DstAlign);
3221 // The type might not be legal for the target. This should only happen
3222 // if the type is smaller than a legal type, as on PPC, so the right
3223 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3224 // to Load/Store if NVT==VT.
3225 // FIXME does the case above also need this?
3226 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3227 assert(NVT.bitsGE(VT));
3228 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3229 getMemBasePlusOffset(Src, SrcOff, DAG),
3230 SrcSV, SrcSVOff + SrcOff, VT, false, Align);
3231 Store = DAG.getTruncStore(Chain, dl, Value,
3232 getMemBasePlusOffset(Dst, DstOff, DAG),
3233 DstSV, DstSVOff + DstOff, VT, false, DstAlign);
3235 OutChains.push_back(Store);
3240 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3241 &OutChains[0], OutChains.size());
3244 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3245 SDValue Chain, SDValue Dst,
3246 SDValue Src, uint64_t Size,
3247 unsigned Align, bool AlwaysInline,
3248 const Value *DstSV, uint64_t DstSVOff,
3249 const Value *SrcSV, uint64_t SrcSVOff){
3250 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3252 // Expand memmove to a series of load and store ops if the size operand falls
3253 // below a certain threshold.
3254 std::vector<EVT> MemOps;
3255 uint64_t Limit = -1ULL;
3257 Limit = TLI.getMaxStoresPerMemmove();
3258 unsigned DstAlign = Align; // Destination alignment can change.
3261 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3262 Str, CopyFromStr, DAG, TLI))
3265 uint64_t SrcOff = 0, DstOff = 0;
3267 SmallVector<SDValue, 8> LoadValues;
3268 SmallVector<SDValue, 8> LoadChains;
3269 SmallVector<SDValue, 8> OutChains;
3270 unsigned NumMemOps = MemOps.size();
3271 for (unsigned i = 0; i < NumMemOps; i++) {
3273 unsigned VTSize = VT.getSizeInBits() / 8;
3274 SDValue Value, Store;
3276 Value = DAG.getLoad(VT, dl, Chain,
3277 getMemBasePlusOffset(Src, SrcOff, DAG),
3278 SrcSV, SrcSVOff + SrcOff, false, Align);
3279 LoadValues.push_back(Value);
3280 LoadChains.push_back(Value.getValue(1));
3283 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3284 &LoadChains[0], LoadChains.size());
3286 for (unsigned i = 0; i < NumMemOps; i++) {
3288 unsigned VTSize = VT.getSizeInBits() / 8;
3289 SDValue Value, Store;
3291 Store = DAG.getStore(Chain, dl, LoadValues[i],
3292 getMemBasePlusOffset(Dst, DstOff, DAG),
3293 DstSV, DstSVOff + DstOff, false, DstAlign);
3294 OutChains.push_back(Store);
3298 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3299 &OutChains[0], OutChains.size());
3302 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3303 SDValue Chain, SDValue Dst,
3304 SDValue Src, uint64_t Size,
3306 const Value *DstSV, uint64_t DstSVOff) {
3307 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3309 // Expand memset to a series of load/store ops if the size operand
3310 // falls below a certain threshold.
3311 std::vector<EVT> MemOps;
3314 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3315 Size, Align, Str, CopyFromStr, DAG, TLI))
3318 SmallVector<SDValue, 8> OutChains;
3319 uint64_t DstOff = 0;
3321 unsigned NumMemOps = MemOps.size();
3322 for (unsigned i = 0; i < NumMemOps; i++) {
3324 unsigned VTSize = VT.getSizeInBits() / 8;
3325 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3326 SDValue Store = DAG.getStore(Chain, dl, Value,
3327 getMemBasePlusOffset(Dst, DstOff, DAG),
3328 DstSV, DstSVOff + DstOff);
3329 OutChains.push_back(Store);
3333 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3334 &OutChains[0], OutChains.size());
3337 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3338 SDValue Src, SDValue Size,
3339 unsigned Align, bool AlwaysInline,
3340 const Value *DstSV, uint64_t DstSVOff,
3341 const Value *SrcSV, uint64_t SrcSVOff) {
3343 // Check to see if we should lower the memcpy to loads and stores first.
3344 // For cases within the target-specified limits, this is the best choice.
3345 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3347 // Memcpy with size zero? Just return the original chain.
3348 if (ConstantSize->isNullValue())
3352 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3353 ConstantSize->getZExtValue(),
3354 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3355 if (Result.getNode())
3359 // Then check to see if we should lower the memcpy with target-specific
3360 // code. If the target chooses to do this, this is the next best.
3362 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3364 DstSV, DstSVOff, SrcSV, SrcSVOff);
3365 if (Result.getNode())
3368 // If we really need inline code and the target declined to provide it,
3369 // use a (potentially long) sequence of loads and stores.
3371 assert(ConstantSize && "AlwaysInline requires a constant size!");
3372 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3373 ConstantSize->getZExtValue(), Align, true,
3374 DstSV, DstSVOff, SrcSV, SrcSVOff);
3377 // Emit a library call.
3378 TargetLowering::ArgListTy Args;
3379 TargetLowering::ArgListEntry Entry;
3380 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3381 Entry.Node = Dst; Args.push_back(Entry);
3382 Entry.Node = Src; Args.push_back(Entry);
3383 Entry.Node = Size; Args.push_back(Entry);
3384 // FIXME: pass in DebugLoc
3385 std::pair<SDValue,SDValue> CallResult =
3386 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3387 false, false, false, false, 0,
3388 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3389 /*isReturnValueUsed=*/false,
3390 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3391 TLI.getPointerTy()),
3393 return CallResult.second;
3396 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3397 SDValue Src, SDValue Size,
3399 const Value *DstSV, uint64_t DstSVOff,
3400 const Value *SrcSV, uint64_t SrcSVOff) {
3402 // Check to see if we should lower the memmove to loads and stores first.
3403 // For cases within the target-specified limits, this is the best choice.
3404 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3406 // Memmove with size zero? Just return the original chain.
3407 if (ConstantSize->isNullValue())
3411 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3412 ConstantSize->getZExtValue(),
3413 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3414 if (Result.getNode())
3418 // Then check to see if we should lower the memmove with target-specific
3419 // code. If the target chooses to do this, this is the next best.
3421 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3422 DstSV, DstSVOff, SrcSV, SrcSVOff);
3423 if (Result.getNode())
3426 // Emit a library call.
3427 TargetLowering::ArgListTy Args;
3428 TargetLowering::ArgListEntry Entry;
3429 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3430 Entry.Node = Dst; Args.push_back(Entry);
3431 Entry.Node = Src; Args.push_back(Entry);
3432 Entry.Node = Size; Args.push_back(Entry);
3433 // FIXME: pass in DebugLoc
3434 std::pair<SDValue,SDValue> CallResult =
3435 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3436 false, false, false, false, 0,
3437 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3438 /*isReturnValueUsed=*/false,
3439 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3440 TLI.getPointerTy()),
3442 return CallResult.second;
3445 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3446 SDValue Src, SDValue Size,
3448 const Value *DstSV, uint64_t DstSVOff) {
3450 // Check to see if we should lower the memset to stores first.
3451 // For cases within the target-specified limits, this is the best choice.
3452 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3454 // Memset with size zero? Just return the original chain.
3455 if (ConstantSize->isNullValue())
3459 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3460 Align, DstSV, DstSVOff);
3461 if (Result.getNode())
3465 // Then check to see if we should lower the memset with target-specific
3466 // code. If the target chooses to do this, this is the next best.
3468 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3470 if (Result.getNode())
3473 // Emit a library call.
3474 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3475 TargetLowering::ArgListTy Args;
3476 TargetLowering::ArgListEntry Entry;
3477 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3478 Args.push_back(Entry);
3479 // Extend or truncate the argument to be an i32 value for the call.
3480 if (Src.getValueType().bitsGT(MVT::i32))
3481 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3483 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3485 Entry.Ty = Type::getInt32Ty(*getContext());
3486 Entry.isSExt = true;
3487 Args.push_back(Entry);
3489 Entry.Ty = IntPtrTy;
3490 Entry.isSExt = false;
3491 Args.push_back(Entry);
3492 // FIXME: pass in DebugLoc
3493 std::pair<SDValue,SDValue> CallResult =
3494 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3495 false, false, false, false, 0,
3496 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3497 /*isReturnValueUsed=*/false,
3498 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3499 TLI.getPointerTy()),
3501 return CallResult.second;
3504 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3506 SDValue Ptr, SDValue Cmp,
3507 SDValue Swp, const Value* PtrVal,
3508 unsigned Alignment) {
3509 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3510 Alignment = getEVTAlignment(MemVT);
3512 // Check if the memory reference references a frame index
3514 if (const FrameIndexSDNode *FI =
3515 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3516 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3518 MachineFunction &MF = getMachineFunction();
3519 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3521 // For now, atomics are considered to be volatile always.
3522 Flags |= MachineMemOperand::MOVolatile;
3524 MachineMemOperand *MMO =
3525 MF.getMachineMemOperand(PtrVal, Flags, 0,
3526 MemVT.getStoreSize(), Alignment);
3528 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3531 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3533 SDValue Ptr, SDValue Cmp,
3534 SDValue Swp, MachineMemOperand *MMO) {
3535 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3536 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3538 EVT VT = Cmp.getValueType();
3540 SDVTList VTs = getVTList(VT, MVT::Other);
3541 FoldingSetNodeID ID;
3542 ID.AddInteger(MemVT.getRawBits());
3543 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3544 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3546 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3547 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3548 return SDValue(E, 0);
3550 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3551 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3552 CSEMap.InsertNode(N, IP);
3553 AllNodes.push_back(N);
3554 return SDValue(N, 0);
3557 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3559 SDValue Ptr, SDValue Val,
3560 const Value* PtrVal,
3561 unsigned Alignment) {
3562 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3563 Alignment = getEVTAlignment(MemVT);
3565 // Check if the memory reference references a frame index
3567 if (const FrameIndexSDNode *FI =
3568 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3569 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3571 MachineFunction &MF = getMachineFunction();
3572 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3574 // For now, atomics are considered to be volatile always.
3575 Flags |= MachineMemOperand::MOVolatile;
3577 MachineMemOperand *MMO =
3578 MF.getMachineMemOperand(PtrVal, Flags, 0,
3579 MemVT.getStoreSize(), Alignment);
3581 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
3584 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3586 SDValue Ptr, SDValue Val,
3587 MachineMemOperand *MMO) {
3588 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3589 Opcode == ISD::ATOMIC_LOAD_SUB ||
3590 Opcode == ISD::ATOMIC_LOAD_AND ||
3591 Opcode == ISD::ATOMIC_LOAD_OR ||
3592 Opcode == ISD::ATOMIC_LOAD_XOR ||
3593 Opcode == ISD::ATOMIC_LOAD_NAND ||
3594 Opcode == ISD::ATOMIC_LOAD_MIN ||
3595 Opcode == ISD::ATOMIC_LOAD_MAX ||
3596 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3597 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3598 Opcode == ISD::ATOMIC_SWAP) &&
3599 "Invalid Atomic Op");
3601 EVT VT = Val.getValueType();
3603 SDVTList VTs = getVTList(VT, MVT::Other);
3604 FoldingSetNodeID ID;
3605 ID.AddInteger(MemVT.getRawBits());
3606 SDValue Ops[] = {Chain, Ptr, Val};
3607 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3609 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3610 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3611 return SDValue(E, 0);
3613 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3614 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Val, MMO);
3615 CSEMap.InsertNode(N, IP);
3616 AllNodes.push_back(N);
3617 return SDValue(N, 0);
3620 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3621 /// Allowed to return something different (and simpler) if Simplify is true.
3622 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3627 SmallVector<EVT, 4> VTs;
3628 VTs.reserve(NumOps);
3629 for (unsigned i = 0; i < NumOps; ++i)
3630 VTs.push_back(Ops[i].getValueType());
3631 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3636 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3637 const EVT *VTs, unsigned NumVTs,
3638 const SDValue *Ops, unsigned NumOps,
3639 EVT MemVT, const Value *srcValue, int SVOff,
3640 unsigned Align, bool Vol,
3641 bool ReadMem, bool WriteMem) {
3642 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3643 MemVT, srcValue, SVOff, Align, Vol,
3648 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3649 const SDValue *Ops, unsigned NumOps,
3650 EVT MemVT, const Value *srcValue, int SVOff,
3651 unsigned Align, bool Vol,
3652 bool ReadMem, bool WriteMem) {
3653 if (Align == 0) // Ensure that codegen never sees alignment 0
3654 Align = getEVTAlignment(MemVT);
3656 MachineFunction &MF = getMachineFunction();
3659 Flags |= MachineMemOperand::MOStore;
3661 Flags |= MachineMemOperand::MOLoad;
3663 Flags |= MachineMemOperand::MOVolatile;
3664 MachineMemOperand *MMO =
3665 MF.getMachineMemOperand(srcValue, Flags, SVOff,
3666 MemVT.getStoreSize(), Align);
3668 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3672 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3673 const SDValue *Ops, unsigned NumOps,
3674 EVT MemVT, MachineMemOperand *MMO) {
3675 assert((Opcode == ISD::INTRINSIC_VOID ||
3676 Opcode == ISD::INTRINSIC_W_CHAIN ||
3677 (Opcode <= INT_MAX &&
3678 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
3679 "Opcode is not a memory-accessing opcode!");
3681 // Memoize the node unless it returns a flag.
3682 MemIntrinsicSDNode *N;
3683 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3684 FoldingSetNodeID ID;
3685 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3687 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3688 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
3689 return SDValue(E, 0);
3692 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3693 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3694 CSEMap.InsertNode(N, IP);
3696 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3697 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3699 AllNodes.push_back(N);
3700 return SDValue(N, 0);
3704 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3705 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3706 SDValue Ptr, SDValue Offset,
3707 const Value *SV, int SVOffset, EVT MemVT,
3708 bool isVolatile, unsigned Alignment) {
3709 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3710 Alignment = getEVTAlignment(VT);
3712 // Check if the memory reference references a frame index
3714 if (const FrameIndexSDNode *FI =
3715 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3716 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3718 MachineFunction &MF = getMachineFunction();
3719 unsigned Flags = MachineMemOperand::MOLoad;
3721 Flags |= MachineMemOperand::MOVolatile;
3722 MachineMemOperand *MMO =
3723 MF.getMachineMemOperand(SV, Flags, SVOffset,
3724 MemVT.getStoreSize(), Alignment);
3725 return getLoad(AM, dl, ExtType, VT, Chain, Ptr, Offset, MemVT, MMO);
3729 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3730 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3731 SDValue Ptr, SDValue Offset, EVT MemVT,
3732 MachineMemOperand *MMO) {
3734 ExtType = ISD::NON_EXTLOAD;
3735 } else if (ExtType == ISD::NON_EXTLOAD) {
3736 assert(VT == MemVT && "Non-extending load from different memory type!");
3740 assert(MemVT.getVectorNumElements() == VT.getVectorNumElements() &&
3741 "Invalid vector extload!");
3743 assert(MemVT.bitsLT(VT) &&
3744 "Should only be an extending load, not truncating!");
3745 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3746 "Cannot sign/zero extend a FP/Vector load!");
3747 assert(VT.isInteger() == MemVT.isInteger() &&
3748 "Cannot convert from FP to Int or Int -> FP!");
3751 bool Indexed = AM != ISD::UNINDEXED;
3752 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3753 "Unindexed load with an offset!");
3755 SDVTList VTs = Indexed ?
3756 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3757 SDValue Ops[] = { Chain, Ptr, Offset };
3758 FoldingSetNodeID ID;
3759 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3760 ID.AddInteger(MemVT.getRawBits());
3761 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile()));
3763 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3764 cast<LoadSDNode>(E)->refineAlignment(MMO);
3765 return SDValue(E, 0);
3767 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3768 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, MemVT, MMO);
3769 CSEMap.InsertNode(N, IP);
3770 AllNodes.push_back(N);
3771 return SDValue(N, 0);
3774 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
3775 SDValue Chain, SDValue Ptr,
3776 const Value *SV, int SVOffset,
3777 bool isVolatile, unsigned Alignment) {
3778 SDValue Undef = getUNDEF(Ptr.getValueType());
3779 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3780 SV, SVOffset, VT, isVolatile, Alignment);
3783 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
3784 SDValue Chain, SDValue Ptr,
3786 int SVOffset, EVT MemVT,
3787 bool isVolatile, unsigned Alignment) {
3788 SDValue Undef = getUNDEF(Ptr.getValueType());
3789 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3790 SV, SVOffset, MemVT, isVolatile, Alignment);
3794 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3795 SDValue Offset, ISD::MemIndexedMode AM) {
3796 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3797 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3798 "Load is already a indexed load!");
3799 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3800 LD->getChain(), Base, Offset, LD->getSrcValue(),
3801 LD->getSrcValueOffset(), LD->getMemoryVT(),
3802 LD->isVolatile(), LD->getAlignment());
3805 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3806 SDValue Ptr, const Value *SV, int SVOffset,
3807 bool isVolatile, unsigned Alignment) {
3808 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3809 Alignment = getEVTAlignment(Val.getValueType());
3811 // Check if the memory reference references a frame index
3813 if (const FrameIndexSDNode *FI =
3814 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3815 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3817 MachineFunction &MF = getMachineFunction();
3818 unsigned Flags = MachineMemOperand::MOStore;
3820 Flags |= MachineMemOperand::MOVolatile;
3821 MachineMemOperand *MMO =
3822 MF.getMachineMemOperand(SV, Flags, SVOffset,
3823 Val.getValueType().getStoreSize(), Alignment);
3825 return getStore(Chain, dl, Val, Ptr, MMO);
3828 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3829 SDValue Ptr, MachineMemOperand *MMO) {
3830 EVT VT = Val.getValueType();
3831 SDVTList VTs = getVTList(MVT::Other);
3832 SDValue Undef = getUNDEF(Ptr.getValueType());
3833 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3834 FoldingSetNodeID ID;
3835 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3836 ID.AddInteger(VT.getRawBits());
3837 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile()));
3839 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3840 cast<StoreSDNode>(E)->refineAlignment(MMO);
3841 return SDValue(E, 0);
3843 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3844 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false, VT, MMO);
3845 CSEMap.InsertNode(N, IP);
3846 AllNodes.push_back(N);
3847 return SDValue(N, 0);
3850 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3851 SDValue Ptr, const Value *SV,
3852 int SVOffset, EVT SVT,
3853 bool isVolatile, unsigned Alignment) {
3854 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3855 Alignment = getEVTAlignment(SVT);
3857 // Check if the memory reference references a frame index
3859 if (const FrameIndexSDNode *FI =
3860 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3861 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3863 MachineFunction &MF = getMachineFunction();
3864 unsigned Flags = MachineMemOperand::MOStore;
3866 Flags |= MachineMemOperand::MOVolatile;
3867 MachineMemOperand *MMO =
3868 MF.getMachineMemOperand(SV, Flags, SVOffset, SVT.getStoreSize(), Alignment);
3870 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
3873 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3874 SDValue Ptr, EVT SVT,
3875 MachineMemOperand *MMO) {
3876 EVT VT = Val.getValueType();
3879 return getStore(Chain, dl, Val, Ptr, MMO);
3881 assert(VT.bitsGT(SVT) && "Not a truncation?");
3882 assert(VT.isInteger() == SVT.isInteger() &&
3883 "Can't do FP-INT conversion!");
3886 SDVTList VTs = getVTList(MVT::Other);
3887 SDValue Undef = getUNDEF(Ptr.getValueType());
3888 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3889 FoldingSetNodeID ID;
3890 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3891 ID.AddInteger(SVT.getRawBits());
3892 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile()));
3894 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3895 cast<StoreSDNode>(E)->refineAlignment(MMO);
3896 return SDValue(E, 0);
3898 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3899 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true, SVT, MMO);
3900 CSEMap.InsertNode(N, IP);
3901 AllNodes.push_back(N);
3902 return SDValue(N, 0);
3906 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
3907 SDValue Offset, ISD::MemIndexedMode AM) {
3908 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3909 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3910 "Store is already a indexed store!");
3911 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3912 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3913 FoldingSetNodeID ID;
3914 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3915 ID.AddInteger(ST->getMemoryVT().getRawBits());
3916 ID.AddInteger(ST->getRawSubclassData());
3918 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3919 return SDValue(E, 0);
3920 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3921 new (N) StoreSDNode(Ops, dl, VTs, AM,
3922 ST->isTruncatingStore(), ST->getMemoryVT(),
3923 ST->getMemOperand());
3924 CSEMap.InsertNode(N, IP);
3925 AllNodes.push_back(N);
3926 return SDValue(N, 0);
3929 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
3930 SDValue Chain, SDValue Ptr,
3932 SDValue Ops[] = { Chain, Ptr, SV };
3933 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
3936 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3937 const SDUse *Ops, unsigned NumOps) {
3939 case 0: return getNode(Opcode, DL, VT);
3940 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3941 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3942 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3946 // Copy from an SDUse array into an SDValue array for use with
3947 // the regular getNode logic.
3948 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3949 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
3952 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3953 const SDValue *Ops, unsigned NumOps) {
3955 case 0: return getNode(Opcode, DL, VT);
3956 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3957 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3958 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3964 case ISD::SELECT_CC: {
3965 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3966 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3967 "LHS and RHS of condition must have same type!");
3968 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3969 "True and False arms of SelectCC must have same type!");
3970 assert(Ops[2].getValueType() == VT &&
3971 "select_cc node must be of same type as true and false value!");
3975 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3976 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3977 "LHS/RHS of comparison should match types!");
3984 SDVTList VTs = getVTList(VT);
3986 if (VT != MVT::Flag) {
3987 FoldingSetNodeID ID;
3988 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3991 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3992 return SDValue(E, 0);
3994 N = NodeAllocator.Allocate<SDNode>();
3995 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3996 CSEMap.InsertNode(N, IP);
3998 N = NodeAllocator.Allocate<SDNode>();
3999 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4002 AllNodes.push_back(N);
4006 return SDValue(N, 0);
4009 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4010 const std::vector<EVT> &ResultTys,
4011 const SDValue *Ops, unsigned NumOps) {
4012 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4016 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4017 const EVT *VTs, unsigned NumVTs,
4018 const SDValue *Ops, unsigned NumOps) {
4020 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4021 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4024 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4025 const SDValue *Ops, unsigned NumOps) {
4026 if (VTList.NumVTs == 1)
4027 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4031 // FIXME: figure out how to safely handle things like
4032 // int foo(int x) { return 1 << (x & 255); }
4033 // int bar() { return foo(256); }
4034 case ISD::SRA_PARTS:
4035 case ISD::SRL_PARTS:
4036 case ISD::SHL_PARTS:
4037 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4038 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4039 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4040 else if (N3.getOpcode() == ISD::AND)
4041 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4042 // If the and is only masking out bits that cannot effect the shift,
4043 // eliminate the and.
4044 unsigned NumBits = VT.getSizeInBits()*2;
4045 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4046 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4052 // Memoize the node unless it returns a flag.
4054 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4055 FoldingSetNodeID ID;
4056 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4058 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4059 return SDValue(E, 0);
4061 N = NodeAllocator.Allocate<UnarySDNode>();
4062 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4063 } else if (NumOps == 2) {
4064 N = NodeAllocator.Allocate<BinarySDNode>();
4065 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4066 } else if (NumOps == 3) {
4067 N = NodeAllocator.Allocate<TernarySDNode>();
4068 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4070 N = NodeAllocator.Allocate<SDNode>();
4071 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4073 CSEMap.InsertNode(N, IP);
4076 N = NodeAllocator.Allocate<UnarySDNode>();
4077 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4078 } else if (NumOps == 2) {
4079 N = NodeAllocator.Allocate<BinarySDNode>();
4080 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4081 } else if (NumOps == 3) {
4082 N = NodeAllocator.Allocate<TernarySDNode>();
4083 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4085 N = NodeAllocator.Allocate<SDNode>();
4086 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4089 AllNodes.push_back(N);
4093 return SDValue(N, 0);
4096 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4097 return getNode(Opcode, DL, VTList, 0, 0);
4100 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4102 SDValue Ops[] = { N1 };
4103 return getNode(Opcode, DL, VTList, Ops, 1);
4106 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4107 SDValue N1, SDValue N2) {
4108 SDValue Ops[] = { N1, N2 };
4109 return getNode(Opcode, DL, VTList, Ops, 2);
4112 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4113 SDValue N1, SDValue N2, SDValue N3) {
4114 SDValue Ops[] = { N1, N2, N3 };
4115 return getNode(Opcode, DL, VTList, Ops, 3);
4118 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4119 SDValue N1, SDValue N2, SDValue N3,
4121 SDValue Ops[] = { N1, N2, N3, N4 };
4122 return getNode(Opcode, DL, VTList, Ops, 4);
4125 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4126 SDValue N1, SDValue N2, SDValue N3,
4127 SDValue N4, SDValue N5) {
4128 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4129 return getNode(Opcode, DL, VTList, Ops, 5);
4132 SDVTList SelectionDAG::getVTList(EVT VT) {
4133 return makeVTList(SDNode::getValueTypeList(VT), 1);
4136 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4137 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4138 E = VTList.rend(); I != E; ++I)
4139 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4142 EVT *Array = Allocator.Allocate<EVT>(2);
4145 SDVTList Result = makeVTList(Array, 2);
4146 VTList.push_back(Result);
4150 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4151 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4152 E = VTList.rend(); I != E; ++I)
4153 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4157 EVT *Array = Allocator.Allocate<EVT>(3);
4161 SDVTList Result = makeVTList(Array, 3);
4162 VTList.push_back(Result);
4166 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4167 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4168 E = VTList.rend(); I != E; ++I)
4169 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4170 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4173 EVT *Array = Allocator.Allocate<EVT>(3);
4178 SDVTList Result = makeVTList(Array, 4);
4179 VTList.push_back(Result);
4183 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4185 case 0: llvm_unreachable("Cannot have nodes without results!");
4186 case 1: return getVTList(VTs[0]);
4187 case 2: return getVTList(VTs[0], VTs[1]);
4188 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4192 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4193 E = VTList.rend(); I != E; ++I) {
4194 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4197 bool NoMatch = false;
4198 for (unsigned i = 2; i != NumVTs; ++i)
4199 if (VTs[i] != I->VTs[i]) {
4207 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4208 std::copy(VTs, VTs+NumVTs, Array);
4209 SDVTList Result = makeVTList(Array, NumVTs);
4210 VTList.push_back(Result);
4215 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4216 /// specified operands. If the resultant node already exists in the DAG,
4217 /// this does not modify the specified node, instead it returns the node that
4218 /// already exists. If the resultant node does not exist in the DAG, the
4219 /// input node is returned. As a degenerate case, if you specify the same
4220 /// input operands as the node already has, the input node is returned.
4221 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4222 SDNode *N = InN.getNode();
4223 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4225 // Check to see if there is no change.
4226 if (Op == N->getOperand(0)) return InN;
4228 // See if the modified node already exists.
4229 void *InsertPos = 0;
4230 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4231 return SDValue(Existing, InN.getResNo());
4233 // Nope it doesn't. Remove the node from its current place in the maps.
4235 if (!RemoveNodeFromCSEMaps(N))
4238 // Now we update the operands.
4239 N->OperandList[0].set(Op);
4241 // If this gets put into a CSE map, add it.
4242 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4246 SDValue SelectionDAG::
4247 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4248 SDNode *N = InN.getNode();
4249 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4251 // Check to see if there is no change.
4252 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4253 return InN; // No operands changed, just return the input node.
4255 // See if the modified node already exists.
4256 void *InsertPos = 0;
4257 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4258 return SDValue(Existing, InN.getResNo());
4260 // Nope it doesn't. Remove the node from its current place in the maps.
4262 if (!RemoveNodeFromCSEMaps(N))
4265 // Now we update the operands.
4266 if (N->OperandList[0] != Op1)
4267 N->OperandList[0].set(Op1);
4268 if (N->OperandList[1] != Op2)
4269 N->OperandList[1].set(Op2);
4271 // If this gets put into a CSE map, add it.
4272 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4276 SDValue SelectionDAG::
4277 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4278 SDValue Ops[] = { Op1, Op2, Op3 };
4279 return UpdateNodeOperands(N, Ops, 3);
4282 SDValue SelectionDAG::
4283 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4284 SDValue Op3, SDValue Op4) {
4285 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4286 return UpdateNodeOperands(N, Ops, 4);
4289 SDValue SelectionDAG::
4290 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4291 SDValue Op3, SDValue Op4, SDValue Op5) {
4292 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4293 return UpdateNodeOperands(N, Ops, 5);
4296 SDValue SelectionDAG::
4297 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4298 SDNode *N = InN.getNode();
4299 assert(N->getNumOperands() == NumOps &&
4300 "Update with wrong number of operands");
4302 // Check to see if there is no change.
4303 bool AnyChange = false;
4304 for (unsigned i = 0; i != NumOps; ++i) {
4305 if (Ops[i] != N->getOperand(i)) {
4311 // No operands changed, just return the input node.
4312 if (!AnyChange) return InN;
4314 // See if the modified node already exists.
4315 void *InsertPos = 0;
4316 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4317 return SDValue(Existing, InN.getResNo());
4319 // Nope it doesn't. Remove the node from its current place in the maps.
4321 if (!RemoveNodeFromCSEMaps(N))
4324 // Now we update the operands.
4325 for (unsigned i = 0; i != NumOps; ++i)
4326 if (N->OperandList[i] != Ops[i])
4327 N->OperandList[i].set(Ops[i]);
4329 // If this gets put into a CSE map, add it.
4330 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4334 /// DropOperands - Release the operands and set this node to have
4336 void SDNode::DropOperands() {
4337 // Unlike the code in MorphNodeTo that does this, we don't need to
4338 // watch for dead nodes here.
4339 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4345 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4348 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4350 SDVTList VTs = getVTList(VT);
4351 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4354 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4355 EVT VT, SDValue Op1) {
4356 SDVTList VTs = getVTList(VT);
4357 SDValue Ops[] = { Op1 };
4358 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4361 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4362 EVT VT, SDValue Op1,
4364 SDVTList VTs = getVTList(VT);
4365 SDValue Ops[] = { Op1, Op2 };
4366 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4369 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4370 EVT VT, SDValue Op1,
4371 SDValue Op2, SDValue Op3) {
4372 SDVTList VTs = getVTList(VT);
4373 SDValue Ops[] = { Op1, Op2, Op3 };
4374 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4377 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4378 EVT VT, const SDValue *Ops,
4380 SDVTList VTs = getVTList(VT);
4381 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4384 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4385 EVT VT1, EVT VT2, const SDValue *Ops,
4387 SDVTList VTs = getVTList(VT1, VT2);
4388 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4391 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4393 SDVTList VTs = getVTList(VT1, VT2);
4394 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4397 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4398 EVT VT1, EVT VT2, EVT VT3,
4399 const SDValue *Ops, unsigned NumOps) {
4400 SDVTList VTs = getVTList(VT1, VT2, VT3);
4401 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4404 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4405 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4406 const SDValue *Ops, unsigned NumOps) {
4407 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4408 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4411 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4414 SDVTList VTs = getVTList(VT1, VT2);
4415 SDValue Ops[] = { Op1 };
4416 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4419 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4421 SDValue Op1, SDValue Op2) {
4422 SDVTList VTs = getVTList(VT1, VT2);
4423 SDValue Ops[] = { Op1, Op2 };
4424 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4427 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4429 SDValue Op1, SDValue Op2,
4431 SDVTList VTs = getVTList(VT1, VT2);
4432 SDValue Ops[] = { Op1, Op2, Op3 };
4433 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4436 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4437 EVT VT1, EVT VT2, EVT VT3,
4438 SDValue Op1, SDValue Op2,
4440 SDVTList VTs = getVTList(VT1, VT2, VT3);
4441 SDValue Ops[] = { Op1, Op2, Op3 };
4442 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4445 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4446 SDVTList VTs, const SDValue *Ops,
4448 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4451 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4453 SDVTList VTs = getVTList(VT);
4454 return MorphNodeTo(N, Opc, VTs, 0, 0);
4457 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4458 EVT VT, SDValue Op1) {
4459 SDVTList VTs = getVTList(VT);
4460 SDValue Ops[] = { Op1 };
4461 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4464 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4465 EVT VT, SDValue Op1,
4467 SDVTList VTs = getVTList(VT);
4468 SDValue Ops[] = { Op1, Op2 };
4469 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4472 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4473 EVT VT, SDValue Op1,
4474 SDValue Op2, SDValue Op3) {
4475 SDVTList VTs = getVTList(VT);
4476 SDValue Ops[] = { Op1, Op2, Op3 };
4477 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4480 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4481 EVT VT, const SDValue *Ops,
4483 SDVTList VTs = getVTList(VT);
4484 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4487 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4488 EVT VT1, EVT VT2, const SDValue *Ops,
4490 SDVTList VTs = getVTList(VT1, VT2);
4491 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4494 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4496 SDVTList VTs = getVTList(VT1, VT2);
4497 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4500 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4501 EVT VT1, EVT VT2, EVT VT3,
4502 const SDValue *Ops, unsigned NumOps) {
4503 SDVTList VTs = getVTList(VT1, VT2, VT3);
4504 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4507 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4510 SDVTList VTs = getVTList(VT1, VT2);
4511 SDValue Ops[] = { Op1 };
4512 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4515 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4517 SDValue Op1, SDValue Op2) {
4518 SDVTList VTs = getVTList(VT1, VT2);
4519 SDValue Ops[] = { Op1, Op2 };
4520 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4523 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4525 SDValue Op1, SDValue Op2,
4527 SDVTList VTs = getVTList(VT1, VT2);
4528 SDValue Ops[] = { Op1, Op2, Op3 };
4529 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4532 /// MorphNodeTo - These *mutate* the specified node to have the specified
4533 /// return type, opcode, and operands.
4535 /// Note that MorphNodeTo returns the resultant node. If there is already a
4536 /// node of the specified opcode and operands, it returns that node instead of
4537 /// the current one. Note that the DebugLoc need not be the same.
4539 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4540 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4541 /// node, and because it doesn't require CSE recalculation for any of
4542 /// the node's users.
4544 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4545 SDVTList VTs, const SDValue *Ops,
4547 // If an identical node already exists, use it.
4549 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4550 FoldingSetNodeID ID;
4551 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4552 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4556 if (!RemoveNodeFromCSEMaps(N))
4559 // Start the morphing.
4561 N->ValueList = VTs.VTs;
4562 N->NumValues = VTs.NumVTs;
4564 // Clear the operands list, updating used nodes to remove this from their
4565 // use list. Keep track of any operands that become dead as a result.
4566 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4567 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4569 SDNode *Used = Use.getNode();
4571 if (Used->use_empty())
4572 DeadNodeSet.insert(Used);
4575 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4576 // Initialize the memory references information.
4577 MN->setMemRefs(0, 0);
4578 // If NumOps is larger than the # of operands we can have in a
4579 // MachineSDNode, reallocate the operand list.
4580 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4581 if (MN->OperandsNeedDelete)
4582 delete[] MN->OperandList;
4583 if (NumOps > array_lengthof(MN->LocalOperands))
4584 // We're creating a final node that will live unmorphed for the
4585 // remainder of the current SelectionDAG iteration, so we can allocate
4586 // the operands directly out of a pool with no recycling metadata.
4587 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4590 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4591 MN->OperandsNeedDelete = false;
4593 MN->InitOperands(MN->OperandList, Ops, NumOps);
4595 // If NumOps is larger than the # of operands we currently have, reallocate
4596 // the operand list.
4597 if (NumOps > N->NumOperands) {
4598 if (N->OperandsNeedDelete)
4599 delete[] N->OperandList;
4600 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4601 N->OperandsNeedDelete = true;
4603 MN->InitOperands(MN->OperandList, Ops, NumOps);
4606 // Delete any nodes that are still dead after adding the uses for the
4608 SmallVector<SDNode *, 16> DeadNodes;
4609 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4610 E = DeadNodeSet.end(); I != E; ++I)
4611 if ((*I)->use_empty())
4612 DeadNodes.push_back(*I);
4613 RemoveDeadNodes(DeadNodes);
4616 CSEMap.InsertNode(N, IP); // Memoize the new node.
4621 /// getMachineNode - These are used for target selectors to create a new node
4622 /// with specified return type(s), MachineInstr opcode, and operands.
4624 /// Note that getMachineNode returns the resultant node. If there is already a
4625 /// node of the specified opcode and operands, it returns that node instead of
4626 /// the current one.
4628 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4629 SDVTList VTs = getVTList(VT);
4630 return getMachineNode(Opcode, dl, VTs, 0, 0);
4634 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
4635 SDVTList VTs = getVTList(VT);
4636 SDValue Ops[] = { Op1 };
4637 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4641 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4642 SDValue Op1, SDValue Op2) {
4643 SDVTList VTs = getVTList(VT);
4644 SDValue Ops[] = { Op1, Op2 };
4645 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4649 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4650 SDValue Op1, SDValue Op2, SDValue Op3) {
4651 SDVTList VTs = getVTList(VT);
4652 SDValue Ops[] = { Op1, Op2, Op3 };
4653 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4657 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4658 const SDValue *Ops, unsigned NumOps) {
4659 SDVTList VTs = getVTList(VT);
4660 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4664 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
4665 SDVTList VTs = getVTList(VT1, VT2);
4666 return getMachineNode(Opcode, dl, VTs, 0, 0);
4670 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4671 EVT VT1, EVT VT2, SDValue Op1) {
4672 SDVTList VTs = getVTList(VT1, VT2);
4673 SDValue Ops[] = { Op1 };
4674 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4678 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4679 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
4680 SDVTList VTs = getVTList(VT1, VT2);
4681 SDValue Ops[] = { Op1, Op2 };
4682 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4686 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4687 EVT VT1, EVT VT2, SDValue Op1,
4688 SDValue Op2, SDValue Op3) {
4689 SDVTList VTs = getVTList(VT1, VT2);
4690 SDValue Ops[] = { Op1, Op2, Op3 };
4691 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4695 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4697 const SDValue *Ops, unsigned NumOps) {
4698 SDVTList VTs = getVTList(VT1, VT2);
4699 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4703 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4704 EVT VT1, EVT VT2, EVT VT3,
4705 SDValue Op1, SDValue Op2) {
4706 SDVTList VTs = getVTList(VT1, VT2, VT3);
4707 SDValue Ops[] = { Op1, Op2 };
4708 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4712 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4713 EVT VT1, EVT VT2, EVT VT3,
4714 SDValue Op1, SDValue Op2, SDValue Op3) {
4715 SDVTList VTs = getVTList(VT1, VT2, VT3);
4716 SDValue Ops[] = { Op1, Op2, Op3 };
4717 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4721 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4722 EVT VT1, EVT VT2, EVT VT3,
4723 const SDValue *Ops, unsigned NumOps) {
4724 SDVTList VTs = getVTList(VT1, VT2, VT3);
4725 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4729 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4730 EVT VT2, EVT VT3, EVT VT4,
4731 const SDValue *Ops, unsigned NumOps) {
4732 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4733 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4737 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4738 const std::vector<EVT> &ResultTys,
4739 const SDValue *Ops, unsigned NumOps) {
4740 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
4741 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4745 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
4746 const SDValue *Ops, unsigned NumOps) {
4747 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Flag;
4752 FoldingSetNodeID ID;
4753 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
4755 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4756 return cast<MachineSDNode>(E);
4759 // Allocate a new MachineSDNode.
4760 N = NodeAllocator.Allocate<MachineSDNode>();
4761 new (N) MachineSDNode(~Opcode, DL, VTs);
4763 // Initialize the operands list.
4764 if (NumOps > array_lengthof(N->LocalOperands))
4765 // We're creating a final node that will live unmorphed for the
4766 // remainder of the current SelectionDAG iteration, so we can allocate
4767 // the operands directly out of a pool with no recycling metadata.
4768 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4771 N->InitOperands(N->LocalOperands, Ops, NumOps);
4772 N->OperandsNeedDelete = false;
4775 CSEMap.InsertNode(N, IP);
4777 AllNodes.push_back(N);
4784 /// getTargetExtractSubreg - A convenience function for creating
4785 /// TargetInstrInfo::EXTRACT_SUBREG nodes.
4787 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4789 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4790 SDNode *Subreg = getMachineNode(TargetInstrInfo::EXTRACT_SUBREG, DL,
4791 VT, Operand, SRIdxVal);
4792 return SDValue(Subreg, 0);
4795 /// getTargetInsertSubreg - A convenience function for creating
4796 /// TargetInstrInfo::INSERT_SUBREG nodes.
4798 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
4799 SDValue Operand, SDValue Subreg) {
4800 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4801 SDNode *Result = getMachineNode(TargetInstrInfo::INSERT_SUBREG, DL,
4802 VT, Operand, Subreg, SRIdxVal);
4803 return SDValue(Result, 0);
4806 /// getNodeIfExists - Get the specified node if it's already available, or
4807 /// else return NULL.
4808 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4809 const SDValue *Ops, unsigned NumOps) {
4810 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4811 FoldingSetNodeID ID;
4812 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4814 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4820 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4821 /// This can cause recursive merging of nodes in the DAG.
4823 /// This version assumes From has a single result value.
4825 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4826 DAGUpdateListener *UpdateListener) {
4827 SDNode *From = FromN.getNode();
4828 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4829 "Cannot replace with this method!");
4830 assert(From != To.getNode() && "Cannot replace uses of with self");
4832 // Iterate over all the existing uses of From. New uses will be added
4833 // to the beginning of the use list, which we avoid visiting.
4834 // This specifically avoids visiting uses of From that arise while the
4835 // replacement is happening, because any such uses would be the result
4836 // of CSE: If an existing node looks like From after one of its operands
4837 // is replaced by To, we don't want to replace of all its users with To
4838 // too. See PR3018 for more info.
4839 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4843 // This node is about to morph, remove its old self from the CSE maps.
4844 RemoveNodeFromCSEMaps(User);
4846 // A user can appear in a use list multiple times, and when this
4847 // happens the uses are usually next to each other in the list.
4848 // To help reduce the number of CSE recomputations, process all
4849 // the uses of this user that we can find this way.
4851 SDUse &Use = UI.getUse();
4854 } while (UI != UE && *UI == User);
4856 // Now that we have modified User, add it back to the CSE maps. If it
4857 // already exists there, recursively merge the results together.
4858 AddModifiedNodeToCSEMaps(User, UpdateListener);
4862 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4863 /// This can cause recursive merging of nodes in the DAG.
4865 /// This version assumes that for each value of From, there is a
4866 /// corresponding value in To in the same position with the same type.
4868 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4869 DAGUpdateListener *UpdateListener) {
4871 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
4872 assert((!From->hasAnyUseOfValue(i) ||
4873 From->getValueType(i) == To->getValueType(i)) &&
4874 "Cannot use this version of ReplaceAllUsesWith!");
4877 // Handle the trivial case.
4881 // Iterate over just the existing users of From. See the comments in
4882 // the ReplaceAllUsesWith above.
4883 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4887 // This node is about to morph, remove its old self from the CSE maps.
4888 RemoveNodeFromCSEMaps(User);
4890 // A user can appear in a use list multiple times, and when this
4891 // happens the uses are usually next to each other in the list.
4892 // To help reduce the number of CSE recomputations, process all
4893 // the uses of this user that we can find this way.
4895 SDUse &Use = UI.getUse();
4898 } while (UI != UE && *UI == User);
4900 // Now that we have modified User, add it back to the CSE maps. If it
4901 // already exists there, recursively merge the results together.
4902 AddModifiedNodeToCSEMaps(User, UpdateListener);
4906 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4907 /// This can cause recursive merging of nodes in the DAG.
4909 /// This version can replace From with any result values. To must match the
4910 /// number and types of values returned by From.
4911 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4913 DAGUpdateListener *UpdateListener) {
4914 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4915 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4917 // Iterate over just the existing users of From. See the comments in
4918 // the ReplaceAllUsesWith above.
4919 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4923 // This node is about to morph, remove its old self from the CSE maps.
4924 RemoveNodeFromCSEMaps(User);
4926 // A user can appear in a use list multiple times, and when this
4927 // happens the uses are usually next to each other in the list.
4928 // To help reduce the number of CSE recomputations, process all
4929 // the uses of this user that we can find this way.
4931 SDUse &Use = UI.getUse();
4932 const SDValue &ToOp = To[Use.getResNo()];
4935 } while (UI != UE && *UI == User);
4937 // Now that we have modified User, add it back to the CSE maps. If it
4938 // already exists there, recursively merge the results together.
4939 AddModifiedNodeToCSEMaps(User, UpdateListener);
4943 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4944 /// uses of other values produced by From.getNode() alone. The Deleted
4945 /// vector is handled the same way as for ReplaceAllUsesWith.
4946 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4947 DAGUpdateListener *UpdateListener){
4948 // Handle the really simple, really trivial case efficiently.
4949 if (From == To) return;
4951 // Handle the simple, trivial, case efficiently.
4952 if (From.getNode()->getNumValues() == 1) {
4953 ReplaceAllUsesWith(From, To, UpdateListener);
4957 // Iterate over just the existing users of From. See the comments in
4958 // the ReplaceAllUsesWith above.
4959 SDNode::use_iterator UI = From.getNode()->use_begin(),
4960 UE = From.getNode()->use_end();
4963 bool UserRemovedFromCSEMaps = false;
4965 // A user can appear in a use list multiple times, and when this
4966 // happens the uses are usually next to each other in the list.
4967 // To help reduce the number of CSE recomputations, process all
4968 // the uses of this user that we can find this way.
4970 SDUse &Use = UI.getUse();
4972 // Skip uses of different values from the same node.
4973 if (Use.getResNo() != From.getResNo()) {
4978 // If this node hasn't been modified yet, it's still in the CSE maps,
4979 // so remove its old self from the CSE maps.
4980 if (!UserRemovedFromCSEMaps) {
4981 RemoveNodeFromCSEMaps(User);
4982 UserRemovedFromCSEMaps = true;
4987 } while (UI != UE && *UI == User);
4989 // We are iterating over all uses of the From node, so if a use
4990 // doesn't use the specific value, no changes are made.
4991 if (!UserRemovedFromCSEMaps)
4994 // Now that we have modified User, add it back to the CSE maps. If it
4995 // already exists there, recursively merge the results together.
4996 AddModifiedNodeToCSEMaps(User, UpdateListener);
5001 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5002 /// to record information about a use.
5009 /// operator< - Sort Memos by User.
5010 bool operator<(const UseMemo &L, const UseMemo &R) {
5011 return (intptr_t)L.User < (intptr_t)R.User;
5015 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5016 /// uses of other values produced by From.getNode() alone. The same value
5017 /// may appear in both the From and To list. The Deleted vector is
5018 /// handled the same way as for ReplaceAllUsesWith.
5019 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5022 DAGUpdateListener *UpdateListener){
5023 // Handle the simple, trivial case efficiently.
5025 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5027 // Read up all the uses and make records of them. This helps
5028 // processing new uses that are introduced during the
5029 // replacement process.
5030 SmallVector<UseMemo, 4> Uses;
5031 for (unsigned i = 0; i != Num; ++i) {
5032 unsigned FromResNo = From[i].getResNo();
5033 SDNode *FromNode = From[i].getNode();
5034 for (SDNode::use_iterator UI = FromNode->use_begin(),
5035 E = FromNode->use_end(); UI != E; ++UI) {
5036 SDUse &Use = UI.getUse();
5037 if (Use.getResNo() == FromResNo) {
5038 UseMemo Memo = { *UI, i, &Use };
5039 Uses.push_back(Memo);
5044 // Sort the uses, so that all the uses from a given User are together.
5045 std::sort(Uses.begin(), Uses.end());
5047 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5048 UseIndex != UseIndexEnd; ) {
5049 // We know that this user uses some value of From. If it is the right
5050 // value, update it.
5051 SDNode *User = Uses[UseIndex].User;
5053 // This node is about to morph, remove its old self from the CSE maps.
5054 RemoveNodeFromCSEMaps(User);
5056 // The Uses array is sorted, so all the uses for a given User
5057 // are next to each other in the list.
5058 // To help reduce the number of CSE recomputations, process all
5059 // the uses of this user that we can find this way.
5061 unsigned i = Uses[UseIndex].Index;
5062 SDUse &Use = *Uses[UseIndex].Use;
5066 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5068 // Now that we have modified User, add it back to the CSE maps. If it
5069 // already exists there, recursively merge the results together.
5070 AddModifiedNodeToCSEMaps(User, UpdateListener);
5074 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5075 /// based on their topological order. It returns the maximum id and a vector
5076 /// of the SDNodes* in assigned order by reference.
5077 unsigned SelectionDAG::AssignTopologicalOrder() {
5079 unsigned DAGSize = 0;
5081 // SortedPos tracks the progress of the algorithm. Nodes before it are
5082 // sorted, nodes after it are unsorted. When the algorithm completes
5083 // it is at the end of the list.
5084 allnodes_iterator SortedPos = allnodes_begin();
5086 // Visit all the nodes. Move nodes with no operands to the front of
5087 // the list immediately. Annotate nodes that do have operands with their
5088 // operand count. Before we do this, the Node Id fields of the nodes
5089 // may contain arbitrary values. After, the Node Id fields for nodes
5090 // before SortedPos will contain the topological sort index, and the
5091 // Node Id fields for nodes At SortedPos and after will contain the
5092 // count of outstanding operands.
5093 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5095 unsigned Degree = N->getNumOperands();
5097 // A node with no uses, add it to the result array immediately.
5098 N->setNodeId(DAGSize++);
5099 allnodes_iterator Q = N;
5101 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5104 // Temporarily use the Node Id as scratch space for the degree count.
5105 N->setNodeId(Degree);
5109 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5110 // such that by the time the end is reached all nodes will be sorted.
5111 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5113 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5116 unsigned Degree = P->getNodeId();
5119 // All of P's operands are sorted, so P may sorted now.
5120 P->setNodeId(DAGSize++);
5122 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5125 // Update P's outstanding operand count.
5126 P->setNodeId(Degree);
5131 assert(SortedPos == AllNodes.end() &&
5132 "Topological sort incomplete!");
5133 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5134 "First node in topological sort is not the entry token!");
5135 assert(AllNodes.front().getNodeId() == 0 &&
5136 "First node in topological sort has non-zero id!");
5137 assert(AllNodes.front().getNumOperands() == 0 &&
5138 "First node in topological sort has operands!");
5139 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5140 "Last node in topologic sort has unexpected id!");
5141 assert(AllNodes.back().use_empty() &&
5142 "Last node in topologic sort has users!");
5143 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5149 //===----------------------------------------------------------------------===//
5151 //===----------------------------------------------------------------------===//
5153 HandleSDNode::~HandleSDNode() {
5157 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
5158 EVT VT, int64_t o, unsigned char TF)
5159 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
5160 Offset(o), TargetFlags(TF) {
5161 TheGlobal = const_cast<GlobalValue*>(GA);
5164 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5165 MachineMemOperand *mmo)
5166 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5167 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile());
5168 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5169 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5172 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5173 const SDValue *Ops, unsigned NumOps, EVT memvt,
5174 MachineMemOperand *mmo)
5175 : SDNode(Opc, dl, VTs, Ops, NumOps),
5176 MemoryVT(memvt), MMO(mmo) {
5177 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile());
5178 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5179 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5182 /// Profile - Gather unique data for the node.
5184 void SDNode::Profile(FoldingSetNodeID &ID) const {
5185 AddNodeIDNode(ID, this);
5190 std::vector<EVT> VTs;
5193 VTs.reserve(MVT::LAST_VALUETYPE);
5194 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5195 VTs.push_back(MVT((MVT::SimpleValueType)i));
5200 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5201 static ManagedStatic<EVTArray> SimpleVTArray;
5202 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5204 /// getValueTypeList - Return a pointer to the specified value type.
5206 const EVT *SDNode::getValueTypeList(EVT VT) {
5207 if (VT.isExtended()) {
5208 sys::SmartScopedLock<true> Lock(*VTMutex);
5209 return &(*EVTs->insert(VT).first);
5211 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5215 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5216 /// indicated value. This method ignores uses of other values defined by this
5218 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5219 assert(Value < getNumValues() && "Bad value!");
5221 // TODO: Only iterate over uses of a given value of the node
5222 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5223 if (UI.getUse().getResNo() == Value) {
5230 // Found exactly the right number of uses?
5235 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5236 /// value. This method ignores uses of other values defined by this operation.
5237 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5238 assert(Value < getNumValues() && "Bad value!");
5240 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5241 if (UI.getUse().getResNo() == Value)
5248 /// isOnlyUserOf - Return true if this node is the only use of N.
5250 bool SDNode::isOnlyUserOf(SDNode *N) const {
5252 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5263 /// isOperand - Return true if this node is an operand of N.
5265 bool SDValue::isOperandOf(SDNode *N) const {
5266 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5267 if (*this == N->getOperand(i))
5272 bool SDNode::isOperandOf(SDNode *N) const {
5273 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5274 if (this == N->OperandList[i].getNode())
5279 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5280 /// be a chain) reaches the specified operand without crossing any
5281 /// side-effecting instructions. In practice, this looks through token
5282 /// factors and non-volatile loads. In order to remain efficient, this only
5283 /// looks a couple of nodes in, it does not do an exhaustive search.
5284 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5285 unsigned Depth) const {
5286 if (*this == Dest) return true;
5288 // Don't search too deeply, we just want to be able to see through
5289 // TokenFactor's etc.
5290 if (Depth == 0) return false;
5292 // If this is a token factor, all inputs to the TF happen in parallel. If any
5293 // of the operands of the TF reach dest, then we can do the xform.
5294 if (getOpcode() == ISD::TokenFactor) {
5295 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5296 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5301 // Loads don't have side effects, look through them.
5302 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5303 if (!Ld->isVolatile())
5304 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5310 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
5311 SmallPtrSet<SDNode *, 32> &Visited) {
5312 if (found || !Visited.insert(N))
5315 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
5316 SDNode *Op = N->getOperand(i).getNode();
5321 findPredecessor(Op, P, found, Visited);
5325 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5326 /// is either an operand of N or it can be reached by recursively traversing
5327 /// up the operands.
5328 /// NOTE: this is an expensive method. Use it carefully.
5329 bool SDNode::isPredecessorOf(SDNode *N) const {
5330 SmallPtrSet<SDNode *, 32> Visited;
5332 findPredecessor(N, this, found, Visited);
5336 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5337 assert(Num < NumOperands && "Invalid child # of SDNode!");
5338 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5341 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5342 switch (getOpcode()) {
5344 if (getOpcode() < ISD::BUILTIN_OP_END)
5345 return "<<Unknown DAG Node>>";
5346 if (isMachineOpcode()) {
5348 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5349 if (getMachineOpcode() < TII->getNumOpcodes())
5350 return TII->get(getMachineOpcode()).getName();
5351 return "<<Unknown Machine Node>>";
5354 const TargetLowering &TLI = G->getTargetLoweringInfo();
5355 const char *Name = TLI.getTargetNodeName(getOpcode());
5356 if (Name) return Name;
5357 return "<<Unknown Target Node>>";
5359 return "<<Unknown Node>>";
5362 case ISD::DELETED_NODE:
5363 return "<<Deleted Node!>>";
5365 case ISD::PREFETCH: return "Prefetch";
5366 case ISD::MEMBARRIER: return "MemBarrier";
5367 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5368 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5369 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5370 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5371 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5372 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5373 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5374 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5375 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5376 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5377 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5378 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5379 case ISD::PCMARKER: return "PCMarker";
5380 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5381 case ISD::SRCVALUE: return "SrcValue";
5382 case ISD::EntryToken: return "EntryToken";
5383 case ISD::TokenFactor: return "TokenFactor";
5384 case ISD::AssertSext: return "AssertSext";
5385 case ISD::AssertZext: return "AssertZext";
5387 case ISD::BasicBlock: return "BasicBlock";
5388 case ISD::VALUETYPE: return "ValueType";
5389 case ISD::Register: return "Register";
5391 case ISD::Constant: return "Constant";
5392 case ISD::ConstantFP: return "ConstantFP";
5393 case ISD::GlobalAddress: return "GlobalAddress";
5394 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5395 case ISD::FrameIndex: return "FrameIndex";
5396 case ISD::JumpTable: return "JumpTable";
5397 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5398 case ISD::RETURNADDR: return "RETURNADDR";
5399 case ISD::FRAMEADDR: return "FRAMEADDR";
5400 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5401 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5402 case ISD::LSDAADDR: return "LSDAADDR";
5403 case ISD::EHSELECTION: return "EHSELECTION";
5404 case ISD::EH_RETURN: return "EH_RETURN";
5405 case ISD::ConstantPool: return "ConstantPool";
5406 case ISD::ExternalSymbol: return "ExternalSymbol";
5407 case ISD::INTRINSIC_WO_CHAIN: {
5408 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
5409 return Intrinsic::getName((Intrinsic::ID)IID);
5411 case ISD::INTRINSIC_VOID:
5412 case ISD::INTRINSIC_W_CHAIN: {
5413 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
5414 return Intrinsic::getName((Intrinsic::ID)IID);
5417 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5418 case ISD::TargetConstant: return "TargetConstant";
5419 case ISD::TargetConstantFP:return "TargetConstantFP";
5420 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5421 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5422 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5423 case ISD::TargetJumpTable: return "TargetJumpTable";
5424 case ISD::TargetConstantPool: return "TargetConstantPool";
5425 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5427 case ISD::CopyToReg: return "CopyToReg";
5428 case ISD::CopyFromReg: return "CopyFromReg";
5429 case ISD::UNDEF: return "undef";
5430 case ISD::MERGE_VALUES: return "merge_values";
5431 case ISD::INLINEASM: return "inlineasm";
5432 case ISD::DBG_LABEL: return "dbg_label";
5433 case ISD::EH_LABEL: return "eh_label";
5434 case ISD::HANDLENODE: return "handlenode";
5437 case ISD::FABS: return "fabs";
5438 case ISD::FNEG: return "fneg";
5439 case ISD::FSQRT: return "fsqrt";
5440 case ISD::FSIN: return "fsin";
5441 case ISD::FCOS: return "fcos";
5442 case ISD::FPOWI: return "fpowi";
5443 case ISD::FPOW: return "fpow";
5444 case ISD::FTRUNC: return "ftrunc";
5445 case ISD::FFLOOR: return "ffloor";
5446 case ISD::FCEIL: return "fceil";
5447 case ISD::FRINT: return "frint";
5448 case ISD::FNEARBYINT: return "fnearbyint";
5451 case ISD::ADD: return "add";
5452 case ISD::SUB: return "sub";
5453 case ISD::MUL: return "mul";
5454 case ISD::MULHU: return "mulhu";
5455 case ISD::MULHS: return "mulhs";
5456 case ISD::SDIV: return "sdiv";
5457 case ISD::UDIV: return "udiv";
5458 case ISD::SREM: return "srem";
5459 case ISD::UREM: return "urem";
5460 case ISD::SMUL_LOHI: return "smul_lohi";
5461 case ISD::UMUL_LOHI: return "umul_lohi";
5462 case ISD::SDIVREM: return "sdivrem";
5463 case ISD::UDIVREM: return "udivrem";
5464 case ISD::AND: return "and";
5465 case ISD::OR: return "or";
5466 case ISD::XOR: return "xor";
5467 case ISD::SHL: return "shl";
5468 case ISD::SRA: return "sra";
5469 case ISD::SRL: return "srl";
5470 case ISD::ROTL: return "rotl";
5471 case ISD::ROTR: return "rotr";
5472 case ISD::FADD: return "fadd";
5473 case ISD::FSUB: return "fsub";
5474 case ISD::FMUL: return "fmul";
5475 case ISD::FDIV: return "fdiv";
5476 case ISD::FREM: return "frem";
5477 case ISD::FCOPYSIGN: return "fcopysign";
5478 case ISD::FGETSIGN: return "fgetsign";
5480 case ISD::SETCC: return "setcc";
5481 case ISD::VSETCC: return "vsetcc";
5482 case ISD::SELECT: return "select";
5483 case ISD::SELECT_CC: return "select_cc";
5484 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5485 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5486 case ISD::CONCAT_VECTORS: return "concat_vectors";
5487 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5488 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5489 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5490 case ISD::CARRY_FALSE: return "carry_false";
5491 case ISD::ADDC: return "addc";
5492 case ISD::ADDE: return "adde";
5493 case ISD::SADDO: return "saddo";
5494 case ISD::UADDO: return "uaddo";
5495 case ISD::SSUBO: return "ssubo";
5496 case ISD::USUBO: return "usubo";
5497 case ISD::SMULO: return "smulo";
5498 case ISD::UMULO: return "umulo";
5499 case ISD::SUBC: return "subc";
5500 case ISD::SUBE: return "sube";
5501 case ISD::SHL_PARTS: return "shl_parts";
5502 case ISD::SRA_PARTS: return "sra_parts";
5503 case ISD::SRL_PARTS: return "srl_parts";
5505 // Conversion operators.
5506 case ISD::SIGN_EXTEND: return "sign_extend";
5507 case ISD::ZERO_EXTEND: return "zero_extend";
5508 case ISD::ANY_EXTEND: return "any_extend";
5509 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5510 case ISD::TRUNCATE: return "truncate";
5511 case ISD::FP_ROUND: return "fp_round";
5512 case ISD::FLT_ROUNDS_: return "flt_rounds";
5513 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5514 case ISD::FP_EXTEND: return "fp_extend";
5516 case ISD::SINT_TO_FP: return "sint_to_fp";
5517 case ISD::UINT_TO_FP: return "uint_to_fp";
5518 case ISD::FP_TO_SINT: return "fp_to_sint";
5519 case ISD::FP_TO_UINT: return "fp_to_uint";
5520 case ISD::BIT_CONVERT: return "bit_convert";
5522 case ISD::CONVERT_RNDSAT: {
5523 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5524 default: llvm_unreachable("Unknown cvt code!");
5525 case ISD::CVT_FF: return "cvt_ff";
5526 case ISD::CVT_FS: return "cvt_fs";
5527 case ISD::CVT_FU: return "cvt_fu";
5528 case ISD::CVT_SF: return "cvt_sf";
5529 case ISD::CVT_UF: return "cvt_uf";
5530 case ISD::CVT_SS: return "cvt_ss";
5531 case ISD::CVT_SU: return "cvt_su";
5532 case ISD::CVT_US: return "cvt_us";
5533 case ISD::CVT_UU: return "cvt_uu";
5537 // Control flow instructions
5538 case ISD::BR: return "br";
5539 case ISD::BRIND: return "brind";
5540 case ISD::BR_JT: return "br_jt";
5541 case ISD::BRCOND: return "brcond";
5542 case ISD::BR_CC: return "br_cc";
5543 case ISD::CALLSEQ_START: return "callseq_start";
5544 case ISD::CALLSEQ_END: return "callseq_end";
5547 case ISD::LOAD: return "load";
5548 case ISD::STORE: return "store";
5549 case ISD::VAARG: return "vaarg";
5550 case ISD::VACOPY: return "vacopy";
5551 case ISD::VAEND: return "vaend";
5552 case ISD::VASTART: return "vastart";
5553 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5554 case ISD::EXTRACT_ELEMENT: return "extract_element";
5555 case ISD::BUILD_PAIR: return "build_pair";
5556 case ISD::STACKSAVE: return "stacksave";
5557 case ISD::STACKRESTORE: return "stackrestore";
5558 case ISD::TRAP: return "trap";
5561 case ISD::BSWAP: return "bswap";
5562 case ISD::CTPOP: return "ctpop";
5563 case ISD::CTTZ: return "cttz";
5564 case ISD::CTLZ: return "ctlz";
5567 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5568 case ISD::DEBUG_LOC: return "debug_loc";
5571 case ISD::TRAMPOLINE: return "trampoline";
5574 switch (cast<CondCodeSDNode>(this)->get()) {
5575 default: llvm_unreachable("Unknown setcc condition!");
5576 case ISD::SETOEQ: return "setoeq";
5577 case ISD::SETOGT: return "setogt";
5578 case ISD::SETOGE: return "setoge";
5579 case ISD::SETOLT: return "setolt";
5580 case ISD::SETOLE: return "setole";
5581 case ISD::SETONE: return "setone";
5583 case ISD::SETO: return "seto";
5584 case ISD::SETUO: return "setuo";
5585 case ISD::SETUEQ: return "setue";
5586 case ISD::SETUGT: return "setugt";
5587 case ISD::SETUGE: return "setuge";
5588 case ISD::SETULT: return "setult";
5589 case ISD::SETULE: return "setule";
5590 case ISD::SETUNE: return "setune";
5592 case ISD::SETEQ: return "seteq";
5593 case ISD::SETGT: return "setgt";
5594 case ISD::SETGE: return "setge";
5595 case ISD::SETLT: return "setlt";
5596 case ISD::SETLE: return "setle";
5597 case ISD::SETNE: return "setne";
5602 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5611 return "<post-inc>";
5613 return "<post-dec>";
5617 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5618 std::string S = "< ";
5632 if (getByValAlign())
5633 S += "byval-align:" + utostr(getByValAlign()) + " ";
5635 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5637 S += "byval-size:" + utostr(getByValSize()) + " ";
5641 void SDNode::dump() const { dump(0); }
5642 void SDNode::dump(const SelectionDAG *G) const {
5646 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5647 OS << (void*)this << ": ";
5649 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5651 if (getValueType(i) == MVT::Other)
5654 OS << getValueType(i).getEVTString();
5656 OS << " = " << getOperationName(G);
5659 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5660 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
5661 if (!MN->memoperands_empty()) {
5664 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
5665 e = MN->memoperands_end(); i != e; ++i) {
5672 } else if (const ShuffleVectorSDNode *SVN =
5673 dyn_cast<ShuffleVectorSDNode>(this)) {
5675 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5676 int Idx = SVN->getMaskElt(i);
5684 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5685 OS << '<' << CSDN->getAPIntValue() << '>';
5686 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5687 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5688 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5689 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5690 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5693 CSDN->getValueAPF().bitcastToAPInt().dump();
5696 } else if (const GlobalAddressSDNode *GADN =
5697 dyn_cast<GlobalAddressSDNode>(this)) {
5698 int64_t offset = GADN->getOffset();
5700 WriteAsOperand(OS, GADN->getGlobal());
5703 OS << " + " << offset;
5705 OS << " " << offset;
5706 if (unsigned int TF = GADN->getTargetFlags())
5707 OS << " [TF=" << TF << ']';
5708 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5709 OS << "<" << FIDN->getIndex() << ">";
5710 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5711 OS << "<" << JTDN->getIndex() << ">";
5712 if (unsigned int TF = JTDN->getTargetFlags())
5713 OS << " [TF=" << TF << ']';
5714 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5715 int offset = CP->getOffset();
5716 if (CP->isMachineConstantPoolEntry())
5717 OS << "<" << *CP->getMachineCPVal() << ">";
5719 OS << "<" << *CP->getConstVal() << ">";
5721 OS << " + " << offset;
5723 OS << " " << offset;
5724 if (unsigned int TF = CP->getTargetFlags())
5725 OS << " [TF=" << TF << ']';
5726 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5728 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5730 OS << LBB->getName() << " ";
5731 OS << (const void*)BBDN->getBasicBlock() << ">";
5732 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5733 if (G && R->getReg() &&
5734 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5735 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5737 OS << " #" << R->getReg();
5739 } else if (const ExternalSymbolSDNode *ES =
5740 dyn_cast<ExternalSymbolSDNode>(this)) {
5741 OS << "'" << ES->getSymbol() << "'";
5742 if (unsigned int TF = ES->getTargetFlags())
5743 OS << " [TF=" << TF << ']';
5744 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5746 OS << "<" << M->getValue() << ">";
5749 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5750 OS << ":" << N->getVT().getEVTString();
5752 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5753 OS << " <" << *LD->getMemOperand();
5756 switch (LD->getExtensionType()) {
5757 default: doExt = false; break;
5758 case ISD::EXTLOAD: OS << ", anyext"; break;
5759 case ISD::SEXTLOAD: OS << ", sext"; break;
5760 case ISD::ZEXTLOAD: OS << ", zext"; break;
5763 OS << " from " << LD->getMemoryVT().getEVTString();
5765 const char *AM = getIndexedModeName(LD->getAddressingMode());
5770 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5771 OS << " <" << *ST->getMemOperand();
5773 if (ST->isTruncatingStore())
5774 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
5776 const char *AM = getIndexedModeName(ST->getAddressingMode());
5781 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
5782 OS << " <" << *M->getMemOperand() << ">";
5786 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5789 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5791 OS << (void*)getOperand(i).getNode();
5792 if (unsigned RN = getOperand(i).getResNo())
5795 print_details(OS, G);
5798 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5799 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5800 if (N->getOperand(i).getNode()->hasOneUse())
5801 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5803 errs() << "\n" << std::string(indent+2, ' ')
5804 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5808 errs().indent(indent);
5812 void SelectionDAG::dump() const {
5813 errs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
5815 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5817 const SDNode *N = I;
5818 if (!N->hasOneUse() && N != getRoot().getNode())
5819 DumpNodes(N, 2, this);
5822 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5827 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
5829 print_details(OS, G);
5832 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
5833 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
5834 const SelectionDAG *G, VisitedSDNodeSet &once) {
5835 if (!once.insert(N)) // If we've been here before, return now.
5837 // Dump the current SDNode, but don't end the line yet.
5838 OS << std::string(indent, ' ');
5840 // Having printed this SDNode, walk the children:
5841 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5842 const SDNode *child = N->getOperand(i).getNode();
5845 if (child->getNumOperands() == 0) {
5846 // This child has no grandchildren; print it inline right here.
5847 child->printr(OS, G);
5849 } else { // Just the address. FIXME: also print the child's opcode
5851 if (unsigned RN = N->getOperand(i).getResNo())
5856 // Dump children that have grandchildren on their own line(s).
5857 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5858 const SDNode *child = N->getOperand(i).getNode();
5859 DumpNodesr(OS, child, indent+2, G, once);
5863 void SDNode::dumpr() const {
5864 VisitedSDNodeSet once;
5865 DumpNodesr(errs(), this, 0, 0, once);
5868 void SDNode::dumpr(const SelectionDAG *G) const {
5869 VisitedSDNodeSet once;
5870 DumpNodesr(errs(), this, 0, G, once);
5874 // getAddressSpace - Return the address space this GlobalAddress belongs to.
5875 unsigned GlobalAddressSDNode::getAddressSpace() const {
5876 return getGlobal()->getType()->getAddressSpace();
5880 const Type *ConstantPoolSDNode::getType() const {
5881 if (isMachineConstantPoolEntry())
5882 return Val.MachineCPVal->getType();
5883 return Val.ConstVal->getType();
5886 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
5888 unsigned &SplatBitSize,
5890 unsigned MinSplatBits) {
5891 EVT VT = getValueType(0);
5892 assert(VT.isVector() && "Expected a vector type");
5893 unsigned sz = VT.getSizeInBits();
5894 if (MinSplatBits > sz)
5897 SplatValue = APInt(sz, 0);
5898 SplatUndef = APInt(sz, 0);
5900 // Get the bits. Bits with undefined values (when the corresponding element
5901 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
5902 // in SplatValue. If any of the values are not constant, give up and return
5904 unsigned int nOps = getNumOperands();
5905 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
5906 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
5907 for (unsigned i = 0; i < nOps; ++i) {
5908 SDValue OpVal = getOperand(i);
5909 unsigned BitPos = i * EltBitSize;
5911 if (OpVal.getOpcode() == ISD::UNDEF)
5912 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos +EltBitSize);
5913 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
5914 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
5915 zextOrTrunc(sz) << BitPos);
5916 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
5917 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
5922 // The build_vector is all constants or undefs. Find the smallest element
5923 // size that splats the vector.
5925 HasAnyUndefs = (SplatUndef != 0);
5928 unsigned HalfSize = sz / 2;
5929 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
5930 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
5931 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
5932 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
5934 // If the two halves do not match (ignoring undef bits), stop here.
5935 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
5936 MinSplatBits > HalfSize)
5939 SplatValue = HighValue | LowValue;
5940 SplatUndef = HighUndef & LowUndef;
5949 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
5950 // Find the first non-undef value in the shuffle mask.
5952 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
5955 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
5957 // Make sure all remaining elements are either undef or the same as the first
5959 for (int Idx = Mask[i]; i != e; ++i)
5960 if (Mask[i] >= 0 && Mask[i] != Idx)