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/Support/MathExtras.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/StringExtras.h"
42 /// makeVTList - Return an instance of the SDVTList struct initialized with the
43 /// specified members.
44 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
45 SDVTList Res = {VTs, NumVTs};
49 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
50 switch (VT.getSimpleVT()) {
51 default: assert(0 && "Unknown FP format");
52 case MVT::f32: return &APFloat::IEEEsingle;
53 case MVT::f64: return &APFloat::IEEEdouble;
54 case MVT::f80: return &APFloat::x87DoubleExtended;
55 case MVT::f128: return &APFloat::IEEEquad;
56 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
60 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
62 //===----------------------------------------------------------------------===//
63 // ConstantFPSDNode Class
64 //===----------------------------------------------------------------------===//
66 /// isExactlyValue - We don't rely on operator== working on double values, as
67 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
68 /// As such, this method can be used to do an exact bit-for-bit comparison of
69 /// two floating point values.
70 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
71 return Value.bitwiseIsEqual(V);
74 bool ConstantFPSDNode::isValueValidForType(MVT VT,
76 assert(VT.isFloatingPoint() && "Can only convert between FP types");
78 // PPC long double cannot be converted to any other type.
79 if (VT == MVT::ppcf128 ||
80 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
85 return Val2.convert(*MVTToAPFloatSemantics(VT),
86 APFloat::rmNearestTiesToEven) == APFloat::opOK;
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 /// isBuildVectorAllOnes - Return true if the specified node is a
94 /// BUILD_VECTOR where all of the elements are ~0 or undef.
95 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
96 // Look through a bit convert.
97 if (N->getOpcode() == ISD::BIT_CONVERT)
98 N = N->getOperand(0).Val;
100 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
102 unsigned i = 0, e = N->getNumOperands();
104 // Skip over all of the undef values.
105 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108 // Do not accept an all-undef vector.
109 if (i == e) return false;
111 // Do not accept build_vectors that aren't all constants or which have non-~0
113 SDOperand NotZero = N->getOperand(i);
114 if (isa<ConstantSDNode>(NotZero)) {
115 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
117 } else if (isa<ConstantFPSDNode>(NotZero)) {
118 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
119 convertToAPInt().isAllOnesValue())
124 // Okay, we have at least one ~0 value, check to see if the rest match or are
126 for (++i; i != e; ++i)
127 if (N->getOperand(i) != NotZero &&
128 N->getOperand(i).getOpcode() != ISD::UNDEF)
134 /// isBuildVectorAllZeros - Return true if the specified node is a
135 /// BUILD_VECTOR where all of the elements are 0 or undef.
136 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
137 // Look through a bit convert.
138 if (N->getOpcode() == ISD::BIT_CONVERT)
139 N = N->getOperand(0).Val;
141 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
143 unsigned i = 0, e = N->getNumOperands();
145 // Skip over all of the undef values.
146 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149 // Do not accept an all-undef vector.
150 if (i == e) return false;
152 // Do not accept build_vectors that aren't all constants or which have non-~0
154 SDOperand Zero = N->getOperand(i);
155 if (isa<ConstantSDNode>(Zero)) {
156 if (!cast<ConstantSDNode>(Zero)->isNullValue())
158 } else if (isa<ConstantFPSDNode>(Zero)) {
159 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
164 // Okay, we have at least one ~0 value, check to see if the rest match or are
166 for (++i; i != e; ++i)
167 if (N->getOperand(i) != Zero &&
168 N->getOperand(i).getOpcode() != ISD::UNDEF)
173 /// isScalarToVector - Return true if the specified node is a
174 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
175 /// element is not an undef.
176 bool ISD::isScalarToVector(const SDNode *N) {
177 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
180 if (N->getOpcode() != ISD::BUILD_VECTOR)
182 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
184 unsigned NumElems = N->getNumOperands();
185 for (unsigned i = 1; i < NumElems; ++i) {
186 SDOperand V = N->getOperand(i);
187 if (V.getOpcode() != ISD::UNDEF)
194 /// isDebugLabel - Return true if the specified node represents a debug
195 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
196 bool ISD::isDebugLabel(const SDNode *N) {
198 if (N->getOpcode() == ISD::DBG_LABEL)
200 if (N->isTargetOpcode() &&
201 N->getTargetOpcode() == TargetInstrInfo::DBG_LABEL)
206 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
207 /// when given the operation for (X op Y).
208 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
209 // To perform this operation, we just need to swap the L and G bits of the
211 unsigned OldL = (Operation >> 2) & 1;
212 unsigned OldG = (Operation >> 1) & 1;
213 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
214 (OldL << 1) | // New G bit
215 (OldG << 2)); // New L bit.
218 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
219 /// 'op' is a valid SetCC operation.
220 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
221 unsigned Operation = Op;
223 Operation ^= 7; // Flip L, G, E bits, but not U.
225 Operation ^= 15; // Flip all of the condition bits.
226 if (Operation > ISD::SETTRUE2)
227 Operation &= ~8; // Don't let N and U bits get set.
228 return ISD::CondCode(Operation);
232 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
233 /// signed operation and 2 if the result is an unsigned comparison. Return zero
234 /// if the operation does not depend on the sign of the input (setne and seteq).
235 static int isSignedOp(ISD::CondCode Opcode) {
237 default: assert(0 && "Illegal integer setcc operation!");
239 case ISD::SETNE: return 0;
243 case ISD::SETGE: return 1;
247 case ISD::SETUGE: return 2;
251 /// getSetCCOrOperation - Return the result of a logical OR between different
252 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
253 /// returns SETCC_INVALID if it is not possible to represent the resultant
255 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
257 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
258 // Cannot fold a signed integer setcc with an unsigned integer setcc.
259 return ISD::SETCC_INVALID;
261 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
263 // If the N and U bits get set then the resultant comparison DOES suddenly
264 // care about orderedness, and is true when ordered.
265 if (Op > ISD::SETTRUE2)
266 Op &= ~16; // Clear the U bit if the N bit is set.
268 // Canonicalize illegal integer setcc's.
269 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
272 return ISD::CondCode(Op);
275 /// getSetCCAndOperation - Return the result of a logical AND between different
276 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
277 /// function returns zero if it is not possible to represent the resultant
279 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
281 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
282 // Cannot fold a signed setcc with an unsigned setcc.
283 return ISD::SETCC_INVALID;
285 // Combine all of the condition bits.
286 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
288 // Canonicalize illegal integer setcc's.
292 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
293 case ISD::SETOEQ: // SETEQ & SETU[LG]E
294 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
295 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
296 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
303 const TargetMachine &SelectionDAG::getTarget() const {
304 return TLI.getTargetMachine();
307 //===----------------------------------------------------------------------===//
308 // SDNode Profile Support
309 //===----------------------------------------------------------------------===//
311 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
313 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
317 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
318 /// solely with their pointer.
319 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
320 ID.AddPointer(VTList.VTs);
323 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
325 static void AddNodeIDOperands(FoldingSetNodeID &ID,
326 SDOperandPtr Ops, unsigned NumOps) {
327 for (; NumOps; --NumOps, ++Ops) {
328 ID.AddPointer(Ops->Val);
329 ID.AddInteger(Ops->ResNo);
333 static void AddNodeIDNode(FoldingSetNodeID &ID,
334 unsigned short OpC, SDVTList VTList,
335 SDOperandPtr OpList, unsigned N) {
336 AddNodeIDOpcode(ID, OpC);
337 AddNodeIDValueTypes(ID, VTList);
338 AddNodeIDOperands(ID, OpList, N);
342 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
344 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
345 AddNodeIDOpcode(ID, N->getOpcode());
346 // Add the return value info.
347 AddNodeIDValueTypes(ID, N->getVTList());
348 // Add the operand info.
349 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
351 // Handle SDNode leafs with special info.
352 switch (N->getOpcode()) {
353 default: break; // Normal nodes don't need extra info.
355 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
357 case ISD::TargetConstant:
359 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
361 case ISD::TargetConstantFP:
362 case ISD::ConstantFP: {
363 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
366 case ISD::TargetGlobalAddress:
367 case ISD::GlobalAddress:
368 case ISD::TargetGlobalTLSAddress:
369 case ISD::GlobalTLSAddress: {
370 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
371 ID.AddPointer(GA->getGlobal());
372 ID.AddInteger(GA->getOffset());
375 case ISD::BasicBlock:
376 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
379 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
381 case ISD::DBG_STOPPOINT: {
382 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
383 ID.AddInteger(DSP->getLine());
384 ID.AddInteger(DSP->getColumn());
385 ID.AddPointer(DSP->getCompileUnit());
390 ID.AddInteger(cast<LabelSDNode>(N)->getLabelID());
393 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
395 case ISD::MEMOPERAND: {
396 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
397 ID.AddPointer(MO.getValue());
398 ID.AddInteger(MO.getFlags());
399 ID.AddInteger(MO.getOffset());
400 ID.AddInteger(MO.getSize());
401 ID.AddInteger(MO.getAlignment());
404 case ISD::FrameIndex:
405 case ISD::TargetFrameIndex:
406 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
409 case ISD::TargetJumpTable:
410 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
412 case ISD::ConstantPool:
413 case ISD::TargetConstantPool: {
414 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
415 ID.AddInteger(CP->getAlignment());
416 ID.AddInteger(CP->getOffset());
417 if (CP->isMachineConstantPoolEntry())
418 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
420 ID.AddPointer(CP->getConstVal());
424 LoadSDNode *LD = cast<LoadSDNode>(N);
425 ID.AddInteger(LD->getAddressingMode());
426 ID.AddInteger(LD->getExtensionType());
427 ID.AddInteger(LD->getMemoryVT().getRawBits());
428 ID.AddInteger(LD->getAlignment());
429 ID.AddInteger(LD->isVolatile());
433 StoreSDNode *ST = cast<StoreSDNode>(N);
434 ID.AddInteger(ST->getAddressingMode());
435 ID.AddInteger(ST->isTruncatingStore());
436 ID.AddInteger(ST->getMemoryVT().getRawBits());
437 ID.AddInteger(ST->getAlignment());
438 ID.AddInteger(ST->isVolatile());
441 case ISD::ATOMIC_CMP_SWAP:
442 case ISD::ATOMIC_LOAD_ADD:
443 case ISD::ATOMIC_SWAP:
444 case ISD::ATOMIC_LOAD_SUB:
445 case ISD::ATOMIC_LOAD_AND:
446 case ISD::ATOMIC_LOAD_OR:
447 case ISD::ATOMIC_LOAD_XOR:
448 case ISD::ATOMIC_LOAD_NAND:
449 case ISD::ATOMIC_LOAD_MIN:
450 case ISD::ATOMIC_LOAD_MAX:
451 case ISD::ATOMIC_LOAD_UMIN:
452 case ISD::ATOMIC_LOAD_UMAX: {
453 AtomicSDNode *AT = cast<AtomicSDNode>(N);
454 ID.AddInteger(AT->getAlignment());
455 ID.AddInteger(AT->isVolatile());
458 } // end switch (N->getOpcode())
461 //===----------------------------------------------------------------------===//
462 // SelectionDAG Class
463 //===----------------------------------------------------------------------===//
465 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
467 void SelectionDAG::RemoveDeadNodes() {
468 // Create a dummy node (which is not added to allnodes), that adds a reference
469 // to the root node, preventing it from being deleted.
470 HandleSDNode Dummy(getRoot());
472 SmallVector<SDNode*, 128> DeadNodes;
474 // Add all obviously-dead nodes to the DeadNodes worklist.
475 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
477 DeadNodes.push_back(I);
479 // Process the worklist, deleting the nodes and adding their uses to the
481 while (!DeadNodes.empty()) {
482 SDNode *N = DeadNodes.back();
483 DeadNodes.pop_back();
485 // Take the node out of the appropriate CSE map.
486 RemoveNodeFromCSEMaps(N);
488 // Next, brutally remove the operand list. This is safe to do, as there are
489 // no cycles in the graph.
490 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
491 SDNode *Operand = I->getVal();
492 Operand->removeUser(std::distance(N->op_begin(), I), N);
494 // Now that we removed this operand, see if there are no uses of it left.
495 if (Operand->use_empty())
496 DeadNodes.push_back(Operand);
498 if (N->OperandsNeedDelete) {
499 delete[] N->OperandList;
504 // Finally, remove N itself.
508 // If the root changed (e.g. it was a dead load, update the root).
509 setRoot(Dummy.getValue());
512 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
513 SmallVector<SDNode*, 16> DeadNodes;
514 DeadNodes.push_back(N);
516 // Process the worklist, deleting the nodes and adding their uses to the
518 while (!DeadNodes.empty()) {
519 SDNode *N = DeadNodes.back();
520 DeadNodes.pop_back();
523 UpdateListener->NodeDeleted(N, 0);
525 // Take the node out of the appropriate CSE map.
526 RemoveNodeFromCSEMaps(N);
528 // Next, brutally remove the operand list. This is safe to do, as there are
529 // no cycles in the graph.
531 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
532 SDNode *Operand = I->getVal();
533 Operand->removeUser(op_num, N);
535 // Now that we removed this operand, see if there are no uses of it left.
536 if (Operand->use_empty())
537 DeadNodes.push_back(Operand);
541 if (N->OperandsNeedDelete) {
542 delete[] N->OperandList;
547 // Finally, remove N itself.
552 void SelectionDAG::DeleteNode(SDNode *N) {
553 assert(N->use_empty() && "Cannot delete a node that is not dead!");
555 // First take this out of the appropriate CSE map.
556 RemoveNodeFromCSEMaps(N);
558 // Finally, remove uses due to operands of this node, remove from the
559 // AllNodes list, and delete the node.
560 DeleteNodeNotInCSEMaps(N);
563 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
565 // Remove it from the AllNodes list.
568 // Drop all of the operands and decrement used nodes use counts.
569 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
570 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
571 if (N->OperandsNeedDelete) {
572 delete[] N->OperandList;
580 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
581 /// correspond to it. This is useful when we're about to delete or repurpose
582 /// the node. We don't want future request for structurally identical nodes
583 /// to return N anymore.
584 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
586 switch (N->getOpcode()) {
587 case ISD::HANDLENODE: return; // noop.
589 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
590 "Cond code doesn't exist!");
591 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
592 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
594 case ISD::ExternalSymbol:
595 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
597 case ISD::TargetExternalSymbol:
599 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
601 case ISD::VALUETYPE: {
602 MVT VT = cast<VTSDNode>(N)->getVT();
603 if (VT.isExtended()) {
604 Erased = ExtendedValueTypeNodes.erase(VT);
606 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
607 ValueTypeNodes[VT.getSimpleVT()] = 0;
612 // Remove it from the CSE Map.
613 Erased = CSEMap.RemoveNode(N);
617 // Verify that the node was actually in one of the CSE maps, unless it has a
618 // flag result (which cannot be CSE'd) or is one of the special cases that are
619 // not subject to CSE.
620 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
621 !N->isTargetOpcode()) {
624 assert(0 && "Node is not in map!");
629 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
630 /// has been taken out and modified in some way. If the specified node already
631 /// exists in the CSE maps, do not modify the maps, but return the existing node
632 /// instead. If it doesn't exist, add it and return null.
634 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
635 assert(N->getNumOperands() && "This is a leaf node!");
636 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
637 return 0; // Never add these nodes.
639 // Check that remaining values produced are not flags.
640 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
641 if (N->getValueType(i) == MVT::Flag)
642 return 0; // Never CSE anything that produces a flag.
644 SDNode *New = CSEMap.GetOrInsertNode(N);
645 if (New != N) return New; // Node already existed.
649 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
650 /// were replaced with those specified. If this node is never memoized,
651 /// return null, otherwise return a pointer to the slot it would take. If a
652 /// node already exists with these operands, the slot will be non-null.
653 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
655 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
656 return 0; // Never add these nodes.
658 // Check that remaining values produced are not flags.
659 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
660 if (N->getValueType(i) == MVT::Flag)
661 return 0; // Never CSE anything that produces a flag.
663 SDOperand Ops[] = { Op };
665 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
666 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
669 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
670 /// were replaced with those specified. If this node is never memoized,
671 /// return null, otherwise return a pointer to the slot it would take. If a
672 /// node already exists with these operands, the slot will be non-null.
673 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
674 SDOperand Op1, SDOperand Op2,
676 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
677 return 0; // Never add these nodes.
679 // Check that remaining values produced are not flags.
680 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
681 if (N->getValueType(i) == MVT::Flag)
682 return 0; // Never CSE anything that produces a flag.
684 SDOperand Ops[] = { Op1, Op2 };
686 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
687 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
691 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
692 /// were replaced with those specified. If this node is never memoized,
693 /// return null, otherwise return a pointer to the slot it would take. If a
694 /// node already exists with these operands, the slot will be non-null.
695 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
696 SDOperandPtr Ops,unsigned NumOps,
698 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
699 return 0; // Never add these nodes.
701 // Check that remaining values produced are not flags.
702 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
703 if (N->getValueType(i) == MVT::Flag)
704 return 0; // Never CSE anything that produces a flag.
707 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
709 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
710 ID.AddInteger(LD->getAddressingMode());
711 ID.AddInteger(LD->getExtensionType());
712 ID.AddInteger(LD->getMemoryVT().getRawBits());
713 ID.AddInteger(LD->getAlignment());
714 ID.AddInteger(LD->isVolatile());
715 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
716 ID.AddInteger(ST->getAddressingMode());
717 ID.AddInteger(ST->isTruncatingStore());
718 ID.AddInteger(ST->getMemoryVT().getRawBits());
719 ID.AddInteger(ST->getAlignment());
720 ID.AddInteger(ST->isVolatile());
723 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
727 SelectionDAG::~SelectionDAG() {
728 while (!AllNodes.empty()) {
729 SDNode *N = AllNodes.begin();
730 N->SetNextInBucket(0);
731 if (N->OperandsNeedDelete) {
732 delete [] N->OperandList;
736 AllNodes.pop_front();
740 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
741 if (Op.getValueType() == VT) return Op;
742 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
744 return getNode(ISD::AND, Op.getValueType(), Op,
745 getConstant(Imm, Op.getValueType()));
748 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
749 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
750 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
753 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
754 assert(VT.isInteger() && "Cannot create FP integer constant!");
756 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
757 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
758 "APInt size does not match type size!");
760 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
762 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
766 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
768 return SDOperand(N, 0);
770 N = new ConstantSDNode(isT, Val, EltVT);
771 CSEMap.InsertNode(N, IP);
772 AllNodes.push_back(N);
775 SDOperand Result(N, 0);
777 SmallVector<SDOperand, 8> Ops;
778 Ops.assign(VT.getVectorNumElements(), Result);
779 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
784 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
785 return getConstant(Val, TLI.getPointerTy(), isTarget);
789 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
790 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
793 VT.isVector() ? VT.getVectorElementType() : VT;
795 // Do the map lookup using the actual bit pattern for the floating point
796 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
797 // we don't have issues with SNANs.
798 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
800 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
804 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
806 return SDOperand(N, 0);
808 N = new ConstantFPSDNode(isTarget, V, EltVT);
809 CSEMap.InsertNode(N, IP);
810 AllNodes.push_back(N);
813 SDOperand Result(N, 0);
815 SmallVector<SDOperand, 8> Ops;
816 Ops.assign(VT.getVectorNumElements(), Result);
817 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
822 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
824 VT.isVector() ? VT.getVectorElementType() : VT;
826 return getConstantFP(APFloat((float)Val), VT, isTarget);
828 return getConstantFP(APFloat(Val), VT, isTarget);
831 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
836 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
838 // If GV is an alias then use the aliasee for determining thread-localness.
839 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
840 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
843 if (GVar && GVar->isThreadLocal())
844 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
846 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
849 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
851 ID.AddInteger(Offset);
853 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
854 return SDOperand(E, 0);
855 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
856 CSEMap.InsertNode(N, IP);
857 AllNodes.push_back(N);
858 return SDOperand(N, 0);
861 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
862 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
864 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
867 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
868 return SDOperand(E, 0);
869 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
870 CSEMap.InsertNode(N, IP);
871 AllNodes.push_back(N);
872 return SDOperand(N, 0);
875 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
876 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
878 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
881 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
882 return SDOperand(E, 0);
883 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
884 CSEMap.InsertNode(N, IP);
885 AllNodes.push_back(N);
886 return SDOperand(N, 0);
889 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
890 unsigned Alignment, int Offset,
892 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
894 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
895 ID.AddInteger(Alignment);
896 ID.AddInteger(Offset);
899 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
900 return SDOperand(E, 0);
901 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
902 CSEMap.InsertNode(N, IP);
903 AllNodes.push_back(N);
904 return SDOperand(N, 0);
908 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
909 unsigned Alignment, int Offset,
911 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
913 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
914 ID.AddInteger(Alignment);
915 ID.AddInteger(Offset);
916 C->AddSelectionDAGCSEId(ID);
918 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
919 return SDOperand(E, 0);
920 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
921 CSEMap.InsertNode(N, IP);
922 AllNodes.push_back(N);
923 return SDOperand(N, 0);
927 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
929 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), (SDOperand*)0, 0);
932 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
933 return SDOperand(E, 0);
934 SDNode *N = new BasicBlockSDNode(MBB);
935 CSEMap.InsertNode(N, IP);
936 AllNodes.push_back(N);
937 return SDOperand(N, 0);
940 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
942 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), (SDOperand*)0, 0);
943 ID.AddInteger(Flags.getRawBits());
945 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
946 return SDOperand(E, 0);
947 SDNode *N = new ARG_FLAGSSDNode(Flags);
948 CSEMap.InsertNode(N, IP);
949 AllNodes.push_back(N);
950 return SDOperand(N, 0);
953 SDOperand SelectionDAG::getValueType(MVT VT) {
954 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
955 ValueTypeNodes.resize(VT.getSimpleVT()+1);
957 SDNode *&N = VT.isExtended() ?
958 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
960 if (N) return SDOperand(N, 0);
961 N = new VTSDNode(VT);
962 AllNodes.push_back(N);
963 return SDOperand(N, 0);
966 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
967 SDNode *&N = ExternalSymbols[Sym];
968 if (N) return SDOperand(N, 0);
969 N = new ExternalSymbolSDNode(false, Sym, VT);
970 AllNodes.push_back(N);
971 return SDOperand(N, 0);
974 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
975 SDNode *&N = TargetExternalSymbols[Sym];
976 if (N) return SDOperand(N, 0);
977 N = new ExternalSymbolSDNode(true, Sym, VT);
978 AllNodes.push_back(N);
979 return SDOperand(N, 0);
982 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
983 if ((unsigned)Cond >= CondCodeNodes.size())
984 CondCodeNodes.resize(Cond+1);
986 if (CondCodeNodes[Cond] == 0) {
987 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
988 AllNodes.push_back(CondCodeNodes[Cond]);
990 return SDOperand(CondCodeNodes[Cond], 0);
993 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
995 AddNodeIDNode(ID, ISD::Register, getVTList(VT), (SDOperand*)0, 0);
996 ID.AddInteger(RegNo);
998 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
999 return SDOperand(E, 0);
1000 SDNode *N = new RegisterSDNode(RegNo, VT);
1001 CSEMap.InsertNode(N, IP);
1002 AllNodes.push_back(N);
1003 return SDOperand(N, 0);
1006 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1007 unsigned Line, unsigned Col,
1008 const CompileUnitDesc *CU) {
1009 FoldingSetNodeID ID;
1010 SDOperand Ops[] = { Root };
1011 AddNodeIDNode(ID, ISD::DBG_STOPPOINT, getVTList(MVT::Other), &Ops[0], 1);
1012 ID.AddInteger(Line);
1016 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1017 return SDOperand(E, 0);
1018 SDNode *N = new DbgStopPointSDNode(Root, Line, Col, CU);
1019 CSEMap.InsertNode(N, IP);
1020 AllNodes.push_back(N);
1021 return SDOperand(N, 0);
1024 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1027 FoldingSetNodeID ID;
1028 SDOperand Ops[] = { Root };
1029 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1030 ID.AddInteger(LabelID);
1032 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1033 return SDOperand(E, 0);
1034 SDNode *N = new LabelSDNode(Opcode, Root, LabelID);
1035 CSEMap.InsertNode(N, IP);
1036 AllNodes.push_back(N);
1037 return SDOperand(N, 0);
1040 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1041 assert((!V || isa<PointerType>(V->getType())) &&
1042 "SrcValue is not a pointer?");
1044 FoldingSetNodeID ID;
1045 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), (SDOperand*)0, 0);
1049 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1050 return SDOperand(E, 0);
1052 SDNode *N = new SrcValueSDNode(V);
1053 CSEMap.InsertNode(N, IP);
1054 AllNodes.push_back(N);
1055 return SDOperand(N, 0);
1058 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1059 const Value *v = MO.getValue();
1060 assert((!v || isa<PointerType>(v->getType())) &&
1061 "SrcValue is not a pointer?");
1063 FoldingSetNodeID ID;
1064 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), (SDOperand*)0, 0);
1066 ID.AddInteger(MO.getFlags());
1067 ID.AddInteger(MO.getOffset());
1068 ID.AddInteger(MO.getSize());
1069 ID.AddInteger(MO.getAlignment());
1072 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1073 return SDOperand(E, 0);
1075 SDNode *N = new MemOperandSDNode(MO);
1076 CSEMap.InsertNode(N, IP);
1077 AllNodes.push_back(N);
1078 return SDOperand(N, 0);
1081 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1082 /// specified value type.
1083 SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1084 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1085 unsigned ByteSize = VT.getSizeInBits()/8;
1086 const Type *Ty = VT.getTypeForMVT();
1087 unsigned StackAlign =
1088 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1090 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1091 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1094 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1095 SDOperand N2, ISD::CondCode Cond) {
1096 // These setcc operations always fold.
1100 case ISD::SETFALSE2: return getConstant(0, VT);
1102 case ISD::SETTRUE2: return getConstant(1, VT);
1114 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1118 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1119 const APInt &C2 = N2C->getAPIntValue();
1120 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1121 const APInt &C1 = N1C->getAPIntValue();
1124 default: assert(0 && "Unknown integer setcc!");
1125 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1126 case ISD::SETNE: return getConstant(C1 != C2, VT);
1127 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1128 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1129 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1130 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1131 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1132 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1133 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1134 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1138 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1139 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1140 // No compile time operations on this type yet.
1141 if (N1C->getValueType(0) == MVT::ppcf128)
1144 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1147 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1148 return getNode(ISD::UNDEF, VT);
1150 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1151 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1152 return getNode(ISD::UNDEF, VT);
1154 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1155 R==APFloat::cmpLessThan, VT);
1156 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1157 return getNode(ISD::UNDEF, VT);
1159 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1160 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1161 return getNode(ISD::UNDEF, VT);
1163 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1164 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1165 return getNode(ISD::UNDEF, VT);
1167 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1168 R==APFloat::cmpEqual, VT);
1169 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1170 return getNode(ISD::UNDEF, VT);
1172 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1173 R==APFloat::cmpEqual, VT);
1174 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1175 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1176 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1177 R==APFloat::cmpEqual, VT);
1178 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1179 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1180 R==APFloat::cmpLessThan, VT);
1181 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1182 R==APFloat::cmpUnordered, VT);
1183 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1184 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1187 // Ensure that the constant occurs on the RHS.
1188 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1192 // Could not fold it.
1196 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1197 /// use this predicate to simplify operations downstream.
1198 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1199 unsigned BitWidth = Op.getValueSizeInBits();
1200 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1203 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1204 /// this predicate to simplify operations downstream. Mask is known to be zero
1205 /// for bits that V cannot have.
1206 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1207 unsigned Depth) const {
1208 APInt KnownZero, KnownOne;
1209 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1210 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1211 return (KnownZero & Mask) == Mask;
1214 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1215 /// known to be either zero or one and return them in the KnownZero/KnownOne
1216 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1218 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1219 APInt &KnownZero, APInt &KnownOne,
1220 unsigned Depth) const {
1221 unsigned BitWidth = Mask.getBitWidth();
1222 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1223 "Mask size mismatches value type size!");
1225 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1226 if (Depth == 6 || Mask == 0)
1227 return; // Limit search depth.
1229 APInt KnownZero2, KnownOne2;
1231 switch (Op.getOpcode()) {
1233 // We know all of the bits for a constant!
1234 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1235 KnownZero = ~KnownOne & Mask;
1238 // If either the LHS or the RHS are Zero, the result is zero.
1239 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1240 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1241 KnownZero2, KnownOne2, Depth+1);
1242 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1243 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1245 // Output known-1 bits are only known if set in both the LHS & RHS.
1246 KnownOne &= KnownOne2;
1247 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1248 KnownZero |= KnownZero2;
1251 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1252 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1253 KnownZero2, KnownOne2, Depth+1);
1254 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1255 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1257 // Output known-0 bits are only known if clear in both the LHS & RHS.
1258 KnownZero &= KnownZero2;
1259 // Output known-1 are known to be set if set in either the LHS | RHS.
1260 KnownOne |= KnownOne2;
1263 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1264 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1265 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1266 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1268 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1269 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1270 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1271 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1272 KnownZero = KnownZeroOut;
1276 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1277 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1278 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1279 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1280 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1282 // If low bits are zero in either operand, output low known-0 bits.
1283 // Also compute a conserative estimate for high known-0 bits.
1284 // More trickiness is possible, but this is sufficient for the
1285 // interesting case of alignment computation.
1287 unsigned TrailZ = KnownZero.countTrailingOnes() +
1288 KnownZero2.countTrailingOnes();
1289 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1290 KnownZero2.countLeadingOnes(),
1291 BitWidth) - BitWidth;
1293 TrailZ = std::min(TrailZ, BitWidth);
1294 LeadZ = std::min(LeadZ, BitWidth);
1295 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1296 APInt::getHighBitsSet(BitWidth, LeadZ);
1301 // For the purposes of computing leading zeros we can conservatively
1302 // treat a udiv as a logical right shift by the power of 2 known to
1303 // be less than the denominator.
1304 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1305 ComputeMaskedBits(Op.getOperand(0),
1306 AllOnes, KnownZero2, KnownOne2, Depth+1);
1307 unsigned LeadZ = KnownZero2.countLeadingOnes();
1311 ComputeMaskedBits(Op.getOperand(1),
1312 AllOnes, KnownZero2, KnownOne2, Depth+1);
1313 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1314 if (RHSUnknownLeadingOnes != BitWidth)
1315 LeadZ = std::min(BitWidth,
1316 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1318 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1322 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1323 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1324 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1325 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1327 // Only known if known in both the LHS and RHS.
1328 KnownOne &= KnownOne2;
1329 KnownZero &= KnownZero2;
1331 case ISD::SELECT_CC:
1332 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1333 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1334 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1335 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1337 // Only known if known in both the LHS and RHS.
1338 KnownOne &= KnownOne2;
1339 KnownZero &= KnownZero2;
1342 // If we know the result of a setcc has the top bits zero, use this info.
1343 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1345 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1348 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1349 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1350 unsigned ShAmt = SA->getValue();
1352 // If the shift count is an invalid immediate, don't do anything.
1353 if (ShAmt >= BitWidth)
1356 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1357 KnownZero, KnownOne, Depth+1);
1358 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1359 KnownZero <<= ShAmt;
1361 // low bits known zero.
1362 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1366 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1367 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1368 unsigned ShAmt = SA->getValue();
1370 // If the shift count is an invalid immediate, don't do anything.
1371 if (ShAmt >= BitWidth)
1374 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1375 KnownZero, KnownOne, Depth+1);
1376 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1377 KnownZero = KnownZero.lshr(ShAmt);
1378 KnownOne = KnownOne.lshr(ShAmt);
1380 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1381 KnownZero |= HighBits; // High bits known zero.
1385 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1386 unsigned ShAmt = SA->getValue();
1388 // If the shift count is an invalid immediate, don't do anything.
1389 if (ShAmt >= BitWidth)
1392 APInt InDemandedMask = (Mask << ShAmt);
1393 // If any of the demanded bits are produced by the sign extension, we also
1394 // demand the input sign bit.
1395 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1396 if (HighBits.getBoolValue())
1397 InDemandedMask |= APInt::getSignBit(BitWidth);
1399 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1401 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1402 KnownZero = KnownZero.lshr(ShAmt);
1403 KnownOne = KnownOne.lshr(ShAmt);
1405 // Handle the sign bits.
1406 APInt SignBit = APInt::getSignBit(BitWidth);
1407 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1409 if (KnownZero.intersects(SignBit)) {
1410 KnownZero |= HighBits; // New bits are known zero.
1411 } else if (KnownOne.intersects(SignBit)) {
1412 KnownOne |= HighBits; // New bits are known one.
1416 case ISD::SIGN_EXTEND_INREG: {
1417 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1418 unsigned EBits = EVT.getSizeInBits();
1420 // Sign extension. Compute the demanded bits in the result that are not
1421 // present in the input.
1422 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1424 APInt InSignBit = APInt::getSignBit(EBits);
1425 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1427 // If the sign extended bits are demanded, we know that the sign
1429 InSignBit.zext(BitWidth);
1430 if (NewBits.getBoolValue())
1431 InputDemandedBits |= InSignBit;
1433 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1434 KnownZero, KnownOne, Depth+1);
1435 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1437 // If the sign bit of the input is known set or clear, then we know the
1438 // top bits of the result.
1439 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1440 KnownZero |= NewBits;
1441 KnownOne &= ~NewBits;
1442 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1443 KnownOne |= NewBits;
1444 KnownZero &= ~NewBits;
1445 } else { // Input sign bit unknown
1446 KnownZero &= ~NewBits;
1447 KnownOne &= ~NewBits;
1454 unsigned LowBits = Log2_32(BitWidth)+1;
1455 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1460 if (ISD::isZEXTLoad(Op.Val)) {
1461 LoadSDNode *LD = cast<LoadSDNode>(Op);
1462 MVT VT = LD->getMemoryVT();
1463 unsigned MemBits = VT.getSizeInBits();
1464 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1468 case ISD::ZERO_EXTEND: {
1469 MVT InVT = Op.getOperand(0).getValueType();
1470 unsigned InBits = InVT.getSizeInBits();
1471 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1472 APInt InMask = Mask;
1473 InMask.trunc(InBits);
1474 KnownZero.trunc(InBits);
1475 KnownOne.trunc(InBits);
1476 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1477 KnownZero.zext(BitWidth);
1478 KnownOne.zext(BitWidth);
1479 KnownZero |= NewBits;
1482 case ISD::SIGN_EXTEND: {
1483 MVT InVT = Op.getOperand(0).getValueType();
1484 unsigned InBits = InVT.getSizeInBits();
1485 APInt InSignBit = APInt::getSignBit(InBits);
1486 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1487 APInt InMask = Mask;
1488 InMask.trunc(InBits);
1490 // If any of the sign extended bits are demanded, we know that the sign
1491 // bit is demanded. Temporarily set this bit in the mask for our callee.
1492 if (NewBits.getBoolValue())
1493 InMask |= InSignBit;
1495 KnownZero.trunc(InBits);
1496 KnownOne.trunc(InBits);
1497 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1499 // Note if the sign bit is known to be zero or one.
1500 bool SignBitKnownZero = KnownZero.isNegative();
1501 bool SignBitKnownOne = KnownOne.isNegative();
1502 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1503 "Sign bit can't be known to be both zero and one!");
1505 // If the sign bit wasn't actually demanded by our caller, we don't
1506 // want it set in the KnownZero and KnownOne result values. Reset the
1507 // mask and reapply it to the result values.
1509 InMask.trunc(InBits);
1510 KnownZero &= InMask;
1513 KnownZero.zext(BitWidth);
1514 KnownOne.zext(BitWidth);
1516 // If the sign bit is known zero or one, the top bits match.
1517 if (SignBitKnownZero)
1518 KnownZero |= NewBits;
1519 else if (SignBitKnownOne)
1520 KnownOne |= NewBits;
1523 case ISD::ANY_EXTEND: {
1524 MVT InVT = Op.getOperand(0).getValueType();
1525 unsigned InBits = InVT.getSizeInBits();
1526 APInt InMask = Mask;
1527 InMask.trunc(InBits);
1528 KnownZero.trunc(InBits);
1529 KnownOne.trunc(InBits);
1530 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1531 KnownZero.zext(BitWidth);
1532 KnownOne.zext(BitWidth);
1535 case ISD::TRUNCATE: {
1536 MVT InVT = Op.getOperand(0).getValueType();
1537 unsigned InBits = InVT.getSizeInBits();
1538 APInt InMask = Mask;
1539 InMask.zext(InBits);
1540 KnownZero.zext(InBits);
1541 KnownOne.zext(InBits);
1542 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1543 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1544 KnownZero.trunc(BitWidth);
1545 KnownOne.trunc(BitWidth);
1548 case ISD::AssertZext: {
1549 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1550 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1551 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1553 KnownZero |= (~InMask) & Mask;
1557 // All bits are zero except the low bit.
1558 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1562 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1563 // We know that the top bits of C-X are clear if X contains less bits
1564 // than C (i.e. no wrap-around can happen). For example, 20-X is
1565 // positive if we can prove that X is >= 0 and < 16.
1566 if (CLHS->getAPIntValue().isNonNegative()) {
1567 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1568 // NLZ can't be BitWidth with no sign bit
1569 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1570 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1573 // If all of the MaskV bits are known to be zero, then we know the
1574 // output top bits are zero, because we now know that the output is
1576 if ((KnownZero2 & MaskV) == MaskV) {
1577 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1578 // Top bits known zero.
1579 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1586 // Output known-0 bits are known if clear or set in both the low clear bits
1587 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1588 // low 3 bits clear.
1589 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1590 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1591 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1592 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1594 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1595 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1596 KnownZeroOut = std::min(KnownZeroOut,
1597 KnownZero2.countTrailingOnes());
1599 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1603 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1604 const APInt &RA = Rem->getAPIntValue();
1605 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1606 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1607 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1608 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1610 // The sign of a remainder is equal to the sign of the first
1611 // operand (zero being positive).
1612 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1613 KnownZero2 |= ~LowBits;
1614 else if (KnownOne2[BitWidth-1])
1615 KnownOne2 |= ~LowBits;
1617 KnownZero |= KnownZero2 & Mask;
1618 KnownOne |= KnownOne2 & Mask;
1620 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1625 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1626 const APInt &RA = Rem->getAPIntValue();
1627 if (RA.isPowerOf2()) {
1628 APInt LowBits = (RA - 1);
1629 APInt Mask2 = LowBits & Mask;
1630 KnownZero |= ~LowBits & Mask;
1631 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1632 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1637 // Since the result is less than or equal to either operand, any leading
1638 // zero bits in either operand must also exist in the result.
1639 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1640 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1642 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1645 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1646 KnownZero2.countLeadingOnes());
1648 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1652 // Allow the target to implement this method for its nodes.
1653 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1654 case ISD::INTRINSIC_WO_CHAIN:
1655 case ISD::INTRINSIC_W_CHAIN:
1656 case ISD::INTRINSIC_VOID:
1657 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1663 /// ComputeNumSignBits - Return the number of times the sign bit of the
1664 /// register is replicated into the other bits. We know that at least 1 bit
1665 /// is always equal to the sign bit (itself), but other cases can give us
1666 /// information. For example, immediately after an "SRA X, 2", we know that
1667 /// the top 3 bits are all equal to each other, so we return 3.
1668 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1669 MVT VT = Op.getValueType();
1670 assert(VT.isInteger() && "Invalid VT!");
1671 unsigned VTBits = VT.getSizeInBits();
1673 unsigned FirstAnswer = 1;
1676 return 1; // Limit search depth.
1678 switch (Op.getOpcode()) {
1680 case ISD::AssertSext:
1681 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1682 return VTBits-Tmp+1;
1683 case ISD::AssertZext:
1684 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1687 case ISD::Constant: {
1688 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1689 // If negative, return # leading ones.
1690 if (Val.isNegative())
1691 return Val.countLeadingOnes();
1693 // Return # leading zeros.
1694 return Val.countLeadingZeros();
1697 case ISD::SIGN_EXTEND:
1698 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1699 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1701 case ISD::SIGN_EXTEND_INREG:
1702 // Max of the input and what this extends.
1703 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1706 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1707 return std::max(Tmp, Tmp2);
1710 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1711 // SRA X, C -> adds C sign bits.
1712 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1713 Tmp += C->getValue();
1714 if (Tmp > VTBits) Tmp = VTBits;
1718 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1719 // shl destroys sign bits.
1720 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1721 if (C->getValue() >= VTBits || // Bad shift.
1722 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1723 return Tmp - C->getValue();
1728 case ISD::XOR: // NOT is handled here.
1729 // Logical binary ops preserve the number of sign bits at the worst.
1730 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1732 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1733 FirstAnswer = std::min(Tmp, Tmp2);
1734 // We computed what we know about the sign bits as our first
1735 // answer. Now proceed to the generic code that uses
1736 // ComputeMaskedBits, and pick whichever answer is better.
1741 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1742 if (Tmp == 1) return 1; // Early out.
1743 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1744 return std::min(Tmp, Tmp2);
1747 // If setcc returns 0/-1, all bits are sign bits.
1748 if (TLI.getSetCCResultContents() ==
1749 TargetLowering::ZeroOrNegativeOneSetCCResult)
1754 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1755 unsigned RotAmt = C->getValue() & (VTBits-1);
1757 // Handle rotate right by N like a rotate left by 32-N.
1758 if (Op.getOpcode() == ISD::ROTR)
1759 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1761 // If we aren't rotating out all of the known-in sign bits, return the
1762 // number that are left. This handles rotl(sext(x), 1) for example.
1763 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1764 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1768 // Add can have at most one carry bit. Thus we know that the output
1769 // is, at worst, one more bit than the inputs.
1770 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1771 if (Tmp == 1) return 1; // Early out.
1773 // Special case decrementing a value (ADD X, -1):
1774 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1775 if (CRHS->isAllOnesValue()) {
1776 APInt KnownZero, KnownOne;
1777 APInt Mask = APInt::getAllOnesValue(VTBits);
1778 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1780 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1782 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1785 // If we are subtracting one from a positive number, there is no carry
1786 // out of the result.
1787 if (KnownZero.isNegative())
1791 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1792 if (Tmp2 == 1) return 1;
1793 return std::min(Tmp, Tmp2)-1;
1797 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1798 if (Tmp2 == 1) return 1;
1801 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1802 if (CLHS->isNullValue()) {
1803 APInt KnownZero, KnownOne;
1804 APInt Mask = APInt::getAllOnesValue(VTBits);
1805 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1806 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1808 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1811 // If the input is known to be positive (the sign bit is known clear),
1812 // the output of the NEG has the same number of sign bits as the input.
1813 if (KnownZero.isNegative())
1816 // Otherwise, we treat this like a SUB.
1819 // Sub can have at most one carry bit. Thus we know that the output
1820 // is, at worst, one more bit than the inputs.
1821 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1822 if (Tmp == 1) return 1; // Early out.
1823 return std::min(Tmp, Tmp2)-1;
1826 // FIXME: it's tricky to do anything useful for this, but it is an important
1827 // case for targets like X86.
1831 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1832 if (Op.getOpcode() == ISD::LOAD) {
1833 LoadSDNode *LD = cast<LoadSDNode>(Op);
1834 unsigned ExtType = LD->getExtensionType();
1837 case ISD::SEXTLOAD: // '17' bits known
1838 Tmp = LD->getMemoryVT().getSizeInBits();
1839 return VTBits-Tmp+1;
1840 case ISD::ZEXTLOAD: // '16' bits known
1841 Tmp = LD->getMemoryVT().getSizeInBits();
1846 // Allow the target to implement this method for its nodes.
1847 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1848 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1849 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1850 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1851 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1852 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1855 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1856 // use this information.
1857 APInt KnownZero, KnownOne;
1858 APInt Mask = APInt::getAllOnesValue(VTBits);
1859 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1861 if (KnownZero.isNegative()) { // sign bit is 0
1863 } else if (KnownOne.isNegative()) { // sign bit is 1;
1870 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1871 // the number of identical bits in the top of the input value.
1873 Mask <<= Mask.getBitWidth()-VTBits;
1874 // Return # leading zeros. We use 'min' here in case Val was zero before
1875 // shifting. We don't want to return '64' as for an i32 "0".
1876 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1880 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1881 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1882 if (!GA) return false;
1883 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1884 if (!GV) return false;
1885 MachineModuleInfo *MMI = getMachineModuleInfo();
1886 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1890 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1891 /// element of the result of the vector shuffle.
1892 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1893 MVT VT = N->getValueType(0);
1894 SDOperand PermMask = N->getOperand(2);
1895 SDOperand Idx = PermMask.getOperand(i);
1896 if (Idx.getOpcode() == ISD::UNDEF)
1897 return getNode(ISD::UNDEF, VT.getVectorElementType());
1898 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1899 unsigned NumElems = PermMask.getNumOperands();
1900 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1903 if (V.getOpcode() == ISD::BIT_CONVERT) {
1904 V = V.getOperand(0);
1905 if (V.getValueType().getVectorNumElements() != NumElems)
1908 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1909 return (Index == 0) ? V.getOperand(0)
1910 : getNode(ISD::UNDEF, VT.getVectorElementType());
1911 if (V.getOpcode() == ISD::BUILD_VECTOR)
1912 return V.getOperand(Index);
1913 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1914 return getShuffleScalarElt(V.Val, Index);
1919 /// getNode - Gets or creates the specified node.
1921 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1922 FoldingSetNodeID ID;
1923 AddNodeIDNode(ID, Opcode, getVTList(VT), (SDOperand*)0, 0);
1925 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1926 return SDOperand(E, 0);
1927 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1928 CSEMap.InsertNode(N, IP);
1930 AllNodes.push_back(N);
1931 return SDOperand(N, 0);
1934 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1935 // Constant fold unary operations with an integer constant operand.
1936 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1937 const APInt &Val = C->getAPIntValue();
1938 unsigned BitWidth = VT.getSizeInBits();
1941 case ISD::SIGN_EXTEND:
1942 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1943 case ISD::ANY_EXTEND:
1944 case ISD::ZERO_EXTEND:
1946 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1947 case ISD::UINT_TO_FP:
1948 case ISD::SINT_TO_FP: {
1949 const uint64_t zero[] = {0, 0};
1950 // No compile time operations on this type.
1951 if (VT==MVT::ppcf128)
1953 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1954 (void)apf.convertFromAPInt(Val,
1955 Opcode==ISD::SINT_TO_FP,
1956 APFloat::rmNearestTiesToEven);
1957 return getConstantFP(apf, VT);
1959 case ISD::BIT_CONVERT:
1960 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1961 return getConstantFP(Val.bitsToFloat(), VT);
1962 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1963 return getConstantFP(Val.bitsToDouble(), VT);
1966 return getConstant(Val.byteSwap(), VT);
1968 return getConstant(Val.countPopulation(), VT);
1970 return getConstant(Val.countLeadingZeros(), VT);
1972 return getConstant(Val.countTrailingZeros(), VT);
1976 // Constant fold unary operations with a floating point constant operand.
1977 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1978 APFloat V = C->getValueAPF(); // make copy
1979 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1983 return getConstantFP(V, VT);
1986 return getConstantFP(V, VT);
1988 case ISD::FP_EXTEND:
1989 // This can return overflow, underflow, or inexact; we don't care.
1990 // FIXME need to be more flexible about rounding mode.
1991 (void)V.convert(*MVTToAPFloatSemantics(VT),
1992 APFloat::rmNearestTiesToEven);
1993 return getConstantFP(V, VT);
1994 case ISD::FP_TO_SINT:
1995 case ISD::FP_TO_UINT: {
1997 assert(integerPartWidth >= 64);
1998 // FIXME need to be more flexible about rounding mode.
1999 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2000 Opcode==ISD::FP_TO_SINT,
2001 APFloat::rmTowardZero);
2002 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2004 return getConstant(x, VT);
2006 case ISD::BIT_CONVERT:
2007 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2008 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2009 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2010 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2016 unsigned OpOpcode = Operand.Val->getOpcode();
2018 case ISD::TokenFactor:
2019 return Operand; // Factor of one node? No need.
2020 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2021 case ISD::FP_EXTEND:
2022 assert(VT.isFloatingPoint() &&
2023 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2024 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2025 if (Operand.getOpcode() == ISD::UNDEF)
2026 return getNode(ISD::UNDEF, VT);
2028 case ISD::SIGN_EXTEND:
2029 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2030 "Invalid SIGN_EXTEND!");
2031 if (Operand.getValueType() == VT) return Operand; // noop extension
2032 assert(Operand.getValueType().bitsLT(VT)
2033 && "Invalid sext node, dst < src!");
2034 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2035 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2037 case ISD::ZERO_EXTEND:
2038 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2039 "Invalid ZERO_EXTEND!");
2040 if (Operand.getValueType() == VT) return Operand; // noop extension
2041 assert(Operand.getValueType().bitsLT(VT)
2042 && "Invalid zext node, dst < src!");
2043 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2044 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2046 case ISD::ANY_EXTEND:
2047 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2048 "Invalid ANY_EXTEND!");
2049 if (Operand.getValueType() == VT) return Operand; // noop extension
2050 assert(Operand.getValueType().bitsLT(VT)
2051 && "Invalid anyext node, dst < src!");
2052 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2053 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2054 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2057 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2058 "Invalid TRUNCATE!");
2059 if (Operand.getValueType() == VT) return Operand; // noop truncate
2060 assert(Operand.getValueType().bitsGT(VT)
2061 && "Invalid truncate node, src < dst!");
2062 if (OpOpcode == ISD::TRUNCATE)
2063 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2064 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2065 OpOpcode == ISD::ANY_EXTEND) {
2066 // If the source is smaller than the dest, we still need an extend.
2067 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2068 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2069 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2070 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2072 return Operand.Val->getOperand(0);
2075 case ISD::BIT_CONVERT:
2076 // Basic sanity checking.
2077 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2078 && "Cannot BIT_CONVERT between types of different sizes!");
2079 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2080 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2081 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2082 if (OpOpcode == ISD::UNDEF)
2083 return getNode(ISD::UNDEF, VT);
2085 case ISD::SCALAR_TO_VECTOR:
2086 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2087 VT.getVectorElementType() == Operand.getValueType() &&
2088 "Illegal SCALAR_TO_VECTOR node!");
2089 if (OpOpcode == ISD::UNDEF)
2090 return getNode(ISD::UNDEF, VT);
2091 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2092 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2093 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2094 Operand.getConstantOperandVal(1) == 0 &&
2095 Operand.getOperand(0).getValueType() == VT)
2096 return Operand.getOperand(0);
2099 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2100 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2101 Operand.Val->getOperand(0));
2102 if (OpOpcode == ISD::FNEG) // --X -> X
2103 return Operand.Val->getOperand(0);
2106 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2107 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2112 SDVTList VTs = getVTList(VT);
2113 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2114 FoldingSetNodeID ID;
2115 SDOperand Ops[1] = { Operand };
2116 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2118 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2119 return SDOperand(E, 0);
2120 N = new UnarySDNode(Opcode, VTs, Operand);
2121 CSEMap.InsertNode(N, IP);
2123 N = new UnarySDNode(Opcode, VTs, Operand);
2125 AllNodes.push_back(N);
2126 return SDOperand(N, 0);
2131 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2132 SDOperand N1, SDOperand N2) {
2133 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2134 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2137 case ISD::TokenFactor:
2138 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2139 N2.getValueType() == MVT::Other && "Invalid token factor!");
2140 // Fold trivial token factors.
2141 if (N1.getOpcode() == ISD::EntryToken) return N2;
2142 if (N2.getOpcode() == ISD::EntryToken) return N1;
2145 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2146 N1.getValueType() == VT && "Binary operator types must match!");
2147 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2148 // worth handling here.
2149 if (N2C && N2C->isNullValue())
2151 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2158 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2159 N1.getValueType() == VT && "Binary operator types must match!");
2160 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2161 // it's worth handling here.
2162 if (N2C && N2C->isNullValue())
2169 assert(VT.isInteger() && "This operator does not apply to FP types!");
2179 assert(N1.getValueType() == N2.getValueType() &&
2180 N1.getValueType() == VT && "Binary operator types must match!");
2182 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2183 assert(N1.getValueType() == VT &&
2184 N1.getValueType().isFloatingPoint() &&
2185 N2.getValueType().isFloatingPoint() &&
2186 "Invalid FCOPYSIGN!");
2193 assert(VT == N1.getValueType() &&
2194 "Shift operators return type must be the same as their first arg");
2195 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2196 "Shifts only work on integers");
2198 // Always fold shifts of i1 values so the code generator doesn't need to
2199 // handle them. Since we know the size of the shift has to be less than the
2200 // size of the value, the shift/rotate count is guaranteed to be zero.
2204 case ISD::FP_ROUND_INREG: {
2205 MVT EVT = cast<VTSDNode>(N2)->getVT();
2206 assert(VT == N1.getValueType() && "Not an inreg round!");
2207 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2208 "Cannot FP_ROUND_INREG integer types");
2209 assert(EVT.bitsLE(VT) && "Not rounding down!");
2210 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2214 assert(VT.isFloatingPoint() &&
2215 N1.getValueType().isFloatingPoint() &&
2216 VT.bitsLE(N1.getValueType()) &&
2217 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2218 if (N1.getValueType() == VT) return N1; // noop conversion.
2220 case ISD::AssertSext:
2221 case ISD::AssertZext: {
2222 MVT EVT = cast<VTSDNode>(N2)->getVT();
2223 assert(VT == N1.getValueType() && "Not an inreg extend!");
2224 assert(VT.isInteger() && EVT.isInteger() &&
2225 "Cannot *_EXTEND_INREG FP types");
2226 assert(EVT.bitsLE(VT) && "Not extending!");
2227 if (VT == EVT) return N1; // noop assertion.
2230 case ISD::SIGN_EXTEND_INREG: {
2231 MVT EVT = cast<VTSDNode>(N2)->getVT();
2232 assert(VT == N1.getValueType() && "Not an inreg extend!");
2233 assert(VT.isInteger() && EVT.isInteger() &&
2234 "Cannot *_EXTEND_INREG FP types");
2235 assert(EVT.bitsLE(VT) && "Not extending!");
2236 if (EVT == VT) return N1; // Not actually extending
2239 APInt Val = N1C->getAPIntValue();
2240 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2241 Val <<= Val.getBitWidth()-FromBits;
2242 Val = Val.ashr(Val.getBitWidth()-FromBits);
2243 return getConstant(Val, VT);
2247 case ISD::EXTRACT_VECTOR_ELT:
2248 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2250 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2251 if (N1.getOpcode() == ISD::UNDEF)
2252 return getNode(ISD::UNDEF, VT);
2254 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2255 // expanding copies of large vectors from registers.
2256 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2257 N1.getNumOperands() > 0) {
2259 N1.getOperand(0).getValueType().getVectorNumElements();
2260 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2261 N1.getOperand(N2C->getValue() / Factor),
2262 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2265 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2266 // expanding large vector constants.
2267 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2268 return N1.getOperand(N2C->getValue());
2270 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2271 // operations are lowered to scalars.
2272 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2273 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2275 return N1.getOperand(1);
2277 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2280 case ISD::EXTRACT_ELEMENT:
2281 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2282 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2283 (N1.getValueType().isInteger() == VT.isInteger()) &&
2284 "Wrong types for EXTRACT_ELEMENT!");
2286 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2287 // 64-bit integers into 32-bit parts. Instead of building the extract of
2288 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2289 if (N1.getOpcode() == ISD::BUILD_PAIR)
2290 return N1.getOperand(N2C->getValue());
2292 // EXTRACT_ELEMENT of a constant int is also very common.
2293 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2294 unsigned ElementSize = VT.getSizeInBits();
2295 unsigned Shift = ElementSize * N2C->getValue();
2296 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2297 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2300 case ISD::EXTRACT_SUBVECTOR:
2301 if (N1.getValueType() == VT) // Trivial extraction.
2308 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2310 case ISD::ADD: return getConstant(C1 + C2, VT);
2311 case ISD::SUB: return getConstant(C1 - C2, VT);
2312 case ISD::MUL: return getConstant(C1 * C2, VT);
2314 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2317 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2320 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2323 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2325 case ISD::AND : return getConstant(C1 & C2, VT);
2326 case ISD::OR : return getConstant(C1 | C2, VT);
2327 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2328 case ISD::SHL : return getConstant(C1 << C2, VT);
2329 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2330 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2331 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2332 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2335 } else { // Cannonicalize constant to RHS if commutative
2336 if (isCommutativeBinOp(Opcode)) {
2337 std::swap(N1C, N2C);
2343 // Constant fold FP operations.
2344 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2345 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2347 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2348 // Cannonicalize constant to RHS if commutative
2349 std::swap(N1CFP, N2CFP);
2351 } else if (N2CFP && VT != MVT::ppcf128) {
2352 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2353 APFloat::opStatus s;
2356 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2357 if (s != APFloat::opInvalidOp)
2358 return getConstantFP(V1, VT);
2361 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2362 if (s!=APFloat::opInvalidOp)
2363 return getConstantFP(V1, VT);
2366 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2367 if (s!=APFloat::opInvalidOp)
2368 return getConstantFP(V1, VT);
2371 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2372 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2373 return getConstantFP(V1, VT);
2376 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2377 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2378 return getConstantFP(V1, VT);
2380 case ISD::FCOPYSIGN:
2382 return getConstantFP(V1, VT);
2388 // Canonicalize an UNDEF to the RHS, even over a constant.
2389 if (N1.getOpcode() == ISD::UNDEF) {
2390 if (isCommutativeBinOp(Opcode)) {
2394 case ISD::FP_ROUND_INREG:
2395 case ISD::SIGN_EXTEND_INREG:
2401 return N1; // fold op(undef, arg2) -> undef
2409 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2410 // For vectors, we can't easily build an all zero vector, just return
2417 // Fold a bunch of operators when the RHS is undef.
2418 if (N2.getOpcode() == ISD::UNDEF) {
2421 if (N1.getOpcode() == ISD::UNDEF)
2422 // Handle undef ^ undef -> 0 special case. This is a common
2424 return getConstant(0, VT);
2439 return N2; // fold op(arg1, undef) -> undef
2445 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2446 // For vectors, we can't easily build an all zero vector, just return
2451 return getConstant(VT.getIntegerVTBitMask(), VT);
2452 // For vectors, we can't easily build an all one vector, just return
2460 // Memoize this node if possible.
2462 SDVTList VTs = getVTList(VT);
2463 if (VT != MVT::Flag) {
2464 SDOperand Ops[] = { N1, N2 };
2465 FoldingSetNodeID ID;
2466 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2468 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2469 return SDOperand(E, 0);
2470 N = new BinarySDNode(Opcode, VTs, N1, N2);
2471 CSEMap.InsertNode(N, IP);
2473 N = new BinarySDNode(Opcode, VTs, N1, N2);
2476 AllNodes.push_back(N);
2477 return SDOperand(N, 0);
2480 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2481 SDOperand N1, SDOperand N2, SDOperand N3) {
2482 // Perform various simplifications.
2483 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2484 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2487 // Use FoldSetCC to simplify SETCC's.
2488 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2489 if (Simp.Val) return Simp;
2494 if (N1C->getValue())
2495 return N2; // select true, X, Y -> X
2497 return N3; // select false, X, Y -> Y
2500 if (N2 == N3) return N2; // select C, X, X -> X
2504 if (N2C->getValue()) // Unconditional branch
2505 return getNode(ISD::BR, MVT::Other, N1, N3);
2507 return N1; // Never-taken branch
2510 case ISD::VECTOR_SHUFFLE:
2511 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2512 VT.isVector() && N3.getValueType().isVector() &&
2513 N3.getOpcode() == ISD::BUILD_VECTOR &&
2514 VT.getVectorNumElements() == N3.getNumOperands() &&
2515 "Illegal VECTOR_SHUFFLE node!");
2517 case ISD::BIT_CONVERT:
2518 // Fold bit_convert nodes from a type to themselves.
2519 if (N1.getValueType() == VT)
2524 // Memoize node if it doesn't produce a flag.
2526 SDVTList VTs = getVTList(VT);
2527 if (VT != MVT::Flag) {
2528 SDOperand Ops[] = { N1, N2, N3 };
2529 FoldingSetNodeID ID;
2530 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2532 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2533 return SDOperand(E, 0);
2534 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2535 CSEMap.InsertNode(N, IP);
2537 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2539 AllNodes.push_back(N);
2540 return SDOperand(N, 0);
2543 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2544 SDOperand N1, SDOperand N2, SDOperand N3,
2546 SDOperand Ops[] = { N1, N2, N3, N4 };
2547 return getNode(Opcode, VT, Ops, 4);
2550 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2551 SDOperand N1, SDOperand N2, SDOperand N3,
2552 SDOperand N4, SDOperand N5) {
2553 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2554 return getNode(Opcode, VT, Ops, 5);
2557 /// getMemsetValue - Vectorized representation of the memset value
2559 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2560 unsigned NumBits = VT.isVector() ?
2561 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2562 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2563 APInt Val = APInt(NumBits, C->getValue() & 255);
2565 for (unsigned i = NumBits; i > 8; i >>= 1) {
2566 Val = (Val << Shift) | Val;
2570 return DAG.getConstant(Val, VT);
2571 return DAG.getConstantFP(APFloat(Val), VT);
2574 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2576 for (unsigned i = NumBits; i > 8; i >>= 1) {
2577 Value = DAG.getNode(ISD::OR, VT,
2578 DAG.getNode(ISD::SHL, VT, Value,
2579 DAG.getConstant(Shift, MVT::i8)), Value);
2586 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2587 /// used when a memcpy is turned into a memset when the source is a constant
2589 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2590 const TargetLowering &TLI,
2591 std::string &Str, unsigned Offset) {
2592 // Handle vector with all elements zero.
2595 return DAG.getConstant(0, VT);
2596 unsigned NumElts = VT.getVectorNumElements();
2597 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2598 return DAG.getNode(ISD::BIT_CONVERT, VT,
2599 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2602 assert(!VT.isVector() && "Can't handle vector type here!");
2603 unsigned NumBits = VT.getSizeInBits();
2604 unsigned MSB = NumBits / 8;
2606 if (TLI.isLittleEndian())
2607 Offset = Offset + MSB - 1;
2608 for (unsigned i = 0; i != MSB; ++i) {
2609 Val = (Val << 8) | (unsigned char)Str[Offset];
2610 Offset += TLI.isLittleEndian() ? -1 : 1;
2612 return DAG.getConstant(Val, VT);
2615 /// getMemBasePlusOffset - Returns base and offset node for the
2617 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2618 SelectionDAG &DAG) {
2619 MVT VT = Base.getValueType();
2620 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2623 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2625 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2626 unsigned SrcDelta = 0;
2627 GlobalAddressSDNode *G = NULL;
2628 if (Src.getOpcode() == ISD::GlobalAddress)
2629 G = cast<GlobalAddressSDNode>(Src);
2630 else if (Src.getOpcode() == ISD::ADD &&
2631 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2632 Src.getOperand(1).getOpcode() == ISD::Constant) {
2633 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2634 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2639 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2640 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2646 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2647 /// to replace the memset / memcpy is below the threshold. It also returns the
2648 /// types of the sequence of memory ops to perform memset / memcpy.
2650 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2651 SDOperand Dst, SDOperand Src,
2652 unsigned Limit, uint64_t Size, unsigned &Align,
2653 std::string &Str, bool &isSrcStr,
2655 const TargetLowering &TLI) {
2656 isSrcStr = isMemSrcFromString(Src, Str);
2657 bool isSrcConst = isa<ConstantSDNode>(Src);
2658 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2659 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2660 if (VT != MVT::iAny) {
2661 unsigned NewAlign = (unsigned)
2662 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2663 // If source is a string constant, this will require an unaligned load.
2664 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2665 if (Dst.getOpcode() != ISD::FrameIndex) {
2666 // Can't change destination alignment. It requires a unaligned store.
2670 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2671 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2672 if (MFI->isFixedObjectIndex(FI)) {
2673 // Can't change destination alignment. It requires a unaligned store.
2677 // Give the stack frame object a larger alignment if needed.
2678 if (MFI->getObjectAlignment(FI) < NewAlign)
2679 MFI->setObjectAlignment(FI, NewAlign);
2686 if (VT == MVT::iAny) {
2690 switch (Align & 7) {
2691 case 0: VT = MVT::i64; break;
2692 case 4: VT = MVT::i32; break;
2693 case 2: VT = MVT::i16; break;
2694 default: VT = MVT::i8; break;
2699 while (!TLI.isTypeLegal(LVT))
2700 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2701 assert(LVT.isInteger());
2707 unsigned NumMemOps = 0;
2709 unsigned VTSize = VT.getSizeInBits() / 8;
2710 while (VTSize > Size) {
2711 // For now, only use non-vector load / store's for the left-over pieces.
2712 if (VT.isVector()) {
2714 while (!TLI.isTypeLegal(VT))
2715 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2716 VTSize = VT.getSizeInBits() / 8;
2718 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2723 if (++NumMemOps > Limit)
2725 MemOps.push_back(VT);
2732 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2733 SDOperand Chain, SDOperand Dst,
2734 SDOperand Src, uint64_t Size,
2735 unsigned Align, bool AlwaysInline,
2736 const Value *DstSV, uint64_t DstSVOff,
2737 const Value *SrcSV, uint64_t SrcSVOff){
2738 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2740 // Expand memcpy to a series of load and store ops if the size operand falls
2741 // below a certain threshold.
2742 std::vector<MVT> MemOps;
2743 uint64_t Limit = -1;
2745 Limit = TLI.getMaxStoresPerMemcpy();
2746 unsigned DstAlign = Align; // Destination alignment can change.
2749 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2750 Str, CopyFromStr, DAG, TLI))
2754 bool isZeroStr = CopyFromStr && Str.empty();
2755 SmallVector<SDOperand, 8> OutChains;
2756 unsigned NumMemOps = MemOps.size();
2757 uint64_t SrcOff = 0, DstOff = 0;
2758 for (unsigned i = 0; i < NumMemOps; i++) {
2760 unsigned VTSize = VT.getSizeInBits() / 8;
2761 SDOperand Value, Store;
2763 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2764 // It's unlikely a store of a vector immediate can be done in a single
2765 // instruction. It would require a load from a constantpool first.
2766 // We also handle store a vector with all zero's.
2767 // FIXME: Handle other cases where store of vector immediate is done in
2768 // a single instruction.
2769 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2770 Store = DAG.getStore(Chain, Value,
2771 getMemBasePlusOffset(Dst, DstOff, DAG),
2772 DstSV, DstSVOff + DstOff);
2774 Value = DAG.getLoad(VT, Chain,
2775 getMemBasePlusOffset(Src, SrcOff, DAG),
2776 SrcSV, SrcSVOff + SrcOff, false, Align);
2777 Store = DAG.getStore(Chain, Value,
2778 getMemBasePlusOffset(Dst, DstOff, DAG),
2779 DstSV, DstSVOff + DstOff, false, DstAlign);
2781 OutChains.push_back(Store);
2786 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2787 &OutChains[0], OutChains.size());
2790 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2791 SDOperand Chain, SDOperand Dst,
2792 SDOperand Src, uint64_t Size,
2793 unsigned Align, bool AlwaysInline,
2794 const Value *DstSV, uint64_t DstSVOff,
2795 const Value *SrcSV, uint64_t SrcSVOff){
2796 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2798 // Expand memmove to a series of load and store ops if the size operand falls
2799 // below a certain threshold.
2800 std::vector<MVT> MemOps;
2801 uint64_t Limit = -1;
2803 Limit = TLI.getMaxStoresPerMemmove();
2804 unsigned DstAlign = Align; // Destination alignment can change.
2807 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2808 Str, CopyFromStr, DAG, TLI))
2811 uint64_t SrcOff = 0, DstOff = 0;
2813 SmallVector<SDOperand, 8> LoadValues;
2814 SmallVector<SDOperand, 8> LoadChains;
2815 SmallVector<SDOperand, 8> OutChains;
2816 unsigned NumMemOps = MemOps.size();
2817 for (unsigned i = 0; i < NumMemOps; i++) {
2819 unsigned VTSize = VT.getSizeInBits() / 8;
2820 SDOperand Value, Store;
2822 Value = DAG.getLoad(VT, Chain,
2823 getMemBasePlusOffset(Src, SrcOff, DAG),
2824 SrcSV, SrcSVOff + SrcOff, false, Align);
2825 LoadValues.push_back(Value);
2826 LoadChains.push_back(Value.getValue(1));
2829 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2830 &LoadChains[0], LoadChains.size());
2832 for (unsigned i = 0; i < NumMemOps; i++) {
2834 unsigned VTSize = VT.getSizeInBits() / 8;
2835 SDOperand Value, Store;
2837 Store = DAG.getStore(Chain, LoadValues[i],
2838 getMemBasePlusOffset(Dst, DstOff, DAG),
2839 DstSV, DstSVOff + DstOff, false, DstAlign);
2840 OutChains.push_back(Store);
2844 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2845 &OutChains[0], OutChains.size());
2848 static SDOperand getMemsetStores(SelectionDAG &DAG,
2849 SDOperand Chain, SDOperand Dst,
2850 SDOperand Src, uint64_t Size,
2852 const Value *DstSV, uint64_t DstSVOff) {
2853 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2855 // Expand memset to a series of load/store ops if the size operand
2856 // falls below a certain threshold.
2857 std::vector<MVT> MemOps;
2860 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2861 Size, Align, Str, CopyFromStr, DAG, TLI))
2864 SmallVector<SDOperand, 8> OutChains;
2865 uint64_t DstOff = 0;
2867 unsigned NumMemOps = MemOps.size();
2868 for (unsigned i = 0; i < NumMemOps; i++) {
2870 unsigned VTSize = VT.getSizeInBits() / 8;
2871 SDOperand Value = getMemsetValue(Src, VT, DAG);
2872 SDOperand Store = DAG.getStore(Chain, Value,
2873 getMemBasePlusOffset(Dst, DstOff, DAG),
2874 DstSV, DstSVOff + DstOff);
2875 OutChains.push_back(Store);
2879 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2880 &OutChains[0], OutChains.size());
2883 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2884 SDOperand Src, SDOperand Size,
2885 unsigned Align, bool AlwaysInline,
2886 const Value *DstSV, uint64_t DstSVOff,
2887 const Value *SrcSV, uint64_t SrcSVOff) {
2889 // Check to see if we should lower the memcpy to loads and stores first.
2890 // For cases within the target-specified limits, this is the best choice.
2891 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2893 // Memcpy with size zero? Just return the original chain.
2894 if (ConstantSize->isNullValue())
2898 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2899 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2904 // Then check to see if we should lower the memcpy with target-specific
2905 // code. If the target chooses to do this, this is the next best.
2907 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2909 DstSV, DstSVOff, SrcSV, SrcSVOff);
2913 // If we really need inline code and the target declined to provide it,
2914 // use a (potentially long) sequence of loads and stores.
2916 assert(ConstantSize && "AlwaysInline requires a constant size!");
2917 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2918 ConstantSize->getValue(), Align, true,
2919 DstSV, DstSVOff, SrcSV, SrcSVOff);
2922 // Emit a library call.
2923 TargetLowering::ArgListTy Args;
2924 TargetLowering::ArgListEntry Entry;
2925 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2926 Entry.Node = Dst; Args.push_back(Entry);
2927 Entry.Node = Src; Args.push_back(Entry);
2928 Entry.Node = Size; Args.push_back(Entry);
2929 std::pair<SDOperand,SDOperand> CallResult =
2930 TLI.LowerCallTo(Chain, Type::VoidTy,
2931 false, false, false, CallingConv::C, false,
2932 getExternalSymbol("memcpy", TLI.getPointerTy()),
2934 return CallResult.second;
2937 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2938 SDOperand Src, SDOperand Size,
2940 const Value *DstSV, uint64_t DstSVOff,
2941 const Value *SrcSV, uint64_t SrcSVOff) {
2943 // Check to see if we should lower the memmove to loads and stores first.
2944 // For cases within the target-specified limits, this is the best choice.
2945 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2947 // Memmove with size zero? Just return the original chain.
2948 if (ConstantSize->isNullValue())
2952 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2953 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2958 // Then check to see if we should lower the memmove with target-specific
2959 // code. If the target chooses to do this, this is the next best.
2961 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2962 DstSV, DstSVOff, SrcSV, SrcSVOff);
2966 // Emit a library call.
2967 TargetLowering::ArgListTy Args;
2968 TargetLowering::ArgListEntry Entry;
2969 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2970 Entry.Node = Dst; Args.push_back(Entry);
2971 Entry.Node = Src; Args.push_back(Entry);
2972 Entry.Node = Size; Args.push_back(Entry);
2973 std::pair<SDOperand,SDOperand> CallResult =
2974 TLI.LowerCallTo(Chain, Type::VoidTy,
2975 false, false, false, CallingConv::C, false,
2976 getExternalSymbol("memmove", TLI.getPointerTy()),
2978 return CallResult.second;
2981 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2982 SDOperand Src, SDOperand Size,
2984 const Value *DstSV, uint64_t DstSVOff) {
2986 // Check to see if we should lower the memset to stores first.
2987 // For cases within the target-specified limits, this is the best choice.
2988 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2990 // Memset with size zero? Just return the original chain.
2991 if (ConstantSize->isNullValue())
2995 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3001 // Then check to see if we should lower the memset with target-specific
3002 // code. If the target chooses to do this, this is the next best.
3004 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3009 // Emit a library call.
3010 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3011 TargetLowering::ArgListTy Args;
3012 TargetLowering::ArgListEntry Entry;
3013 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3014 Args.push_back(Entry);
3015 // Extend or truncate the argument to be an i32 value for the call.
3016 if (Src.getValueType().bitsGT(MVT::i32))
3017 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3019 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3020 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3021 Args.push_back(Entry);
3022 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3023 Args.push_back(Entry);
3024 std::pair<SDOperand,SDOperand> CallResult =
3025 TLI.LowerCallTo(Chain, Type::VoidTy,
3026 false, false, false, CallingConv::C, false,
3027 getExternalSymbol("memset", TLI.getPointerTy()),
3029 return CallResult.second;
3032 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3033 SDOperand Ptr, SDOperand Cmp,
3034 SDOperand Swp, const Value* PtrVal,
3035 unsigned Alignment) {
3036 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3037 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3038 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3039 FoldingSetNodeID ID;
3040 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3041 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3043 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3044 return SDOperand(E, 0);
3045 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp,
3047 CSEMap.InsertNode(N, IP);
3048 AllNodes.push_back(N);
3049 return SDOperand(N, 0);
3052 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3053 SDOperand Ptr, SDOperand Val,
3054 const Value* PtrVal,
3055 unsigned Alignment) {
3056 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3057 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3058 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3059 || Opcode == ISD::ATOMIC_LOAD_NAND
3060 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3061 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3062 && "Invalid Atomic Op");
3063 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3064 FoldingSetNodeID ID;
3065 SDOperand Ops[] = {Chain, Ptr, Val};
3066 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3068 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3069 return SDOperand(E, 0);
3070 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val,
3072 CSEMap.InsertNode(N, IP);
3073 AllNodes.push_back(N);
3074 return SDOperand(N, 0);
3077 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3078 /// Allowed to return something different (and simpler) if Simplify is true.
3079 SDOperand SelectionDAG::getMergeValues(SDOperandPtr Ops, unsigned NumOps,
3081 if (Simplify && NumOps == 1)
3084 SmallVector<MVT, 4> VTs;
3085 VTs.reserve(NumOps);
3086 for (unsigned i = 0; i < NumOps; ++i)
3087 VTs.push_back(Ops[i].getValueType());
3088 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3092 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3093 MVT VT, SDOperand Chain,
3094 SDOperand Ptr, SDOperand Offset,
3095 const Value *SV, int SVOffset, MVT EVT,
3096 bool isVolatile, unsigned Alignment) {
3097 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3099 if (VT != MVT::iPTR) {
3100 Ty = VT.getTypeForMVT();
3102 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3103 assert(PT && "Value for load must be a pointer");
3104 Ty = PT->getElementType();
3106 assert(Ty && "Could not get type information for load");
3107 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3111 ExtType = ISD::NON_EXTLOAD;
3112 } else if (ExtType == ISD::NON_EXTLOAD) {
3113 assert(VT == EVT && "Non-extending load from different memory type!");
3117 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3119 assert(EVT.bitsLT(VT) &&
3120 "Should only be an extending load, not truncating!");
3121 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3122 "Cannot sign/zero extend a FP/Vector load!");
3123 assert(VT.isInteger() == EVT.isInteger() &&
3124 "Cannot convert from FP to Int or Int -> FP!");
3127 bool Indexed = AM != ISD::UNINDEXED;
3128 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3129 "Unindexed load with an offset!");
3131 SDVTList VTs = Indexed ?
3132 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3133 SDOperand Ops[] = { Chain, Ptr, Offset };
3134 FoldingSetNodeID ID;
3135 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3137 ID.AddInteger(ExtType);
3138 ID.AddInteger(EVT.getRawBits());
3139 ID.AddInteger(Alignment);
3140 ID.AddInteger(isVolatile);
3142 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3143 return SDOperand(E, 0);
3144 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3145 Alignment, isVolatile);
3146 CSEMap.InsertNode(N, IP);
3147 AllNodes.push_back(N);
3148 return SDOperand(N, 0);
3151 SDOperand SelectionDAG::getLoad(MVT VT,
3152 SDOperand Chain, SDOperand Ptr,
3153 const Value *SV, int SVOffset,
3154 bool isVolatile, unsigned Alignment) {
3155 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3156 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3157 SV, SVOffset, VT, isVolatile, Alignment);
3160 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3161 SDOperand Chain, SDOperand Ptr,
3163 int SVOffset, MVT EVT,
3164 bool isVolatile, unsigned Alignment) {
3165 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3166 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3167 SV, SVOffset, EVT, isVolatile, Alignment);
3171 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3172 SDOperand Offset, ISD::MemIndexedMode AM) {
3173 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3174 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3175 "Load is already a indexed load!");
3176 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3177 LD->getChain(), Base, Offset, LD->getSrcValue(),
3178 LD->getSrcValueOffset(), LD->getMemoryVT(),
3179 LD->isVolatile(), LD->getAlignment());
3182 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3183 SDOperand Ptr, const Value *SV, int SVOffset,
3184 bool isVolatile, unsigned Alignment) {
3185 MVT VT = Val.getValueType();
3187 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3189 if (VT != MVT::iPTR) {
3190 Ty = VT.getTypeForMVT();
3192 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3193 assert(PT && "Value for store must be a pointer");
3194 Ty = PT->getElementType();
3196 assert(Ty && "Could not get type information for store");
3197 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3199 SDVTList VTs = getVTList(MVT::Other);
3200 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3201 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3202 FoldingSetNodeID ID;
3203 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3204 ID.AddInteger(ISD::UNINDEXED);
3205 ID.AddInteger(false);
3206 ID.AddInteger(VT.getRawBits());
3207 ID.AddInteger(Alignment);
3208 ID.AddInteger(isVolatile);
3210 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3211 return SDOperand(E, 0);
3212 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3213 VT, SV, SVOffset, Alignment, isVolatile);
3214 CSEMap.InsertNode(N, IP);
3215 AllNodes.push_back(N);
3216 return SDOperand(N, 0);
3219 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3220 SDOperand Ptr, const Value *SV,
3221 int SVOffset, MVT SVT,
3222 bool isVolatile, unsigned Alignment) {
3223 MVT VT = Val.getValueType();
3226 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3228 assert(VT.bitsGT(SVT) && "Not a truncation?");
3229 assert(VT.isInteger() == SVT.isInteger() &&
3230 "Can't do FP-INT conversion!");
3232 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3234 if (VT != MVT::iPTR) {
3235 Ty = VT.getTypeForMVT();
3237 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3238 assert(PT && "Value for store must be a pointer");
3239 Ty = PT->getElementType();
3241 assert(Ty && "Could not get type information for store");
3242 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3244 SDVTList VTs = getVTList(MVT::Other);
3245 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3246 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3247 FoldingSetNodeID ID;
3248 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3249 ID.AddInteger(ISD::UNINDEXED);
3251 ID.AddInteger(SVT.getRawBits());
3252 ID.AddInteger(Alignment);
3253 ID.AddInteger(isVolatile);
3255 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3256 return SDOperand(E, 0);
3257 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3258 SVT, SV, SVOffset, Alignment, isVolatile);
3259 CSEMap.InsertNode(N, IP);
3260 AllNodes.push_back(N);
3261 return SDOperand(N, 0);
3265 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3266 SDOperand Offset, ISD::MemIndexedMode AM) {
3267 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3268 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3269 "Store is already a indexed store!");
3270 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3271 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3272 FoldingSetNodeID ID;
3273 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3275 ID.AddInteger(ST->isTruncatingStore());
3276 ID.AddInteger(ST->getMemoryVT().getRawBits());
3277 ID.AddInteger(ST->getAlignment());
3278 ID.AddInteger(ST->isVolatile());
3280 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3281 return SDOperand(E, 0);
3282 SDNode *N = new StoreSDNode(Ops, VTs, AM,
3283 ST->isTruncatingStore(), ST->getMemoryVT(),
3284 ST->getSrcValue(), ST->getSrcValueOffset(),
3285 ST->getAlignment(), ST->isVolatile());
3286 CSEMap.InsertNode(N, IP);
3287 AllNodes.push_back(N);
3288 return SDOperand(N, 0);
3291 SDOperand SelectionDAG::getVAArg(MVT VT,
3292 SDOperand Chain, SDOperand Ptr,
3294 SDOperand Ops[] = { Chain, Ptr, SV };
3295 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3298 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3299 SDOperandPtr Ops, unsigned NumOps) {
3301 case 0: return getNode(Opcode, VT);
3302 case 1: return getNode(Opcode, VT, Ops[0]);
3303 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3304 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3310 case ISD::SELECT_CC: {
3311 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3312 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3313 "LHS and RHS of condition must have same type!");
3314 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3315 "True and False arms of SelectCC must have same type!");
3316 assert(Ops[2].getValueType() == VT &&
3317 "select_cc node must be of same type as true and false value!");
3321 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3322 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3323 "LHS/RHS of comparison should match types!");
3330 SDVTList VTs = getVTList(VT);
3331 if (VT != MVT::Flag) {
3332 FoldingSetNodeID ID;
3333 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3335 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3336 return SDOperand(E, 0);
3337 N = new SDNode(Opcode, VTs, Ops, NumOps);
3338 CSEMap.InsertNode(N, IP);
3340 N = new SDNode(Opcode, VTs, Ops, NumOps);
3342 AllNodes.push_back(N);
3343 return SDOperand(N, 0);
3346 SDOperand SelectionDAG::getNode(unsigned Opcode,
3347 std::vector<MVT> &ResultTys,
3348 SDOperandPtr Ops, unsigned NumOps) {
3349 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3353 SDOperand SelectionDAG::getNode(unsigned Opcode,
3354 const MVT *VTs, unsigned NumVTs,
3355 SDOperandPtr Ops, unsigned NumOps) {
3357 return getNode(Opcode, VTs[0], Ops, NumOps);
3358 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3361 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3362 SDOperandPtr Ops, unsigned NumOps) {
3363 if (VTList.NumVTs == 1)
3364 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3367 // FIXME: figure out how to safely handle things like
3368 // int foo(int x) { return 1 << (x & 255); }
3369 // int bar() { return foo(256); }
3371 case ISD::SRA_PARTS:
3372 case ISD::SRL_PARTS:
3373 case ISD::SHL_PARTS:
3374 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3375 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3376 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3377 else if (N3.getOpcode() == ISD::AND)
3378 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3379 // If the and is only masking out bits that cannot effect the shift,
3380 // eliminate the and.
3381 unsigned NumBits = VT.getSizeInBits()*2;
3382 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3383 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3389 // Memoize the node unless it returns a flag.
3391 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3392 FoldingSetNodeID ID;
3393 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3395 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3396 return SDOperand(E, 0);
3398 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3399 else if (NumOps == 2)
3400 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3401 else if (NumOps == 3)
3402 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3404 N = new SDNode(Opcode, VTList, Ops, NumOps);
3405 CSEMap.InsertNode(N, IP);
3408 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3409 else if (NumOps == 2)
3410 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3411 else if (NumOps == 3)
3412 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3414 N = new SDNode(Opcode, VTList, Ops, NumOps);
3416 AllNodes.push_back(N);
3417 return SDOperand(N, 0);
3420 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3421 return getNode(Opcode, VTList, (SDOperand*)0, 0);
3424 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3426 SDOperand Ops[] = { N1 };
3427 return getNode(Opcode, VTList, Ops, 1);
3430 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3431 SDOperand N1, SDOperand N2) {
3432 SDOperand Ops[] = { N1, N2 };
3433 return getNode(Opcode, VTList, Ops, 2);
3436 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3437 SDOperand N1, SDOperand N2, SDOperand N3) {
3438 SDOperand Ops[] = { N1, N2, N3 };
3439 return getNode(Opcode, VTList, Ops, 3);
3442 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3443 SDOperand N1, SDOperand N2, SDOperand N3,
3445 SDOperand Ops[] = { N1, N2, N3, N4 };
3446 return getNode(Opcode, VTList, Ops, 4);
3449 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3450 SDOperand N1, SDOperand N2, SDOperand N3,
3451 SDOperand N4, SDOperand N5) {
3452 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3453 return getNode(Opcode, VTList, Ops, 5);
3456 SDVTList SelectionDAG::getVTList(MVT VT) {
3457 return makeVTList(SDNode::getValueTypeList(VT), 1);
3460 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3461 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3462 E = VTList.end(); I != E; ++I) {
3463 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3464 return makeVTList(&(*I)[0], 2);
3469 VTList.push_front(V);
3470 return makeVTList(&(*VTList.begin())[0], 2);
3472 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3474 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3475 E = VTList.end(); I != E; ++I) {
3476 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3478 return makeVTList(&(*I)[0], 3);
3484 VTList.push_front(V);
3485 return makeVTList(&(*VTList.begin())[0], 3);
3488 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3490 case 0: assert(0 && "Cannot have nodes without results!");
3491 case 1: return getVTList(VTs[0]);
3492 case 2: return getVTList(VTs[0], VTs[1]);
3493 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3497 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3498 E = VTList.end(); I != E; ++I) {
3499 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3501 bool NoMatch = false;
3502 for (unsigned i = 2; i != NumVTs; ++i)
3503 if (VTs[i] != (*I)[i]) {
3508 return makeVTList(&*I->begin(), NumVTs);
3511 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3512 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3516 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3517 /// specified operands. If the resultant node already exists in the DAG,
3518 /// this does not modify the specified node, instead it returns the node that
3519 /// already exists. If the resultant node does not exist in the DAG, the
3520 /// input node is returned. As a degenerate case, if you specify the same
3521 /// input operands as the node already has, the input node is returned.
3522 SDOperand SelectionDAG::
3523 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3524 SDNode *N = InN.Val;
3525 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3527 // Check to see if there is no change.
3528 if (Op == N->getOperand(0)) return InN;
3530 // See if the modified node already exists.
3531 void *InsertPos = 0;
3532 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3533 return SDOperand(Existing, InN.ResNo);
3535 // Nope it doesn't. Remove the node from it's current place in the maps.
3537 RemoveNodeFromCSEMaps(N);
3539 // Now we update the operands.
3540 N->OperandList[0].getVal()->removeUser(0, N);
3541 N->OperandList[0] = Op;
3542 N->OperandList[0].setUser(N);
3543 Op.Val->addUser(0, N);
3545 // If this gets put into a CSE map, add it.
3546 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3550 SDOperand SelectionDAG::
3551 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3552 SDNode *N = InN.Val;
3553 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3555 // Check to see if there is no change.
3556 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3557 return InN; // No operands changed, just return the input node.
3559 // See if the modified node already exists.
3560 void *InsertPos = 0;
3561 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3562 return SDOperand(Existing, InN.ResNo);
3564 // Nope it doesn't. Remove the node from it's current place in the maps.
3566 RemoveNodeFromCSEMaps(N);
3568 // Now we update the operands.
3569 if (N->OperandList[0] != Op1) {
3570 N->OperandList[0].getVal()->removeUser(0, N);
3571 N->OperandList[0] = Op1;
3572 N->OperandList[0].setUser(N);
3573 Op1.Val->addUser(0, N);
3575 if (N->OperandList[1] != Op2) {
3576 N->OperandList[1].getVal()->removeUser(1, N);
3577 N->OperandList[1] = Op2;
3578 N->OperandList[1].setUser(N);
3579 Op2.Val->addUser(1, N);
3582 // If this gets put into a CSE map, add it.
3583 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3587 SDOperand SelectionDAG::
3588 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3589 SDOperand Ops[] = { Op1, Op2, Op3 };
3590 return UpdateNodeOperands(N, Ops, 3);
3593 SDOperand SelectionDAG::
3594 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3595 SDOperand Op3, SDOperand Op4) {
3596 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3597 return UpdateNodeOperands(N, Ops, 4);
3600 SDOperand SelectionDAG::
3601 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3602 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3603 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3604 return UpdateNodeOperands(N, Ops, 5);
3607 SDOperand SelectionDAG::
3608 UpdateNodeOperands(SDOperand InN, SDOperandPtr Ops, unsigned NumOps) {
3609 SDNode *N = InN.Val;
3610 assert(N->getNumOperands() == NumOps &&
3611 "Update with wrong number of operands");
3613 // Check to see if there is no change.
3614 bool AnyChange = false;
3615 for (unsigned i = 0; i != NumOps; ++i) {
3616 if (Ops[i] != N->getOperand(i)) {
3622 // No operands changed, just return the input node.
3623 if (!AnyChange) return InN;
3625 // See if the modified node already exists.
3626 void *InsertPos = 0;
3627 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3628 return SDOperand(Existing, InN.ResNo);
3630 // Nope it doesn't. Remove the node from its current place in the maps.
3632 RemoveNodeFromCSEMaps(N);
3634 // Now we update the operands.
3635 for (unsigned i = 0; i != NumOps; ++i) {
3636 if (N->OperandList[i] != Ops[i]) {
3637 N->OperandList[i].getVal()->removeUser(i, N);
3638 N->OperandList[i] = Ops[i];
3639 N->OperandList[i].setUser(N);
3640 Ops[i].Val->addUser(i, N);
3644 // If this gets put into a CSE map, add it.
3645 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3649 /// MorphNodeTo - This frees the operands of the current node, resets the
3650 /// opcode, types, and operands to the specified value. This should only be
3651 /// used by the SelectionDAG class.
3652 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3653 SDOperandPtr Ops, unsigned NumOps) {
3656 NumValues = L.NumVTs;
3658 // Clear the operands list, updating used nodes to remove this from their
3660 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3661 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3663 // If NumOps is larger than the # of operands we currently have, reallocate
3664 // the operand list.
3665 if (NumOps > NumOperands) {
3666 if (OperandsNeedDelete) {
3667 delete [] OperandList;
3669 OperandList = new SDUse[NumOps];
3670 OperandsNeedDelete = true;
3673 // Assign the new operands.
3674 NumOperands = NumOps;
3676 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3677 OperandList[i] = Ops[i];
3678 OperandList[i].setUser(this);
3679 SDNode *N = OperandList[i].getVal();
3680 N->addUser(i, this);
3685 /// SelectNodeTo - These are used for target selectors to *mutate* the
3686 /// specified node to have the specified return type, Target opcode, and
3687 /// operands. Note that target opcodes are stored as
3688 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3690 /// Note that SelectNodeTo returns the resultant node. If there is already a
3691 /// node of the specified opcode and operands, it returns that node instead of
3692 /// the current one.
3693 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3695 SDVTList VTs = getVTList(VT);
3696 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand*)0, 0);
3699 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3700 MVT VT, SDOperand Op1) {
3701 SDVTList VTs = getVTList(VT);
3702 SDOperand Ops[] = { Op1 };
3703 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3706 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3707 MVT VT, SDOperand Op1,
3709 SDVTList VTs = getVTList(VT);
3710 SDOperand Ops[] = { Op1, Op2 };
3711 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3714 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3715 MVT VT, SDOperand Op1,
3716 SDOperand Op2, SDOperand Op3) {
3717 SDVTList VTs = getVTList(VT);
3718 SDOperand Ops[] = { Op1, Op2, Op3 };
3719 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3722 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3723 MVT VT, SDOperandPtr Ops,
3725 SDVTList VTs = getVTList(VT);
3726 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3729 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3730 MVT VT1, MVT VT2, SDOperandPtr Ops,
3732 SDVTList VTs = getVTList(VT1, VT2);
3733 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3736 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3738 SDVTList VTs = getVTList(VT1, VT2);
3739 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand *)0, 0);
3742 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3743 MVT VT1, MVT VT2, MVT VT3, SDOperandPtr Ops,
3745 SDVTList VTs = getVTList(VT1, VT2, VT3);
3746 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3749 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3752 SDVTList VTs = getVTList(VT1, VT2);
3753 SDOperand Ops[] = { Op1 };
3754 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3757 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3759 SDOperand Op1, SDOperand Op2) {
3760 SDVTList VTs = getVTList(VT1, VT2);
3761 SDOperand Ops[] = { Op1, Op2 };
3762 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3765 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3767 SDOperand Op1, SDOperand Op2,
3769 SDVTList VTs = getVTList(VT1, VT2);
3770 SDOperand Ops[] = { Op1, Op2, Op3 };
3771 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3774 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3775 SDVTList VTs, SDOperandPtr Ops,
3777 // If an identical node already exists, use it.
3778 FoldingSetNodeID ID;
3779 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3781 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3784 RemoveNodeFromCSEMaps(N);
3786 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3787 CSEMap.InsertNode(N, IP); // Memoize the new node.
3792 /// getTargetNode - These are used for target selectors to create a new node
3793 /// with specified return type(s), target opcode, and operands.
3795 /// Note that getTargetNode returns the resultant node. If there is already a
3796 /// node of the specified opcode and operands, it returns that node instead of
3797 /// the current one.
3798 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3799 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3801 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3802 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3804 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3805 SDOperand Op1, SDOperand Op2) {
3806 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3808 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3809 SDOperand Op1, SDOperand Op2,
3811 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3813 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3814 SDOperandPtr Ops, unsigned NumOps) {
3815 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3817 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3818 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3820 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3822 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3823 MVT VT2, SDOperand Op1) {
3824 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3825 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3827 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3828 MVT VT2, SDOperand Op1,
3830 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3831 SDOperand Ops[] = { Op1, Op2 };
3832 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3834 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3835 MVT VT2, SDOperand Op1,
3836 SDOperand Op2, SDOperand Op3) {
3837 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3838 SDOperand Ops[] = { Op1, Op2, Op3 };
3839 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3841 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3842 SDOperandPtr Ops, unsigned NumOps) {
3843 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3844 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3846 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3847 SDOperand Op1, SDOperand Op2) {
3848 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3849 SDOperand Ops[] = { Op1, Op2 };
3850 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3852 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3853 SDOperand Op1, SDOperand Op2,
3855 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3856 SDOperand Ops[] = { Op1, Op2, Op3 };
3857 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3859 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3860 SDOperandPtr Ops, unsigned NumOps) {
3861 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3862 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3864 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3865 MVT VT2, MVT VT3, MVT VT4,
3866 SDOperandPtr Ops, unsigned NumOps) {
3867 std::vector<MVT> VTList;
3868 VTList.push_back(VT1);
3869 VTList.push_back(VT2);
3870 VTList.push_back(VT3);
3871 VTList.push_back(VT4);
3872 const MVT *VTs = getNodeValueTypes(VTList);
3873 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3875 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3876 std::vector<MVT> &ResultTys,
3877 SDOperandPtr Ops, unsigned NumOps) {
3878 const MVT *VTs = getNodeValueTypes(ResultTys);
3879 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3883 /// getNodeIfExists - Get the specified node if it's already available, or
3884 /// else return NULL.
3885 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3886 SDOperandPtr Ops, unsigned NumOps) {
3887 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3888 FoldingSetNodeID ID;
3889 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3891 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3898 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3899 /// This can cause recursive merging of nodes in the DAG.
3901 /// This version assumes From has a single result value.
3903 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3904 DAGUpdateListener *UpdateListener) {
3905 SDNode *From = FromN.Val;
3906 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3907 "Cannot replace with this method!");
3908 assert(From != To.Val && "Cannot replace uses of with self");
3910 while (!From->use_empty()) {
3911 SDNode::use_iterator UI = From->use_begin();
3912 SDNode *U = UI->getUser();
3914 // This node is about to morph, remove its old self from the CSE maps.
3915 RemoveNodeFromCSEMaps(U);
3917 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3918 I != E; ++I, ++operandNum)
3919 if (I->getVal() == From) {
3920 From->removeUser(operandNum, U);
3923 To.Val->addUser(operandNum, U);
3926 // Now that we have modified U, add it back to the CSE maps. If it already
3927 // exists there, recursively merge the results together.
3928 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3929 ReplaceAllUsesWith(U, Existing, UpdateListener);
3930 // U is now dead. Inform the listener if it exists and delete it.
3932 UpdateListener->NodeDeleted(U, Existing);
3933 DeleteNodeNotInCSEMaps(U);
3935 // If the node doesn't already exist, we updated it. Inform a listener if
3938 UpdateListener->NodeUpdated(U);
3943 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3944 /// This can cause recursive merging of nodes in the DAG.
3946 /// This version assumes From/To have matching types and numbers of result
3949 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3950 DAGUpdateListener *UpdateListener) {
3951 assert(From != To && "Cannot replace uses of with self");
3952 assert(From->getNumValues() == To->getNumValues() &&
3953 "Cannot use this version of ReplaceAllUsesWith!");
3954 if (From->getNumValues() == 1) // If possible, use the faster version.
3955 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3958 while (!From->use_empty()) {
3959 SDNode::use_iterator UI = From->use_begin();
3960 SDNode *U = UI->getUser();
3962 // This node is about to morph, remove its old self from the CSE maps.
3963 RemoveNodeFromCSEMaps(U);
3965 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3966 I != E; ++I, ++operandNum)
3967 if (I->getVal() == From) {
3968 From->removeUser(operandNum, U);
3970 To->addUser(operandNum, U);
3973 // Now that we have modified U, add it back to the CSE maps. If it already
3974 // exists there, recursively merge the results together.
3975 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3976 ReplaceAllUsesWith(U, Existing, UpdateListener);
3977 // U is now dead. Inform the listener if it exists and delete it.
3979 UpdateListener->NodeDeleted(U, Existing);
3980 DeleteNodeNotInCSEMaps(U);
3982 // If the node doesn't already exist, we updated it. Inform a listener if
3985 UpdateListener->NodeUpdated(U);
3990 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3991 /// This can cause recursive merging of nodes in the DAG.
3993 /// This version can replace From with any result values. To must match the
3994 /// number and types of values returned by From.
3995 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3997 DAGUpdateListener *UpdateListener) {
3998 if (From->getNumValues() == 1) // Handle the simple case efficiently.
3999 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4001 while (!From->use_empty()) {
4002 SDNode::use_iterator UI = From->use_begin();
4003 SDNode *U = UI->getUser();
4005 // This node is about to morph, remove its old self from the CSE maps.
4006 RemoveNodeFromCSEMaps(U);
4008 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4009 I != E; ++I, ++operandNum)
4010 if (I->getVal() == From) {
4011 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4012 From->removeUser(operandNum, U);
4015 ToOp.Val->addUser(operandNum, U);
4018 // Now that we have modified U, add it back to the CSE maps. If it already
4019 // exists there, recursively merge the results together.
4020 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4021 ReplaceAllUsesWith(U, Existing, UpdateListener);
4022 // U is now dead. Inform the listener if it exists and delete it.
4024 UpdateListener->NodeDeleted(U, Existing);
4025 DeleteNodeNotInCSEMaps(U);
4027 // If the node doesn't already exist, we updated it. Inform a listener if
4030 UpdateListener->NodeUpdated(U);
4036 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4037 /// any deleted nodes from the set passed into its constructor and recursively
4038 /// notifies another update listener if specified.
4039 class ChainedSetUpdaterListener :
4040 public SelectionDAG::DAGUpdateListener {
4041 SmallSetVector<SDNode*, 16> &Set;
4042 SelectionDAG::DAGUpdateListener *Chain;
4044 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4045 SelectionDAG::DAGUpdateListener *chain)
4046 : Set(set), Chain(chain) {}
4048 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4050 if (Chain) Chain->NodeDeleted(N, E);
4052 virtual void NodeUpdated(SDNode *N) {
4053 if (Chain) Chain->NodeUpdated(N);
4058 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4059 /// uses of other values produced by From.Val alone. The Deleted vector is
4060 /// handled the same way as for ReplaceAllUsesWith.
4061 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4062 DAGUpdateListener *UpdateListener){
4063 assert(From != To && "Cannot replace a value with itself");
4065 // Handle the simple, trivial, case efficiently.
4066 if (From.Val->getNumValues() == 1) {
4067 ReplaceAllUsesWith(From, To, UpdateListener);
4071 if (From.use_empty()) return;
4073 // Get all of the users of From.Val. We want these in a nice,
4074 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4075 SmallSetVector<SDNode*, 16> Users;
4076 for (SDNode::use_iterator UI = From.Val->use_begin(),
4077 E = From.Val->use_end(); UI != E; ++UI) {
4078 SDNode *User = UI->getUser();
4082 // When one of the recursive merges deletes nodes from the graph, we need to
4083 // make sure that UpdateListener is notified *and* that the node is removed
4084 // from Users if present. CSUL does this.
4085 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4087 while (!Users.empty()) {
4088 // We know that this user uses some value of From. If it is the right
4089 // value, update it.
4090 SDNode *User = Users.back();
4093 // Scan for an operand that matches From.
4094 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4095 for (; Op != E; ++Op)
4096 if (*Op == From) break;
4098 // If there are no matches, the user must use some other result of From.
4099 if (Op == E) continue;
4101 // Okay, we know this user needs to be updated. Remove its old self
4102 // from the CSE maps.
4103 RemoveNodeFromCSEMaps(User);
4105 // Update all operands that match "From" in case there are multiple uses.
4106 for (; Op != E; ++Op) {
4108 From.Val->removeUser(Op-User->op_begin(), User);
4111 To.Val->addUser(Op-User->op_begin(), User);
4115 // Now that we have modified User, add it back to the CSE maps. If it
4116 // already exists there, recursively merge the results together.
4117 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4119 if (UpdateListener) UpdateListener->NodeUpdated(User);
4120 continue; // Continue on to next user.
4123 // If there was already an existing matching node, use ReplaceAllUsesWith
4124 // to replace the dead one with the existing one. This can cause
4125 // recursive merging of other unrelated nodes down the line. The merging
4126 // can cause deletion of nodes that used the old value. To handle this, we
4127 // use CSUL to remove them from the Users set.
4128 ReplaceAllUsesWith(User, Existing, &CSUL);
4130 // User is now dead. Notify a listener if present.
4131 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4132 DeleteNodeNotInCSEMaps(User);
4136 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4137 /// their allnodes order. It returns the maximum id.
4138 unsigned SelectionDAG::AssignNodeIds() {
4140 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4147 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4148 /// based on their topological order. It returns the maximum id and a vector
4149 /// of the SDNodes* in assigned order by reference.
4150 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4151 unsigned DAGSize = AllNodes.size();
4152 std::vector<unsigned> InDegree(DAGSize);
4153 std::vector<SDNode*> Sources;
4155 // Use a two pass approach to avoid using a std::map which is slow.
4157 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4160 unsigned Degree = N->use_size();
4161 InDegree[N->getNodeId()] = Degree;
4163 Sources.push_back(N);
4167 while (!Sources.empty()) {
4168 SDNode *N = Sources.back();
4170 TopOrder.push_back(N);
4171 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4172 SDNode *P = I->getVal();
4173 unsigned Degree = --InDegree[P->getNodeId()];
4175 Sources.push_back(P);
4179 // Second pass, assign the actual topological order as node ids.
4181 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4183 (*TI)->setNodeId(Id++);
4190 //===----------------------------------------------------------------------===//
4192 //===----------------------------------------------------------------------===//
4194 // Out-of-line virtual method to give class a home.
4195 void SDNode::ANCHOR() {}
4196 void UnarySDNode::ANCHOR() {}
4197 void BinarySDNode::ANCHOR() {}
4198 void TernarySDNode::ANCHOR() {}
4199 void HandleSDNode::ANCHOR() {}
4200 void ConstantSDNode::ANCHOR() {}
4201 void ConstantFPSDNode::ANCHOR() {}
4202 void GlobalAddressSDNode::ANCHOR() {}
4203 void FrameIndexSDNode::ANCHOR() {}
4204 void JumpTableSDNode::ANCHOR() {}
4205 void ConstantPoolSDNode::ANCHOR() {}
4206 void BasicBlockSDNode::ANCHOR() {}
4207 void SrcValueSDNode::ANCHOR() {}
4208 void MemOperandSDNode::ANCHOR() {}
4209 void RegisterSDNode::ANCHOR() {}
4210 void DbgStopPointSDNode::ANCHOR() {}
4211 void LabelSDNode::ANCHOR() {}
4212 void ExternalSymbolSDNode::ANCHOR() {}
4213 void CondCodeSDNode::ANCHOR() {}
4214 void ARG_FLAGSSDNode::ANCHOR() {}
4215 void VTSDNode::ANCHOR() {}
4216 void MemSDNode::ANCHOR() {}
4217 void LoadSDNode::ANCHOR() {}
4218 void StoreSDNode::ANCHOR() {}
4219 void AtomicSDNode::ANCHOR() {}
4221 HandleSDNode::~HandleSDNode() {
4222 SDVTList VTs = { 0, 0 };
4223 MorphNodeTo(ISD::HANDLENODE, VTs, SDOperandPtr(), 0); // Drops operand uses.
4226 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4228 : SDNode(isa<GlobalVariable>(GA) &&
4229 cast<GlobalVariable>(GA)->isThreadLocal() ?
4231 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4233 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4234 getSDVTList(VT)), Offset(o) {
4235 TheGlobal = const_cast<GlobalValue*>(GA);
4238 /// getMemOperand - Return a MachineMemOperand object describing the memory
4239 /// reference performed by this atomic.
4240 MachineMemOperand AtomicSDNode::getMemOperand() const {
4241 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4242 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4243 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4245 // Check if the atomic references a frame index
4246 const FrameIndexSDNode *FI =
4247 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4248 if (!getSrcValue() && FI)
4249 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4250 FI->getIndex(), Size, getAlignment());
4252 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4253 Size, getAlignment());
4256 /// getMemOperand - Return a MachineMemOperand object describing the memory
4257 /// reference performed by this load or store.
4258 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4259 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4261 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4262 MachineMemOperand::MOStore;
4263 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4265 // Check if the load references a frame index, and does not have
4267 const FrameIndexSDNode *FI =
4268 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4269 if (!getSrcValue() && FI)
4270 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4271 FI->getIndex(), Size, getAlignment());
4273 return MachineMemOperand(getSrcValue(), Flags,
4274 getSrcValueOffset(), Size, getAlignment());
4277 /// Profile - Gather unique data for the node.
4279 void SDNode::Profile(FoldingSetNodeID &ID) {
4280 AddNodeIDNode(ID, this);
4283 /// getValueTypeList - Return a pointer to the specified value type.
4285 const MVT *SDNode::getValueTypeList(MVT VT) {
4286 if (VT.isExtended()) {
4287 static std::set<MVT, MVT::compareRawBits> EVTs;
4288 return &(*EVTs.insert(VT).first);
4290 static MVT VTs[MVT::LAST_VALUETYPE];
4291 VTs[VT.getSimpleVT()] = VT;
4292 return &VTs[VT.getSimpleVT()];
4296 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4297 /// indicated value. This method ignores uses of other values defined by this
4299 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4300 assert(Value < getNumValues() && "Bad value!");
4302 // If there is only one value, this is easy.
4303 if (getNumValues() == 1)
4304 return use_size() == NUses;
4305 if (use_size() < NUses) return false;
4307 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4309 SmallPtrSet<SDNode*, 32> UsersHandled;
4311 // TODO: Only iterate over uses of a given value of the node
4312 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4313 if (*UI == TheValue) {
4320 // Found exactly the right number of uses?
4325 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4326 /// value. This method ignores uses of other values defined by this operation.
4327 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4328 assert(Value < getNumValues() && "Bad value!");
4330 if (use_empty()) return false;
4332 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4334 SmallPtrSet<SDNode*, 32> UsersHandled;
4336 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4337 SDNode *User = UI->getUser();
4338 if (User->getNumOperands() == 1 ||
4339 UsersHandled.insert(User)) // First time we've seen this?
4340 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4341 if (User->getOperand(i) == TheValue) {
4350 /// isOnlyUseOf - Return true if this node is the only use of N.
4352 bool SDNode::isOnlyUseOf(SDNode *N) const {
4354 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4355 SDNode *User = I->getUser();
4365 /// isOperand - Return true if this node is an operand of N.
4367 bool SDOperand::isOperandOf(SDNode *N) const {
4368 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4369 if (*this == N->getOperand(i))
4374 bool SDNode::isOperandOf(SDNode *N) const {
4375 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4376 if (this == N->OperandList[i].getVal())
4381 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4382 /// be a chain) reaches the specified operand without crossing any
4383 /// side-effecting instructions. In practice, this looks through token
4384 /// factors and non-volatile loads. In order to remain efficient, this only
4385 /// looks a couple of nodes in, it does not do an exhaustive search.
4386 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4387 unsigned Depth) const {
4388 if (*this == Dest) return true;
4390 // Don't search too deeply, we just want to be able to see through
4391 // TokenFactor's etc.
4392 if (Depth == 0) return false;
4394 // If this is a token factor, all inputs to the TF happen in parallel. If any
4395 // of the operands of the TF reach dest, then we can do the xform.
4396 if (getOpcode() == ISD::TokenFactor) {
4397 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4398 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4403 // Loads don't have side effects, look through them.
4404 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4405 if (!Ld->isVolatile())
4406 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4412 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4413 SmallPtrSet<SDNode *, 32> &Visited) {
4414 if (found || !Visited.insert(N))
4417 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4418 SDNode *Op = N->getOperand(i).Val;
4423 findPredecessor(Op, P, found, Visited);
4427 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4428 /// is either an operand of N or it can be reached by recursively traversing
4429 /// up the operands.
4430 /// NOTE: this is an expensive method. Use it carefully.
4431 bool SDNode::isPredecessorOf(SDNode *N) const {
4432 SmallPtrSet<SDNode *, 32> Visited;
4434 findPredecessor(N, this, found, Visited);
4438 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4439 assert(Num < NumOperands && "Invalid child # of SDNode!");
4440 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4443 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4444 switch (getOpcode()) {
4446 if (getOpcode() < ISD::BUILTIN_OP_END)
4447 return "<<Unknown DAG Node>>";
4450 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4451 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4452 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4454 TargetLowering &TLI = G->getTargetLoweringInfo();
4456 TLI.getTargetNodeName(getOpcode());
4457 if (Name) return Name;
4460 return "<<Unknown Target Node>>";
4463 case ISD::PREFETCH: return "Prefetch";
4464 case ISD::MEMBARRIER: return "MemBarrier";
4465 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4466 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4467 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4468 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4469 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4470 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4471 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4472 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4473 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4474 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4475 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4476 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4477 case ISD::PCMARKER: return "PCMarker";
4478 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4479 case ISD::SRCVALUE: return "SrcValue";
4480 case ISD::MEMOPERAND: return "MemOperand";
4481 case ISD::EntryToken: return "EntryToken";
4482 case ISD::TokenFactor: return "TokenFactor";
4483 case ISD::AssertSext: return "AssertSext";
4484 case ISD::AssertZext: return "AssertZext";
4486 case ISD::BasicBlock: return "BasicBlock";
4487 case ISD::ARG_FLAGS: return "ArgFlags";
4488 case ISD::VALUETYPE: return "ValueType";
4489 case ISD::Register: return "Register";
4491 case ISD::Constant: return "Constant";
4492 case ISD::ConstantFP: return "ConstantFP";
4493 case ISD::GlobalAddress: return "GlobalAddress";
4494 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4495 case ISD::FrameIndex: return "FrameIndex";
4496 case ISD::JumpTable: return "JumpTable";
4497 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4498 case ISD::RETURNADDR: return "RETURNADDR";
4499 case ISD::FRAMEADDR: return "FRAMEADDR";
4500 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4501 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4502 case ISD::EHSELECTION: return "EHSELECTION";
4503 case ISD::EH_RETURN: return "EH_RETURN";
4504 case ISD::ConstantPool: return "ConstantPool";
4505 case ISD::ExternalSymbol: return "ExternalSymbol";
4506 case ISD::INTRINSIC_WO_CHAIN: {
4507 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4508 return Intrinsic::getName((Intrinsic::ID)IID);
4510 case ISD::INTRINSIC_VOID:
4511 case ISD::INTRINSIC_W_CHAIN: {
4512 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4513 return Intrinsic::getName((Intrinsic::ID)IID);
4516 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4517 case ISD::TargetConstant: return "TargetConstant";
4518 case ISD::TargetConstantFP:return "TargetConstantFP";
4519 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4520 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4521 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4522 case ISD::TargetJumpTable: return "TargetJumpTable";
4523 case ISD::TargetConstantPool: return "TargetConstantPool";
4524 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4526 case ISD::CopyToReg: return "CopyToReg";
4527 case ISD::CopyFromReg: return "CopyFromReg";
4528 case ISD::UNDEF: return "undef";
4529 case ISD::MERGE_VALUES: return "merge_values";
4530 case ISD::INLINEASM: return "inlineasm";
4531 case ISD::DBG_LABEL: return "dbg_label";
4532 case ISD::EH_LABEL: return "eh_label";
4533 case ISD::DECLARE: return "declare";
4534 case ISD::HANDLENODE: return "handlenode";
4535 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4536 case ISD::CALL: return "call";
4539 case ISD::FABS: return "fabs";
4540 case ISD::FNEG: return "fneg";
4541 case ISD::FSQRT: return "fsqrt";
4542 case ISD::FSIN: return "fsin";
4543 case ISD::FCOS: return "fcos";
4544 case ISD::FPOWI: return "fpowi";
4545 case ISD::FPOW: return "fpow";
4548 case ISD::ADD: return "add";
4549 case ISD::SUB: return "sub";
4550 case ISD::MUL: return "mul";
4551 case ISD::MULHU: return "mulhu";
4552 case ISD::MULHS: return "mulhs";
4553 case ISD::SDIV: return "sdiv";
4554 case ISD::UDIV: return "udiv";
4555 case ISD::SREM: return "srem";
4556 case ISD::UREM: return "urem";
4557 case ISD::SMUL_LOHI: return "smul_lohi";
4558 case ISD::UMUL_LOHI: return "umul_lohi";
4559 case ISD::SDIVREM: return "sdivrem";
4560 case ISD::UDIVREM: return "divrem";
4561 case ISD::AND: return "and";
4562 case ISD::OR: return "or";
4563 case ISD::XOR: return "xor";
4564 case ISD::SHL: return "shl";
4565 case ISD::SRA: return "sra";
4566 case ISD::SRL: return "srl";
4567 case ISD::ROTL: return "rotl";
4568 case ISD::ROTR: return "rotr";
4569 case ISD::FADD: return "fadd";
4570 case ISD::FSUB: return "fsub";
4571 case ISD::FMUL: return "fmul";
4572 case ISD::FDIV: return "fdiv";
4573 case ISD::FREM: return "frem";
4574 case ISD::FCOPYSIGN: return "fcopysign";
4575 case ISD::FGETSIGN: return "fgetsign";
4577 case ISD::SETCC: return "setcc";
4578 case ISD::VSETCC: return "vsetcc";
4579 case ISD::SELECT: return "select";
4580 case ISD::SELECT_CC: return "select_cc";
4581 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4582 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4583 case ISD::CONCAT_VECTORS: return "concat_vectors";
4584 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4585 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4586 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4587 case ISD::CARRY_FALSE: return "carry_false";
4588 case ISD::ADDC: return "addc";
4589 case ISD::ADDE: return "adde";
4590 case ISD::SUBC: return "subc";
4591 case ISD::SUBE: return "sube";
4592 case ISD::SHL_PARTS: return "shl_parts";
4593 case ISD::SRA_PARTS: return "sra_parts";
4594 case ISD::SRL_PARTS: return "srl_parts";
4596 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4597 case ISD::INSERT_SUBREG: return "insert_subreg";
4599 // Conversion operators.
4600 case ISD::SIGN_EXTEND: return "sign_extend";
4601 case ISD::ZERO_EXTEND: return "zero_extend";
4602 case ISD::ANY_EXTEND: return "any_extend";
4603 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4604 case ISD::TRUNCATE: return "truncate";
4605 case ISD::FP_ROUND: return "fp_round";
4606 case ISD::FLT_ROUNDS_: return "flt_rounds";
4607 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4608 case ISD::FP_EXTEND: return "fp_extend";
4610 case ISD::SINT_TO_FP: return "sint_to_fp";
4611 case ISD::UINT_TO_FP: return "uint_to_fp";
4612 case ISD::FP_TO_SINT: return "fp_to_sint";
4613 case ISD::FP_TO_UINT: return "fp_to_uint";
4614 case ISD::BIT_CONVERT: return "bit_convert";
4616 // Control flow instructions
4617 case ISD::BR: return "br";
4618 case ISD::BRIND: return "brind";
4619 case ISD::BR_JT: return "br_jt";
4620 case ISD::BRCOND: return "brcond";
4621 case ISD::BR_CC: return "br_cc";
4622 case ISD::RET: return "ret";
4623 case ISD::CALLSEQ_START: return "callseq_start";
4624 case ISD::CALLSEQ_END: return "callseq_end";
4627 case ISD::LOAD: return "load";
4628 case ISD::STORE: return "store";
4629 case ISD::VAARG: return "vaarg";
4630 case ISD::VACOPY: return "vacopy";
4631 case ISD::VAEND: return "vaend";
4632 case ISD::VASTART: return "vastart";
4633 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4634 case ISD::EXTRACT_ELEMENT: return "extract_element";
4635 case ISD::BUILD_PAIR: return "build_pair";
4636 case ISD::STACKSAVE: return "stacksave";
4637 case ISD::STACKRESTORE: return "stackrestore";
4638 case ISD::TRAP: return "trap";
4641 case ISD::BSWAP: return "bswap";
4642 case ISD::CTPOP: return "ctpop";
4643 case ISD::CTTZ: return "cttz";
4644 case ISD::CTLZ: return "ctlz";
4647 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4648 case ISD::DEBUG_LOC: return "debug_loc";
4651 case ISD::TRAMPOLINE: return "trampoline";
4654 switch (cast<CondCodeSDNode>(this)->get()) {
4655 default: assert(0 && "Unknown setcc condition!");
4656 case ISD::SETOEQ: return "setoeq";
4657 case ISD::SETOGT: return "setogt";
4658 case ISD::SETOGE: return "setoge";
4659 case ISD::SETOLT: return "setolt";
4660 case ISD::SETOLE: return "setole";
4661 case ISD::SETONE: return "setone";
4663 case ISD::SETO: return "seto";
4664 case ISD::SETUO: return "setuo";
4665 case ISD::SETUEQ: return "setue";
4666 case ISD::SETUGT: return "setugt";
4667 case ISD::SETUGE: return "setuge";
4668 case ISD::SETULT: return "setult";
4669 case ISD::SETULE: return "setule";
4670 case ISD::SETUNE: return "setune";
4672 case ISD::SETEQ: return "seteq";
4673 case ISD::SETGT: return "setgt";
4674 case ISD::SETGE: return "setge";
4675 case ISD::SETLT: return "setlt";
4676 case ISD::SETLE: return "setle";
4677 case ISD::SETNE: return "setne";
4682 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4691 return "<post-inc>";
4693 return "<post-dec>";
4697 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4698 std::string S = "< ";
4712 if (getByValAlign())
4713 S += "byval-align:" + utostr(getByValAlign()) + " ";
4715 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4717 S += "byval-size:" + utostr(getByValSize()) + " ";
4721 void SDNode::dump() const { dump(0); }
4722 void SDNode::dump(const SelectionDAG *G) const {
4723 cerr << (void*)this << ": ";
4725 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4727 if (getValueType(i) == MVT::Other)
4730 cerr << getValueType(i).getMVTString();
4732 cerr << " = " << getOperationName(G);
4735 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4736 if (i) cerr << ", ";
4737 cerr << (void*)getOperand(i).Val;
4738 if (unsigned RN = getOperand(i).ResNo)
4742 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4743 SDNode *Mask = getOperand(2).Val;
4745 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4747 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4750 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4755 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4756 cerr << "<" << CSDN->getValue() << ">";
4757 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4758 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4759 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4760 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4761 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4763 cerr << "<APFloat(";
4764 CSDN->getValueAPF().convertToAPInt().dump();
4767 } else if (const GlobalAddressSDNode *GADN =
4768 dyn_cast<GlobalAddressSDNode>(this)) {
4769 int offset = GADN->getOffset();
4771 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4773 cerr << " + " << offset;
4775 cerr << " " << offset;
4776 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4777 cerr << "<" << FIDN->getIndex() << ">";
4778 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4779 cerr << "<" << JTDN->getIndex() << ">";
4780 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4781 int offset = CP->getOffset();
4782 if (CP->isMachineConstantPoolEntry())
4783 cerr << "<" << *CP->getMachineCPVal() << ">";
4785 cerr << "<" << *CP->getConstVal() << ">";
4787 cerr << " + " << offset;
4789 cerr << " " << offset;
4790 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4792 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4794 cerr << LBB->getName() << " ";
4795 cerr << (const void*)BBDN->getBasicBlock() << ">";
4796 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4797 if (G && R->getReg() &&
4798 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4799 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4801 cerr << " #" << R->getReg();
4803 } else if (const ExternalSymbolSDNode *ES =
4804 dyn_cast<ExternalSymbolSDNode>(this)) {
4805 cerr << "'" << ES->getSymbol() << "'";
4806 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4808 cerr << "<" << M->getValue() << ">";
4811 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4812 if (M->MO.getValue())
4813 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4815 cerr << "<null:" << M->MO.getOffset() << ">";
4816 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4817 cerr << N->getArgFlags().getArgFlagsString();
4818 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4819 cerr << ":" << N->getVT().getMVTString();
4821 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4822 const Value *SrcValue = LD->getSrcValue();
4823 int SrcOffset = LD->getSrcValueOffset();
4829 cerr << ":" << SrcOffset << ">";
4832 switch (LD->getExtensionType()) {
4833 default: doExt = false; break;
4835 cerr << " <anyext ";
4845 cerr << LD->getMemoryVT().getMVTString() << ">";
4847 const char *AM = getIndexedModeName(LD->getAddressingMode());
4850 if (LD->isVolatile())
4851 cerr << " <volatile>";
4852 cerr << " alignment=" << LD->getAlignment();
4853 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4854 const Value *SrcValue = ST->getSrcValue();
4855 int SrcOffset = ST->getSrcValueOffset();
4861 cerr << ":" << SrcOffset << ">";
4863 if (ST->isTruncatingStore())
4865 << ST->getMemoryVT().getMVTString() << ">";
4867 const char *AM = getIndexedModeName(ST->getAddressingMode());
4870 if (ST->isVolatile())
4871 cerr << " <volatile>";
4872 cerr << " alignment=" << ST->getAlignment();
4873 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4874 const Value *SrcValue = AT->getSrcValue();
4875 int SrcOffset = AT->getSrcValueOffset();
4881 cerr << ":" << SrcOffset << ">";
4882 if (AT->isVolatile())
4883 cerr << " <volatile>";
4884 cerr << " alignment=" << AT->getAlignment();
4888 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4889 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4890 if (N->getOperand(i).Val->hasOneUse())
4891 DumpNodes(N->getOperand(i).Val, indent+2, G);
4893 cerr << "\n" << std::string(indent+2, ' ')
4894 << (void*)N->getOperand(i).Val << ": <multiple use>";
4897 cerr << "\n" << std::string(indent, ' ');
4901 void SelectionDAG::dump() const {
4902 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4903 std::vector<const SDNode*> Nodes;
4904 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4908 std::sort(Nodes.begin(), Nodes.end());
4910 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4911 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4912 DumpNodes(Nodes[i], 2, this);
4915 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4920 const Type *ConstantPoolSDNode::getType() const {
4921 if (isMachineConstantPoolEntry())
4922 return Val.MachineCPVal->getType();
4923 return Val.ConstVal->getType();