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/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/StringExtras.h"
43 /// makeVTList - Return an instance of the SDVTList struct initialized with the
44 /// specified members.
45 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
46 SDVTList Res = {VTs, NumVTs};
50 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
51 switch (VT.getSimpleVT()) {
52 default: assert(0 && "Unknown FP format");
53 case MVT::f32: return &APFloat::IEEEsingle;
54 case MVT::f64: return &APFloat::IEEEdouble;
55 case MVT::f80: return &APFloat::x87DoubleExtended;
56 case MVT::f128: return &APFloat::IEEEquad;
57 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
61 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
63 //===----------------------------------------------------------------------===//
64 // ConstantFPSDNode Class
65 //===----------------------------------------------------------------------===//
67 /// isExactlyValue - We don't rely on operator== working on double values, as
68 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
69 /// As such, this method can be used to do an exact bit-for-bit comparison of
70 /// two floating point values.
71 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
72 return Value.bitwiseIsEqual(V);
75 bool ConstantFPSDNode::isValueValidForType(MVT VT,
77 assert(VT.isFloatingPoint() && "Can only convert between FP types");
79 // PPC long double cannot be converted to any other type.
80 if (VT == MVT::ppcf128 ||
81 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
84 // convert modifies in place, so make a copy.
85 APFloat Val2 = APFloat(Val);
86 return Val2.convert(*MVTToAPFloatSemantics(VT),
87 APFloat::rmNearestTiesToEven) == APFloat::opOK;
90 //===----------------------------------------------------------------------===//
92 //===----------------------------------------------------------------------===//
94 /// isBuildVectorAllOnes - Return true if the specified node is a
95 /// BUILD_VECTOR where all of the elements are ~0 or undef.
96 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
97 // Look through a bit convert.
98 if (N->getOpcode() == ISD::BIT_CONVERT)
99 N = N->getOperand(0).Val;
101 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
103 unsigned i = 0, e = N->getNumOperands();
105 // Skip over all of the undef values.
106 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
109 // Do not accept an all-undef vector.
110 if (i == e) return false;
112 // Do not accept build_vectors that aren't all constants or which have non-~0
114 SDValue NotZero = N->getOperand(i);
115 if (isa<ConstantSDNode>(NotZero)) {
116 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
118 } else if (isa<ConstantFPSDNode>(NotZero)) {
119 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
120 convertToAPInt().isAllOnesValue())
125 // Okay, we have at least one ~0 value, check to see if the rest match or are
127 for (++i; i != e; ++i)
128 if (N->getOperand(i) != NotZero &&
129 N->getOperand(i).getOpcode() != ISD::UNDEF)
135 /// isBuildVectorAllZeros - Return true if the specified node is a
136 /// BUILD_VECTOR where all of the elements are 0 or undef.
137 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
138 // Look through a bit convert.
139 if (N->getOpcode() == ISD::BIT_CONVERT)
140 N = N->getOperand(0).Val;
142 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
144 unsigned i = 0, e = N->getNumOperands();
146 // Skip over all of the undef values.
147 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
150 // Do not accept an all-undef vector.
151 if (i == e) return false;
153 // Do not accept build_vectors that aren't all constants or which have non-~0
155 SDValue Zero = N->getOperand(i);
156 if (isa<ConstantSDNode>(Zero)) {
157 if (!cast<ConstantSDNode>(Zero)->isNullValue())
159 } else if (isa<ConstantFPSDNode>(Zero)) {
160 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
165 // Okay, we have at least one ~0 value, check to see if the rest match or are
167 for (++i; i != e; ++i)
168 if (N->getOperand(i) != Zero &&
169 N->getOperand(i).getOpcode() != ISD::UNDEF)
174 /// isScalarToVector - Return true if the specified node is a
175 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
176 /// element is not an undef.
177 bool ISD::isScalarToVector(const SDNode *N) {
178 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
181 if (N->getOpcode() != ISD::BUILD_VECTOR)
183 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
185 unsigned NumElems = N->getNumOperands();
186 for (unsigned i = 1; i < NumElems; ++i) {
187 SDValue V = N->getOperand(i);
188 if (V.getOpcode() != ISD::UNDEF)
195 /// isDebugLabel - Return true if the specified node represents a debug
196 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
197 bool ISD::isDebugLabel(const SDNode *N) {
199 if (N->getOpcode() == ISD::DBG_LABEL)
201 if (N->isMachineOpcode() &&
202 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
207 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
208 /// when given the operation for (X op Y).
209 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
210 // To perform this operation, we just need to swap the L and G bits of the
212 unsigned OldL = (Operation >> 2) & 1;
213 unsigned OldG = (Operation >> 1) & 1;
214 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
215 (OldL << 1) | // New G bit
216 (OldG << 2)); // New L bit.
219 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
220 /// 'op' is a valid SetCC operation.
221 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
222 unsigned Operation = Op;
224 Operation ^= 7; // Flip L, G, E bits, but not U.
226 Operation ^= 15; // Flip all of the condition bits.
227 if (Operation > ISD::SETTRUE2)
228 Operation &= ~8; // Don't let N and U bits get set.
229 return ISD::CondCode(Operation);
233 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
234 /// signed operation and 2 if the result is an unsigned comparison. Return zero
235 /// if the operation does not depend on the sign of the input (setne and seteq).
236 static int isSignedOp(ISD::CondCode Opcode) {
238 default: assert(0 && "Illegal integer setcc operation!");
240 case ISD::SETNE: return 0;
244 case ISD::SETGE: return 1;
248 case ISD::SETUGE: return 2;
252 /// getSetCCOrOperation - Return the result of a logical OR between different
253 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
254 /// returns SETCC_INVALID if it is not possible to represent the resultant
256 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
258 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
259 // Cannot fold a signed integer setcc with an unsigned integer setcc.
260 return ISD::SETCC_INVALID;
262 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
264 // If the N and U bits get set then the resultant comparison DOES suddenly
265 // care about orderedness, and is true when ordered.
266 if (Op > ISD::SETTRUE2)
267 Op &= ~16; // Clear the U bit if the N bit is set.
269 // Canonicalize illegal integer setcc's.
270 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
273 return ISD::CondCode(Op);
276 /// getSetCCAndOperation - Return the result of a logical AND between different
277 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
278 /// function returns zero if it is not possible to represent the resultant
280 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
282 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
283 // Cannot fold a signed setcc with an unsigned setcc.
284 return ISD::SETCC_INVALID;
286 // Combine all of the condition bits.
287 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
289 // Canonicalize illegal integer setcc's.
293 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
294 case ISD::SETOEQ: // SETEQ & SETU[LG]E
295 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
296 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
297 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
304 const TargetMachine &SelectionDAG::getTarget() const {
305 return TLI.getTargetMachine();
308 //===----------------------------------------------------------------------===//
309 // SDNode Profile Support
310 //===----------------------------------------------------------------------===//
312 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
314 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
318 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
319 /// solely with their pointer.
320 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
321 ID.AddPointer(VTList.VTs);
324 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
326 static void AddNodeIDOperands(FoldingSetNodeID &ID,
327 const SDValue *Ops, unsigned NumOps) {
328 for (; NumOps; --NumOps, ++Ops) {
329 ID.AddPointer(Ops->Val);
330 ID.AddInteger(Ops->ResNo);
334 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
336 static void AddNodeIDOperands(FoldingSetNodeID &ID,
337 const SDUse *Ops, unsigned NumOps) {
338 for (; NumOps; --NumOps, ++Ops) {
339 ID.AddPointer(Ops->getVal());
340 ID.AddInteger(Ops->getSDValue().ResNo);
344 static void AddNodeIDNode(FoldingSetNodeID &ID,
345 unsigned short OpC, SDVTList VTList,
346 const SDValue *OpList, unsigned N) {
347 AddNodeIDOpcode(ID, OpC);
348 AddNodeIDValueTypes(ID, VTList);
349 AddNodeIDOperands(ID, OpList, N);
353 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
355 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
356 AddNodeIDOpcode(ID, N->getOpcode());
357 // Add the return value info.
358 AddNodeIDValueTypes(ID, N->getVTList());
359 // Add the operand info.
360 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
362 // Handle SDNode leafs with special info.
363 switch (N->getOpcode()) {
364 default: break; // Normal nodes don't need extra info.
366 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
368 case ISD::TargetConstant:
370 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
372 case ISD::TargetConstantFP:
373 case ISD::ConstantFP: {
374 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
377 case ISD::TargetGlobalAddress:
378 case ISD::GlobalAddress:
379 case ISD::TargetGlobalTLSAddress:
380 case ISD::GlobalTLSAddress: {
381 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
382 ID.AddPointer(GA->getGlobal());
383 ID.AddInteger(GA->getOffset());
386 case ISD::BasicBlock:
387 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
390 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
392 case ISD::DBG_STOPPOINT: {
393 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
394 ID.AddInteger(DSP->getLine());
395 ID.AddInteger(DSP->getColumn());
396 ID.AddPointer(DSP->getCompileUnit());
400 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
402 case ISD::MEMOPERAND: {
403 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
407 case ISD::FrameIndex:
408 case ISD::TargetFrameIndex:
409 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
412 case ISD::TargetJumpTable:
413 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
415 case ISD::ConstantPool:
416 case ISD::TargetConstantPool: {
417 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
418 ID.AddInteger(CP->getAlignment());
419 ID.AddInteger(CP->getOffset());
420 if (CP->isMachineConstantPoolEntry())
421 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
423 ID.AddPointer(CP->getConstVal());
427 const LoadSDNode *LD = cast<LoadSDNode>(N);
428 ID.AddInteger(LD->getAddressingMode());
429 ID.AddInteger(LD->getExtensionType());
430 ID.AddInteger(LD->getMemoryVT().getRawBits());
431 ID.AddInteger(LD->getRawFlags());
435 const StoreSDNode *ST = cast<StoreSDNode>(N);
436 ID.AddInteger(ST->getAddressingMode());
437 ID.AddInteger(ST->isTruncatingStore());
438 ID.AddInteger(ST->getMemoryVT().getRawBits());
439 ID.AddInteger(ST->getRawFlags());
442 case ISD::ATOMIC_CMP_SWAP:
443 case ISD::ATOMIC_LOAD_ADD:
444 case ISD::ATOMIC_SWAP:
445 case ISD::ATOMIC_LOAD_SUB:
446 case ISD::ATOMIC_LOAD_AND:
447 case ISD::ATOMIC_LOAD_OR:
448 case ISD::ATOMIC_LOAD_XOR:
449 case ISD::ATOMIC_LOAD_NAND:
450 case ISD::ATOMIC_LOAD_MIN:
451 case ISD::ATOMIC_LOAD_MAX:
452 case ISD::ATOMIC_LOAD_UMIN:
453 case ISD::ATOMIC_LOAD_UMAX: {
454 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
455 ID.AddInteger(AT->getRawFlags());
458 } // end switch (N->getOpcode())
461 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
462 /// the CSE map that carries both alignment and volatility information.
464 static unsigned encodeMemSDNodeFlags(bool isVolatile, unsigned Alignment) {
465 return isVolatile | ((Log2_32(Alignment) + 1) << 1);
468 //===----------------------------------------------------------------------===//
469 // SelectionDAG Class
470 //===----------------------------------------------------------------------===//
472 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
474 void SelectionDAG::RemoveDeadNodes() {
475 // Create a dummy node (which is not added to allnodes), that adds a reference
476 // to the root node, preventing it from being deleted.
477 HandleSDNode Dummy(getRoot());
479 SmallVector<SDNode*, 128> DeadNodes;
481 // Add all obviously-dead nodes to the DeadNodes worklist.
482 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
484 DeadNodes.push_back(I);
486 RemoveDeadNodes(DeadNodes);
488 // If the root changed (e.g. it was a dead load, update the root).
489 setRoot(Dummy.getValue());
492 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
493 /// given list, and any nodes that become unreachable as a result.
494 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
495 DAGUpdateListener *UpdateListener) {
497 // Process the worklist, deleting the nodes and adding their uses to the
499 while (!DeadNodes.empty()) {
500 SDNode *N = DeadNodes.back();
501 DeadNodes.pop_back();
504 UpdateListener->NodeDeleted(N, 0);
506 // Take the node out of the appropriate CSE map.
507 RemoveNodeFromCSEMaps(N);
509 // Next, brutally remove the operand list. This is safe to do, as there are
510 // no cycles in the graph.
511 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
512 SDNode *Operand = I->getVal();
513 Operand->removeUser(std::distance(N->op_begin(), I), N);
515 // Now that we removed this operand, see if there are no uses of it left.
516 if (Operand->use_empty())
517 DeadNodes.push_back(Operand);
519 if (N->OperandsNeedDelete) {
520 delete[] N->OperandList;
525 // Finally, remove N itself.
526 NodeAllocator.Deallocate(AllNodes.remove(N));
530 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
531 SmallVector<SDNode*, 16> DeadNodes(1, N);
532 RemoveDeadNodes(DeadNodes, UpdateListener);
535 void SelectionDAG::DeleteNode(SDNode *N) {
536 assert(N->use_empty() && "Cannot delete a node that is not dead!");
538 // First take this out of the appropriate CSE map.
539 RemoveNodeFromCSEMaps(N);
541 // Finally, remove uses due to operands of this node, remove from the
542 // AllNodes list, and delete the node.
543 DeleteNodeNotInCSEMaps(N);
546 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
548 // Drop all of the operands and decrement used nodes use counts.
549 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
550 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
551 if (N->OperandsNeedDelete)
552 delete[] N->OperandList;
554 assert(N != AllNodes.begin());
555 NodeAllocator.Deallocate(AllNodes.remove(N));
558 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
559 /// correspond to it. This is useful when we're about to delete or repurpose
560 /// the node. We don't want future request for structurally identical nodes
561 /// to return N anymore.
562 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
564 switch (N->getOpcode()) {
565 case ISD::EntryToken:
566 assert(0 && "EntryToken should not be in CSEMaps!");
568 case ISD::HANDLENODE: return; // noop.
570 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
571 "Cond code doesn't exist!");
572 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
573 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
575 case ISD::ExternalSymbol:
576 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
578 case ISD::TargetExternalSymbol:
580 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
582 case ISD::VALUETYPE: {
583 MVT VT = cast<VTSDNode>(N)->getVT();
584 if (VT.isExtended()) {
585 Erased = ExtendedValueTypeNodes.erase(VT);
587 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
588 ValueTypeNodes[VT.getSimpleVT()] = 0;
593 // Remove it from the CSE Map.
594 Erased = CSEMap.RemoveNode(N);
598 // Verify that the node was actually in one of the CSE maps, unless it has a
599 // flag result (which cannot be CSE'd) or is one of the special cases that are
600 // not subject to CSE.
601 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
602 !N->isTargetOpcode() &&
603 N->getOpcode() != ISD::DBG_LABEL &&
604 N->getOpcode() != ISD::DBG_STOPPOINT &&
605 N->getOpcode() != ISD::EH_LABEL &&
606 N->getOpcode() != ISD::DECLARE) {
609 assert(0 && "Node is not in map!");
614 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
615 /// has been taken out and modified in some way. If the specified node already
616 /// exists in the CSE maps, do not modify the maps, but return the existing node
617 /// instead. If it doesn't exist, add it and return null.
619 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
620 assert(N->getNumOperands() && "This is a leaf node!");
622 if (N->getValueType(0) == MVT::Flag)
623 return 0; // Never CSE anything that produces a flag.
625 switch (N->getOpcode()) {
627 case ISD::HANDLENODE:
629 case ISD::DBG_STOPPOINT:
632 return 0; // Never add these nodes.
635 // Check that remaining values produced are not flags.
636 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
637 if (N->getValueType(i) == MVT::Flag)
638 return 0; // Never CSE anything that produces a flag.
640 SDNode *New = CSEMap.GetOrInsertNode(N);
641 if (New != N) return New; // Node already existed.
645 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
646 /// were replaced with those specified. If this node is never memoized,
647 /// return null, otherwise return a pointer to the slot it would take. If a
648 /// node already exists with these operands, the slot will be non-null.
649 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
651 if (N->getValueType(0) == MVT::Flag)
652 return 0; // Never CSE anything that produces a flag.
654 switch (N->getOpcode()) {
656 case ISD::HANDLENODE:
658 case ISD::DBG_STOPPOINT:
660 return 0; // Never add these nodes.
663 // Check that remaining values produced are not flags.
664 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
665 if (N->getValueType(i) == MVT::Flag)
666 return 0; // Never CSE anything that produces a flag.
668 SDValue Ops[] = { Op };
670 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
671 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
674 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
675 /// were replaced with those specified. If this node is never memoized,
676 /// return null, otherwise return a pointer to the slot it would take. If a
677 /// node already exists with these operands, the slot will be non-null.
678 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
679 SDValue Op1, SDValue Op2,
681 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
683 // Check that remaining values produced are not flags.
684 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
685 if (N->getValueType(i) == MVT::Flag)
686 return 0; // Never CSE anything that produces a flag.
688 SDValue Ops[] = { Op1, Op2 };
690 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
691 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
695 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
696 /// were replaced with those specified. If this node is never memoized,
697 /// return null, otherwise return a pointer to the slot it would take. If a
698 /// node already exists with these operands, the slot will be non-null.
699 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
700 const SDValue *Ops,unsigned NumOps,
702 if (N->getValueType(0) == MVT::Flag)
703 return 0; // Never CSE anything that produces a flag.
705 switch (N->getOpcode()) {
707 case ISD::HANDLENODE:
709 case ISD::DBG_STOPPOINT:
712 return 0; // Never add these nodes.
715 // Check that remaining values produced are not flags.
716 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
717 if (N->getValueType(i) == MVT::Flag)
718 return 0; // Never CSE anything that produces a flag.
721 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
723 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
724 ID.AddInteger(LD->getAddressingMode());
725 ID.AddInteger(LD->getExtensionType());
726 ID.AddInteger(LD->getMemoryVT().getRawBits());
727 ID.AddInteger(LD->getRawFlags());
728 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
729 ID.AddInteger(ST->getAddressingMode());
730 ID.AddInteger(ST->isTruncatingStore());
731 ID.AddInteger(ST->getMemoryVT().getRawBits());
732 ID.AddInteger(ST->getRawFlags());
735 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
738 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
739 void SelectionDAG::VerifyNode(SDNode *N) {
740 switch (N->getOpcode()) {
743 case ISD::BUILD_VECTOR: {
744 assert(N->getNumValues() == 1 && "Too many results for BUILD_VECTOR!");
745 assert(N->getValueType(0).isVector() && "Wrong BUILD_VECTOR return type!");
746 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
747 "Wrong number of BUILD_VECTOR operands!");
748 MVT EltVT = N->getValueType(0).getVectorElementType();
749 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
750 assert(I->getSDValue().getValueType() == EltVT &&
751 "Wrong BUILD_VECTOR operand type!");
757 /// getMVTAlignment - Compute the default alignment value for the
760 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
761 const Type *Ty = VT == MVT::iPTR ?
762 PointerType::get(Type::Int8Ty, 0) :
765 return TLI.getTargetData()->getABITypeAlignment(Ty);
768 SelectionDAG::SelectionDAG(TargetLowering &tli, MachineFunction &mf,
769 FunctionLoweringInfo &fli, MachineModuleInfo *mmi)
770 : TLI(tli), MF(mf), FLI(fli), MMI(mmi),
771 EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
772 Root(getEntryNode()) {
773 AllNodes.push_back(&EntryNode);
776 SelectionDAG::~SelectionDAG() {
780 void SelectionDAG::allnodes_clear() {
781 assert(&*AllNodes.begin() == &EntryNode);
782 AllNodes.remove(AllNodes.begin());
783 while (!AllNodes.empty()) {
784 SDNode *N = AllNodes.remove(AllNodes.begin());
785 N->SetNextInBucket(0);
786 if (N->OperandsNeedDelete)
787 delete [] N->OperandList;
788 NodeAllocator.Deallocate(N);
792 void SelectionDAG::reset() {
794 OperandAllocator.Reset();
797 ExtendedValueTypeNodes.clear();
798 ExternalSymbols.clear();
799 TargetExternalSymbols.clear();
800 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
801 static_cast<CondCodeSDNode*>(0));
802 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
803 static_cast<SDNode*>(0));
806 AllNodes.push_back(&EntryNode);
807 Root = getEntryNode();
810 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
811 if (Op.getValueType() == VT) return Op;
812 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
814 return getNode(ISD::AND, Op.getValueType(), Op,
815 getConstant(Imm, Op.getValueType()));
818 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
819 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
820 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
823 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
824 assert(VT.isInteger() && "Cannot create FP integer constant!");
826 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
827 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
828 "APInt size does not match type size!");
830 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
832 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
836 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
838 return SDValue(N, 0);
840 N = NodeAllocator.Allocate<ConstantSDNode>();
841 new (N) ConstantSDNode(isT, Val, EltVT);
842 CSEMap.InsertNode(N, IP);
843 AllNodes.push_back(N);
846 SDValue Result(N, 0);
848 SmallVector<SDValue, 8> Ops;
849 Ops.assign(VT.getVectorNumElements(), Result);
850 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
855 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
856 return getConstant(Val, TLI.getPointerTy(), isTarget);
860 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
861 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
864 VT.isVector() ? VT.getVectorElementType() : VT;
866 // Do the map lookup using the actual bit pattern for the floating point
867 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
868 // we don't have issues with SNANs.
869 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
871 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
875 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
877 return SDValue(N, 0);
879 N = NodeAllocator.Allocate<ConstantFPSDNode>();
880 new (N) ConstantFPSDNode(isTarget, V, EltVT);
881 CSEMap.InsertNode(N, IP);
882 AllNodes.push_back(N);
885 SDValue Result(N, 0);
887 SmallVector<SDValue, 8> Ops;
888 Ops.assign(VT.getVectorNumElements(), Result);
889 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
894 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
896 VT.isVector() ? VT.getVectorElementType() : VT;
898 return getConstantFP(APFloat((float)Val), VT, isTarget);
900 return getConstantFP(APFloat(Val), VT, isTarget);
903 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
908 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
910 // If GV is an alias then use the aliasee for determining thread-localness.
911 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
912 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
915 if (GVar && GVar->isThreadLocal())
916 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
918 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
921 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
923 ID.AddInteger(Offset);
925 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
926 return SDValue(E, 0);
927 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
928 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
929 CSEMap.InsertNode(N, IP);
930 AllNodes.push_back(N);
931 return SDValue(N, 0);
934 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
935 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
937 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
940 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
941 return SDValue(E, 0);
942 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
943 new (N) FrameIndexSDNode(FI, VT, isTarget);
944 CSEMap.InsertNode(N, IP);
945 AllNodes.push_back(N);
946 return SDValue(N, 0);
949 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
950 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
952 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
955 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
956 return SDValue(E, 0);
957 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
958 new (N) JumpTableSDNode(JTI, VT, isTarget);
959 CSEMap.InsertNode(N, IP);
960 AllNodes.push_back(N);
961 return SDValue(N, 0);
964 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
965 unsigned Alignment, int Offset,
967 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
969 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
970 ID.AddInteger(Alignment);
971 ID.AddInteger(Offset);
974 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
975 return SDValue(E, 0);
976 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
977 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
978 CSEMap.InsertNode(N, IP);
979 AllNodes.push_back(N);
980 return SDValue(N, 0);
984 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
985 unsigned Alignment, int Offset,
987 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
989 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
990 ID.AddInteger(Alignment);
991 ID.AddInteger(Offset);
992 C->AddSelectionDAGCSEId(ID);
994 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
995 return SDValue(E, 0);
996 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
997 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
998 CSEMap.InsertNode(N, IP);
999 AllNodes.push_back(N);
1000 return SDValue(N, 0);
1004 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1005 FoldingSetNodeID ID;
1006 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1009 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1010 return SDValue(E, 0);
1011 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1012 new (N) BasicBlockSDNode(MBB);
1013 CSEMap.InsertNode(N, IP);
1014 AllNodes.push_back(N);
1015 return SDValue(N, 0);
1018 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
1019 FoldingSetNodeID ID;
1020 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
1021 ID.AddInteger(Flags.getRawBits());
1023 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1024 return SDValue(E, 0);
1025 SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
1026 new (N) ARG_FLAGSSDNode(Flags);
1027 CSEMap.InsertNode(N, IP);
1028 AllNodes.push_back(N);
1029 return SDValue(N, 0);
1032 SDValue SelectionDAG::getValueType(MVT VT) {
1033 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1034 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1036 SDNode *&N = VT.isExtended() ?
1037 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1039 if (N) return SDValue(N, 0);
1040 N = NodeAllocator.Allocate<VTSDNode>();
1041 new (N) VTSDNode(VT);
1042 AllNodes.push_back(N);
1043 return SDValue(N, 0);
1046 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1047 SDNode *&N = ExternalSymbols[Sym];
1048 if (N) return SDValue(N, 0);
1049 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1050 new (N) ExternalSymbolSDNode(false, Sym, VT);
1051 AllNodes.push_back(N);
1052 return SDValue(N, 0);
1055 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1056 SDNode *&N = TargetExternalSymbols[Sym];
1057 if (N) return SDValue(N, 0);
1058 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1059 new (N) ExternalSymbolSDNode(true, Sym, VT);
1060 AllNodes.push_back(N);
1061 return SDValue(N, 0);
1064 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1065 if ((unsigned)Cond >= CondCodeNodes.size())
1066 CondCodeNodes.resize(Cond+1);
1068 if (CondCodeNodes[Cond] == 0) {
1069 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1070 new (N) CondCodeSDNode(Cond);
1071 CondCodeNodes[Cond] = N;
1072 AllNodes.push_back(N);
1074 return SDValue(CondCodeNodes[Cond], 0);
1077 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1078 FoldingSetNodeID ID;
1079 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1080 ID.AddInteger(RegNo);
1082 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1083 return SDValue(E, 0);
1084 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1085 new (N) RegisterSDNode(RegNo, VT);
1086 CSEMap.InsertNode(N, IP);
1087 AllNodes.push_back(N);
1088 return SDValue(N, 0);
1091 SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
1092 unsigned Line, unsigned Col,
1093 const CompileUnitDesc *CU) {
1094 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1095 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1096 AllNodes.push_back(N);
1097 return SDValue(N, 0);
1100 SDValue SelectionDAG::getLabel(unsigned Opcode,
1103 FoldingSetNodeID ID;
1104 SDValue Ops[] = { Root };
1105 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1106 ID.AddInteger(LabelID);
1108 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1109 return SDValue(E, 0);
1110 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1111 new (N) LabelSDNode(Opcode, Root, LabelID);
1112 CSEMap.InsertNode(N, IP);
1113 AllNodes.push_back(N);
1114 return SDValue(N, 0);
1117 SDValue SelectionDAG::getSrcValue(const Value *V) {
1118 assert((!V || isa<PointerType>(V->getType())) &&
1119 "SrcValue is not a pointer?");
1121 FoldingSetNodeID ID;
1122 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1126 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1127 return SDValue(E, 0);
1129 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1130 new (N) SrcValueSDNode(V);
1131 CSEMap.InsertNode(N, IP);
1132 AllNodes.push_back(N);
1133 return SDValue(N, 0);
1136 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1137 const Value *v = MO.getValue();
1138 assert((!v || isa<PointerType>(v->getType())) &&
1139 "SrcValue is not a pointer?");
1141 FoldingSetNodeID ID;
1142 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1146 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1147 return SDValue(E, 0);
1149 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1150 new (N) MemOperandSDNode(MO);
1151 CSEMap.InsertNode(N, IP);
1152 AllNodes.push_back(N);
1153 return SDValue(N, 0);
1156 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1157 /// specified value type.
1158 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1159 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1160 unsigned ByteSize = VT.getSizeInBits()/8;
1161 const Type *Ty = VT.getTypeForMVT();
1162 unsigned StackAlign =
1163 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1165 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1166 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1169 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1170 SDValue N2, ISD::CondCode Cond) {
1171 // These setcc operations always fold.
1175 case ISD::SETFALSE2: return getConstant(0, VT);
1177 case ISD::SETTRUE2: return getConstant(1, VT);
1189 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1193 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1194 const APInt &C2 = N2C->getAPIntValue();
1195 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1196 const APInt &C1 = N1C->getAPIntValue();
1199 default: assert(0 && "Unknown integer setcc!");
1200 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1201 case ISD::SETNE: return getConstant(C1 != C2, VT);
1202 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1203 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1204 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1205 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1206 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1207 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1208 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1209 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1213 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1214 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1215 // No compile time operations on this type yet.
1216 if (N1C->getValueType(0) == MVT::ppcf128)
1219 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1222 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1223 return getNode(ISD::UNDEF, VT);
1225 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1226 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1227 return getNode(ISD::UNDEF, VT);
1229 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1230 R==APFloat::cmpLessThan, VT);
1231 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1232 return getNode(ISD::UNDEF, VT);
1234 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1235 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1236 return getNode(ISD::UNDEF, VT);
1238 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1239 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1240 return getNode(ISD::UNDEF, VT);
1242 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1243 R==APFloat::cmpEqual, VT);
1244 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1245 return getNode(ISD::UNDEF, VT);
1247 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1248 R==APFloat::cmpEqual, VT);
1249 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1250 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1251 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1252 R==APFloat::cmpEqual, VT);
1253 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1254 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1255 R==APFloat::cmpLessThan, VT);
1256 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1257 R==APFloat::cmpUnordered, VT);
1258 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1259 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1262 // Ensure that the constant occurs on the RHS.
1263 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1267 // Could not fold it.
1271 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1272 /// use this predicate to simplify operations downstream.
1273 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1274 unsigned BitWidth = Op.getValueSizeInBits();
1275 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1278 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1279 /// this predicate to simplify operations downstream. Mask is known to be zero
1280 /// for bits that V cannot have.
1281 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1282 unsigned Depth) const {
1283 APInt KnownZero, KnownOne;
1284 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1285 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1286 return (KnownZero & Mask) == Mask;
1289 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1290 /// known to be either zero or one and return them in the KnownZero/KnownOne
1291 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1293 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1294 APInt &KnownZero, APInt &KnownOne,
1295 unsigned Depth) const {
1296 unsigned BitWidth = Mask.getBitWidth();
1297 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1298 "Mask size mismatches value type size!");
1300 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1301 if (Depth == 6 || Mask == 0)
1302 return; // Limit search depth.
1304 APInt KnownZero2, KnownOne2;
1306 switch (Op.getOpcode()) {
1308 // We know all of the bits for a constant!
1309 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1310 KnownZero = ~KnownOne & Mask;
1313 // If either the LHS or the RHS are Zero, the result is zero.
1314 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1315 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1316 KnownZero2, KnownOne2, Depth+1);
1317 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1318 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1320 // Output known-1 bits are only known if set in both the LHS & RHS.
1321 KnownOne &= KnownOne2;
1322 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1323 KnownZero |= KnownZero2;
1326 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1327 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1328 KnownZero2, KnownOne2, Depth+1);
1329 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1330 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1332 // Output known-0 bits are only known if clear in both the LHS & RHS.
1333 KnownZero &= KnownZero2;
1334 // Output known-1 are known to be set if set in either the LHS | RHS.
1335 KnownOne |= KnownOne2;
1338 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1339 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1340 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1341 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1343 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1344 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1345 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1346 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1347 KnownZero = KnownZeroOut;
1351 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1352 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1353 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1354 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1355 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1357 // If low bits are zero in either operand, output low known-0 bits.
1358 // Also compute a conserative estimate for high known-0 bits.
1359 // More trickiness is possible, but this is sufficient for the
1360 // interesting case of alignment computation.
1362 unsigned TrailZ = KnownZero.countTrailingOnes() +
1363 KnownZero2.countTrailingOnes();
1364 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1365 KnownZero2.countLeadingOnes(),
1366 BitWidth) - BitWidth;
1368 TrailZ = std::min(TrailZ, BitWidth);
1369 LeadZ = std::min(LeadZ, BitWidth);
1370 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1371 APInt::getHighBitsSet(BitWidth, LeadZ);
1376 // For the purposes of computing leading zeros we can conservatively
1377 // treat a udiv as a logical right shift by the power of 2 known to
1378 // be less than the denominator.
1379 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1380 ComputeMaskedBits(Op.getOperand(0),
1381 AllOnes, KnownZero2, KnownOne2, Depth+1);
1382 unsigned LeadZ = KnownZero2.countLeadingOnes();
1386 ComputeMaskedBits(Op.getOperand(1),
1387 AllOnes, KnownZero2, KnownOne2, Depth+1);
1388 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1389 if (RHSUnknownLeadingOnes != BitWidth)
1390 LeadZ = std::min(BitWidth,
1391 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1393 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1397 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1398 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1399 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1400 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1402 // Only known if known in both the LHS and RHS.
1403 KnownOne &= KnownOne2;
1404 KnownZero &= KnownZero2;
1406 case ISD::SELECT_CC:
1407 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1408 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1409 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1410 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1412 // Only known if known in both the LHS and RHS.
1413 KnownOne &= KnownOne2;
1414 KnownZero &= KnownZero2;
1417 // If we know the result of a setcc has the top bits zero, use this info.
1418 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1420 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1423 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1424 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1425 unsigned ShAmt = SA->getValue();
1427 // If the shift count is an invalid immediate, don't do anything.
1428 if (ShAmt >= BitWidth)
1431 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1432 KnownZero, KnownOne, Depth+1);
1433 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1434 KnownZero <<= ShAmt;
1436 // low bits known zero.
1437 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1441 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1442 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1443 unsigned ShAmt = SA->getValue();
1445 // If the shift count is an invalid immediate, don't do anything.
1446 if (ShAmt >= BitWidth)
1449 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1450 KnownZero, KnownOne, Depth+1);
1451 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1452 KnownZero = KnownZero.lshr(ShAmt);
1453 KnownOne = KnownOne.lshr(ShAmt);
1455 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1456 KnownZero |= HighBits; // High bits known zero.
1460 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1461 unsigned ShAmt = SA->getValue();
1463 // If the shift count is an invalid immediate, don't do anything.
1464 if (ShAmt >= BitWidth)
1467 APInt InDemandedMask = (Mask << ShAmt);
1468 // If any of the demanded bits are produced by the sign extension, we also
1469 // demand the input sign bit.
1470 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1471 if (HighBits.getBoolValue())
1472 InDemandedMask |= APInt::getSignBit(BitWidth);
1474 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1476 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1477 KnownZero = KnownZero.lshr(ShAmt);
1478 KnownOne = KnownOne.lshr(ShAmt);
1480 // Handle the sign bits.
1481 APInt SignBit = APInt::getSignBit(BitWidth);
1482 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1484 if (KnownZero.intersects(SignBit)) {
1485 KnownZero |= HighBits; // New bits are known zero.
1486 } else if (KnownOne.intersects(SignBit)) {
1487 KnownOne |= HighBits; // New bits are known one.
1491 case ISD::SIGN_EXTEND_INREG: {
1492 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1493 unsigned EBits = EVT.getSizeInBits();
1495 // Sign extension. Compute the demanded bits in the result that are not
1496 // present in the input.
1497 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1499 APInt InSignBit = APInt::getSignBit(EBits);
1500 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1502 // If the sign extended bits are demanded, we know that the sign
1504 InSignBit.zext(BitWidth);
1505 if (NewBits.getBoolValue())
1506 InputDemandedBits |= InSignBit;
1508 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1509 KnownZero, KnownOne, Depth+1);
1510 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1512 // If the sign bit of the input is known set or clear, then we know the
1513 // top bits of the result.
1514 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1515 KnownZero |= NewBits;
1516 KnownOne &= ~NewBits;
1517 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1518 KnownOne |= NewBits;
1519 KnownZero &= ~NewBits;
1520 } else { // Input sign bit unknown
1521 KnownZero &= ~NewBits;
1522 KnownOne &= ~NewBits;
1529 unsigned LowBits = Log2_32(BitWidth)+1;
1530 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1535 if (ISD::isZEXTLoad(Op.Val)) {
1536 LoadSDNode *LD = cast<LoadSDNode>(Op);
1537 MVT VT = LD->getMemoryVT();
1538 unsigned MemBits = VT.getSizeInBits();
1539 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1543 case ISD::ZERO_EXTEND: {
1544 MVT InVT = Op.getOperand(0).getValueType();
1545 unsigned InBits = InVT.getSizeInBits();
1546 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1547 APInt InMask = Mask;
1548 InMask.trunc(InBits);
1549 KnownZero.trunc(InBits);
1550 KnownOne.trunc(InBits);
1551 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1552 KnownZero.zext(BitWidth);
1553 KnownOne.zext(BitWidth);
1554 KnownZero |= NewBits;
1557 case ISD::SIGN_EXTEND: {
1558 MVT InVT = Op.getOperand(0).getValueType();
1559 unsigned InBits = InVT.getSizeInBits();
1560 APInt InSignBit = APInt::getSignBit(InBits);
1561 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1562 APInt InMask = Mask;
1563 InMask.trunc(InBits);
1565 // If any of the sign extended bits are demanded, we know that the sign
1566 // bit is demanded. Temporarily set this bit in the mask for our callee.
1567 if (NewBits.getBoolValue())
1568 InMask |= InSignBit;
1570 KnownZero.trunc(InBits);
1571 KnownOne.trunc(InBits);
1572 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1574 // Note if the sign bit is known to be zero or one.
1575 bool SignBitKnownZero = KnownZero.isNegative();
1576 bool SignBitKnownOne = KnownOne.isNegative();
1577 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1578 "Sign bit can't be known to be both zero and one!");
1580 // If the sign bit wasn't actually demanded by our caller, we don't
1581 // want it set in the KnownZero and KnownOne result values. Reset the
1582 // mask and reapply it to the result values.
1584 InMask.trunc(InBits);
1585 KnownZero &= InMask;
1588 KnownZero.zext(BitWidth);
1589 KnownOne.zext(BitWidth);
1591 // If the sign bit is known zero or one, the top bits match.
1592 if (SignBitKnownZero)
1593 KnownZero |= NewBits;
1594 else if (SignBitKnownOne)
1595 KnownOne |= NewBits;
1598 case ISD::ANY_EXTEND: {
1599 MVT InVT = Op.getOperand(0).getValueType();
1600 unsigned InBits = InVT.getSizeInBits();
1601 APInt InMask = Mask;
1602 InMask.trunc(InBits);
1603 KnownZero.trunc(InBits);
1604 KnownOne.trunc(InBits);
1605 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1606 KnownZero.zext(BitWidth);
1607 KnownOne.zext(BitWidth);
1610 case ISD::TRUNCATE: {
1611 MVT InVT = Op.getOperand(0).getValueType();
1612 unsigned InBits = InVT.getSizeInBits();
1613 APInt InMask = Mask;
1614 InMask.zext(InBits);
1615 KnownZero.zext(InBits);
1616 KnownOne.zext(InBits);
1617 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1618 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1619 KnownZero.trunc(BitWidth);
1620 KnownOne.trunc(BitWidth);
1623 case ISD::AssertZext: {
1624 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1625 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1626 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1628 KnownZero |= (~InMask) & Mask;
1632 // All bits are zero except the low bit.
1633 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1637 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1638 // We know that the top bits of C-X are clear if X contains less bits
1639 // than C (i.e. no wrap-around can happen). For example, 20-X is
1640 // positive if we can prove that X is >= 0 and < 16.
1641 if (CLHS->getAPIntValue().isNonNegative()) {
1642 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1643 // NLZ can't be BitWidth with no sign bit
1644 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1645 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1648 // If all of the MaskV bits are known to be zero, then we know the
1649 // output top bits are zero, because we now know that the output is
1651 if ((KnownZero2 & MaskV) == MaskV) {
1652 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1653 // Top bits known zero.
1654 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1661 // Output known-0 bits are known if clear or set in both the low clear bits
1662 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1663 // low 3 bits clear.
1664 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1665 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1666 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1667 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1669 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1670 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1671 KnownZeroOut = std::min(KnownZeroOut,
1672 KnownZero2.countTrailingOnes());
1674 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1678 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1679 const APInt &RA = Rem->getAPIntValue();
1680 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1681 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1682 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1683 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1685 // If the sign bit of the first operand is zero, the sign bit of
1686 // the result is zero. If the first operand has no one bits below
1687 // the second operand's single 1 bit, its sign will be zero.
1688 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1689 KnownZero2 |= ~LowBits;
1691 KnownZero |= KnownZero2 & Mask;
1693 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1698 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1699 const APInt &RA = Rem->getAPIntValue();
1700 if (RA.isPowerOf2()) {
1701 APInt LowBits = (RA - 1);
1702 APInt Mask2 = LowBits & Mask;
1703 KnownZero |= ~LowBits & Mask;
1704 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1705 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1710 // Since the result is less than or equal to either operand, any leading
1711 // zero bits in either operand must also exist in the result.
1712 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1713 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1715 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1718 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1719 KnownZero2.countLeadingOnes());
1721 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1725 // Allow the target to implement this method for its nodes.
1726 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1727 case ISD::INTRINSIC_WO_CHAIN:
1728 case ISD::INTRINSIC_W_CHAIN:
1729 case ISD::INTRINSIC_VOID:
1730 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1736 /// ComputeNumSignBits - Return the number of times the sign bit of the
1737 /// register is replicated into the other bits. We know that at least 1 bit
1738 /// is always equal to the sign bit (itself), but other cases can give us
1739 /// information. For example, immediately after an "SRA X, 2", we know that
1740 /// the top 3 bits are all equal to each other, so we return 3.
1741 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1742 MVT VT = Op.getValueType();
1743 assert(VT.isInteger() && "Invalid VT!");
1744 unsigned VTBits = VT.getSizeInBits();
1746 unsigned FirstAnswer = 1;
1749 return 1; // Limit search depth.
1751 switch (Op.getOpcode()) {
1753 case ISD::AssertSext:
1754 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1755 return VTBits-Tmp+1;
1756 case ISD::AssertZext:
1757 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1760 case ISD::Constant: {
1761 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1762 // If negative, return # leading ones.
1763 if (Val.isNegative())
1764 return Val.countLeadingOnes();
1766 // Return # leading zeros.
1767 return Val.countLeadingZeros();
1770 case ISD::SIGN_EXTEND:
1771 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1772 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1774 case ISD::SIGN_EXTEND_INREG:
1775 // Max of the input and what this extends.
1776 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1779 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1780 return std::max(Tmp, Tmp2);
1783 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1784 // SRA X, C -> adds C sign bits.
1785 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1786 Tmp += C->getValue();
1787 if (Tmp > VTBits) Tmp = VTBits;
1791 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1792 // shl destroys sign bits.
1793 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1794 if (C->getValue() >= VTBits || // Bad shift.
1795 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1796 return Tmp - C->getValue();
1801 case ISD::XOR: // NOT is handled here.
1802 // Logical binary ops preserve the number of sign bits at the worst.
1803 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1805 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1806 FirstAnswer = std::min(Tmp, Tmp2);
1807 // We computed what we know about the sign bits as our first
1808 // answer. Now proceed to the generic code that uses
1809 // ComputeMaskedBits, and pick whichever answer is better.
1814 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1815 if (Tmp == 1) return 1; // Early out.
1816 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1817 return std::min(Tmp, Tmp2);
1820 // If setcc returns 0/-1, all bits are sign bits.
1821 if (TLI.getSetCCResultContents() ==
1822 TargetLowering::ZeroOrNegativeOneSetCCResult)
1827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1828 unsigned RotAmt = C->getValue() & (VTBits-1);
1830 // Handle rotate right by N like a rotate left by 32-N.
1831 if (Op.getOpcode() == ISD::ROTR)
1832 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1834 // If we aren't rotating out all of the known-in sign bits, return the
1835 // number that are left. This handles rotl(sext(x), 1) for example.
1836 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1837 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1841 // Add can have at most one carry bit. Thus we know that the output
1842 // is, at worst, one more bit than the inputs.
1843 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1844 if (Tmp == 1) return 1; // Early out.
1846 // Special case decrementing a value (ADD X, -1):
1847 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1848 if (CRHS->isAllOnesValue()) {
1849 APInt KnownZero, KnownOne;
1850 APInt Mask = APInt::getAllOnesValue(VTBits);
1851 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1853 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1855 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1858 // If we are subtracting one from a positive number, there is no carry
1859 // out of the result.
1860 if (KnownZero.isNegative())
1864 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1865 if (Tmp2 == 1) return 1;
1866 return std::min(Tmp, Tmp2)-1;
1870 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1871 if (Tmp2 == 1) return 1;
1874 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1875 if (CLHS->isNullValue()) {
1876 APInt KnownZero, KnownOne;
1877 APInt Mask = APInt::getAllOnesValue(VTBits);
1878 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1879 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1881 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1884 // If the input is known to be positive (the sign bit is known clear),
1885 // the output of the NEG has the same number of sign bits as the input.
1886 if (KnownZero.isNegative())
1889 // Otherwise, we treat this like a SUB.
1892 // Sub can have at most one carry bit. Thus we know that the output
1893 // is, at worst, one more bit than the inputs.
1894 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1895 if (Tmp == 1) return 1; // Early out.
1896 return std::min(Tmp, Tmp2)-1;
1899 // FIXME: it's tricky to do anything useful for this, but it is an important
1900 // case for targets like X86.
1904 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1905 if (Op.getOpcode() == ISD::LOAD) {
1906 LoadSDNode *LD = cast<LoadSDNode>(Op);
1907 unsigned ExtType = LD->getExtensionType();
1910 case ISD::SEXTLOAD: // '17' bits known
1911 Tmp = LD->getMemoryVT().getSizeInBits();
1912 return VTBits-Tmp+1;
1913 case ISD::ZEXTLOAD: // '16' bits known
1914 Tmp = LD->getMemoryVT().getSizeInBits();
1919 // Allow the target to implement this method for its nodes.
1920 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1921 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1922 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1923 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1924 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1925 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1928 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1929 // use this information.
1930 APInt KnownZero, KnownOne;
1931 APInt Mask = APInt::getAllOnesValue(VTBits);
1932 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1934 if (KnownZero.isNegative()) { // sign bit is 0
1936 } else if (KnownOne.isNegative()) { // sign bit is 1;
1943 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1944 // the number of identical bits in the top of the input value.
1946 Mask <<= Mask.getBitWidth()-VTBits;
1947 // Return # leading zeros. We use 'min' here in case Val was zero before
1948 // shifting. We don't want to return '64' as for an i32 "0".
1949 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1953 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
1954 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1955 if (!GA) return false;
1956 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1957 if (!GV) return false;
1958 MachineModuleInfo *MMI = getMachineModuleInfo();
1959 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1963 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1964 /// element of the result of the vector shuffle.
1965 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1966 MVT VT = N->getValueType(0);
1967 SDValue PermMask = N->getOperand(2);
1968 SDValue Idx = PermMask.getOperand(i);
1969 if (Idx.getOpcode() == ISD::UNDEF)
1970 return getNode(ISD::UNDEF, VT.getVectorElementType());
1971 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1972 unsigned NumElems = PermMask.getNumOperands();
1973 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1976 if (V.getOpcode() == ISD::BIT_CONVERT) {
1977 V = V.getOperand(0);
1978 if (V.getValueType().getVectorNumElements() != NumElems)
1981 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1982 return (Index == 0) ? V.getOperand(0)
1983 : getNode(ISD::UNDEF, VT.getVectorElementType());
1984 if (V.getOpcode() == ISD::BUILD_VECTOR)
1985 return V.getOperand(Index);
1986 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1987 return getShuffleScalarElt(V.Val, Index);
1992 /// getNode - Gets or creates the specified node.
1994 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1995 FoldingSetNodeID ID;
1996 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1998 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1999 return SDValue(E, 0);
2000 SDNode *N = NodeAllocator.Allocate<SDNode>();
2001 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
2002 CSEMap.InsertNode(N, IP);
2004 AllNodes.push_back(N);
2008 return SDValue(N, 0);
2011 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
2012 // Constant fold unary operations with an integer constant operand.
2013 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
2014 const APInt &Val = C->getAPIntValue();
2015 unsigned BitWidth = VT.getSizeInBits();
2018 case ISD::SIGN_EXTEND:
2019 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2020 case ISD::ANY_EXTEND:
2021 case ISD::ZERO_EXTEND:
2023 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2024 case ISD::UINT_TO_FP:
2025 case ISD::SINT_TO_FP: {
2026 const uint64_t zero[] = {0, 0};
2027 // No compile time operations on this type.
2028 if (VT==MVT::ppcf128)
2030 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2031 (void)apf.convertFromAPInt(Val,
2032 Opcode==ISD::SINT_TO_FP,
2033 APFloat::rmNearestTiesToEven);
2034 return getConstantFP(apf, VT);
2036 case ISD::BIT_CONVERT:
2037 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2038 return getConstantFP(Val.bitsToFloat(), VT);
2039 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2040 return getConstantFP(Val.bitsToDouble(), VT);
2043 return getConstant(Val.byteSwap(), VT);
2045 return getConstant(Val.countPopulation(), VT);
2047 return getConstant(Val.countLeadingZeros(), VT);
2049 return getConstant(Val.countTrailingZeros(), VT);
2053 // Constant fold unary operations with a floating point constant operand.
2054 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
2055 APFloat V = C->getValueAPF(); // make copy
2056 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2060 return getConstantFP(V, VT);
2063 return getConstantFP(V, VT);
2065 case ISD::FP_EXTEND:
2066 // This can return overflow, underflow, or inexact; we don't care.
2067 // FIXME need to be more flexible about rounding mode.
2068 (void)V.convert(*MVTToAPFloatSemantics(VT),
2069 APFloat::rmNearestTiesToEven);
2070 return getConstantFP(V, VT);
2071 case ISD::FP_TO_SINT:
2072 case ISD::FP_TO_UINT: {
2074 assert(integerPartWidth >= 64);
2075 // FIXME need to be more flexible about rounding mode.
2076 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2077 Opcode==ISD::FP_TO_SINT,
2078 APFloat::rmTowardZero);
2079 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2081 return getConstant(x, VT);
2083 case ISD::BIT_CONVERT:
2084 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2085 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2086 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2087 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2093 unsigned OpOpcode = Operand.Val->getOpcode();
2095 case ISD::TokenFactor:
2096 case ISD::CONCAT_VECTORS:
2097 return Operand; // Factor or concat of one node? No need.
2098 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2099 case ISD::FP_EXTEND:
2100 assert(VT.isFloatingPoint() &&
2101 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2102 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2103 if (Operand.getOpcode() == ISD::UNDEF)
2104 return getNode(ISD::UNDEF, VT);
2106 case ISD::SIGN_EXTEND:
2107 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2108 "Invalid SIGN_EXTEND!");
2109 if (Operand.getValueType() == VT) return Operand; // noop extension
2110 assert(Operand.getValueType().bitsLT(VT)
2111 && "Invalid sext node, dst < src!");
2112 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2113 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2115 case ISD::ZERO_EXTEND:
2116 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2117 "Invalid ZERO_EXTEND!");
2118 if (Operand.getValueType() == VT) return Operand; // noop extension
2119 assert(Operand.getValueType().bitsLT(VT)
2120 && "Invalid zext node, dst < src!");
2121 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2122 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2124 case ISD::ANY_EXTEND:
2125 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2126 "Invalid ANY_EXTEND!");
2127 if (Operand.getValueType() == VT) return Operand; // noop extension
2128 assert(Operand.getValueType().bitsLT(VT)
2129 && "Invalid anyext node, dst < src!");
2130 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2131 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2132 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2135 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2136 "Invalid TRUNCATE!");
2137 if (Operand.getValueType() == VT) return Operand; // noop truncate
2138 assert(Operand.getValueType().bitsGT(VT)
2139 && "Invalid truncate node, src < dst!");
2140 if (OpOpcode == ISD::TRUNCATE)
2141 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2142 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2143 OpOpcode == ISD::ANY_EXTEND) {
2144 // If the source is smaller than the dest, we still need an extend.
2145 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2146 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2147 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2148 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2150 return Operand.Val->getOperand(0);
2153 case ISD::BIT_CONVERT:
2154 // Basic sanity checking.
2155 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2156 && "Cannot BIT_CONVERT between types of different sizes!");
2157 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2158 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2159 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2160 if (OpOpcode == ISD::UNDEF)
2161 return getNode(ISD::UNDEF, VT);
2163 case ISD::SCALAR_TO_VECTOR:
2164 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2165 VT.getVectorElementType() == Operand.getValueType() &&
2166 "Illegal SCALAR_TO_VECTOR node!");
2167 if (OpOpcode == ISD::UNDEF)
2168 return getNode(ISD::UNDEF, VT);
2169 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2170 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2171 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2172 Operand.getConstantOperandVal(1) == 0 &&
2173 Operand.getOperand(0).getValueType() == VT)
2174 return Operand.getOperand(0);
2177 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2178 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2179 Operand.Val->getOperand(0));
2180 if (OpOpcode == ISD::FNEG) // --X -> X
2181 return Operand.Val->getOperand(0);
2184 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2185 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2190 SDVTList VTs = getVTList(VT);
2191 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2192 FoldingSetNodeID ID;
2193 SDValue Ops[1] = { Operand };
2194 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2196 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2197 return SDValue(E, 0);
2198 N = NodeAllocator.Allocate<UnarySDNode>();
2199 new (N) UnarySDNode(Opcode, VTs, Operand);
2200 CSEMap.InsertNode(N, IP);
2202 N = NodeAllocator.Allocate<UnarySDNode>();
2203 new (N) UnarySDNode(Opcode, VTs, Operand);
2206 AllNodes.push_back(N);
2210 return SDValue(N, 0);
2213 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2214 SDValue N1, SDValue N2) {
2215 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2216 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2219 case ISD::TokenFactor:
2220 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2221 N2.getValueType() == MVT::Other && "Invalid token factor!");
2222 // Fold trivial token factors.
2223 if (N1.getOpcode() == ISD::EntryToken) return N2;
2224 if (N2.getOpcode() == ISD::EntryToken) return N1;
2226 case ISD::CONCAT_VECTORS:
2227 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2228 // one big BUILD_VECTOR.
2229 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2230 N2.getOpcode() == ISD::BUILD_VECTOR) {
2231 SmallVector<SDValue, 16> Elts(N1.Val->op_begin(), N1.Val->op_end());
2232 Elts.insert(Elts.end(), N2.Val->op_begin(), N2.Val->op_end());
2233 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2237 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2238 N1.getValueType() == VT && "Binary operator types must match!");
2239 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2240 // worth handling here.
2241 if (N2C && N2C->isNullValue())
2243 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2250 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2251 N1.getValueType() == VT && "Binary operator types must match!");
2252 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2253 // it's worth handling here.
2254 if (N2C && N2C->isNullValue())
2261 assert(VT.isInteger() && "This operator does not apply to FP types!");
2271 assert(N1.getValueType() == N2.getValueType() &&
2272 N1.getValueType() == VT && "Binary operator types must match!");
2274 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2275 assert(N1.getValueType() == VT &&
2276 N1.getValueType().isFloatingPoint() &&
2277 N2.getValueType().isFloatingPoint() &&
2278 "Invalid FCOPYSIGN!");
2285 assert(VT == N1.getValueType() &&
2286 "Shift operators return type must be the same as their first arg");
2287 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2288 "Shifts only work on integers");
2290 // Always fold shifts of i1 values so the code generator doesn't need to
2291 // handle them. Since we know the size of the shift has to be less than the
2292 // size of the value, the shift/rotate count is guaranteed to be zero.
2296 case ISD::FP_ROUND_INREG: {
2297 MVT EVT = cast<VTSDNode>(N2)->getVT();
2298 assert(VT == N1.getValueType() && "Not an inreg round!");
2299 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2300 "Cannot FP_ROUND_INREG integer types");
2301 assert(EVT.bitsLE(VT) && "Not rounding down!");
2302 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2306 assert(VT.isFloatingPoint() &&
2307 N1.getValueType().isFloatingPoint() &&
2308 VT.bitsLE(N1.getValueType()) &&
2309 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2310 if (N1.getValueType() == VT) return N1; // noop conversion.
2312 case ISD::AssertSext:
2313 case ISD::AssertZext: {
2314 MVT EVT = cast<VTSDNode>(N2)->getVT();
2315 assert(VT == N1.getValueType() && "Not an inreg extend!");
2316 assert(VT.isInteger() && EVT.isInteger() &&
2317 "Cannot *_EXTEND_INREG FP types");
2318 assert(EVT.bitsLE(VT) && "Not extending!");
2319 if (VT == EVT) return N1; // noop assertion.
2322 case ISD::SIGN_EXTEND_INREG: {
2323 MVT EVT = cast<VTSDNode>(N2)->getVT();
2324 assert(VT == N1.getValueType() && "Not an inreg extend!");
2325 assert(VT.isInteger() && EVT.isInteger() &&
2326 "Cannot *_EXTEND_INREG FP types");
2327 assert(EVT.bitsLE(VT) && "Not extending!");
2328 if (EVT == VT) return N1; // Not actually extending
2331 APInt Val = N1C->getAPIntValue();
2332 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2333 Val <<= Val.getBitWidth()-FromBits;
2334 Val = Val.ashr(Val.getBitWidth()-FromBits);
2335 return getConstant(Val, VT);
2339 case ISD::EXTRACT_VECTOR_ELT:
2340 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2341 if (N1.getOpcode() == ISD::UNDEF)
2342 return getNode(ISD::UNDEF, VT);
2344 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2345 // expanding copies of large vectors from registers.
2347 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2348 N1.getNumOperands() > 0) {
2350 N1.getOperand(0).getValueType().getVectorNumElements();
2351 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2352 N1.getOperand(N2C->getValue() / Factor),
2353 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2356 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2357 // expanding large vector constants.
2358 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
2359 return N1.getOperand(N2C->getValue());
2361 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2362 // operations are lowered to scalars.
2363 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2364 if (N1.getOperand(2) == N2)
2365 return N1.getOperand(1);
2367 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2370 case ISD::EXTRACT_ELEMENT:
2371 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2372 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2373 (N1.getValueType().isInteger() == VT.isInteger()) &&
2374 "Wrong types for EXTRACT_ELEMENT!");
2376 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2377 // 64-bit integers into 32-bit parts. Instead of building the extract of
2378 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2379 if (N1.getOpcode() == ISD::BUILD_PAIR)
2380 return N1.getOperand(N2C->getValue());
2382 // EXTRACT_ELEMENT of a constant int is also very common.
2383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2384 unsigned ElementSize = VT.getSizeInBits();
2385 unsigned Shift = ElementSize * N2C->getValue();
2386 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2387 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2390 case ISD::EXTRACT_SUBVECTOR:
2391 if (N1.getValueType() == VT) // Trivial extraction.
2398 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2400 case ISD::ADD: return getConstant(C1 + C2, VT);
2401 case ISD::SUB: return getConstant(C1 - C2, VT);
2402 case ISD::MUL: return getConstant(C1 * C2, VT);
2404 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2407 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2410 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2413 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2415 case ISD::AND : return getConstant(C1 & C2, VT);
2416 case ISD::OR : return getConstant(C1 | C2, VT);
2417 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2418 case ISD::SHL : return getConstant(C1 << C2, VT);
2419 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2420 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2421 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2422 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2425 } else { // Cannonicalize constant to RHS if commutative
2426 if (isCommutativeBinOp(Opcode)) {
2427 std::swap(N1C, N2C);
2433 // Constant fold FP operations.
2434 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2435 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2437 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2438 // Cannonicalize constant to RHS if commutative
2439 std::swap(N1CFP, N2CFP);
2441 } else if (N2CFP && VT != MVT::ppcf128) {
2442 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2443 APFloat::opStatus s;
2446 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2447 if (s != APFloat::opInvalidOp)
2448 return getConstantFP(V1, VT);
2451 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2452 if (s!=APFloat::opInvalidOp)
2453 return getConstantFP(V1, VT);
2456 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2457 if (s!=APFloat::opInvalidOp)
2458 return getConstantFP(V1, VT);
2461 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2462 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2463 return getConstantFP(V1, VT);
2466 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2467 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2468 return getConstantFP(V1, VT);
2470 case ISD::FCOPYSIGN:
2472 return getConstantFP(V1, VT);
2478 // Canonicalize an UNDEF to the RHS, even over a constant.
2479 if (N1.getOpcode() == ISD::UNDEF) {
2480 if (isCommutativeBinOp(Opcode)) {
2484 case ISD::FP_ROUND_INREG:
2485 case ISD::SIGN_EXTEND_INREG:
2491 return N1; // fold op(undef, arg2) -> undef
2499 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2500 // For vectors, we can't easily build an all zero vector, just return
2507 // Fold a bunch of operators when the RHS is undef.
2508 if (N2.getOpcode() == ISD::UNDEF) {
2511 if (N1.getOpcode() == ISD::UNDEF)
2512 // Handle undef ^ undef -> 0 special case. This is a common
2514 return getConstant(0, VT);
2529 return N2; // fold op(arg1, undef) -> undef
2535 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2536 // For vectors, we can't easily build an all zero vector, just return
2541 return getConstant(VT.getIntegerVTBitMask(), VT);
2542 // For vectors, we can't easily build an all one vector, just return
2550 // Memoize this node if possible.
2552 SDVTList VTs = getVTList(VT);
2553 if (VT != MVT::Flag) {
2554 SDValue Ops[] = { N1, N2 };
2555 FoldingSetNodeID ID;
2556 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2558 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2559 return SDValue(E, 0);
2560 N = NodeAllocator.Allocate<BinarySDNode>();
2561 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2562 CSEMap.InsertNode(N, IP);
2564 N = NodeAllocator.Allocate<BinarySDNode>();
2565 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2568 AllNodes.push_back(N);
2572 return SDValue(N, 0);
2575 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2576 SDValue N1, SDValue N2, SDValue N3) {
2577 // Perform various simplifications.
2578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2579 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2581 case ISD::CONCAT_VECTORS:
2582 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2583 // one big BUILD_VECTOR.
2584 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2585 N2.getOpcode() == ISD::BUILD_VECTOR &&
2586 N3.getOpcode() == ISD::BUILD_VECTOR) {
2587 SmallVector<SDValue, 16> Elts(N1.Val->op_begin(), N1.Val->op_end());
2588 Elts.insert(Elts.end(), N2.Val->op_begin(), N2.Val->op_end());
2589 Elts.insert(Elts.end(), N3.Val->op_begin(), N3.Val->op_end());
2590 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2594 // Use FoldSetCC to simplify SETCC's.
2595 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2596 if (Simp.Val) return Simp;
2601 if (N1C->getValue())
2602 return N2; // select true, X, Y -> X
2604 return N3; // select false, X, Y -> Y
2607 if (N2 == N3) return N2; // select C, X, X -> X
2611 if (N2C->getValue()) // Unconditional branch
2612 return getNode(ISD::BR, MVT::Other, N1, N3);
2614 return N1; // Never-taken branch
2617 case ISD::VECTOR_SHUFFLE:
2618 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2619 VT.isVector() && N3.getValueType().isVector() &&
2620 N3.getOpcode() == ISD::BUILD_VECTOR &&
2621 VT.getVectorNumElements() == N3.getNumOperands() &&
2622 "Illegal VECTOR_SHUFFLE node!");
2624 case ISD::BIT_CONVERT:
2625 // Fold bit_convert nodes from a type to themselves.
2626 if (N1.getValueType() == VT)
2631 // Memoize node if it doesn't produce a flag.
2633 SDVTList VTs = getVTList(VT);
2634 if (VT != MVT::Flag) {
2635 SDValue Ops[] = { N1, N2, N3 };
2636 FoldingSetNodeID ID;
2637 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2639 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2640 return SDValue(E, 0);
2641 N = NodeAllocator.Allocate<TernarySDNode>();
2642 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2643 CSEMap.InsertNode(N, IP);
2645 N = NodeAllocator.Allocate<TernarySDNode>();
2646 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2648 AllNodes.push_back(N);
2652 return SDValue(N, 0);
2655 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2656 SDValue N1, SDValue N2, SDValue N3,
2658 SDValue Ops[] = { N1, N2, N3, N4 };
2659 return getNode(Opcode, VT, Ops, 4);
2662 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2663 SDValue N1, SDValue N2, SDValue N3,
2664 SDValue N4, SDValue N5) {
2665 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2666 return getNode(Opcode, VT, Ops, 5);
2669 /// getMemsetValue - Vectorized representation of the memset value
2671 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
2672 unsigned NumBits = VT.isVector() ?
2673 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2674 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2675 APInt Val = APInt(NumBits, C->getValue() & 255);
2677 for (unsigned i = NumBits; i > 8; i >>= 1) {
2678 Val = (Val << Shift) | Val;
2682 return DAG.getConstant(Val, VT);
2683 return DAG.getConstantFP(APFloat(Val), VT);
2686 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2688 for (unsigned i = NumBits; i > 8; i >>= 1) {
2689 Value = DAG.getNode(ISD::OR, VT,
2690 DAG.getNode(ISD::SHL, VT, Value,
2691 DAG.getConstant(Shift, MVT::i8)), Value);
2698 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2699 /// used when a memcpy is turned into a memset when the source is a constant
2701 static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2702 const TargetLowering &TLI,
2703 std::string &Str, unsigned Offset) {
2704 // Handle vector with all elements zero.
2707 return DAG.getConstant(0, VT);
2708 unsigned NumElts = VT.getVectorNumElements();
2709 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2710 return DAG.getNode(ISD::BIT_CONVERT, VT,
2711 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2714 assert(!VT.isVector() && "Can't handle vector type here!");
2715 unsigned NumBits = VT.getSizeInBits();
2716 unsigned MSB = NumBits / 8;
2718 if (TLI.isLittleEndian())
2719 Offset = Offset + MSB - 1;
2720 for (unsigned i = 0; i != MSB; ++i) {
2721 Val = (Val << 8) | (unsigned char)Str[Offset];
2722 Offset += TLI.isLittleEndian() ? -1 : 1;
2724 return DAG.getConstant(Val, VT);
2727 /// getMemBasePlusOffset - Returns base and offset node for the
2729 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2730 SelectionDAG &DAG) {
2731 MVT VT = Base.getValueType();
2732 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2735 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2737 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
2738 unsigned SrcDelta = 0;
2739 GlobalAddressSDNode *G = NULL;
2740 if (Src.getOpcode() == ISD::GlobalAddress)
2741 G = cast<GlobalAddressSDNode>(Src);
2742 else if (Src.getOpcode() == ISD::ADD &&
2743 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2744 Src.getOperand(1).getOpcode() == ISD::Constant) {
2745 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2746 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2751 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2752 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2758 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2759 /// to replace the memset / memcpy is below the threshold. It also returns the
2760 /// types of the sequence of memory ops to perform memset / memcpy.
2762 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2763 SDValue Dst, SDValue Src,
2764 unsigned Limit, uint64_t Size, unsigned &Align,
2765 std::string &Str, bool &isSrcStr,
2767 const TargetLowering &TLI) {
2768 isSrcStr = isMemSrcFromString(Src, Str);
2769 bool isSrcConst = isa<ConstantSDNode>(Src);
2770 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2771 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2772 if (VT != MVT::iAny) {
2773 unsigned NewAlign = (unsigned)
2774 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2775 // If source is a string constant, this will require an unaligned load.
2776 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2777 if (Dst.getOpcode() != ISD::FrameIndex) {
2778 // Can't change destination alignment. It requires a unaligned store.
2782 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2783 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2784 if (MFI->isFixedObjectIndex(FI)) {
2785 // Can't change destination alignment. It requires a unaligned store.
2789 // Give the stack frame object a larger alignment if needed.
2790 if (MFI->getObjectAlignment(FI) < NewAlign)
2791 MFI->setObjectAlignment(FI, NewAlign);
2798 if (VT == MVT::iAny) {
2802 switch (Align & 7) {
2803 case 0: VT = MVT::i64; break;
2804 case 4: VT = MVT::i32; break;
2805 case 2: VT = MVT::i16; break;
2806 default: VT = MVT::i8; break;
2811 while (!TLI.isTypeLegal(LVT))
2812 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2813 assert(LVT.isInteger());
2819 unsigned NumMemOps = 0;
2821 unsigned VTSize = VT.getSizeInBits() / 8;
2822 while (VTSize > Size) {
2823 // For now, only use non-vector load / store's for the left-over pieces.
2824 if (VT.isVector()) {
2826 while (!TLI.isTypeLegal(VT))
2827 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2828 VTSize = VT.getSizeInBits() / 8;
2830 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2835 if (++NumMemOps > Limit)
2837 MemOps.push_back(VT);
2844 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
2845 SDValue Chain, SDValue Dst,
2846 SDValue Src, uint64_t Size,
2847 unsigned Align, bool AlwaysInline,
2848 const Value *DstSV, uint64_t DstSVOff,
2849 const Value *SrcSV, uint64_t SrcSVOff){
2850 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2852 // Expand memcpy to a series of load and store ops if the size operand falls
2853 // below a certain threshold.
2854 std::vector<MVT> MemOps;
2855 uint64_t Limit = -1;
2857 Limit = TLI.getMaxStoresPerMemcpy();
2858 unsigned DstAlign = Align; // Destination alignment can change.
2861 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2862 Str, CopyFromStr, DAG, TLI))
2866 bool isZeroStr = CopyFromStr && Str.empty();
2867 SmallVector<SDValue, 8> OutChains;
2868 unsigned NumMemOps = MemOps.size();
2869 uint64_t SrcOff = 0, DstOff = 0;
2870 for (unsigned i = 0; i < NumMemOps; i++) {
2872 unsigned VTSize = VT.getSizeInBits() / 8;
2873 SDValue Value, Store;
2875 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2876 // It's unlikely a store of a vector immediate can be done in a single
2877 // instruction. It would require a load from a constantpool first.
2878 // We also handle store a vector with all zero's.
2879 // FIXME: Handle other cases where store of vector immediate is done in
2880 // a single instruction.
2881 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2882 Store = DAG.getStore(Chain, Value,
2883 getMemBasePlusOffset(Dst, DstOff, DAG),
2884 DstSV, DstSVOff + DstOff, false, DstAlign);
2886 Value = DAG.getLoad(VT, Chain,
2887 getMemBasePlusOffset(Src, SrcOff, DAG),
2888 SrcSV, SrcSVOff + SrcOff, false, Align);
2889 Store = DAG.getStore(Chain, Value,
2890 getMemBasePlusOffset(Dst, DstOff, DAG),
2891 DstSV, DstSVOff + DstOff, false, DstAlign);
2893 OutChains.push_back(Store);
2898 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2899 &OutChains[0], OutChains.size());
2902 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
2903 SDValue Chain, SDValue Dst,
2904 SDValue Src, uint64_t Size,
2905 unsigned Align, bool AlwaysInline,
2906 const Value *DstSV, uint64_t DstSVOff,
2907 const Value *SrcSV, uint64_t SrcSVOff){
2908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2910 // Expand memmove to a series of load and store ops if the size operand falls
2911 // below a certain threshold.
2912 std::vector<MVT> MemOps;
2913 uint64_t Limit = -1;
2915 Limit = TLI.getMaxStoresPerMemmove();
2916 unsigned DstAlign = Align; // Destination alignment can change.
2919 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2920 Str, CopyFromStr, DAG, TLI))
2923 uint64_t SrcOff = 0, DstOff = 0;
2925 SmallVector<SDValue, 8> LoadValues;
2926 SmallVector<SDValue, 8> LoadChains;
2927 SmallVector<SDValue, 8> OutChains;
2928 unsigned NumMemOps = MemOps.size();
2929 for (unsigned i = 0; i < NumMemOps; i++) {
2931 unsigned VTSize = VT.getSizeInBits() / 8;
2932 SDValue Value, Store;
2934 Value = DAG.getLoad(VT, Chain,
2935 getMemBasePlusOffset(Src, SrcOff, DAG),
2936 SrcSV, SrcSVOff + SrcOff, false, Align);
2937 LoadValues.push_back(Value);
2938 LoadChains.push_back(Value.getValue(1));
2941 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2942 &LoadChains[0], LoadChains.size());
2944 for (unsigned i = 0; i < NumMemOps; i++) {
2946 unsigned VTSize = VT.getSizeInBits() / 8;
2947 SDValue Value, Store;
2949 Store = DAG.getStore(Chain, LoadValues[i],
2950 getMemBasePlusOffset(Dst, DstOff, DAG),
2951 DstSV, DstSVOff + DstOff, false, DstAlign);
2952 OutChains.push_back(Store);
2956 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2957 &OutChains[0], OutChains.size());
2960 static SDValue getMemsetStores(SelectionDAG &DAG,
2961 SDValue Chain, SDValue Dst,
2962 SDValue Src, uint64_t Size,
2964 const Value *DstSV, uint64_t DstSVOff) {
2965 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2967 // Expand memset to a series of load/store ops if the size operand
2968 // falls below a certain threshold.
2969 std::vector<MVT> MemOps;
2972 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2973 Size, Align, Str, CopyFromStr, DAG, TLI))
2976 SmallVector<SDValue, 8> OutChains;
2977 uint64_t DstOff = 0;
2979 unsigned NumMemOps = MemOps.size();
2980 for (unsigned i = 0; i < NumMemOps; i++) {
2982 unsigned VTSize = VT.getSizeInBits() / 8;
2983 SDValue Value = getMemsetValue(Src, VT, DAG);
2984 SDValue Store = DAG.getStore(Chain, Value,
2985 getMemBasePlusOffset(Dst, DstOff, DAG),
2986 DstSV, DstSVOff + DstOff);
2987 OutChains.push_back(Store);
2991 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2992 &OutChains[0], OutChains.size());
2995 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
2996 SDValue Src, SDValue Size,
2997 unsigned Align, bool AlwaysInline,
2998 const Value *DstSV, uint64_t DstSVOff,
2999 const Value *SrcSV, uint64_t SrcSVOff) {
3001 // Check to see if we should lower the memcpy to loads and stores first.
3002 // For cases within the target-specified limits, this is the best choice.
3003 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3005 // Memcpy with size zero? Just return the original chain.
3006 if (ConstantSize->isNullValue())
3010 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
3011 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3016 // Then check to see if we should lower the memcpy with target-specific
3017 // code. If the target chooses to do this, this is the next best.
3019 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
3021 DstSV, DstSVOff, SrcSV, SrcSVOff);
3025 // If we really need inline code and the target declined to provide it,
3026 // use a (potentially long) sequence of loads and stores.
3028 assert(ConstantSize && "AlwaysInline requires a constant size!");
3029 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3030 ConstantSize->getValue(), Align, true,
3031 DstSV, DstSVOff, SrcSV, SrcSVOff);
3034 // Emit a library call.
3035 TargetLowering::ArgListTy Args;
3036 TargetLowering::ArgListEntry Entry;
3037 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3038 Entry.Node = Dst; Args.push_back(Entry);
3039 Entry.Node = Src; Args.push_back(Entry);
3040 Entry.Node = Size; Args.push_back(Entry);
3041 std::pair<SDValue,SDValue> CallResult =
3042 TLI.LowerCallTo(Chain, Type::VoidTy,
3043 false, false, false, CallingConv::C, false,
3044 getExternalSymbol("memcpy", TLI.getPointerTy()),
3046 return CallResult.second;
3049 SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
3050 SDValue Src, SDValue Size,
3052 const Value *DstSV, uint64_t DstSVOff,
3053 const Value *SrcSV, uint64_t SrcSVOff) {
3055 // Check to see if we should lower the memmove to loads and stores first.
3056 // For cases within the target-specified limits, this is the best choice.
3057 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3059 // Memmove with size zero? Just return the original chain.
3060 if (ConstantSize->isNullValue())
3064 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
3065 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3070 // Then check to see if we should lower the memmove with target-specific
3071 // code. If the target chooses to do this, this is the next best.
3073 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3074 DstSV, DstSVOff, SrcSV, SrcSVOff);
3078 // Emit a library call.
3079 TargetLowering::ArgListTy Args;
3080 TargetLowering::ArgListEntry Entry;
3081 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3082 Entry.Node = Dst; Args.push_back(Entry);
3083 Entry.Node = Src; Args.push_back(Entry);
3084 Entry.Node = Size; Args.push_back(Entry);
3085 std::pair<SDValue,SDValue> CallResult =
3086 TLI.LowerCallTo(Chain, Type::VoidTy,
3087 false, false, false, CallingConv::C, false,
3088 getExternalSymbol("memmove", TLI.getPointerTy()),
3090 return CallResult.second;
3093 SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
3094 SDValue Src, SDValue Size,
3096 const Value *DstSV, uint64_t DstSVOff) {
3098 // Check to see if we should lower the memset to stores first.
3099 // For cases within the target-specified limits, this is the best choice.
3100 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3102 // Memset with size zero? Just return the original chain.
3103 if (ConstantSize->isNullValue())
3107 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3113 // Then check to see if we should lower the memset with target-specific
3114 // code. If the target chooses to do this, this is the next best.
3116 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3121 // Emit a library call.
3122 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3123 TargetLowering::ArgListTy Args;
3124 TargetLowering::ArgListEntry Entry;
3125 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3126 Args.push_back(Entry);
3127 // Extend or truncate the argument to be an i32 value for the call.
3128 if (Src.getValueType().bitsGT(MVT::i32))
3129 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3131 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3132 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3133 Args.push_back(Entry);
3134 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3135 Args.push_back(Entry);
3136 std::pair<SDValue,SDValue> CallResult =
3137 TLI.LowerCallTo(Chain, Type::VoidTy,
3138 false, false, false, CallingConv::C, false,
3139 getExternalSymbol("memset", TLI.getPointerTy()),
3141 return CallResult.second;
3144 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3145 SDValue Ptr, SDValue Cmp,
3146 SDValue Swp, const Value* PtrVal,
3147 unsigned Alignment) {
3148 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3149 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3151 MVT VT = Cmp.getValueType();
3153 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3154 Alignment = getMVTAlignment(VT);
3156 SDVTList VTs = getVTList(VT, MVT::Other);
3157 FoldingSetNodeID ID;
3158 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3159 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3161 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3162 return SDValue(E, 0);
3163 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3164 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3165 CSEMap.InsertNode(N, IP);
3166 AllNodes.push_back(N);
3167 return SDValue(N, 0);
3170 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3171 SDValue Ptr, SDValue Val,
3172 const Value* PtrVal,
3173 unsigned Alignment) {
3174 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3175 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3176 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3177 || Opcode == ISD::ATOMIC_LOAD_NAND
3178 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3179 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3180 && "Invalid Atomic Op");
3182 MVT VT = Val.getValueType();
3184 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3185 Alignment = getMVTAlignment(VT);
3187 SDVTList VTs = getVTList(VT, MVT::Other);
3188 FoldingSetNodeID ID;
3189 SDValue Ops[] = {Chain, Ptr, Val};
3190 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3192 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3193 return SDValue(E, 0);
3194 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3195 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3196 CSEMap.InsertNode(N, IP);
3197 AllNodes.push_back(N);
3198 return SDValue(N, 0);
3201 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3202 /// Allowed to return something different (and simpler) if Simplify is true.
3203 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3205 if (Simplify && NumOps == 1)
3208 SmallVector<MVT, 4> VTs;
3209 VTs.reserve(NumOps);
3210 for (unsigned i = 0; i < NumOps; ++i)
3211 VTs.push_back(Ops[i].getValueType());
3212 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3216 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3217 MVT VT, SDValue Chain,
3218 SDValue Ptr, SDValue Offset,
3219 const Value *SV, int SVOffset, MVT EVT,
3220 bool isVolatile, unsigned Alignment) {
3221 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3222 Alignment = getMVTAlignment(VT);
3225 ExtType = ISD::NON_EXTLOAD;
3226 } else if (ExtType == ISD::NON_EXTLOAD) {
3227 assert(VT == EVT && "Non-extending load from different memory type!");
3231 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3232 "Invalid vector extload!");
3234 assert(EVT.bitsLT(VT) &&
3235 "Should only be an extending load, not truncating!");
3236 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3237 "Cannot sign/zero extend a FP/Vector load!");
3238 assert(VT.isInteger() == EVT.isInteger() &&
3239 "Cannot convert from FP to Int or Int -> FP!");
3242 bool Indexed = AM != ISD::UNINDEXED;
3243 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3244 "Unindexed load with an offset!");
3246 SDVTList VTs = Indexed ?
3247 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3248 SDValue Ops[] = { Chain, Ptr, Offset };
3249 FoldingSetNodeID ID;
3250 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3252 ID.AddInteger(ExtType);
3253 ID.AddInteger(EVT.getRawBits());
3254 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3256 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3257 return SDValue(E, 0);
3258 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3259 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3260 Alignment, isVolatile);
3261 CSEMap.InsertNode(N, IP);
3262 AllNodes.push_back(N);
3263 return SDValue(N, 0);
3266 SDValue SelectionDAG::getLoad(MVT VT,
3267 SDValue Chain, SDValue Ptr,
3268 const Value *SV, int SVOffset,
3269 bool isVolatile, unsigned Alignment) {
3270 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3271 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3272 SV, SVOffset, VT, isVolatile, Alignment);
3275 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3276 SDValue Chain, SDValue Ptr,
3278 int SVOffset, MVT EVT,
3279 bool isVolatile, unsigned Alignment) {
3280 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3281 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3282 SV, SVOffset, EVT, isVolatile, Alignment);
3286 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
3287 SDValue Offset, ISD::MemIndexedMode AM) {
3288 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3289 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3290 "Load is already a indexed load!");
3291 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3292 LD->getChain(), Base, Offset, LD->getSrcValue(),
3293 LD->getSrcValueOffset(), LD->getMemoryVT(),
3294 LD->isVolatile(), LD->getAlignment());
3297 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3298 SDValue Ptr, const Value *SV, int SVOffset,
3299 bool isVolatile, unsigned Alignment) {
3300 MVT VT = Val.getValueType();
3302 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3303 Alignment = getMVTAlignment(VT);
3305 SDVTList VTs = getVTList(MVT::Other);
3306 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3307 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3308 FoldingSetNodeID ID;
3309 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3310 ID.AddInteger(ISD::UNINDEXED);
3311 ID.AddInteger(false);
3312 ID.AddInteger(VT.getRawBits());
3313 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3315 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3316 return SDValue(E, 0);
3317 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3318 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3319 VT, SV, SVOffset, Alignment, isVolatile);
3320 CSEMap.InsertNode(N, IP);
3321 AllNodes.push_back(N);
3322 return SDValue(N, 0);
3325 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
3326 SDValue Ptr, const Value *SV,
3327 int SVOffset, MVT SVT,
3328 bool isVolatile, unsigned Alignment) {
3329 MVT VT = Val.getValueType();
3332 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3334 assert(VT.bitsGT(SVT) && "Not a truncation?");
3335 assert(VT.isInteger() == SVT.isInteger() &&
3336 "Can't do FP-INT conversion!");
3338 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3339 Alignment = getMVTAlignment(VT);
3341 SDVTList VTs = getVTList(MVT::Other);
3342 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3343 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3344 FoldingSetNodeID ID;
3345 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3346 ID.AddInteger(ISD::UNINDEXED);
3348 ID.AddInteger(SVT.getRawBits());
3349 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3351 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3352 return SDValue(E, 0);
3353 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3354 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3355 SVT, SV, SVOffset, Alignment, isVolatile);
3356 CSEMap.InsertNode(N, IP);
3357 AllNodes.push_back(N);
3358 return SDValue(N, 0);
3362 SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
3363 SDValue Offset, ISD::MemIndexedMode AM) {
3364 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3365 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3366 "Store is already a indexed store!");
3367 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3368 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3369 FoldingSetNodeID ID;
3370 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3372 ID.AddInteger(ST->isTruncatingStore());
3373 ID.AddInteger(ST->getMemoryVT().getRawBits());
3374 ID.AddInteger(ST->getRawFlags());
3376 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3377 return SDValue(E, 0);
3378 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3379 new (N) StoreSDNode(Ops, VTs, AM,
3380 ST->isTruncatingStore(), ST->getMemoryVT(),
3381 ST->getSrcValue(), ST->getSrcValueOffset(),
3382 ST->getAlignment(), ST->isVolatile());
3383 CSEMap.InsertNode(N, IP);
3384 AllNodes.push_back(N);
3385 return SDValue(N, 0);
3388 SDValue SelectionDAG::getVAArg(MVT VT,
3389 SDValue Chain, SDValue Ptr,
3391 SDValue Ops[] = { Chain, Ptr, SV };
3392 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3395 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3396 const SDUse *Ops, unsigned NumOps) {
3398 case 0: return getNode(Opcode, VT);
3399 case 1: return getNode(Opcode, VT, Ops[0]);
3400 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3401 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3405 // Copy from an SDUse array into an SDValue array for use with
3406 // the regular getNode logic.
3407 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3408 return getNode(Opcode, VT, &NewOps[0], NumOps);
3411 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3412 const SDValue *Ops, unsigned NumOps) {
3414 case 0: return getNode(Opcode, VT);
3415 case 1: return getNode(Opcode, VT, Ops[0]);
3416 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3417 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3423 case ISD::SELECT_CC: {
3424 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3425 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3426 "LHS and RHS of condition must have same type!");
3427 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3428 "True and False arms of SelectCC must have same type!");
3429 assert(Ops[2].getValueType() == VT &&
3430 "select_cc node must be of same type as true and false value!");
3434 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3435 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3436 "LHS/RHS of comparison should match types!");
3443 SDVTList VTs = getVTList(VT);
3444 if (VT != MVT::Flag) {
3445 FoldingSetNodeID ID;
3446 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3448 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3449 return SDValue(E, 0);
3450 N = NodeAllocator.Allocate<SDNode>();
3451 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3452 CSEMap.InsertNode(N, IP);
3454 N = NodeAllocator.Allocate<SDNode>();
3455 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3457 AllNodes.push_back(N);
3461 return SDValue(N, 0);
3464 SDValue SelectionDAG::getNode(unsigned Opcode,
3465 const std::vector<MVT> &ResultTys,
3466 const SDValue *Ops, unsigned NumOps) {
3467 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3471 SDValue SelectionDAG::getNode(unsigned Opcode,
3472 const MVT *VTs, unsigned NumVTs,
3473 const SDValue *Ops, unsigned NumOps) {
3475 return getNode(Opcode, VTs[0], Ops, NumOps);
3476 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3479 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3480 const SDValue *Ops, unsigned NumOps) {
3481 if (VTList.NumVTs == 1)
3482 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3485 // FIXME: figure out how to safely handle things like
3486 // int foo(int x) { return 1 << (x & 255); }
3487 // int bar() { return foo(256); }
3489 case ISD::SRA_PARTS:
3490 case ISD::SRL_PARTS:
3491 case ISD::SHL_PARTS:
3492 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3493 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3494 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3495 else if (N3.getOpcode() == ISD::AND)
3496 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3497 // If the and is only masking out bits that cannot effect the shift,
3498 // eliminate the and.
3499 unsigned NumBits = VT.getSizeInBits()*2;
3500 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3501 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3507 // Memoize the node unless it returns a flag.
3509 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3510 FoldingSetNodeID ID;
3511 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3513 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3514 return SDValue(E, 0);
3516 N = NodeAllocator.Allocate<UnarySDNode>();
3517 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3518 } else if (NumOps == 2) {
3519 N = NodeAllocator.Allocate<BinarySDNode>();
3520 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3521 } else if (NumOps == 3) {
3522 N = NodeAllocator.Allocate<TernarySDNode>();
3523 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3525 N = NodeAllocator.Allocate<SDNode>();
3526 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3528 CSEMap.InsertNode(N, IP);
3531 N = NodeAllocator.Allocate<UnarySDNode>();
3532 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3533 } else if (NumOps == 2) {
3534 N = NodeAllocator.Allocate<BinarySDNode>();
3535 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3536 } else if (NumOps == 3) {
3537 N = NodeAllocator.Allocate<TernarySDNode>();
3538 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3540 N = NodeAllocator.Allocate<SDNode>();
3541 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3544 AllNodes.push_back(N);
3548 return SDValue(N, 0);
3551 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3552 return getNode(Opcode, VTList, 0, 0);
3555 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3557 SDValue Ops[] = { N1 };
3558 return getNode(Opcode, VTList, Ops, 1);
3561 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3562 SDValue N1, SDValue N2) {
3563 SDValue Ops[] = { N1, N2 };
3564 return getNode(Opcode, VTList, Ops, 2);
3567 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3568 SDValue N1, SDValue N2, SDValue N3) {
3569 SDValue Ops[] = { N1, N2, N3 };
3570 return getNode(Opcode, VTList, Ops, 3);
3573 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3574 SDValue N1, SDValue N2, SDValue N3,
3576 SDValue Ops[] = { N1, N2, N3, N4 };
3577 return getNode(Opcode, VTList, Ops, 4);
3580 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3581 SDValue N1, SDValue N2, SDValue N3,
3582 SDValue N4, SDValue N5) {
3583 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3584 return getNode(Opcode, VTList, Ops, 5);
3587 SDVTList SelectionDAG::getVTList(MVT VT) {
3588 return makeVTList(SDNode::getValueTypeList(VT), 1);
3591 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3592 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3593 E = VTList.rend(); I != E; ++I)
3594 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
3597 MVT *Array = Allocator.Allocate<MVT>(2);
3600 SDVTList Result = makeVTList(Array, 2);
3601 VTList.push_back(Result);
3605 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
3606 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3607 E = VTList.rend(); I != E; ++I)
3608 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
3612 MVT *Array = Allocator.Allocate<MVT>(3);
3616 SDVTList Result = makeVTList(Array, 3);
3617 VTList.push_back(Result);
3621 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3623 case 0: assert(0 && "Cannot have nodes without results!");
3624 case 1: return getVTList(VTs[0]);
3625 case 2: return getVTList(VTs[0], VTs[1]);
3626 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3630 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3631 E = VTList.rend(); I != E; ++I) {
3632 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
3635 bool NoMatch = false;
3636 for (unsigned i = 2; i != NumVTs; ++i)
3637 if (VTs[i] != I->VTs[i]) {
3645 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
3646 std::copy(VTs, VTs+NumVTs, Array);
3647 SDVTList Result = makeVTList(Array, NumVTs);
3648 VTList.push_back(Result);
3653 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3654 /// specified operands. If the resultant node already exists in the DAG,
3655 /// this does not modify the specified node, instead it returns the node that
3656 /// already exists. If the resultant node does not exist in the DAG, the
3657 /// input node is returned. As a degenerate case, if you specify the same
3658 /// input operands as the node already has, the input node is returned.
3659 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
3660 SDNode *N = InN.Val;
3661 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3663 // Check to see if there is no change.
3664 if (Op == N->getOperand(0)) return InN;
3666 // See if the modified node already exists.
3667 void *InsertPos = 0;
3668 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3669 return SDValue(Existing, InN.ResNo);
3671 // Nope it doesn't. Remove the node from its current place in the maps.
3673 RemoveNodeFromCSEMaps(N);
3675 // Now we update the operands.
3676 N->OperandList[0].getVal()->removeUser(0, N);
3677 N->OperandList[0] = Op;
3678 N->OperandList[0].setUser(N);
3679 Op.Val->addUser(0, N);
3681 // If this gets put into a CSE map, add it.
3682 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3686 SDValue SelectionDAG::
3687 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
3688 SDNode *N = InN.Val;
3689 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3691 // Check to see if there is no change.
3692 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3693 return InN; // No operands changed, just return the input node.
3695 // See if the modified node already exists.
3696 void *InsertPos = 0;
3697 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3698 return SDValue(Existing, InN.ResNo);
3700 // Nope it doesn't. Remove the node from its current place in the maps.
3702 RemoveNodeFromCSEMaps(N);
3704 // Now we update the operands.
3705 if (N->OperandList[0] != Op1) {
3706 N->OperandList[0].getVal()->removeUser(0, N);
3707 N->OperandList[0] = Op1;
3708 N->OperandList[0].setUser(N);
3709 Op1.Val->addUser(0, N);
3711 if (N->OperandList[1] != Op2) {
3712 N->OperandList[1].getVal()->removeUser(1, N);
3713 N->OperandList[1] = Op2;
3714 N->OperandList[1].setUser(N);
3715 Op2.Val->addUser(1, N);
3718 // If this gets put into a CSE map, add it.
3719 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3723 SDValue SelectionDAG::
3724 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
3725 SDValue Ops[] = { Op1, Op2, Op3 };
3726 return UpdateNodeOperands(N, Ops, 3);
3729 SDValue SelectionDAG::
3730 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3731 SDValue Op3, SDValue Op4) {
3732 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
3733 return UpdateNodeOperands(N, Ops, 4);
3736 SDValue SelectionDAG::
3737 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3738 SDValue Op3, SDValue Op4, SDValue Op5) {
3739 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3740 return UpdateNodeOperands(N, Ops, 5);
3743 SDValue SelectionDAG::
3744 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
3745 SDNode *N = InN.Val;
3746 assert(N->getNumOperands() == NumOps &&
3747 "Update with wrong number of operands");
3749 // Check to see if there is no change.
3750 bool AnyChange = false;
3751 for (unsigned i = 0; i != NumOps; ++i) {
3752 if (Ops[i] != N->getOperand(i)) {
3758 // No operands changed, just return the input node.
3759 if (!AnyChange) return InN;
3761 // See if the modified node already exists.
3762 void *InsertPos = 0;
3763 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3764 return SDValue(Existing, InN.ResNo);
3766 // Nope it doesn't. Remove the node from its current place in the maps.
3768 RemoveNodeFromCSEMaps(N);
3770 // Now we update the operands.
3771 for (unsigned i = 0; i != NumOps; ++i) {
3772 if (N->OperandList[i] != Ops[i]) {
3773 N->OperandList[i].getVal()->removeUser(i, N);
3774 N->OperandList[i] = Ops[i];
3775 N->OperandList[i].setUser(N);
3776 Ops[i].Val->addUser(i, N);
3780 // If this gets put into a CSE map, add it.
3781 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3785 /// DropOperands - Release the operands and set this node to have
3787 void SDNode::DropOperands() {
3788 // Unlike the code in MorphNodeTo that does this, we don't need to
3789 // watch for dead nodes here.
3790 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3791 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3796 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
3799 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3801 SDVTList VTs = getVTList(VT);
3802 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
3805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3806 MVT VT, SDValue Op1) {
3807 SDVTList VTs = getVTList(VT);
3808 SDValue Ops[] = { Op1 };
3809 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3812 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3813 MVT VT, SDValue Op1,
3815 SDVTList VTs = getVTList(VT);
3816 SDValue Ops[] = { Op1, Op2 };
3817 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3820 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3821 MVT VT, SDValue Op1,
3822 SDValue Op2, SDValue Op3) {
3823 SDVTList VTs = getVTList(VT);
3824 SDValue Ops[] = { Op1, Op2, Op3 };
3825 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3828 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3829 MVT VT, const SDValue *Ops,
3831 SDVTList VTs = getVTList(VT);
3832 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3835 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3836 MVT VT1, MVT VT2, const SDValue *Ops,
3838 SDVTList VTs = getVTList(VT1, VT2);
3839 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3842 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3844 SDVTList VTs = getVTList(VT1, VT2);
3845 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
3848 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3849 MVT VT1, MVT VT2, MVT VT3,
3850 const SDValue *Ops, unsigned NumOps) {
3851 SDVTList VTs = getVTList(VT1, VT2, VT3);
3852 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3855 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3858 SDVTList VTs = getVTList(VT1, VT2);
3859 SDValue Ops[] = { Op1 };
3860 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3863 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3865 SDValue Op1, SDValue Op2) {
3866 SDVTList VTs = getVTList(VT1, VT2);
3867 SDValue Ops[] = { Op1, Op2 };
3868 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3871 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3873 SDValue Op1, SDValue Op2,
3875 SDVTList VTs = getVTList(VT1, VT2);
3876 SDValue Ops[] = { Op1, Op2, Op3 };
3877 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3880 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3881 SDVTList VTs, const SDValue *Ops,
3883 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
3886 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3888 SDVTList VTs = getVTList(VT);
3889 return MorphNodeTo(N, Opc, VTs, 0, 0);
3892 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3893 MVT VT, SDValue Op1) {
3894 SDVTList VTs = getVTList(VT);
3895 SDValue Ops[] = { Op1 };
3896 return MorphNodeTo(N, Opc, VTs, Ops, 1);
3899 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3900 MVT VT, SDValue Op1,
3902 SDVTList VTs = getVTList(VT);
3903 SDValue Ops[] = { Op1, Op2 };
3904 return MorphNodeTo(N, Opc, VTs, Ops, 2);
3907 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3908 MVT VT, SDValue Op1,
3909 SDValue Op2, SDValue Op3) {
3910 SDVTList VTs = getVTList(VT);
3911 SDValue Ops[] = { Op1, Op2, Op3 };
3912 return MorphNodeTo(N, Opc, VTs, Ops, 3);
3915 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3916 MVT VT, const SDValue *Ops,
3918 SDVTList VTs = getVTList(VT);
3919 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3922 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3923 MVT VT1, MVT VT2, const SDValue *Ops,
3925 SDVTList VTs = getVTList(VT1, VT2);
3926 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3929 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3931 SDVTList VTs = getVTList(VT1, VT2);
3932 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
3935 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3936 MVT VT1, MVT VT2, MVT VT3,
3937 const SDValue *Ops, unsigned NumOps) {
3938 SDVTList VTs = getVTList(VT1, VT2, VT3);
3939 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3942 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3945 SDVTList VTs = getVTList(VT1, VT2);
3946 SDValue Ops[] = { Op1 };
3947 return MorphNodeTo(N, Opc, VTs, Ops, 1);
3950 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3952 SDValue Op1, SDValue Op2) {
3953 SDVTList VTs = getVTList(VT1, VT2);
3954 SDValue Ops[] = { Op1, Op2 };
3955 return MorphNodeTo(N, Opc, VTs, Ops, 2);
3958 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3960 SDValue Op1, SDValue Op2,
3962 SDVTList VTs = getVTList(VT1, VT2);
3963 SDValue Ops[] = { Op1, Op2, Op3 };
3964 return MorphNodeTo(N, Opc, VTs, Ops, 3);
3967 /// MorphNodeTo - These *mutate* the specified node to have the specified
3968 /// return type, opcode, and operands.
3970 /// Note that MorphNodeTo returns the resultant node. If there is already a
3971 /// node of the specified opcode and operands, it returns that node instead of
3972 /// the current one.
3974 /// Using MorphNodeTo is faster than creating a new node and swapping it in
3975 /// with ReplaceAllUsesWith both because it often avoids allocating a new
3976 /// node, and because it doesn't require CSE recalulation for any of
3977 /// the node's users.
3979 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3980 SDVTList VTs, const SDValue *Ops,
3982 // If an identical node already exists, use it.
3984 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
3985 FoldingSetNodeID ID;
3986 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
3987 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3991 RemoveNodeFromCSEMaps(N);
3993 // Start the morphing.
3995 N->ValueList = VTs.VTs;
3996 N->NumValues = VTs.NumVTs;
3998 // Clear the operands list, updating used nodes to remove this from their
3999 // use list. Keep track of any operands that become dead as a result.
4000 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4001 for (SDNode::op_iterator B = N->op_begin(), I = B, E = N->op_end();
4003 SDNode *Used = I->getVal();
4004 Used->removeUser(std::distance(B, I), N);
4005 if (Used->use_empty())
4006 DeadNodeSet.insert(Used);
4009 // If NumOps is larger than the # of operands we currently have, reallocate
4010 // the operand list.
4011 if (NumOps > N->NumOperands) {
4012 if (N->OperandsNeedDelete)
4013 delete[] N->OperandList;
4014 if (N->isMachineOpcode()) {
4015 // We're creating a final node that will live unmorphed for the
4016 // remainder of the current SelectionDAG iteration, so we can allocate
4017 // the operands directly out of a pool with no recycling metadata.
4018 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4019 N->OperandsNeedDelete = false;
4021 N->OperandList = new SDUse[NumOps];
4022 N->OperandsNeedDelete = true;
4026 // Assign the new operands.
4027 N->NumOperands = NumOps;
4028 for (unsigned i = 0, e = NumOps; i != e; ++i) {
4029 N->OperandList[i] = Ops[i];
4030 N->OperandList[i].setUser(N);
4031 SDNode *ToUse = N->OperandList[i].getVal();
4032 ToUse->addUser(i, N);
4035 // Delete any nodes that are still dead after adding the uses for the
4037 SmallVector<SDNode *, 16> DeadNodes;
4038 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4039 E = DeadNodeSet.end(); I != E; ++I)
4040 if ((*I)->use_empty())
4041 DeadNodes.push_back(*I);
4042 RemoveDeadNodes(DeadNodes);
4045 CSEMap.InsertNode(N, IP); // Memoize the new node.
4050 /// getTargetNode - These are used for target selectors to create a new node
4051 /// with specified return type(s), target opcode, and operands.
4053 /// Note that getTargetNode returns the resultant node. If there is already a
4054 /// node of the specified opcode and operands, it returns that node instead of
4055 /// the current one.
4056 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4057 return getNode(~Opcode, VT).Val;
4059 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4060 return getNode(~Opcode, VT, Op1).Val;
4062 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4063 SDValue Op1, SDValue Op2) {
4064 return getNode(~Opcode, VT, Op1, Op2).Val;
4066 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4067 SDValue Op1, SDValue Op2,
4069 return getNode(~Opcode, VT, Op1, Op2, Op3).Val;
4071 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4072 const SDValue *Ops, unsigned NumOps) {
4073 return getNode(~Opcode, VT, Ops, NumOps).Val;
4075 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4076 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4078 return getNode(~Opcode, VTs, 2, &Op, 0).Val;
4080 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4081 MVT VT2, SDValue Op1) {
4082 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4083 return getNode(~Opcode, VTs, 2, &Op1, 1).Val;
4085 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4086 MVT VT2, SDValue Op1,
4088 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4089 SDValue Ops[] = { Op1, Op2 };
4090 return getNode(~Opcode, VTs, 2, Ops, 2).Val;
4092 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4093 MVT VT2, SDValue Op1,
4094 SDValue Op2, SDValue Op3) {
4095 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4096 SDValue Ops[] = { Op1, Op2, Op3 };
4097 return getNode(~Opcode, VTs, 2, Ops, 3).Val;
4099 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4100 const SDValue *Ops, unsigned NumOps) {
4101 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4102 return getNode(~Opcode, VTs, 2, Ops, NumOps).Val;
4104 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4105 SDValue Op1, SDValue Op2) {
4106 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4107 SDValue Ops[] = { Op1, Op2 };
4108 return getNode(~Opcode, VTs, 3, Ops, 2).Val;
4110 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4111 SDValue Op1, SDValue Op2,
4113 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4114 SDValue Ops[] = { Op1, Op2, Op3 };
4115 return getNode(~Opcode, VTs, 3, Ops, 3).Val;
4117 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4118 const SDValue *Ops, unsigned NumOps) {
4119 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4120 return getNode(~Opcode, VTs, 3, Ops, NumOps).Val;
4122 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4123 MVT VT2, MVT VT3, MVT VT4,
4124 const SDValue *Ops, unsigned NumOps) {
4125 std::vector<MVT> VTList;
4126 VTList.push_back(VT1);
4127 VTList.push_back(VT2);
4128 VTList.push_back(VT3);
4129 VTList.push_back(VT4);
4130 const MVT *VTs = getNodeValueTypes(VTList);
4131 return getNode(~Opcode, VTs, 4, Ops, NumOps).Val;
4133 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4134 const std::vector<MVT> &ResultTys,
4135 const SDValue *Ops, unsigned NumOps) {
4136 const MVT *VTs = getNodeValueTypes(ResultTys);
4137 return getNode(~Opcode, VTs, ResultTys.size(),
4141 /// getNodeIfExists - Get the specified node if it's already available, or
4142 /// else return NULL.
4143 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4144 const SDValue *Ops, unsigned NumOps) {
4145 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4146 FoldingSetNodeID ID;
4147 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4149 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4156 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4157 /// This can cause recursive merging of nodes in the DAG.
4159 /// This version assumes From has a single result value.
4161 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4162 DAGUpdateListener *UpdateListener) {
4163 SDNode *From = FromN.Val;
4164 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
4165 "Cannot replace with this method!");
4166 assert(From != To.Val && "Cannot replace uses of with self");
4168 while (!From->use_empty()) {
4169 SDNode::use_iterator UI = From->use_begin();
4172 // This node is about to morph, remove its old self from the CSE maps.
4173 RemoveNodeFromCSEMaps(U);
4175 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4176 I != E; ++I, ++operandNum)
4177 if (I->getVal() == From) {
4178 From->removeUser(operandNum, U);
4181 To.Val->addUser(operandNum, U);
4184 // Now that we have modified U, add it back to the CSE maps. If it already
4185 // exists there, recursively merge the results together.
4186 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4187 ReplaceAllUsesWith(U, Existing, UpdateListener);
4188 // U is now dead. Inform the listener if it exists and delete it.
4190 UpdateListener->NodeDeleted(U, Existing);
4191 DeleteNodeNotInCSEMaps(U);
4193 // If the node doesn't already exist, we updated it. Inform a listener if
4196 UpdateListener->NodeUpdated(U);
4201 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4202 /// This can cause recursive merging of nodes in the DAG.
4204 /// This version assumes From/To have matching types and numbers of result
4207 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4208 DAGUpdateListener *UpdateListener) {
4209 assert(From->getVTList().VTs == To->getVTList().VTs &&
4210 From->getNumValues() == To->getNumValues() &&
4211 "Cannot use this version of ReplaceAllUsesWith!");
4213 // Handle the trivial case.
4217 while (!From->use_empty()) {
4218 SDNode::use_iterator UI = From->use_begin();
4221 // This node is about to morph, remove its old self from the CSE maps.
4222 RemoveNodeFromCSEMaps(U);
4224 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4225 I != E; ++I, ++operandNum)
4226 if (I->getVal() == From) {
4227 From->removeUser(operandNum, U);
4229 To->addUser(operandNum, U);
4232 // Now that we have modified U, add it back to the CSE maps. If it already
4233 // exists there, recursively merge the results together.
4234 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4235 ReplaceAllUsesWith(U, Existing, UpdateListener);
4236 // U is now dead. Inform the listener if it exists and delete it.
4238 UpdateListener->NodeDeleted(U, Existing);
4239 DeleteNodeNotInCSEMaps(U);
4241 // If the node doesn't already exist, we updated it. Inform a listener if
4244 UpdateListener->NodeUpdated(U);
4249 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4250 /// This can cause recursive merging of nodes in the DAG.
4252 /// This version can replace From with any result values. To must match the
4253 /// number and types of values returned by From.
4254 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4256 DAGUpdateListener *UpdateListener) {
4257 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4258 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4260 while (!From->use_empty()) {
4261 SDNode::use_iterator UI = From->use_begin();
4264 // This node is about to morph, remove its old self from the CSE maps.
4265 RemoveNodeFromCSEMaps(U);
4267 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4268 I != E; ++I, ++operandNum)
4269 if (I->getVal() == From) {
4270 const SDValue &ToOp = To[I->getSDValue().ResNo];
4271 From->removeUser(operandNum, U);
4274 ToOp.Val->addUser(operandNum, U);
4277 // Now that we have modified U, add it back to the CSE maps. If it already
4278 // exists there, recursively merge the results together.
4279 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4280 ReplaceAllUsesWith(U, Existing, UpdateListener);
4281 // U is now dead. Inform the listener if it exists and delete it.
4283 UpdateListener->NodeDeleted(U, Existing);
4284 DeleteNodeNotInCSEMaps(U);
4286 // If the node doesn't already exist, we updated it. Inform a listener if
4289 UpdateListener->NodeUpdated(U);
4294 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4295 /// uses of other values produced by From.Val alone. The Deleted vector is
4296 /// handled the same way as for ReplaceAllUsesWith.
4297 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4298 DAGUpdateListener *UpdateListener){
4299 // Handle the really simple, really trivial case efficiently.
4300 if (From == To) return;
4302 // Handle the simple, trivial, case efficiently.
4303 if (From.Val->getNumValues() == 1) {
4304 ReplaceAllUsesWith(From, To, UpdateListener);
4308 // Get all of the users of From.Val. We want these in a nice,
4309 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4310 SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
4312 while (!Users.empty()) {
4313 // We know that this user uses some value of From. If it is the right
4314 // value, update it.
4315 SDNode *User = Users.back();
4318 // Scan for an operand that matches From.
4319 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4320 for (; Op != E; ++Op)
4321 if (*Op == From) break;
4323 // If there are no matches, the user must use some other result of From.
4324 if (Op == E) continue;
4326 // Okay, we know this user needs to be updated. Remove its old self
4327 // from the CSE maps.
4328 RemoveNodeFromCSEMaps(User);
4330 // Update all operands that match "From" in case there are multiple uses.
4331 for (; Op != E; ++Op) {
4333 From.Val->removeUser(Op-User->op_begin(), User);
4336 To.Val->addUser(Op-User->op_begin(), User);
4340 // Now that we have modified User, add it back to the CSE maps. If it
4341 // already exists there, recursively merge the results together.
4342 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4344 if (UpdateListener) UpdateListener->NodeUpdated(User);
4345 continue; // Continue on to next user.
4348 // If there was already an existing matching node, use ReplaceAllUsesWith
4349 // to replace the dead one with the existing one. This can cause
4350 // recursive merging of other unrelated nodes down the line.
4351 ReplaceAllUsesWith(User, Existing, UpdateListener);
4353 // User is now dead. Notify a listener if present.
4354 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4355 DeleteNodeNotInCSEMaps(User);
4359 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4360 /// uses of other values produced by From.Val alone. The same value may
4361 /// appear in both the From and To list. The Deleted vector is
4362 /// handled the same way as for ReplaceAllUsesWith.
4363 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4366 DAGUpdateListener *UpdateListener){
4367 // Handle the simple, trivial case efficiently.
4369 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4371 SmallVector<std::pair<SDNode *, unsigned>, 16> Users;
4372 for (unsigned i = 0; i != Num; ++i)
4373 for (SDNode::use_iterator UI = From[i].Val->use_begin(),
4374 E = From[i].Val->use_end(); UI != E; ++UI)
4375 Users.push_back(std::make_pair(*UI, i));
4377 while (!Users.empty()) {
4378 // We know that this user uses some value of From. If it is the right
4379 // value, update it.
4380 SDNode *User = Users.back().first;
4381 unsigned i = Users.back().second;
4384 // Scan for an operand that matches From.
4385 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4386 for (; Op != E; ++Op)
4387 if (*Op == From[i]) break;
4389 // If there are no matches, the user must use some other result of From.
4390 if (Op == E) continue;
4392 // Okay, we know this user needs to be updated. Remove its old self
4393 // from the CSE maps.
4394 RemoveNodeFromCSEMaps(User);
4396 // Update all operands that match "From" in case there are multiple uses.
4397 for (; Op != E; ++Op) {
4398 if (*Op == From[i]) {
4399 From[i].Val->removeUser(Op-User->op_begin(), User);
4402 To[i].Val->addUser(Op-User->op_begin(), User);
4406 // Now that we have modified User, add it back to the CSE maps. If it
4407 // already exists there, recursively merge the results together.
4408 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4410 if (UpdateListener) UpdateListener->NodeUpdated(User);
4411 continue; // Continue on to next user.
4414 // If there was already an existing matching node, use ReplaceAllUsesWith
4415 // to replace the dead one with the existing one. This can cause
4416 // recursive merging of other unrelated nodes down the line.
4417 ReplaceAllUsesWith(User, Existing, UpdateListener);
4419 // User is now dead. Notify a listener if present.
4420 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4421 DeleteNodeNotInCSEMaps(User);
4425 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4426 /// based on their topological order. It returns the maximum id and a vector
4427 /// of the SDNodes* in assigned order by reference.
4428 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4429 unsigned DAGSize = AllNodes.size();
4430 std::vector<SDNode*> Sources;
4432 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4434 unsigned Degree = N->use_size();
4435 // Temporarily use the Node Id as scratch space for the degree count.
4436 N->setNodeId(Degree);
4438 Sources.push_back(N);
4442 TopOrder.reserve(DAGSize);
4444 while (!Sources.empty()) {
4445 SDNode *N = Sources.back();
4447 TopOrder.push_back(N);
4449 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4450 SDNode *P = I->getVal();
4451 unsigned Degree = P->getNodeId();
4453 P->setNodeId(Degree);
4455 Sources.push_back(P);
4464 //===----------------------------------------------------------------------===//
4466 //===----------------------------------------------------------------------===//
4468 // Out-of-line virtual method to give class a home.
4469 void SDNode::ANCHOR() {}
4470 void UnarySDNode::ANCHOR() {}
4471 void BinarySDNode::ANCHOR() {}
4472 void TernarySDNode::ANCHOR() {}
4473 void HandleSDNode::ANCHOR() {}
4474 void ConstantSDNode::ANCHOR() {}
4475 void ConstantFPSDNode::ANCHOR() {}
4476 void GlobalAddressSDNode::ANCHOR() {}
4477 void FrameIndexSDNode::ANCHOR() {}
4478 void JumpTableSDNode::ANCHOR() {}
4479 void ConstantPoolSDNode::ANCHOR() {}
4480 void BasicBlockSDNode::ANCHOR() {}
4481 void SrcValueSDNode::ANCHOR() {}
4482 void MemOperandSDNode::ANCHOR() {}
4483 void RegisterSDNode::ANCHOR() {}
4484 void DbgStopPointSDNode::ANCHOR() {}
4485 void LabelSDNode::ANCHOR() {}
4486 void ExternalSymbolSDNode::ANCHOR() {}
4487 void CondCodeSDNode::ANCHOR() {}
4488 void ARG_FLAGSSDNode::ANCHOR() {}
4489 void VTSDNode::ANCHOR() {}
4490 void MemSDNode::ANCHOR() {}
4491 void LoadSDNode::ANCHOR() {}
4492 void StoreSDNode::ANCHOR() {}
4493 void AtomicSDNode::ANCHOR() {}
4495 HandleSDNode::~HandleSDNode() {
4499 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4501 : SDNode(isa<GlobalVariable>(GA) &&
4502 cast<GlobalVariable>(GA)->isThreadLocal() ?
4504 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4506 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4507 getSDVTList(VT)), Offset(o) {
4508 TheGlobal = const_cast<GlobalValue*>(GA);
4511 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
4512 const Value *srcValue, int SVO,
4513 unsigned alignment, bool vol)
4514 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4515 Flags(encodeMemSDNodeFlags(vol, alignment)) {
4517 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4518 assert(getAlignment() == alignment && "Alignment representation error!");
4519 assert(isVolatile() == vol && "Volatile representation error!");
4522 /// getMemOperand - Return a MachineMemOperand object describing the memory
4523 /// reference performed by this memory reference.
4524 MachineMemOperand MemSDNode::getMemOperand() const {
4526 if (isa<LoadSDNode>(this))
4527 Flags = MachineMemOperand::MOLoad;
4528 else if (isa<StoreSDNode>(this))
4529 Flags = MachineMemOperand::MOStore;
4531 assert(isa<AtomicSDNode>(this) && "Unknown MemSDNode opcode!");
4532 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4535 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4536 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4538 // Check if the memory reference references a frame index
4539 const FrameIndexSDNode *FI =
4540 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4541 if (!getSrcValue() && FI)
4542 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
4543 Flags, 0, Size, getAlignment());
4545 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4546 Size, getAlignment());
4549 /// Profile - Gather unique data for the node.
4551 void SDNode::Profile(FoldingSetNodeID &ID) const {
4552 AddNodeIDNode(ID, this);
4555 /// getValueTypeList - Return a pointer to the specified value type.
4557 const MVT *SDNode::getValueTypeList(MVT VT) {
4558 if (VT.isExtended()) {
4559 static std::set<MVT, MVT::compareRawBits> EVTs;
4560 return &(*EVTs.insert(VT).first);
4562 static MVT VTs[MVT::LAST_VALUETYPE];
4563 VTs[VT.getSimpleVT()] = VT;
4564 return &VTs[VT.getSimpleVT()];
4568 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4569 /// indicated value. This method ignores uses of other values defined by this
4571 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4572 assert(Value < getNumValues() && "Bad value!");
4574 // TODO: Only iterate over uses of a given value of the node
4575 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4576 if (UI.getUse().getSDValue().ResNo == Value) {
4583 // Found exactly the right number of uses?
4588 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4589 /// value. This method ignores uses of other values defined by this operation.
4590 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4591 assert(Value < getNumValues() && "Bad value!");
4593 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
4594 if (UI.getUse().getSDValue().ResNo == Value)
4601 /// isOnlyUserOf - Return true if this node is the only use of N.
4603 bool SDNode::isOnlyUserOf(SDNode *N) const {
4605 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4616 /// isOperand - Return true if this node is an operand of N.
4618 bool SDValue::isOperandOf(SDNode *N) const {
4619 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4620 if (*this == N->getOperand(i))
4625 bool SDNode::isOperandOf(SDNode *N) const {
4626 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4627 if (this == N->OperandList[i].getVal())
4632 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4633 /// be a chain) reaches the specified operand without crossing any
4634 /// side-effecting instructions. In practice, this looks through token
4635 /// factors and non-volatile loads. In order to remain efficient, this only
4636 /// looks a couple of nodes in, it does not do an exhaustive search.
4637 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
4638 unsigned Depth) const {
4639 if (*this == Dest) return true;
4641 // Don't search too deeply, we just want to be able to see through
4642 // TokenFactor's etc.
4643 if (Depth == 0) return false;
4645 // If this is a token factor, all inputs to the TF happen in parallel. If any
4646 // of the operands of the TF reach dest, then we can do the xform.
4647 if (getOpcode() == ISD::TokenFactor) {
4648 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4649 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4654 // Loads don't have side effects, look through them.
4655 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4656 if (!Ld->isVolatile())
4657 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4663 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4664 SmallPtrSet<SDNode *, 32> &Visited) {
4665 if (found || !Visited.insert(N))
4668 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4669 SDNode *Op = N->getOperand(i).Val;
4674 findPredecessor(Op, P, found, Visited);
4678 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4679 /// is either an operand of N or it can be reached by recursively traversing
4680 /// up the operands.
4681 /// NOTE: this is an expensive method. Use it carefully.
4682 bool SDNode::isPredecessorOf(SDNode *N) const {
4683 SmallPtrSet<SDNode *, 32> Visited;
4685 findPredecessor(N, this, found, Visited);
4689 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4690 assert(Num < NumOperands && "Invalid child # of SDNode!");
4691 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4694 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4695 switch (getOpcode()) {
4697 if (getOpcode() < ISD::BUILTIN_OP_END)
4698 return "<<Unknown DAG Node>>";
4699 if (isMachineOpcode()) {
4701 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4702 if (getMachineOpcode() < TII->getNumOpcodes())
4703 return TII->get(getMachineOpcode()).getName();
4704 return "<<Unknown Machine Node>>";
4707 TargetLowering &TLI = G->getTargetLoweringInfo();
4708 const char *Name = TLI.getTargetNodeName(getOpcode());
4709 if (Name) return Name;
4710 return "<<Unknown Target Node>>";
4712 return "<<Unknown Node>>";
4715 case ISD::DELETED_NODE:
4716 return "<<Deleted Node!>>";
4718 case ISD::PREFETCH: return "Prefetch";
4719 case ISD::MEMBARRIER: return "MemBarrier";
4720 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4721 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4722 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4723 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4724 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4725 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4726 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4727 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4728 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4729 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4730 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4731 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4732 case ISD::PCMARKER: return "PCMarker";
4733 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4734 case ISD::SRCVALUE: return "SrcValue";
4735 case ISD::MEMOPERAND: return "MemOperand";
4736 case ISD::EntryToken: return "EntryToken";
4737 case ISD::TokenFactor: return "TokenFactor";
4738 case ISD::AssertSext: return "AssertSext";
4739 case ISD::AssertZext: return "AssertZext";
4741 case ISD::BasicBlock: return "BasicBlock";
4742 case ISD::ARG_FLAGS: return "ArgFlags";
4743 case ISD::VALUETYPE: return "ValueType";
4744 case ISD::Register: return "Register";
4746 case ISD::Constant: return "Constant";
4747 case ISD::ConstantFP: return "ConstantFP";
4748 case ISD::GlobalAddress: return "GlobalAddress";
4749 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4750 case ISD::FrameIndex: return "FrameIndex";
4751 case ISD::JumpTable: return "JumpTable";
4752 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4753 case ISD::RETURNADDR: return "RETURNADDR";
4754 case ISD::FRAMEADDR: return "FRAMEADDR";
4755 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4756 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4757 case ISD::EHSELECTION: return "EHSELECTION";
4758 case ISD::EH_RETURN: return "EH_RETURN";
4759 case ISD::ConstantPool: return "ConstantPool";
4760 case ISD::ExternalSymbol: return "ExternalSymbol";
4761 case ISD::INTRINSIC_WO_CHAIN: {
4762 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4763 return Intrinsic::getName((Intrinsic::ID)IID);
4765 case ISD::INTRINSIC_VOID:
4766 case ISD::INTRINSIC_W_CHAIN: {
4767 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4768 return Intrinsic::getName((Intrinsic::ID)IID);
4771 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4772 case ISD::TargetConstant: return "TargetConstant";
4773 case ISD::TargetConstantFP:return "TargetConstantFP";
4774 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4775 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4776 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4777 case ISD::TargetJumpTable: return "TargetJumpTable";
4778 case ISD::TargetConstantPool: return "TargetConstantPool";
4779 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4781 case ISD::CopyToReg: return "CopyToReg";
4782 case ISD::CopyFromReg: return "CopyFromReg";
4783 case ISD::UNDEF: return "undef";
4784 case ISD::MERGE_VALUES: return "merge_values";
4785 case ISD::INLINEASM: return "inlineasm";
4786 case ISD::DBG_LABEL: return "dbg_label";
4787 case ISD::EH_LABEL: return "eh_label";
4788 case ISD::DECLARE: return "declare";
4789 case ISD::HANDLENODE: return "handlenode";
4790 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4791 case ISD::CALL: return "call";
4794 case ISD::FABS: return "fabs";
4795 case ISD::FNEG: return "fneg";
4796 case ISD::FSQRT: return "fsqrt";
4797 case ISD::FSIN: return "fsin";
4798 case ISD::FCOS: return "fcos";
4799 case ISD::FPOWI: return "fpowi";
4800 case ISD::FPOW: return "fpow";
4801 case ISD::FTRUNC: return "ftrunc";
4802 case ISD::FFLOOR: return "ffloor";
4803 case ISD::FCEIL: return "fceil";
4804 case ISD::FRINT: return "frint";
4805 case ISD::FNEARBYINT: return "fnearbyint";
4808 case ISD::ADD: return "add";
4809 case ISD::SUB: return "sub";
4810 case ISD::MUL: return "mul";
4811 case ISD::MULHU: return "mulhu";
4812 case ISD::MULHS: return "mulhs";
4813 case ISD::SDIV: return "sdiv";
4814 case ISD::UDIV: return "udiv";
4815 case ISD::SREM: return "srem";
4816 case ISD::UREM: return "urem";
4817 case ISD::SMUL_LOHI: return "smul_lohi";
4818 case ISD::UMUL_LOHI: return "umul_lohi";
4819 case ISD::SDIVREM: return "sdivrem";
4820 case ISD::UDIVREM: return "divrem";
4821 case ISD::AND: return "and";
4822 case ISD::OR: return "or";
4823 case ISD::XOR: return "xor";
4824 case ISD::SHL: return "shl";
4825 case ISD::SRA: return "sra";
4826 case ISD::SRL: return "srl";
4827 case ISD::ROTL: return "rotl";
4828 case ISD::ROTR: return "rotr";
4829 case ISD::FADD: return "fadd";
4830 case ISD::FSUB: return "fsub";
4831 case ISD::FMUL: return "fmul";
4832 case ISD::FDIV: return "fdiv";
4833 case ISD::FREM: return "frem";
4834 case ISD::FCOPYSIGN: return "fcopysign";
4835 case ISD::FGETSIGN: return "fgetsign";
4837 case ISD::SETCC: return "setcc";
4838 case ISD::VSETCC: return "vsetcc";
4839 case ISD::SELECT: return "select";
4840 case ISD::SELECT_CC: return "select_cc";
4841 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4842 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4843 case ISD::CONCAT_VECTORS: return "concat_vectors";
4844 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4845 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4846 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4847 case ISD::CARRY_FALSE: return "carry_false";
4848 case ISD::ADDC: return "addc";
4849 case ISD::ADDE: return "adde";
4850 case ISD::SUBC: return "subc";
4851 case ISD::SUBE: return "sube";
4852 case ISD::SHL_PARTS: return "shl_parts";
4853 case ISD::SRA_PARTS: return "sra_parts";
4854 case ISD::SRL_PARTS: return "srl_parts";
4856 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4857 case ISD::INSERT_SUBREG: return "insert_subreg";
4859 // Conversion operators.
4860 case ISD::SIGN_EXTEND: return "sign_extend";
4861 case ISD::ZERO_EXTEND: return "zero_extend";
4862 case ISD::ANY_EXTEND: return "any_extend";
4863 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4864 case ISD::TRUNCATE: return "truncate";
4865 case ISD::FP_ROUND: return "fp_round";
4866 case ISD::FLT_ROUNDS_: return "flt_rounds";
4867 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4868 case ISD::FP_EXTEND: return "fp_extend";
4870 case ISD::SINT_TO_FP: return "sint_to_fp";
4871 case ISD::UINT_TO_FP: return "uint_to_fp";
4872 case ISD::FP_TO_SINT: return "fp_to_sint";
4873 case ISD::FP_TO_UINT: return "fp_to_uint";
4874 case ISD::BIT_CONVERT: return "bit_convert";
4876 // Control flow instructions
4877 case ISD::BR: return "br";
4878 case ISD::BRIND: return "brind";
4879 case ISD::BR_JT: return "br_jt";
4880 case ISD::BRCOND: return "brcond";
4881 case ISD::BR_CC: return "br_cc";
4882 case ISD::RET: return "ret";
4883 case ISD::CALLSEQ_START: return "callseq_start";
4884 case ISD::CALLSEQ_END: return "callseq_end";
4887 case ISD::LOAD: return "load";
4888 case ISD::STORE: return "store";
4889 case ISD::VAARG: return "vaarg";
4890 case ISD::VACOPY: return "vacopy";
4891 case ISD::VAEND: return "vaend";
4892 case ISD::VASTART: return "vastart";
4893 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4894 case ISD::EXTRACT_ELEMENT: return "extract_element";
4895 case ISD::BUILD_PAIR: return "build_pair";
4896 case ISD::STACKSAVE: return "stacksave";
4897 case ISD::STACKRESTORE: return "stackrestore";
4898 case ISD::TRAP: return "trap";
4901 case ISD::BSWAP: return "bswap";
4902 case ISD::CTPOP: return "ctpop";
4903 case ISD::CTTZ: return "cttz";
4904 case ISD::CTLZ: return "ctlz";
4907 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4908 case ISD::DEBUG_LOC: return "debug_loc";
4911 case ISD::TRAMPOLINE: return "trampoline";
4914 switch (cast<CondCodeSDNode>(this)->get()) {
4915 default: assert(0 && "Unknown setcc condition!");
4916 case ISD::SETOEQ: return "setoeq";
4917 case ISD::SETOGT: return "setogt";
4918 case ISD::SETOGE: return "setoge";
4919 case ISD::SETOLT: return "setolt";
4920 case ISD::SETOLE: return "setole";
4921 case ISD::SETONE: return "setone";
4923 case ISD::SETO: return "seto";
4924 case ISD::SETUO: return "setuo";
4925 case ISD::SETUEQ: return "setue";
4926 case ISD::SETUGT: return "setugt";
4927 case ISD::SETUGE: return "setuge";
4928 case ISD::SETULT: return "setult";
4929 case ISD::SETULE: return "setule";
4930 case ISD::SETUNE: return "setune";
4932 case ISD::SETEQ: return "seteq";
4933 case ISD::SETGT: return "setgt";
4934 case ISD::SETGE: return "setge";
4935 case ISD::SETLT: return "setlt";
4936 case ISD::SETLE: return "setle";
4937 case ISD::SETNE: return "setne";
4942 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4951 return "<post-inc>";
4953 return "<post-dec>";
4957 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4958 std::string S = "< ";
4972 if (getByValAlign())
4973 S += "byval-align:" + utostr(getByValAlign()) + " ";
4975 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4977 S += "byval-size:" + utostr(getByValSize()) + " ";
4981 void SDNode::dump() const { dump(0); }
4982 void SDNode::dump(const SelectionDAG *G) const {
4987 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
4988 OS << (void*)this << ": ";
4990 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4992 if (getValueType(i) == MVT::Other)
4995 OS << getValueType(i).getMVTString();
4997 OS << " = " << getOperationName(G);
5000 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5002 OS << (void*)getOperand(i).Val;
5003 if (unsigned RN = getOperand(i).ResNo)
5007 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5008 SDNode *Mask = getOperand(2).Val;
5010 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
5012 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
5015 OS << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
5020 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5021 OS << '<' << CSDN->getAPIntValue() << '>';
5022 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5023 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5024 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5025 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5026 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5029 CSDN->getValueAPF().convertToAPInt().dump();
5032 } else if (const GlobalAddressSDNode *GADN =
5033 dyn_cast<GlobalAddressSDNode>(this)) {
5034 int offset = GADN->getOffset();
5036 WriteAsOperand(OS, GADN->getGlobal());
5039 OS << " + " << offset;
5041 OS << " " << offset;
5042 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5043 OS << "<" << FIDN->getIndex() << ">";
5044 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5045 OS << "<" << JTDN->getIndex() << ">";
5046 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5047 int offset = CP->getOffset();
5048 if (CP->isMachineConstantPoolEntry())
5049 OS << "<" << *CP->getMachineCPVal() << ">";
5051 OS << "<" << *CP->getConstVal() << ">";
5053 OS << " + " << offset;
5055 OS << " " << offset;
5056 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5058 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5060 OS << LBB->getName() << " ";
5061 OS << (const void*)BBDN->getBasicBlock() << ">";
5062 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5063 if (G && R->getReg() &&
5064 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5065 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5067 OS << " #" << R->getReg();
5069 } else if (const ExternalSymbolSDNode *ES =
5070 dyn_cast<ExternalSymbolSDNode>(this)) {
5071 OS << "'" << ES->getSymbol() << "'";
5072 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5074 OS << "<" << M->getValue() << ">";
5077 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5078 if (M->MO.getValue())
5079 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5081 OS << "<null:" << M->MO.getOffset() << ">";
5082 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5083 OS << N->getArgFlags().getArgFlagsString();
5084 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5085 OS << ":" << N->getVT().getMVTString();
5087 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5088 const Value *SrcValue = LD->getSrcValue();
5089 int SrcOffset = LD->getSrcValueOffset();
5095 OS << ":" << SrcOffset << ">";
5098 switch (LD->getExtensionType()) {
5099 default: doExt = false; break;
5100 case ISD::EXTLOAD: OS << " <anyext "; break;
5101 case ISD::SEXTLOAD: OS << " <sext "; break;
5102 case ISD::ZEXTLOAD: OS << " <zext "; break;
5105 OS << LD->getMemoryVT().getMVTString() << ">";
5107 const char *AM = getIndexedModeName(LD->getAddressingMode());
5110 if (LD->isVolatile())
5111 OS << " <volatile>";
5112 OS << " alignment=" << LD->getAlignment();
5113 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5114 const Value *SrcValue = ST->getSrcValue();
5115 int SrcOffset = ST->getSrcValueOffset();
5121 OS << ":" << SrcOffset << ">";
5123 if (ST->isTruncatingStore())
5124 OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
5126 const char *AM = getIndexedModeName(ST->getAddressingMode());
5129 if (ST->isVolatile())
5130 OS << " <volatile>";
5131 OS << " alignment=" << ST->getAlignment();
5132 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5133 const Value *SrcValue = AT->getSrcValue();
5134 int SrcOffset = AT->getSrcValueOffset();
5140 OS << ":" << SrcOffset << ">";
5141 if (AT->isVolatile())
5142 OS << " <volatile>";
5143 OS << " alignment=" << AT->getAlignment();
5147 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5148 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5149 if (N->getOperand(i).Val->hasOneUse())
5150 DumpNodes(N->getOperand(i).Val, indent+2, G);
5152 cerr << "\n" << std::string(indent+2, ' ')
5153 << (void*)N->getOperand(i).Val << ": <multiple use>";
5156 cerr << "\n" << std::string(indent, ' ');
5160 void SelectionDAG::dump() const {
5161 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5163 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5165 const SDNode *N = I;
5166 if (!N->hasOneUse() && N != getRoot().Val)
5167 DumpNodes(N, 2, this);
5170 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
5175 const Type *ConstantPoolSDNode::getType() const {
5176 if (isMachineConstantPoolEntry())
5177 return Val.MachineCPVal->getType();
5178 return Val.ConstVal->getType();