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::LABEL or TargetInstrInfo::LABEL node and third operand
197 bool ISD::isDebugLabel(const SDNode *N) {
199 if (N->getOpcode() == ISD::LABEL)
200 Zero = N->getOperand(2);
201 else if (N->isTargetOpcode() &&
202 N->getTargetOpcode() == TargetInstrInfo::LABEL)
203 // Chain moved to last operand.
204 Zero = N->getOperand(1);
207 return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
210 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
211 /// when given the operation for (X op Y).
212 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
213 // To perform this operation, we just need to swap the L and G bits of the
215 unsigned OldL = (Operation >> 2) & 1;
216 unsigned OldG = (Operation >> 1) & 1;
217 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
218 (OldL << 1) | // New G bit
219 (OldG << 2)); // New L bit.
222 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
223 /// 'op' is a valid SetCC operation.
224 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
225 unsigned Operation = Op;
227 Operation ^= 7; // Flip L, G, E bits, but not U.
229 Operation ^= 15; // Flip all of the condition bits.
230 if (Operation > ISD::SETTRUE2)
231 Operation &= ~8; // Don't let N and U bits get set.
232 return ISD::CondCode(Operation);
236 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
237 /// signed operation and 2 if the result is an unsigned comparison. Return zero
238 /// if the operation does not depend on the sign of the input (setne and seteq).
239 static int isSignedOp(ISD::CondCode Opcode) {
241 default: assert(0 && "Illegal integer setcc operation!");
243 case ISD::SETNE: return 0;
247 case ISD::SETGE: return 1;
251 case ISD::SETUGE: return 2;
255 /// getSetCCOrOperation - Return the result of a logical OR between different
256 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
257 /// returns SETCC_INVALID if it is not possible to represent the resultant
259 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
261 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
262 // Cannot fold a signed integer setcc with an unsigned integer setcc.
263 return ISD::SETCC_INVALID;
265 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
267 // If the N and U bits get set then the resultant comparison DOES suddenly
268 // care about orderedness, and is true when ordered.
269 if (Op > ISD::SETTRUE2)
270 Op &= ~16; // Clear the U bit if the N bit is set.
272 // Canonicalize illegal integer setcc's.
273 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
276 return ISD::CondCode(Op);
279 /// getSetCCAndOperation - Return the result of a logical AND between different
280 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
281 /// function returns zero if it is not possible to represent the resultant
283 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
285 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
286 // Cannot fold a signed setcc with an unsigned setcc.
287 return ISD::SETCC_INVALID;
289 // Combine all of the condition bits.
290 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
292 // Canonicalize illegal integer setcc's.
296 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
297 case ISD::SETOEQ: // SETEQ & SETU[LG]E
298 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
299 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
300 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
307 const TargetMachine &SelectionDAG::getTarget() const {
308 return TLI.getTargetMachine();
311 //===----------------------------------------------------------------------===//
312 // SDNode Profile Support
313 //===----------------------------------------------------------------------===//
315 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
317 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
321 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
322 /// solely with their pointer.
323 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
324 ID.AddPointer(VTList.VTs);
327 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
329 static void AddNodeIDOperands(FoldingSetNodeID &ID,
330 SDOperandPtr Ops, unsigned NumOps) {
331 for (; NumOps; --NumOps, ++Ops) {
332 ID.AddPointer(Ops->Val);
333 ID.AddInteger(Ops->ResNo);
337 static void AddNodeIDNode(FoldingSetNodeID &ID,
338 unsigned short OpC, SDVTList VTList,
339 SDOperandPtr OpList, unsigned N) {
340 AddNodeIDOpcode(ID, OpC);
341 AddNodeIDValueTypes(ID, VTList);
342 AddNodeIDOperands(ID, OpList, N);
346 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
348 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
349 AddNodeIDOpcode(ID, N->getOpcode());
350 // Add the return value info.
351 AddNodeIDValueTypes(ID, N->getVTList());
352 // Add the operand info.
353 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
355 // Handle SDNode leafs with special info.
356 switch (N->getOpcode()) {
357 default: break; // Normal nodes don't need extra info.
359 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
361 case ISD::TargetConstant:
363 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
365 case ISD::TargetConstantFP:
366 case ISD::ConstantFP: {
367 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
370 case ISD::TargetGlobalAddress:
371 case ISD::GlobalAddress:
372 case ISD::TargetGlobalTLSAddress:
373 case ISD::GlobalTLSAddress: {
374 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
375 ID.AddPointer(GA->getGlobal());
376 ID.AddInteger(GA->getOffset());
379 case ISD::BasicBlock:
380 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
383 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
385 case ISD::DBG_STOPPOINT: {
386 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
387 ID.AddInteger(DSP->getLine());
388 ID.AddInteger(DSP->getColumn());
389 ID.AddPointer(DSP->getCompileUnit());
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.
530 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
531 SDNode *Operand = I->getVal();
532 Operand->removeUser(std::distance(N->op_begin(), I), N);
534 // Now that we removed this operand, see if there are no uses of it left.
535 if (Operand->use_empty())
536 DeadNodes.push_back(Operand);
538 if (N->OperandsNeedDelete) {
539 delete[] N->OperandList;
544 // Finally, remove N itself.
549 void SelectionDAG::DeleteNode(SDNode *N) {
550 assert(N->use_empty() && "Cannot delete a node that is not dead!");
552 // First take this out of the appropriate CSE map.
553 RemoveNodeFromCSEMaps(N);
555 // Finally, remove uses due to operands of this node, remove from the
556 // AllNodes list, and delete the node.
557 DeleteNodeNotInCSEMaps(N);
560 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
562 // Remove it from the AllNodes list.
565 // Drop all of the operands and decrement used nodes use counts.
566 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
567 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
568 if (N->OperandsNeedDelete) {
569 delete[] N->OperandList;
577 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
578 /// correspond to it. This is useful when we're about to delete or repurpose
579 /// the node. We don't want future request for structurally identical nodes
580 /// to return N anymore.
581 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
583 switch (N->getOpcode()) {
584 case ISD::HANDLENODE: return; // noop.
586 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
587 "Cond code doesn't exist!");
588 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
589 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
591 case ISD::ExternalSymbol:
592 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
594 case ISD::TargetExternalSymbol:
596 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
598 case ISD::VALUETYPE: {
599 MVT VT = cast<VTSDNode>(N)->getVT();
600 if (VT.isExtended()) {
601 Erased = ExtendedValueTypeNodes.erase(VT);
603 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
604 ValueTypeNodes[VT.getSimpleVT()] = 0;
609 // Remove it from the CSE Map.
610 Erased = CSEMap.RemoveNode(N);
614 // Verify that the node was actually in one of the CSE maps, unless it has a
615 // flag result (which cannot be CSE'd) or is one of the special cases that are
616 // not subject to CSE.
617 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
618 !N->isTargetOpcode()) {
621 assert(0 && "Node is not in map!");
626 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
627 /// has been taken out and modified in some way. If the specified node already
628 /// exists in the CSE maps, do not modify the maps, but return the existing node
629 /// instead. If it doesn't exist, add it and return null.
631 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
632 assert(N->getNumOperands() && "This is a leaf node!");
633 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
634 return 0; // Never add these nodes.
636 // Check that remaining values produced are not flags.
637 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
638 if (N->getValueType(i) == MVT::Flag)
639 return 0; // Never CSE anything that produces a flag.
641 SDNode *New = CSEMap.GetOrInsertNode(N);
642 if (New != N) return New; // Node already existed.
646 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
647 /// were replaced with those specified. If this node is never memoized,
648 /// return null, otherwise return a pointer to the slot it would take. If a
649 /// node already exists with these operands, the slot will be non-null.
650 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
652 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
653 return 0; // Never add these nodes.
655 // Check that remaining values produced are not flags.
656 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
657 if (N->getValueType(i) == MVT::Flag)
658 return 0; // Never CSE anything that produces a flag.
660 SDOperand Ops[] = { Op };
662 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
663 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
666 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
667 /// were replaced with those specified. If this node is never memoized,
668 /// return null, otherwise return a pointer to the slot it would take. If a
669 /// node already exists with these operands, the slot will be non-null.
670 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
671 SDOperand Op1, SDOperand Op2,
673 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
674 return 0; // Never add these nodes.
676 // Check that remaining values produced are not flags.
677 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
678 if (N->getValueType(i) == MVT::Flag)
679 return 0; // Never CSE anything that produces a flag.
681 SDOperand Ops[] = { Op1, Op2 };
683 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
684 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
688 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
689 /// were replaced with those specified. If this node is never memoized,
690 /// return null, otherwise return a pointer to the slot it would take. If a
691 /// node already exists with these operands, the slot will be non-null.
692 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
693 SDOperandPtr Ops,unsigned NumOps,
695 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
696 return 0; // Never add these nodes.
698 // Check that remaining values produced are not flags.
699 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
700 if (N->getValueType(i) == MVT::Flag)
701 return 0; // Never CSE anything that produces a flag.
704 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
706 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
707 ID.AddInteger(LD->getAddressingMode());
708 ID.AddInteger(LD->getExtensionType());
709 ID.AddInteger(LD->getMemoryVT().getRawBits());
710 ID.AddInteger(LD->getAlignment());
711 ID.AddInteger(LD->isVolatile());
712 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
713 ID.AddInteger(ST->getAddressingMode());
714 ID.AddInteger(ST->isTruncatingStore());
715 ID.AddInteger(ST->getMemoryVT().getRawBits());
716 ID.AddInteger(ST->getAlignment());
717 ID.AddInteger(ST->isVolatile());
720 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
724 SelectionDAG::~SelectionDAG() {
725 while (!AllNodes.empty()) {
726 SDNode *N = AllNodes.begin();
727 N->SetNextInBucket(0);
728 if (N->OperandsNeedDelete) {
729 delete [] N->OperandList;
733 AllNodes.pop_front();
737 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
738 if (Op.getValueType() == VT) return Op;
739 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
741 return getNode(ISD::AND, Op.getValueType(), Op,
742 getConstant(Imm, Op.getValueType()));
745 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
746 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
747 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
750 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
751 assert(VT.isInteger() && "Cannot create FP integer constant!");
753 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
754 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
755 "APInt size does not match type size!");
757 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
759 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
763 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
765 return SDOperand(N, 0);
767 N = new ConstantSDNode(isT, Val, EltVT);
768 CSEMap.InsertNode(N, IP);
769 AllNodes.push_back(N);
772 SDOperand Result(N, 0);
774 SmallVector<SDOperand, 8> Ops;
775 Ops.assign(VT.getVectorNumElements(), Result);
776 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
781 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
782 return getConstant(Val, TLI.getPointerTy(), isTarget);
786 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
787 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
790 VT.isVector() ? VT.getVectorElementType() : VT;
792 // Do the map lookup using the actual bit pattern for the floating point
793 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
794 // we don't have issues with SNANs.
795 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
797 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
801 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
803 return SDOperand(N, 0);
805 N = new ConstantFPSDNode(isTarget, V, EltVT);
806 CSEMap.InsertNode(N, IP);
807 AllNodes.push_back(N);
810 SDOperand Result(N, 0);
812 SmallVector<SDOperand, 8> Ops;
813 Ops.assign(VT.getVectorNumElements(), Result);
814 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
819 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
821 VT.isVector() ? VT.getVectorElementType() : VT;
823 return getConstantFP(APFloat((float)Val), VT, isTarget);
825 return getConstantFP(APFloat(Val), VT, isTarget);
828 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
833 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
835 // If GV is an alias then use the aliasee for determining thread-localness.
836 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
837 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
840 if (GVar && GVar->isThreadLocal())
841 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
843 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
846 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
848 ID.AddInteger(Offset);
850 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
851 return SDOperand(E, 0);
852 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
853 CSEMap.InsertNode(N, IP);
854 AllNodes.push_back(N);
855 return SDOperand(N, 0);
858 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
859 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
861 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
864 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
865 return SDOperand(E, 0);
866 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
867 CSEMap.InsertNode(N, IP);
868 AllNodes.push_back(N);
869 return SDOperand(N, 0);
872 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
873 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
875 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
878 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
879 return SDOperand(E, 0);
880 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
881 CSEMap.InsertNode(N, IP);
882 AllNodes.push_back(N);
883 return SDOperand(N, 0);
886 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
887 unsigned Alignment, int Offset,
889 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
891 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
892 ID.AddInteger(Alignment);
893 ID.AddInteger(Offset);
896 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
897 return SDOperand(E, 0);
898 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
899 CSEMap.InsertNode(N, IP);
900 AllNodes.push_back(N);
901 return SDOperand(N, 0);
905 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
906 unsigned Alignment, int Offset,
908 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
910 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
911 ID.AddInteger(Alignment);
912 ID.AddInteger(Offset);
913 C->AddSelectionDAGCSEId(ID);
915 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
916 return SDOperand(E, 0);
917 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
918 CSEMap.InsertNode(N, IP);
919 AllNodes.push_back(N);
920 return SDOperand(N, 0);
924 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
926 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), (SDOperand*)0, 0);
929 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
930 return SDOperand(E, 0);
931 SDNode *N = new BasicBlockSDNode(MBB);
932 CSEMap.InsertNode(N, IP);
933 AllNodes.push_back(N);
934 return SDOperand(N, 0);
937 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
939 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), (SDOperand*)0, 0);
940 ID.AddInteger(Flags.getRawBits());
942 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
943 return SDOperand(E, 0);
944 SDNode *N = new ARG_FLAGSSDNode(Flags);
945 CSEMap.InsertNode(N, IP);
946 AllNodes.push_back(N);
947 return SDOperand(N, 0);
950 SDOperand SelectionDAG::getValueType(MVT VT) {
951 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
952 ValueTypeNodes.resize(VT.getSimpleVT()+1);
954 SDNode *&N = VT.isExtended() ?
955 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
957 if (N) return SDOperand(N, 0);
958 N = new VTSDNode(VT);
959 AllNodes.push_back(N);
960 return SDOperand(N, 0);
963 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
964 SDNode *&N = ExternalSymbols[Sym];
965 if (N) return SDOperand(N, 0);
966 N = new ExternalSymbolSDNode(false, Sym, VT);
967 AllNodes.push_back(N);
968 return SDOperand(N, 0);
971 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
972 SDNode *&N = TargetExternalSymbols[Sym];
973 if (N) return SDOperand(N, 0);
974 N = new ExternalSymbolSDNode(true, Sym, VT);
975 AllNodes.push_back(N);
976 return SDOperand(N, 0);
979 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
980 if ((unsigned)Cond >= CondCodeNodes.size())
981 CondCodeNodes.resize(Cond+1);
983 if (CondCodeNodes[Cond] == 0) {
984 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
985 AllNodes.push_back(CondCodeNodes[Cond]);
987 return SDOperand(CondCodeNodes[Cond], 0);
990 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
992 AddNodeIDNode(ID, ISD::Register, getVTList(VT), (SDOperand*)0, 0);
993 ID.AddInteger(RegNo);
995 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
996 return SDOperand(E, 0);
997 SDNode *N = new RegisterSDNode(RegNo, VT);
998 CSEMap.InsertNode(N, IP);
999 AllNodes.push_back(N);
1000 return SDOperand(N, 0);
1003 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1004 unsigned Line, unsigned Col,
1005 const CompileUnitDesc *CU) {
1006 FoldingSetNodeID ID;
1007 SDOperand Ops[] = { Root };
1008 AddNodeIDNode(ID, ISD::DBG_STOPPOINT, getVTList(MVT::Other), &Ops[0], 1);
1009 ID.AddInteger(Line);
1013 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1014 return SDOperand(E, 0);
1015 SDNode *N = new DbgStopPointSDNode(Root, Line, Col, CU);
1016 CSEMap.InsertNode(N, IP);
1017 AllNodes.push_back(N);
1018 return SDOperand(N, 0);
1021 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1022 assert((!V || isa<PointerType>(V->getType())) &&
1023 "SrcValue is not a pointer?");
1025 FoldingSetNodeID ID;
1026 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), (SDOperand*)0, 0);
1030 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1031 return SDOperand(E, 0);
1033 SDNode *N = new SrcValueSDNode(V);
1034 CSEMap.InsertNode(N, IP);
1035 AllNodes.push_back(N);
1036 return SDOperand(N, 0);
1039 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1040 const Value *v = MO.getValue();
1041 assert((!v || isa<PointerType>(v->getType())) &&
1042 "SrcValue is not a pointer?");
1044 FoldingSetNodeID ID;
1045 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), (SDOperand*)0, 0);
1047 ID.AddInteger(MO.getFlags());
1048 ID.AddInteger(MO.getOffset());
1049 ID.AddInteger(MO.getSize());
1050 ID.AddInteger(MO.getAlignment());
1053 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1054 return SDOperand(E, 0);
1056 SDNode *N = new MemOperandSDNode(MO);
1057 CSEMap.InsertNode(N, IP);
1058 AllNodes.push_back(N);
1059 return SDOperand(N, 0);
1062 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1063 /// specified value type.
1064 SDOperand SelectionDAG::CreateStackTemporary(MVT VT) {
1065 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1066 unsigned ByteSize = VT.getSizeInBits()/8;
1067 const Type *Ty = VT.getTypeForMVT();
1068 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
1069 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1070 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1074 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1075 SDOperand N2, ISD::CondCode Cond) {
1076 // These setcc operations always fold.
1080 case ISD::SETFALSE2: return getConstant(0, VT);
1082 case ISD::SETTRUE2: return getConstant(1, VT);
1094 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1098 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1099 const APInt &C2 = N2C->getAPIntValue();
1100 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1101 const APInt &C1 = N1C->getAPIntValue();
1104 default: assert(0 && "Unknown integer setcc!");
1105 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1106 case ISD::SETNE: return getConstant(C1 != C2, VT);
1107 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1108 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1109 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1110 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1111 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1112 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1113 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1114 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1118 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1119 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1120 // No compile time operations on this type yet.
1121 if (N1C->getValueType(0) == MVT::ppcf128)
1124 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1127 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1128 return getNode(ISD::UNDEF, VT);
1130 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1131 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1132 return getNode(ISD::UNDEF, VT);
1134 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1135 R==APFloat::cmpLessThan, VT);
1136 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1137 return getNode(ISD::UNDEF, VT);
1139 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1140 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1141 return getNode(ISD::UNDEF, VT);
1143 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1144 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1145 return getNode(ISD::UNDEF, VT);
1147 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1148 R==APFloat::cmpEqual, VT);
1149 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1150 return getNode(ISD::UNDEF, VT);
1152 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1153 R==APFloat::cmpEqual, VT);
1154 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1155 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1156 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1157 R==APFloat::cmpEqual, VT);
1158 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1159 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1160 R==APFloat::cmpLessThan, VT);
1161 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1162 R==APFloat::cmpUnordered, VT);
1163 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1164 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1167 // Ensure that the constant occurs on the RHS.
1168 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1172 // Could not fold it.
1176 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1177 /// use this predicate to simplify operations downstream.
1178 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1179 unsigned BitWidth = Op.getValueSizeInBits();
1180 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1183 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1184 /// this predicate to simplify operations downstream. Mask is known to be zero
1185 /// for bits that V cannot have.
1186 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1187 unsigned Depth) const {
1188 APInt KnownZero, KnownOne;
1189 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1190 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1191 return (KnownZero & Mask) == Mask;
1194 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1195 /// known to be either zero or one and return them in the KnownZero/KnownOne
1196 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1198 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1199 APInt &KnownZero, APInt &KnownOne,
1200 unsigned Depth) const {
1201 unsigned BitWidth = Mask.getBitWidth();
1202 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1203 "Mask size mismatches value type size!");
1205 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1206 if (Depth == 6 || Mask == 0)
1207 return; // Limit search depth.
1209 APInt KnownZero2, KnownOne2;
1211 switch (Op.getOpcode()) {
1213 // We know all of the bits for a constant!
1214 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1215 KnownZero = ~KnownOne & Mask;
1218 // If either the LHS or the RHS are Zero, the result is zero.
1219 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1220 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1221 KnownZero2, KnownOne2, Depth+1);
1222 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1223 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1225 // Output known-1 bits are only known if set in both the LHS & RHS.
1226 KnownOne &= KnownOne2;
1227 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1228 KnownZero |= KnownZero2;
1231 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1232 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1233 KnownZero2, KnownOne2, Depth+1);
1234 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1235 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1237 // Output known-0 bits are only known if clear in both the LHS & RHS.
1238 KnownZero &= KnownZero2;
1239 // Output known-1 are known to be set if set in either the LHS | RHS.
1240 KnownOne |= KnownOne2;
1243 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1244 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1245 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1246 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1248 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1249 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1250 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1251 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1252 KnownZero = KnownZeroOut;
1256 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1257 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1258 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1259 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1260 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1262 // If low bits are zero in either operand, output low known-0 bits.
1263 // Also compute a conserative estimate for high known-0 bits.
1264 // More trickiness is possible, but this is sufficient for the
1265 // interesting case of alignment computation.
1267 unsigned TrailZ = KnownZero.countTrailingOnes() +
1268 KnownZero2.countTrailingOnes();
1269 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1270 KnownZero2.countLeadingOnes(),
1271 BitWidth) - BitWidth;
1273 TrailZ = std::min(TrailZ, BitWidth);
1274 LeadZ = std::min(LeadZ, BitWidth);
1275 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1276 APInt::getHighBitsSet(BitWidth, LeadZ);
1281 // For the purposes of computing leading zeros we can conservatively
1282 // treat a udiv as a logical right shift by the power of 2 known to
1283 // be less than the denominator.
1284 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1285 ComputeMaskedBits(Op.getOperand(0),
1286 AllOnes, KnownZero2, KnownOne2, Depth+1);
1287 unsigned LeadZ = KnownZero2.countLeadingOnes();
1291 ComputeMaskedBits(Op.getOperand(1),
1292 AllOnes, KnownZero2, KnownOne2, Depth+1);
1293 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1294 if (RHSUnknownLeadingOnes != BitWidth)
1295 LeadZ = std::min(BitWidth,
1296 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1298 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1302 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1303 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1304 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1305 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1307 // Only known if known in both the LHS and RHS.
1308 KnownOne &= KnownOne2;
1309 KnownZero &= KnownZero2;
1311 case ISD::SELECT_CC:
1312 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1313 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1314 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1315 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1317 // Only known if known in both the LHS and RHS.
1318 KnownOne &= KnownOne2;
1319 KnownZero &= KnownZero2;
1322 // If we know the result of a setcc has the top bits zero, use this info.
1323 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1325 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1328 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1329 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1330 unsigned ShAmt = SA->getValue();
1332 // If the shift count is an invalid immediate, don't do anything.
1333 if (ShAmt >= BitWidth)
1336 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1337 KnownZero, KnownOne, Depth+1);
1338 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1339 KnownZero <<= ShAmt;
1341 // low bits known zero.
1342 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1346 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1347 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1348 unsigned ShAmt = SA->getValue();
1350 // If the shift count is an invalid immediate, don't do anything.
1351 if (ShAmt >= BitWidth)
1354 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1355 KnownZero, KnownOne, Depth+1);
1356 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1357 KnownZero = KnownZero.lshr(ShAmt);
1358 KnownOne = KnownOne.lshr(ShAmt);
1360 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1361 KnownZero |= HighBits; // High bits known zero.
1365 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1366 unsigned ShAmt = SA->getValue();
1368 // If the shift count is an invalid immediate, don't do anything.
1369 if (ShAmt >= BitWidth)
1372 APInt InDemandedMask = (Mask << ShAmt);
1373 // If any of the demanded bits are produced by the sign extension, we also
1374 // demand the input sign bit.
1375 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1376 if (HighBits.getBoolValue())
1377 InDemandedMask |= APInt::getSignBit(BitWidth);
1379 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1381 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1382 KnownZero = KnownZero.lshr(ShAmt);
1383 KnownOne = KnownOne.lshr(ShAmt);
1385 // Handle the sign bits.
1386 APInt SignBit = APInt::getSignBit(BitWidth);
1387 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1389 if (KnownZero.intersects(SignBit)) {
1390 KnownZero |= HighBits; // New bits are known zero.
1391 } else if (KnownOne.intersects(SignBit)) {
1392 KnownOne |= HighBits; // New bits are known one.
1396 case ISD::SIGN_EXTEND_INREG: {
1397 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1398 unsigned EBits = EVT.getSizeInBits();
1400 // Sign extension. Compute the demanded bits in the result that are not
1401 // present in the input.
1402 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1404 APInt InSignBit = APInt::getSignBit(EBits);
1405 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1407 // If the sign extended bits are demanded, we know that the sign
1409 InSignBit.zext(BitWidth);
1410 if (NewBits.getBoolValue())
1411 InputDemandedBits |= InSignBit;
1413 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1414 KnownZero, KnownOne, Depth+1);
1415 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1417 // If the sign bit of the input is known set or clear, then we know the
1418 // top bits of the result.
1419 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1420 KnownZero |= NewBits;
1421 KnownOne &= ~NewBits;
1422 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1423 KnownOne |= NewBits;
1424 KnownZero &= ~NewBits;
1425 } else { // Input sign bit unknown
1426 KnownZero &= ~NewBits;
1427 KnownOne &= ~NewBits;
1434 unsigned LowBits = Log2_32(BitWidth)+1;
1435 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1440 if (ISD::isZEXTLoad(Op.Val)) {
1441 LoadSDNode *LD = cast<LoadSDNode>(Op);
1442 MVT VT = LD->getMemoryVT();
1443 unsigned MemBits = VT.getSizeInBits();
1444 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1448 case ISD::ZERO_EXTEND: {
1449 MVT InVT = Op.getOperand(0).getValueType();
1450 unsigned InBits = InVT.getSizeInBits();
1451 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1452 APInt InMask = Mask;
1453 InMask.trunc(InBits);
1454 KnownZero.trunc(InBits);
1455 KnownOne.trunc(InBits);
1456 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1457 KnownZero.zext(BitWidth);
1458 KnownOne.zext(BitWidth);
1459 KnownZero |= NewBits;
1462 case ISD::SIGN_EXTEND: {
1463 MVT InVT = Op.getOperand(0).getValueType();
1464 unsigned InBits = InVT.getSizeInBits();
1465 APInt InSignBit = APInt::getSignBit(InBits);
1466 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1467 APInt InMask = Mask;
1468 InMask.trunc(InBits);
1470 // If any of the sign extended bits are demanded, we know that the sign
1471 // bit is demanded. Temporarily set this bit in the mask for our callee.
1472 if (NewBits.getBoolValue())
1473 InMask |= InSignBit;
1475 KnownZero.trunc(InBits);
1476 KnownOne.trunc(InBits);
1477 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1479 // Note if the sign bit is known to be zero or one.
1480 bool SignBitKnownZero = KnownZero.isNegative();
1481 bool SignBitKnownOne = KnownOne.isNegative();
1482 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1483 "Sign bit can't be known to be both zero and one!");
1485 // If the sign bit wasn't actually demanded by our caller, we don't
1486 // want it set in the KnownZero and KnownOne result values. Reset the
1487 // mask and reapply it to the result values.
1489 InMask.trunc(InBits);
1490 KnownZero &= InMask;
1493 KnownZero.zext(BitWidth);
1494 KnownOne.zext(BitWidth);
1496 // If the sign bit is known zero or one, the top bits match.
1497 if (SignBitKnownZero)
1498 KnownZero |= NewBits;
1499 else if (SignBitKnownOne)
1500 KnownOne |= NewBits;
1503 case ISD::ANY_EXTEND: {
1504 MVT InVT = Op.getOperand(0).getValueType();
1505 unsigned InBits = InVT.getSizeInBits();
1506 APInt InMask = Mask;
1507 InMask.trunc(InBits);
1508 KnownZero.trunc(InBits);
1509 KnownOne.trunc(InBits);
1510 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1511 KnownZero.zext(BitWidth);
1512 KnownOne.zext(BitWidth);
1515 case ISD::TRUNCATE: {
1516 MVT InVT = Op.getOperand(0).getValueType();
1517 unsigned InBits = InVT.getSizeInBits();
1518 APInt InMask = Mask;
1519 InMask.zext(InBits);
1520 KnownZero.zext(InBits);
1521 KnownOne.zext(InBits);
1522 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1523 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1524 KnownZero.trunc(BitWidth);
1525 KnownOne.trunc(BitWidth);
1528 case ISD::AssertZext: {
1529 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1530 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1531 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1533 KnownZero |= (~InMask) & Mask;
1537 // All bits are zero except the low bit.
1538 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1542 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1543 // We know that the top bits of C-X are clear if X contains less bits
1544 // than C (i.e. no wrap-around can happen). For example, 20-X is
1545 // positive if we can prove that X is >= 0 and < 16.
1546 if (CLHS->getAPIntValue().isNonNegative()) {
1547 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1548 // NLZ can't be BitWidth with no sign bit
1549 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1550 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1553 // If all of the MaskV bits are known to be zero, then we know the
1554 // output top bits are zero, because we now know that the output is
1556 if ((KnownZero2 & MaskV) == MaskV) {
1557 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1558 // Top bits known zero.
1559 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1566 // Output known-0 bits are known if clear or set in both the low clear bits
1567 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1568 // low 3 bits clear.
1569 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1570 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1571 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1572 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1574 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1575 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1576 KnownZeroOut = std::min(KnownZeroOut,
1577 KnownZero2.countTrailingOnes());
1579 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1583 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1584 APInt RA = Rem->getAPIntValue();
1585 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1586 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1587 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1588 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1590 // The sign of a remainder is equal to the sign of the first
1591 // operand (zero being positive).
1592 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1593 KnownZero2 |= ~LowBits;
1594 else if (KnownOne2[BitWidth-1])
1595 KnownOne2 |= ~LowBits;
1597 KnownZero |= KnownZero2 & Mask;
1598 KnownOne |= KnownOne2 & Mask;
1600 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1605 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1606 APInt RA = Rem->getAPIntValue();
1607 if (RA.isPowerOf2()) {
1608 APInt LowBits = (RA - 1);
1609 APInt Mask2 = LowBits & Mask;
1610 KnownZero |= ~LowBits & Mask;
1611 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1612 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1617 // Since the result is less than or equal to either operand, any leading
1618 // zero bits in either operand must also exist in the result.
1619 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1620 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1622 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1625 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1626 KnownZero2.countLeadingOnes());
1628 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1632 // Allow the target to implement this method for its nodes.
1633 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1634 case ISD::INTRINSIC_WO_CHAIN:
1635 case ISD::INTRINSIC_W_CHAIN:
1636 case ISD::INTRINSIC_VOID:
1637 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1643 /// ComputeNumSignBits - Return the number of times the sign bit of the
1644 /// register is replicated into the other bits. We know that at least 1 bit
1645 /// is always equal to the sign bit (itself), but other cases can give us
1646 /// information. For example, immediately after an "SRA X, 2", we know that
1647 /// the top 3 bits are all equal to each other, so we return 3.
1648 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1649 MVT VT = Op.getValueType();
1650 assert(VT.isInteger() && "Invalid VT!");
1651 unsigned VTBits = VT.getSizeInBits();
1653 unsigned FirstAnswer = 1;
1656 return 1; // Limit search depth.
1658 switch (Op.getOpcode()) {
1660 case ISD::AssertSext:
1661 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1662 return VTBits-Tmp+1;
1663 case ISD::AssertZext:
1664 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1667 case ISD::Constant: {
1668 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1669 // If negative, return # leading ones.
1670 if (Val.isNegative())
1671 return Val.countLeadingOnes();
1673 // Return # leading zeros.
1674 return Val.countLeadingZeros();
1677 case ISD::SIGN_EXTEND:
1678 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1679 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1681 case ISD::SIGN_EXTEND_INREG:
1682 // Max of the input and what this extends.
1683 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1686 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1687 return std::max(Tmp, Tmp2);
1690 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1691 // SRA X, C -> adds C sign bits.
1692 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1693 Tmp += C->getValue();
1694 if (Tmp > VTBits) Tmp = VTBits;
1698 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1699 // shl destroys sign bits.
1700 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1701 if (C->getValue() >= VTBits || // Bad shift.
1702 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1703 return Tmp - C->getValue();
1708 case ISD::XOR: // NOT is handled here.
1709 // Logical binary ops preserve the number of sign bits at the worst.
1710 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1712 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1713 FirstAnswer = std::min(Tmp, Tmp2);
1714 // We computed what we know about the sign bits as our first
1715 // answer. Now proceed to the generic code that uses
1716 // ComputeMaskedBits, and pick whichever answer is better.
1721 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1722 if (Tmp == 1) return 1; // Early out.
1723 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1724 return std::min(Tmp, Tmp2);
1727 // If setcc returns 0/-1, all bits are sign bits.
1728 if (TLI.getSetCCResultContents() ==
1729 TargetLowering::ZeroOrNegativeOneSetCCResult)
1734 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1735 unsigned RotAmt = C->getValue() & (VTBits-1);
1737 // Handle rotate right by N like a rotate left by 32-N.
1738 if (Op.getOpcode() == ISD::ROTR)
1739 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1741 // If we aren't rotating out all of the known-in sign bits, return the
1742 // number that are left. This handles rotl(sext(x), 1) for example.
1743 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1744 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1748 // Add can have at most one carry bit. Thus we know that the output
1749 // is, at worst, one more bit than the inputs.
1750 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1751 if (Tmp == 1) return 1; // Early out.
1753 // Special case decrementing a value (ADD X, -1):
1754 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1755 if (CRHS->isAllOnesValue()) {
1756 APInt KnownZero, KnownOne;
1757 APInt Mask = APInt::getAllOnesValue(VTBits);
1758 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1760 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1762 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1765 // If we are subtracting one from a positive number, there is no carry
1766 // out of the result.
1767 if (KnownZero.isNegative())
1771 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1772 if (Tmp2 == 1) return 1;
1773 return std::min(Tmp, Tmp2)-1;
1777 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1778 if (Tmp2 == 1) return 1;
1781 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1782 if (CLHS->isNullValue()) {
1783 APInt KnownZero, KnownOne;
1784 APInt Mask = APInt::getAllOnesValue(VTBits);
1785 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1786 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1788 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1791 // If the input is known to be positive (the sign bit is known clear),
1792 // the output of the NEG has the same number of sign bits as the input.
1793 if (KnownZero.isNegative())
1796 // Otherwise, we treat this like a SUB.
1799 // Sub can have at most one carry bit. Thus we know that the output
1800 // is, at worst, one more bit than the inputs.
1801 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1802 if (Tmp == 1) return 1; // Early out.
1803 return std::min(Tmp, Tmp2)-1;
1806 // FIXME: it's tricky to do anything useful for this, but it is an important
1807 // case for targets like X86.
1811 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1812 if (Op.getOpcode() == ISD::LOAD) {
1813 LoadSDNode *LD = cast<LoadSDNode>(Op);
1814 unsigned ExtType = LD->getExtensionType();
1817 case ISD::SEXTLOAD: // '17' bits known
1818 Tmp = LD->getMemoryVT().getSizeInBits();
1819 return VTBits-Tmp+1;
1820 case ISD::ZEXTLOAD: // '16' bits known
1821 Tmp = LD->getMemoryVT().getSizeInBits();
1826 // Allow the target to implement this method for its nodes.
1827 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1828 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1829 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1830 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1831 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1832 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1835 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1836 // use this information.
1837 APInt KnownZero, KnownOne;
1838 APInt Mask = APInt::getAllOnesValue(VTBits);
1839 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1841 if (KnownZero.isNegative()) { // sign bit is 0
1843 } else if (KnownOne.isNegative()) { // sign bit is 1;
1850 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1851 // the number of identical bits in the top of the input value.
1853 Mask <<= Mask.getBitWidth()-VTBits;
1854 // Return # leading zeros. We use 'min' here in case Val was zero before
1855 // shifting. We don't want to return '64' as for an i32 "0".
1856 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1860 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1861 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1862 if (!GA) return false;
1863 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1864 if (!GV) return false;
1865 MachineModuleInfo *MMI = getMachineModuleInfo();
1866 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1870 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1871 /// element of the result of the vector shuffle.
1872 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1873 MVT VT = N->getValueType(0);
1874 SDOperand PermMask = N->getOperand(2);
1875 SDOperand Idx = PermMask.getOperand(i);
1876 if (Idx.getOpcode() == ISD::UNDEF)
1877 return getNode(ISD::UNDEF, VT.getVectorElementType());
1878 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1879 unsigned NumElems = PermMask.getNumOperands();
1880 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1883 if (V.getOpcode() == ISD::BIT_CONVERT) {
1884 V = V.getOperand(0);
1885 if (V.getValueType().getVectorNumElements() != NumElems)
1888 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1889 return (Index == 0) ? V.getOperand(0)
1890 : getNode(ISD::UNDEF, VT.getVectorElementType());
1891 if (V.getOpcode() == ISD::BUILD_VECTOR)
1892 return V.getOperand(Index);
1893 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1894 return getShuffleScalarElt(V.Val, Index);
1899 /// getNode - Gets or creates the specified node.
1901 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1902 FoldingSetNodeID ID;
1903 AddNodeIDNode(ID, Opcode, getVTList(VT), (SDOperand*)0, 0);
1905 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1906 return SDOperand(E, 0);
1907 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1908 CSEMap.InsertNode(N, IP);
1910 AllNodes.push_back(N);
1911 return SDOperand(N, 0);
1914 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1915 // Constant fold unary operations with an integer constant operand.
1916 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1917 const APInt &Val = C->getAPIntValue();
1918 unsigned BitWidth = VT.getSizeInBits();
1921 case ISD::SIGN_EXTEND:
1922 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1923 case ISD::ANY_EXTEND:
1924 case ISD::ZERO_EXTEND:
1926 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1927 case ISD::UINT_TO_FP:
1928 case ISD::SINT_TO_FP: {
1929 const uint64_t zero[] = {0, 0};
1930 // No compile time operations on this type.
1931 if (VT==MVT::ppcf128)
1933 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1934 (void)apf.convertFromAPInt(Val,
1935 Opcode==ISD::SINT_TO_FP,
1936 APFloat::rmNearestTiesToEven);
1937 return getConstantFP(apf, VT);
1939 case ISD::BIT_CONVERT:
1940 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1941 return getConstantFP(Val.bitsToFloat(), VT);
1942 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1943 return getConstantFP(Val.bitsToDouble(), VT);
1946 return getConstant(Val.byteSwap(), VT);
1948 return getConstant(Val.countPopulation(), VT);
1950 return getConstant(Val.countLeadingZeros(), VT);
1952 return getConstant(Val.countTrailingZeros(), VT);
1956 // Constant fold unary operations with a floating point constant operand.
1957 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1958 APFloat V = C->getValueAPF(); // make copy
1959 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1963 return getConstantFP(V, VT);
1966 return getConstantFP(V, VT);
1968 case ISD::FP_EXTEND:
1969 // This can return overflow, underflow, or inexact; we don't care.
1970 // FIXME need to be more flexible about rounding mode.
1971 (void)V.convert(*MVTToAPFloatSemantics(VT),
1972 APFloat::rmNearestTiesToEven);
1973 return getConstantFP(V, VT);
1974 case ISD::FP_TO_SINT:
1975 case ISD::FP_TO_UINT: {
1977 assert(integerPartWidth >= 64);
1978 // FIXME need to be more flexible about rounding mode.
1979 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1980 Opcode==ISD::FP_TO_SINT,
1981 APFloat::rmTowardZero);
1982 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1984 return getConstant(x, VT);
1986 case ISD::BIT_CONVERT:
1987 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1988 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1989 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1990 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1996 unsigned OpOpcode = Operand.Val->getOpcode();
1998 case ISD::TokenFactor:
1999 return Operand; // Factor of one node? No need.
2000 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2001 case ISD::FP_EXTEND:
2002 assert(VT.isFloatingPoint() &&
2003 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2004 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2005 if (Operand.getOpcode() == ISD::UNDEF)
2006 return getNode(ISD::UNDEF, VT);
2008 case ISD::SIGN_EXTEND:
2009 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2010 "Invalid SIGN_EXTEND!");
2011 if (Operand.getValueType() == VT) return Operand; // noop extension
2012 assert(Operand.getValueType().bitsLT(VT)
2013 && "Invalid sext node, dst < src!");
2014 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2015 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2017 case ISD::ZERO_EXTEND:
2018 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2019 "Invalid ZERO_EXTEND!");
2020 if (Operand.getValueType() == VT) return Operand; // noop extension
2021 assert(Operand.getValueType().bitsLT(VT)
2022 && "Invalid zext node, dst < src!");
2023 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2024 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2026 case ISD::ANY_EXTEND:
2027 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2028 "Invalid ANY_EXTEND!");
2029 if (Operand.getValueType() == VT) return Operand; // noop extension
2030 assert(Operand.getValueType().bitsLT(VT)
2031 && "Invalid anyext node, dst < src!");
2032 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2033 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2034 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2037 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2038 "Invalid TRUNCATE!");
2039 if (Operand.getValueType() == VT) return Operand; // noop truncate
2040 assert(Operand.getValueType().bitsGT(VT)
2041 && "Invalid truncate node, src < dst!");
2042 if (OpOpcode == ISD::TRUNCATE)
2043 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2044 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2045 OpOpcode == ISD::ANY_EXTEND) {
2046 // If the source is smaller than the dest, we still need an extend.
2047 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2048 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2049 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2050 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2052 return Operand.Val->getOperand(0);
2055 case ISD::BIT_CONVERT:
2056 // Basic sanity checking.
2057 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2058 && "Cannot BIT_CONVERT between types of different sizes!");
2059 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2060 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2061 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2062 if (OpOpcode == ISD::UNDEF)
2063 return getNode(ISD::UNDEF, VT);
2065 case ISD::SCALAR_TO_VECTOR:
2066 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2067 VT.getVectorElementType() == Operand.getValueType() &&
2068 "Illegal SCALAR_TO_VECTOR node!");
2069 if (OpOpcode == ISD::UNDEF)
2070 return getNode(ISD::UNDEF, VT);
2071 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2072 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2073 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2074 Operand.getConstantOperandVal(1) == 0 &&
2075 Operand.getOperand(0).getValueType() == VT)
2076 return Operand.getOperand(0);
2079 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2080 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2081 Operand.Val->getOperand(0));
2082 if (OpOpcode == ISD::FNEG) // --X -> X
2083 return Operand.Val->getOperand(0);
2086 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2087 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2092 SDVTList VTs = getVTList(VT);
2093 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2094 FoldingSetNodeID ID;
2095 SDOperand Ops[1] = { Operand };
2096 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2098 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2099 return SDOperand(E, 0);
2100 N = new UnarySDNode(Opcode, VTs, Operand);
2101 CSEMap.InsertNode(N, IP);
2103 N = new UnarySDNode(Opcode, VTs, Operand);
2105 AllNodes.push_back(N);
2106 return SDOperand(N, 0);
2111 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2112 SDOperand N1, SDOperand N2) {
2113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2114 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2117 case ISD::TokenFactor:
2118 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2119 N2.getValueType() == MVT::Other && "Invalid token factor!");
2120 // Fold trivial token factors.
2121 if (N1.getOpcode() == ISD::EntryToken) return N2;
2122 if (N2.getOpcode() == ISD::EntryToken) return N1;
2125 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2126 N1.getValueType() == VT && "Binary operator types must match!");
2127 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2128 // worth handling here.
2129 if (N2C && N2C->isNullValue())
2131 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2138 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2139 N1.getValueType() == VT && "Binary operator types must match!");
2140 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2141 // it's worth handling here.
2142 if (N2C && N2C->isNullValue())
2149 assert(VT.isInteger() && "This operator does not apply to FP types!");
2159 assert(N1.getValueType() == N2.getValueType() &&
2160 N1.getValueType() == VT && "Binary operator types must match!");
2162 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2163 assert(N1.getValueType() == VT &&
2164 N1.getValueType().isFloatingPoint() &&
2165 N2.getValueType().isFloatingPoint() &&
2166 "Invalid FCOPYSIGN!");
2173 assert(VT == N1.getValueType() &&
2174 "Shift operators return type must be the same as their first arg");
2175 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2176 VT != MVT::i1 && "Shifts only work on integers");
2178 case ISD::FP_ROUND_INREG: {
2179 MVT EVT = cast<VTSDNode>(N2)->getVT();
2180 assert(VT == N1.getValueType() && "Not an inreg round!");
2181 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2182 "Cannot FP_ROUND_INREG integer types");
2183 assert(EVT.bitsLE(VT) && "Not rounding down!");
2184 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2188 assert(VT.isFloatingPoint() &&
2189 N1.getValueType().isFloatingPoint() &&
2190 VT.bitsLE(N1.getValueType()) &&
2191 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2192 if (N1.getValueType() == VT) return N1; // noop conversion.
2194 case ISD::AssertSext:
2195 case ISD::AssertZext: {
2196 MVT EVT = cast<VTSDNode>(N2)->getVT();
2197 assert(VT == N1.getValueType() && "Not an inreg extend!");
2198 assert(VT.isInteger() && EVT.isInteger() &&
2199 "Cannot *_EXTEND_INREG FP types");
2200 assert(EVT.bitsLE(VT) && "Not extending!");
2201 if (VT == EVT) return N1; // noop assertion.
2204 case ISD::SIGN_EXTEND_INREG: {
2205 MVT EVT = cast<VTSDNode>(N2)->getVT();
2206 assert(VT == N1.getValueType() && "Not an inreg extend!");
2207 assert(VT.isInteger() && EVT.isInteger() &&
2208 "Cannot *_EXTEND_INREG FP types");
2209 assert(EVT.bitsLE(VT) && "Not extending!");
2210 if (EVT == VT) return N1; // Not actually extending
2213 APInt Val = N1C->getAPIntValue();
2214 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2215 Val <<= Val.getBitWidth()-FromBits;
2216 Val = Val.ashr(Val.getBitWidth()-FromBits);
2217 return getConstant(Val, VT);
2221 case ISD::EXTRACT_VECTOR_ELT:
2222 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2224 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2225 if (N1.getOpcode() == ISD::UNDEF)
2226 return getNode(ISD::UNDEF, VT);
2228 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2229 // expanding copies of large vectors from registers.
2230 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2231 N1.getNumOperands() > 0) {
2233 N1.getOperand(0).getValueType().getVectorNumElements();
2234 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2235 N1.getOperand(N2C->getValue() / Factor),
2236 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2239 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2240 // expanding large vector constants.
2241 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2242 return N1.getOperand(N2C->getValue());
2244 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2245 // operations are lowered to scalars.
2246 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2247 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2249 return N1.getOperand(1);
2251 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2254 case ISD::EXTRACT_ELEMENT:
2255 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2256 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2257 (N1.getValueType().isInteger() == VT.isInteger()) &&
2258 "Wrong types for EXTRACT_ELEMENT!");
2260 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2261 // 64-bit integers into 32-bit parts. Instead of building the extract of
2262 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2263 if (N1.getOpcode() == ISD::BUILD_PAIR)
2264 return N1.getOperand(N2C->getValue());
2266 // EXTRACT_ELEMENT of a constant int is also very common.
2267 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2268 unsigned ElementSize = VT.getSizeInBits();
2269 unsigned Shift = ElementSize * N2C->getValue();
2270 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2271 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2274 case ISD::EXTRACT_SUBVECTOR:
2275 if (N1.getValueType() == VT) // Trivial extraction.
2282 APInt C1 = N1C->getAPIntValue(), C2 = N2C->getAPIntValue();
2284 case ISD::ADD: return getConstant(C1 + C2, VT);
2285 case ISD::SUB: return getConstant(C1 - C2, VT);
2286 case ISD::MUL: return getConstant(C1 * C2, VT);
2288 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2291 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2294 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2297 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2299 case ISD::AND : return getConstant(C1 & C2, VT);
2300 case ISD::OR : return getConstant(C1 | C2, VT);
2301 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2302 case ISD::SHL : return getConstant(C1 << C2, VT);
2303 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2304 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2305 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2306 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2309 } else { // Cannonicalize constant to RHS if commutative
2310 if (isCommutativeBinOp(Opcode)) {
2311 std::swap(N1C, N2C);
2317 // Constant fold FP operations.
2318 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2319 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2321 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2322 // Cannonicalize constant to RHS if commutative
2323 std::swap(N1CFP, N2CFP);
2325 } else if (N2CFP && VT != MVT::ppcf128) {
2326 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2327 APFloat::opStatus s;
2330 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2331 if (s != APFloat::opInvalidOp)
2332 return getConstantFP(V1, VT);
2335 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2336 if (s!=APFloat::opInvalidOp)
2337 return getConstantFP(V1, VT);
2340 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2341 if (s!=APFloat::opInvalidOp)
2342 return getConstantFP(V1, VT);
2345 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2346 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2347 return getConstantFP(V1, VT);
2350 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2351 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2352 return getConstantFP(V1, VT);
2354 case ISD::FCOPYSIGN:
2356 return getConstantFP(V1, VT);
2362 // Canonicalize an UNDEF to the RHS, even over a constant.
2363 if (N1.getOpcode() == ISD::UNDEF) {
2364 if (isCommutativeBinOp(Opcode)) {
2368 case ISD::FP_ROUND_INREG:
2369 case ISD::SIGN_EXTEND_INREG:
2375 return N1; // fold op(undef, arg2) -> undef
2383 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2384 // For vectors, we can't easily build an all zero vector, just return
2391 // Fold a bunch of operators when the RHS is undef.
2392 if (N2.getOpcode() == ISD::UNDEF) {
2395 if (N1.getOpcode() == ISD::UNDEF)
2396 // Handle undef ^ undef -> 0 special case. This is a common
2398 return getConstant(0, VT);
2413 return N2; // fold op(arg1, undef) -> undef
2419 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2420 // For vectors, we can't easily build an all zero vector, just return
2425 return getConstant(VT.getIntegerVTBitMask(), VT);
2426 // For vectors, we can't easily build an all one vector, just return
2434 // Memoize this node if possible.
2436 SDVTList VTs = getVTList(VT);
2437 if (VT != MVT::Flag) {
2438 SDOperand Ops[] = { N1, N2 };
2439 FoldingSetNodeID ID;
2440 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2442 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2443 return SDOperand(E, 0);
2444 N = new BinarySDNode(Opcode, VTs, N1, N2);
2445 CSEMap.InsertNode(N, IP);
2447 N = new BinarySDNode(Opcode, VTs, N1, N2);
2450 AllNodes.push_back(N);
2451 return SDOperand(N, 0);
2454 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2455 SDOperand N1, SDOperand N2, SDOperand N3) {
2456 // Perform various simplifications.
2457 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2458 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2461 // Use FoldSetCC to simplify SETCC's.
2462 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2463 if (Simp.Val) return Simp;
2468 if (N1C->getValue())
2469 return N2; // select true, X, Y -> X
2471 return N3; // select false, X, Y -> Y
2474 if (N2 == N3) return N2; // select C, X, X -> X
2478 if (N2C->getValue()) // Unconditional branch
2479 return getNode(ISD::BR, MVT::Other, N1, N3);
2481 return N1; // Never-taken branch
2484 case ISD::VECTOR_SHUFFLE:
2485 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2486 VT.isVector() && N3.getValueType().isVector() &&
2487 N3.getOpcode() == ISD::BUILD_VECTOR &&
2488 VT.getVectorNumElements() == N3.getNumOperands() &&
2489 "Illegal VECTOR_SHUFFLE node!");
2491 case ISD::BIT_CONVERT:
2492 // Fold bit_convert nodes from a type to themselves.
2493 if (N1.getValueType() == VT)
2498 // Memoize node if it doesn't produce a flag.
2500 SDVTList VTs = getVTList(VT);
2501 if (VT != MVT::Flag) {
2502 SDOperand Ops[] = { N1, N2, N3 };
2503 FoldingSetNodeID ID;
2504 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2506 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2507 return SDOperand(E, 0);
2508 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2509 CSEMap.InsertNode(N, IP);
2511 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2513 AllNodes.push_back(N);
2514 return SDOperand(N, 0);
2517 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2518 SDOperand N1, SDOperand N2, SDOperand N3,
2520 SDOperand Ops[] = { N1, N2, N3, N4 };
2521 return getNode(Opcode, VT, Ops, 4);
2524 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2525 SDOperand N1, SDOperand N2, SDOperand N3,
2526 SDOperand N4, SDOperand N5) {
2527 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2528 return getNode(Opcode, VT, Ops, 5);
2531 /// getMemsetValue - Vectorized representation of the memset value
2533 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2534 unsigned NumBits = VT.isVector() ?
2535 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2536 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2537 APInt Val = APInt(NumBits, C->getValue() & 255);
2539 for (unsigned i = NumBits; i > 8; i >>= 1) {
2540 Val = (Val << Shift) | Val;
2544 return DAG.getConstant(Val, VT);
2545 return DAG.getConstantFP(APFloat(Val), VT);
2548 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2550 for (unsigned i = NumBits; i > 8; i >>= 1) {
2551 Value = DAG.getNode(ISD::OR, VT,
2552 DAG.getNode(ISD::SHL, VT, Value,
2553 DAG.getConstant(Shift, MVT::i8)), Value);
2560 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2561 /// used when a memcpy is turned into a memset when the source is a constant
2563 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2564 const TargetLowering &TLI,
2565 std::string &Str, unsigned Offset) {
2566 // Handle vector with all elements zero.
2569 return DAG.getConstant(0, VT);
2570 unsigned NumElts = VT.getVectorNumElements();
2571 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2572 return DAG.getNode(ISD::BIT_CONVERT, VT,
2573 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2576 assert(!VT.isVector() && "Can't handle vector type here!");
2577 unsigned NumBits = VT.getSizeInBits();
2578 unsigned MSB = NumBits / 8;
2580 if (TLI.isLittleEndian())
2581 Offset = Offset + MSB - 1;
2582 for (unsigned i = 0; i != MSB; ++i) {
2583 Val = (Val << 8) | (unsigned char)Str[Offset];
2584 Offset += TLI.isLittleEndian() ? -1 : 1;
2586 return DAG.getConstant(Val, VT);
2589 /// getMemBasePlusOffset - Returns base and offset node for the
2591 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2592 SelectionDAG &DAG) {
2593 MVT VT = Base.getValueType();
2594 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2597 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2599 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2600 unsigned SrcDelta = 0;
2601 GlobalAddressSDNode *G = NULL;
2602 if (Src.getOpcode() == ISD::GlobalAddress)
2603 G = cast<GlobalAddressSDNode>(Src);
2604 else if (Src.getOpcode() == ISD::ADD &&
2605 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2606 Src.getOperand(1).getOpcode() == ISD::Constant) {
2607 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2608 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2613 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2614 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2620 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2621 /// to replace the memset / memcpy is below the threshold. It also returns the
2622 /// types of the sequence of memory ops to perform memset / memcpy.
2624 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2625 SDOperand Dst, SDOperand Src,
2626 unsigned Limit, uint64_t Size, unsigned &Align,
2627 std::string &Str, bool &isSrcStr,
2629 const TargetLowering &TLI) {
2630 isSrcStr = isMemSrcFromString(Src, Str);
2631 bool isSrcConst = isa<ConstantSDNode>(Src);
2632 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2633 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2634 if (VT != MVT::iAny) {
2635 unsigned NewAlign = (unsigned)
2636 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2637 // If source is a string constant, this will require an unaligned load.
2638 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2639 if (Dst.getOpcode() != ISD::FrameIndex) {
2640 // Can't change destination alignment. It requires a unaligned store.
2644 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2645 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2646 if (MFI->isFixedObjectIndex(FI)) {
2647 // Can't change destination alignment. It requires a unaligned store.
2651 // Give the stack frame object a larger alignment if needed.
2652 if (MFI->getObjectAlignment(FI) < NewAlign)
2653 MFI->setObjectAlignment(FI, NewAlign);
2660 if (VT == MVT::iAny) {
2664 switch (Align & 7) {
2665 case 0: VT = MVT::i64; break;
2666 case 4: VT = MVT::i32; break;
2667 case 2: VT = MVT::i16; break;
2668 default: VT = MVT::i8; break;
2673 while (!TLI.isTypeLegal(LVT))
2674 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2675 assert(LVT.isInteger());
2681 unsigned NumMemOps = 0;
2683 unsigned VTSize = VT.getSizeInBits() / 8;
2684 while (VTSize > Size) {
2685 // For now, only use non-vector load / store's for the left-over pieces.
2686 if (VT.isVector()) {
2688 while (!TLI.isTypeLegal(VT))
2689 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2690 VTSize = VT.getSizeInBits() / 8;
2692 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2697 if (++NumMemOps > Limit)
2699 MemOps.push_back(VT);
2706 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2707 SDOperand Chain, SDOperand Dst,
2708 SDOperand Src, uint64_t Size,
2709 unsigned Align, bool AlwaysInline,
2710 const Value *DstSV, uint64_t DstSVOff,
2711 const Value *SrcSV, uint64_t SrcSVOff){
2712 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2714 // Expand memcpy to a series of load and store ops if the size operand falls
2715 // below a certain threshold.
2716 std::vector<MVT> MemOps;
2717 uint64_t Limit = -1;
2719 Limit = TLI.getMaxStoresPerMemcpy();
2720 unsigned DstAlign = Align; // Destination alignment can change.
2723 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2724 Str, CopyFromStr, DAG, TLI))
2728 bool isZeroStr = CopyFromStr && Str.empty();
2729 SmallVector<SDOperand, 8> OutChains;
2730 unsigned NumMemOps = MemOps.size();
2731 uint64_t SrcOff = 0, DstOff = 0;
2732 for (unsigned i = 0; i < NumMemOps; i++) {
2734 unsigned VTSize = VT.getSizeInBits() / 8;
2735 SDOperand Value, Store;
2737 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2738 // It's unlikely a store of a vector immediate can be done in a single
2739 // instruction. It would require a load from a constantpool first.
2740 // We also handle store a vector with all zero's.
2741 // FIXME: Handle other cases where store of vector immediate is done in
2742 // a single instruction.
2743 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2744 Store = DAG.getStore(Chain, Value,
2745 getMemBasePlusOffset(Dst, DstOff, DAG),
2746 DstSV, DstSVOff + DstOff);
2748 Value = DAG.getLoad(VT, Chain,
2749 getMemBasePlusOffset(Src, SrcOff, DAG),
2750 SrcSV, SrcSVOff + SrcOff, false, Align);
2751 Store = DAG.getStore(Chain, Value,
2752 getMemBasePlusOffset(Dst, DstOff, DAG),
2753 DstSV, DstSVOff + DstOff, false, DstAlign);
2755 OutChains.push_back(Store);
2760 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2761 &OutChains[0], OutChains.size());
2764 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2765 SDOperand Chain, SDOperand Dst,
2766 SDOperand Src, uint64_t Size,
2767 unsigned Align, bool AlwaysInline,
2768 const Value *DstSV, uint64_t DstSVOff,
2769 const Value *SrcSV, uint64_t SrcSVOff){
2770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2772 // Expand memmove to a series of load and store ops if the size operand falls
2773 // below a certain threshold.
2774 std::vector<MVT> MemOps;
2775 uint64_t Limit = -1;
2777 Limit = TLI.getMaxStoresPerMemmove();
2778 unsigned DstAlign = Align; // Destination alignment can change.
2781 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2782 Str, CopyFromStr, DAG, TLI))
2785 uint64_t SrcOff = 0, DstOff = 0;
2787 SmallVector<SDOperand, 8> LoadValues;
2788 SmallVector<SDOperand, 8> LoadChains;
2789 SmallVector<SDOperand, 8> OutChains;
2790 unsigned NumMemOps = MemOps.size();
2791 for (unsigned i = 0; i < NumMemOps; i++) {
2793 unsigned VTSize = VT.getSizeInBits() / 8;
2794 SDOperand Value, Store;
2796 Value = DAG.getLoad(VT, Chain,
2797 getMemBasePlusOffset(Src, SrcOff, DAG),
2798 SrcSV, SrcSVOff + SrcOff, false, Align);
2799 LoadValues.push_back(Value);
2800 LoadChains.push_back(Value.getValue(1));
2803 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2804 &LoadChains[0], LoadChains.size());
2806 for (unsigned i = 0; i < NumMemOps; i++) {
2808 unsigned VTSize = VT.getSizeInBits() / 8;
2809 SDOperand Value, Store;
2811 Store = DAG.getStore(Chain, LoadValues[i],
2812 getMemBasePlusOffset(Dst, DstOff, DAG),
2813 DstSV, DstSVOff + DstOff, false, DstAlign);
2814 OutChains.push_back(Store);
2818 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2819 &OutChains[0], OutChains.size());
2822 static SDOperand getMemsetStores(SelectionDAG &DAG,
2823 SDOperand Chain, SDOperand Dst,
2824 SDOperand Src, uint64_t Size,
2826 const Value *DstSV, uint64_t DstSVOff) {
2827 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2829 // Expand memset to a series of load/store ops if the size operand
2830 // falls below a certain threshold.
2831 std::vector<MVT> MemOps;
2834 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2835 Size, Align, Str, CopyFromStr, DAG, TLI))
2838 SmallVector<SDOperand, 8> OutChains;
2839 uint64_t DstOff = 0;
2841 unsigned NumMemOps = MemOps.size();
2842 for (unsigned i = 0; i < NumMemOps; i++) {
2844 unsigned VTSize = VT.getSizeInBits() / 8;
2845 SDOperand Value = getMemsetValue(Src, VT, DAG);
2846 SDOperand Store = DAG.getStore(Chain, Value,
2847 getMemBasePlusOffset(Dst, DstOff, DAG),
2848 DstSV, DstSVOff + DstOff);
2849 OutChains.push_back(Store);
2853 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2854 &OutChains[0], OutChains.size());
2857 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2858 SDOperand Src, SDOperand Size,
2859 unsigned Align, bool AlwaysInline,
2860 const Value *DstSV, uint64_t DstSVOff,
2861 const Value *SrcSV, uint64_t SrcSVOff) {
2863 // Check to see if we should lower the memcpy to loads and stores first.
2864 // For cases within the target-specified limits, this is the best choice.
2865 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2867 // Memcpy with size zero? Just return the original chain.
2868 if (ConstantSize->isNullValue())
2872 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2873 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2878 // Then check to see if we should lower the memcpy with target-specific
2879 // code. If the target chooses to do this, this is the next best.
2881 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2883 DstSV, DstSVOff, SrcSV, SrcSVOff);
2887 // If we really need inline code and the target declined to provide it,
2888 // use a (potentially long) sequence of loads and stores.
2890 assert(ConstantSize && "AlwaysInline requires a constant size!");
2891 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2892 ConstantSize->getValue(), Align, true,
2893 DstSV, DstSVOff, SrcSV, SrcSVOff);
2896 // Emit a library call.
2897 TargetLowering::ArgListTy Args;
2898 TargetLowering::ArgListEntry Entry;
2899 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2900 Entry.Node = Dst; Args.push_back(Entry);
2901 Entry.Node = Src; Args.push_back(Entry);
2902 Entry.Node = Size; Args.push_back(Entry);
2903 std::pair<SDOperand,SDOperand> CallResult =
2904 TLI.LowerCallTo(Chain, Type::VoidTy,
2905 false, false, false, CallingConv::C, false,
2906 getExternalSymbol("memcpy", TLI.getPointerTy()),
2908 return CallResult.second;
2911 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2912 SDOperand Src, SDOperand Size,
2914 const Value *DstSV, uint64_t DstSVOff,
2915 const Value *SrcSV, uint64_t SrcSVOff) {
2917 // Check to see if we should lower the memmove to loads and stores first.
2918 // For cases within the target-specified limits, this is the best choice.
2919 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2921 // Memmove with size zero? Just return the original chain.
2922 if (ConstantSize->isNullValue())
2926 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2927 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2932 // Then check to see if we should lower the memmove with target-specific
2933 // code. If the target chooses to do this, this is the next best.
2935 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2936 DstSV, DstSVOff, SrcSV, SrcSVOff);
2940 // Emit a library call.
2941 TargetLowering::ArgListTy Args;
2942 TargetLowering::ArgListEntry Entry;
2943 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2944 Entry.Node = Dst; Args.push_back(Entry);
2945 Entry.Node = Src; Args.push_back(Entry);
2946 Entry.Node = Size; Args.push_back(Entry);
2947 std::pair<SDOperand,SDOperand> CallResult =
2948 TLI.LowerCallTo(Chain, Type::VoidTy,
2949 false, false, false, CallingConv::C, false,
2950 getExternalSymbol("memmove", TLI.getPointerTy()),
2952 return CallResult.second;
2955 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2956 SDOperand Src, SDOperand Size,
2958 const Value *DstSV, uint64_t DstSVOff) {
2960 // Check to see if we should lower the memset to stores first.
2961 // For cases within the target-specified limits, this is the best choice.
2962 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2964 // Memset with size zero? Just return the original chain.
2965 if (ConstantSize->isNullValue())
2969 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
2975 // Then check to see if we should lower the memset with target-specific
2976 // code. If the target chooses to do this, this is the next best.
2978 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
2983 // Emit a library call.
2984 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2985 TargetLowering::ArgListTy Args;
2986 TargetLowering::ArgListEntry Entry;
2987 Entry.Node = Dst; Entry.Ty = IntPtrTy;
2988 Args.push_back(Entry);
2989 // Extend or truncate the argument to be an i32 value for the call.
2990 if (Src.getValueType().bitsGT(MVT::i32))
2991 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
2993 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
2994 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
2995 Args.push_back(Entry);
2996 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
2997 Args.push_back(Entry);
2998 std::pair<SDOperand,SDOperand> CallResult =
2999 TLI.LowerCallTo(Chain, Type::VoidTy,
3000 false, false, false, CallingConv::C, false,
3001 getExternalSymbol("memset", TLI.getPointerTy()),
3003 return CallResult.second;
3006 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3007 SDOperand Ptr, SDOperand Cmp,
3008 SDOperand Swp, const Value* PtrVal,
3009 unsigned Alignment) {
3010 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3011 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3012 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3013 FoldingSetNodeID ID;
3014 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3015 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3017 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3018 return SDOperand(E, 0);
3019 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp,
3021 CSEMap.InsertNode(N, IP);
3022 AllNodes.push_back(N);
3023 return SDOperand(N, 0);
3026 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3027 SDOperand Ptr, SDOperand Val,
3028 const Value* PtrVal,
3029 unsigned Alignment) {
3030 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3031 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3032 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3033 || Opcode == ISD::ATOMIC_LOAD_NAND
3034 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3035 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3036 && "Invalid Atomic Op");
3037 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3038 FoldingSetNodeID ID;
3039 SDOperand Ops[] = {Chain, Ptr, Val};
3040 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3042 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3043 return SDOperand(E, 0);
3044 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val,
3046 CSEMap.InsertNode(N, IP);
3047 AllNodes.push_back(N);
3048 return SDOperand(N, 0);
3052 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3053 MVT VT, SDOperand Chain,
3054 SDOperand Ptr, SDOperand Offset,
3055 const Value *SV, int SVOffset, MVT EVT,
3056 bool isVolatile, unsigned Alignment) {
3057 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3059 if (VT != MVT::iPTR) {
3060 Ty = VT.getTypeForMVT();
3062 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3063 assert(PT && "Value for load must be a pointer");
3064 Ty = PT->getElementType();
3066 assert(Ty && "Could not get type information for load");
3067 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3071 ExtType = ISD::NON_EXTLOAD;
3072 } else if (ExtType == ISD::NON_EXTLOAD) {
3073 assert(VT == EVT && "Non-extending load from different memory type!");
3077 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3079 assert(EVT.bitsLT(VT) &&
3080 "Should only be an extending load, not truncating!");
3081 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3082 "Cannot sign/zero extend a FP/Vector load!");
3083 assert(VT.isInteger() == EVT.isInteger() &&
3084 "Cannot convert from FP to Int or Int -> FP!");
3087 bool Indexed = AM != ISD::UNINDEXED;
3088 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3089 "Unindexed load with an offset!");
3091 SDVTList VTs = Indexed ?
3092 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3093 SDOperand Ops[] = { Chain, Ptr, Offset };
3094 FoldingSetNodeID ID;
3095 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3097 ID.AddInteger(ExtType);
3098 ID.AddInteger(EVT.getRawBits());
3099 ID.AddInteger(Alignment);
3100 ID.AddInteger(isVolatile);
3102 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3103 return SDOperand(E, 0);
3104 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3105 Alignment, isVolatile);
3106 CSEMap.InsertNode(N, IP);
3107 AllNodes.push_back(N);
3108 return SDOperand(N, 0);
3111 SDOperand SelectionDAG::getLoad(MVT VT,
3112 SDOperand Chain, SDOperand Ptr,
3113 const Value *SV, int SVOffset,
3114 bool isVolatile, unsigned Alignment) {
3115 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3116 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3117 SV, SVOffset, VT, isVolatile, Alignment);
3120 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3121 SDOperand Chain, SDOperand Ptr,
3123 int SVOffset, MVT EVT,
3124 bool isVolatile, unsigned Alignment) {
3125 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3126 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3127 SV, SVOffset, EVT, isVolatile, Alignment);
3131 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3132 SDOperand Offset, ISD::MemIndexedMode AM) {
3133 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3134 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3135 "Load is already a indexed load!");
3136 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3137 LD->getChain(), Base, Offset, LD->getSrcValue(),
3138 LD->getSrcValueOffset(), LD->getMemoryVT(),
3139 LD->isVolatile(), LD->getAlignment());
3142 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3143 SDOperand Ptr, const Value *SV, int SVOffset,
3144 bool isVolatile, unsigned Alignment) {
3145 MVT VT = Val.getValueType();
3147 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3149 if (VT != MVT::iPTR) {
3150 Ty = VT.getTypeForMVT();
3152 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3153 assert(PT && "Value for store must be a pointer");
3154 Ty = PT->getElementType();
3156 assert(Ty && "Could not get type information for store");
3157 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3159 SDVTList VTs = getVTList(MVT::Other);
3160 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3161 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3162 FoldingSetNodeID ID;
3163 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3164 ID.AddInteger(ISD::UNINDEXED);
3165 ID.AddInteger(false);
3166 ID.AddInteger(VT.getRawBits());
3167 ID.AddInteger(Alignment);
3168 ID.AddInteger(isVolatile);
3170 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3171 return SDOperand(E, 0);
3172 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3173 VT, SV, SVOffset, Alignment, isVolatile);
3174 CSEMap.InsertNode(N, IP);
3175 AllNodes.push_back(N);
3176 return SDOperand(N, 0);
3179 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3180 SDOperand Ptr, const Value *SV,
3181 int SVOffset, MVT SVT,
3182 bool isVolatile, unsigned Alignment) {
3183 MVT VT = Val.getValueType();
3186 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3188 assert(VT.bitsGT(SVT) && "Not a truncation?");
3189 assert(VT.isInteger() == SVT.isInteger() &&
3190 "Can't do FP-INT conversion!");
3192 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3194 if (VT != MVT::iPTR) {
3195 Ty = VT.getTypeForMVT();
3197 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3198 assert(PT && "Value for store must be a pointer");
3199 Ty = PT->getElementType();
3201 assert(Ty && "Could not get type information for store");
3202 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3204 SDVTList VTs = getVTList(MVT::Other);
3205 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3206 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3207 FoldingSetNodeID ID;
3208 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3209 ID.AddInteger(ISD::UNINDEXED);
3211 ID.AddInteger(SVT.getRawBits());
3212 ID.AddInteger(Alignment);
3213 ID.AddInteger(isVolatile);
3215 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3216 return SDOperand(E, 0);
3217 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3218 SVT, SV, SVOffset, Alignment, isVolatile);
3219 CSEMap.InsertNode(N, IP);
3220 AllNodes.push_back(N);
3221 return SDOperand(N, 0);
3225 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3226 SDOperand Offset, ISD::MemIndexedMode AM) {
3227 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3228 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3229 "Store is already a indexed store!");
3230 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3231 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3232 FoldingSetNodeID ID;
3233 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3235 ID.AddInteger(ST->isTruncatingStore());
3236 ID.AddInteger(ST->getMemoryVT().getRawBits());
3237 ID.AddInteger(ST->getAlignment());
3238 ID.AddInteger(ST->isVolatile());
3240 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3241 return SDOperand(E, 0);
3242 SDNode *N = new StoreSDNode(Ops, VTs, AM,
3243 ST->isTruncatingStore(), ST->getMemoryVT(),
3244 ST->getSrcValue(), ST->getSrcValueOffset(),
3245 ST->getAlignment(), ST->isVolatile());
3246 CSEMap.InsertNode(N, IP);
3247 AllNodes.push_back(N);
3248 return SDOperand(N, 0);
3251 SDOperand SelectionDAG::getVAArg(MVT VT,
3252 SDOperand Chain, SDOperand Ptr,
3254 SDOperand Ops[] = { Chain, Ptr, SV };
3255 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3258 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3259 SDOperandPtr Ops, unsigned NumOps) {
3261 case 0: return getNode(Opcode, VT);
3262 case 1: return getNode(Opcode, VT, Ops[0]);
3263 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3264 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3270 case ISD::SELECT_CC: {
3271 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3272 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3273 "LHS and RHS of condition must have same type!");
3274 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3275 "True and False arms of SelectCC must have same type!");
3276 assert(Ops[2].getValueType() == VT &&
3277 "select_cc node must be of same type as true and false value!");
3281 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3282 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3283 "LHS/RHS of comparison should match types!");
3290 SDVTList VTs = getVTList(VT);
3291 if (VT != MVT::Flag) {
3292 FoldingSetNodeID ID;
3293 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3295 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3296 return SDOperand(E, 0);
3297 N = new SDNode(Opcode, VTs, Ops, NumOps);
3298 CSEMap.InsertNode(N, IP);
3300 N = new SDNode(Opcode, VTs, Ops, NumOps);
3302 AllNodes.push_back(N);
3303 return SDOperand(N, 0);
3306 SDOperand SelectionDAG::getNode(unsigned Opcode,
3307 std::vector<MVT> &ResultTys,
3308 SDOperandPtr Ops, unsigned NumOps) {
3309 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3313 SDOperand SelectionDAG::getNode(unsigned Opcode,
3314 const MVT *VTs, unsigned NumVTs,
3315 SDOperandPtr Ops, unsigned NumOps) {
3317 return getNode(Opcode, VTs[0], Ops, NumOps);
3318 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3321 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3322 SDOperandPtr Ops, unsigned NumOps) {
3323 if (VTList.NumVTs == 1)
3324 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3327 // FIXME: figure out how to safely handle things like
3328 // int foo(int x) { return 1 << (x & 255); }
3329 // int bar() { return foo(256); }
3331 case ISD::SRA_PARTS:
3332 case ISD::SRL_PARTS:
3333 case ISD::SHL_PARTS:
3334 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3335 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3336 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3337 else if (N3.getOpcode() == ISD::AND)
3338 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3339 // If the and is only masking out bits that cannot effect the shift,
3340 // eliminate the and.
3341 unsigned NumBits = VT.getSizeInBits()*2;
3342 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3343 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3349 // Memoize the node unless it returns a flag.
3351 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3352 FoldingSetNodeID ID;
3353 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3355 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3356 return SDOperand(E, 0);
3358 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3359 else if (NumOps == 2)
3360 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3361 else if (NumOps == 3)
3362 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3364 N = new SDNode(Opcode, VTList, Ops, NumOps);
3365 CSEMap.InsertNode(N, IP);
3368 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3369 else if (NumOps == 2)
3370 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3371 else if (NumOps == 3)
3372 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3374 N = new SDNode(Opcode, VTList, Ops, NumOps);
3376 AllNodes.push_back(N);
3377 return SDOperand(N, 0);
3380 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3381 return getNode(Opcode, VTList, (SDOperand*)0, 0);
3384 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3386 SDOperand Ops[] = { N1 };
3387 return getNode(Opcode, VTList, Ops, 1);
3390 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3391 SDOperand N1, SDOperand N2) {
3392 SDOperand Ops[] = { N1, N2 };
3393 return getNode(Opcode, VTList, Ops, 2);
3396 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3397 SDOperand N1, SDOperand N2, SDOperand N3) {
3398 SDOperand Ops[] = { N1, N2, N3 };
3399 return getNode(Opcode, VTList, Ops, 3);
3402 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3403 SDOperand N1, SDOperand N2, SDOperand N3,
3405 SDOperand Ops[] = { N1, N2, N3, N4 };
3406 return getNode(Opcode, VTList, Ops, 4);
3409 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3410 SDOperand N1, SDOperand N2, SDOperand N3,
3411 SDOperand N4, SDOperand N5) {
3412 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3413 return getNode(Opcode, VTList, Ops, 5);
3416 SDVTList SelectionDAG::getVTList(MVT VT) {
3417 return makeVTList(SDNode::getValueTypeList(VT), 1);
3420 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3421 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3422 E = VTList.end(); I != E; ++I) {
3423 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3424 return makeVTList(&(*I)[0], 2);
3429 VTList.push_front(V);
3430 return makeVTList(&(*VTList.begin())[0], 2);
3432 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3434 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3435 E = VTList.end(); I != E; ++I) {
3436 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3438 return makeVTList(&(*I)[0], 3);
3444 VTList.push_front(V);
3445 return makeVTList(&(*VTList.begin())[0], 3);
3448 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3450 case 0: assert(0 && "Cannot have nodes without results!");
3451 case 1: return getVTList(VTs[0]);
3452 case 2: return getVTList(VTs[0], VTs[1]);
3453 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3457 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3458 E = VTList.end(); I != E; ++I) {
3459 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3461 bool NoMatch = false;
3462 for (unsigned i = 2; i != NumVTs; ++i)
3463 if (VTs[i] != (*I)[i]) {
3468 return makeVTList(&*I->begin(), NumVTs);
3471 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3472 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3476 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3477 /// specified operands. If the resultant node already exists in the DAG,
3478 /// this does not modify the specified node, instead it returns the node that
3479 /// already exists. If the resultant node does not exist in the DAG, the
3480 /// input node is returned. As a degenerate case, if you specify the same
3481 /// input operands as the node already has, the input node is returned.
3482 SDOperand SelectionDAG::
3483 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3484 SDNode *N = InN.Val;
3485 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3487 // Check to see if there is no change.
3488 if (Op == N->getOperand(0)) return InN;
3490 // See if the modified node already exists.
3491 void *InsertPos = 0;
3492 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3493 return SDOperand(Existing, InN.ResNo);
3495 // Nope it doesn't. Remove the node from it's current place in the maps.
3497 RemoveNodeFromCSEMaps(N);
3499 // Now we update the operands.
3500 N->OperandList[0].getVal()->removeUser(0, N);
3501 N->OperandList[0] = Op;
3502 N->OperandList[0].setUser(N);
3503 Op.Val->addUser(0, N);
3505 // If this gets put into a CSE map, add it.
3506 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3510 SDOperand SelectionDAG::
3511 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3512 SDNode *N = InN.Val;
3513 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3515 // Check to see if there is no change.
3516 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3517 return InN; // No operands changed, just return the input node.
3519 // See if the modified node already exists.
3520 void *InsertPos = 0;
3521 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3522 return SDOperand(Existing, InN.ResNo);
3524 // Nope it doesn't. Remove the node from it's current place in the maps.
3526 RemoveNodeFromCSEMaps(N);
3528 // Now we update the operands.
3529 if (N->OperandList[0] != Op1) {
3530 N->OperandList[0].getVal()->removeUser(0, N);
3531 N->OperandList[0] = Op1;
3532 N->OperandList[0].setUser(N);
3533 Op1.Val->addUser(0, N);
3535 if (N->OperandList[1] != Op2) {
3536 N->OperandList[1].getVal()->removeUser(1, N);
3537 N->OperandList[1] = Op2;
3538 N->OperandList[1].setUser(N);
3539 Op2.Val->addUser(1, N);
3542 // If this gets put into a CSE map, add it.
3543 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3547 SDOperand SelectionDAG::
3548 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3549 SDOperand Ops[] = { Op1, Op2, Op3 };
3550 return UpdateNodeOperands(N, Ops, 3);
3553 SDOperand SelectionDAG::
3554 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3555 SDOperand Op3, SDOperand Op4) {
3556 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3557 return UpdateNodeOperands(N, Ops, 4);
3560 SDOperand SelectionDAG::
3561 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3562 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3563 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3564 return UpdateNodeOperands(N, Ops, 5);
3567 SDOperand SelectionDAG::
3568 UpdateNodeOperands(SDOperand InN, SDOperandPtr Ops, unsigned NumOps) {
3569 SDNode *N = InN.Val;
3570 assert(N->getNumOperands() == NumOps &&
3571 "Update with wrong number of operands");
3573 // Check to see if there is no change.
3574 bool AnyChange = false;
3575 for (unsigned i = 0; i != NumOps; ++i) {
3576 if (Ops[i] != N->getOperand(i)) {
3582 // No operands changed, just return the input node.
3583 if (!AnyChange) return InN;
3585 // See if the modified node already exists.
3586 void *InsertPos = 0;
3587 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3588 return SDOperand(Existing, InN.ResNo);
3590 // Nope it doesn't. Remove the node from its current place in the maps.
3592 RemoveNodeFromCSEMaps(N);
3594 // Now we update the operands.
3595 for (unsigned i = 0; i != NumOps; ++i) {
3596 if (N->OperandList[i] != Ops[i]) {
3597 N->OperandList[i].getVal()->removeUser(i, N);
3598 N->OperandList[i] = Ops[i];
3599 N->OperandList[i].setUser(N);
3600 Ops[i].Val->addUser(i, N);
3604 // If this gets put into a CSE map, add it.
3605 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3609 /// MorphNodeTo - This frees the operands of the current node, resets the
3610 /// opcode, types, and operands to the specified value. This should only be
3611 /// used by the SelectionDAG class.
3612 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3613 SDOperandPtr Ops, unsigned NumOps) {
3616 NumValues = L.NumVTs;
3618 // Clear the operands list, updating used nodes to remove this from their
3620 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3621 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3623 // If NumOps is larger than the # of operands we currently have, reallocate
3624 // the operand list.
3625 if (NumOps > NumOperands) {
3626 if (OperandsNeedDelete) {
3627 delete [] OperandList;
3629 OperandList = new SDUse[NumOps];
3630 OperandsNeedDelete = true;
3633 // Assign the new operands.
3634 NumOperands = NumOps;
3636 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3637 OperandList[i] = Ops[i];
3638 OperandList[i].setUser(this);
3639 SDNode *N = OperandList[i].getVal();
3640 N->addUser(i, this);
3645 /// SelectNodeTo - These are used for target selectors to *mutate* the
3646 /// specified node to have the specified return type, Target opcode, and
3647 /// operands. Note that target opcodes are stored as
3648 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3650 /// Note that SelectNodeTo returns the resultant node. If there is already a
3651 /// node of the specified opcode and operands, it returns that node instead of
3652 /// the current one.
3653 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3655 SDVTList VTs = getVTList(VT);
3656 FoldingSetNodeID ID;
3657 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, (SDOperand*)0, 0);
3659 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3662 RemoveNodeFromCSEMaps(N);
3664 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, SDOperandPtr(), 0);
3666 CSEMap.InsertNode(N, IP);
3670 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3671 MVT VT, SDOperand Op1) {
3672 // If an identical node already exists, use it.
3673 SDVTList VTs = getVTList(VT);
3674 SDOperand Ops[] = { Op1 };
3676 FoldingSetNodeID ID;
3677 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3679 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3682 RemoveNodeFromCSEMaps(N);
3683 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3684 CSEMap.InsertNode(N, IP);
3688 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3689 MVT VT, SDOperand Op1,
3691 // If an identical node already exists, use it.
3692 SDVTList VTs = getVTList(VT);
3693 SDOperand Ops[] = { Op1, Op2 };
3695 FoldingSetNodeID ID;
3696 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3698 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3701 RemoveNodeFromCSEMaps(N);
3703 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3705 CSEMap.InsertNode(N, IP); // Memoize the new node.
3709 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3710 MVT VT, SDOperand Op1,
3711 SDOperand Op2, SDOperand Op3) {
3712 // If an identical node already exists, use it.
3713 SDVTList VTs = getVTList(VT);
3714 SDOperand Ops[] = { Op1, Op2, Op3 };
3715 FoldingSetNodeID ID;
3716 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3718 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3721 RemoveNodeFromCSEMaps(N);
3723 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3725 CSEMap.InsertNode(N, IP); // Memoize the new node.
3729 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3730 MVT VT, SDOperandPtr Ops,
3732 // If an identical node already exists, use it.
3733 SDVTList VTs = getVTList(VT);
3734 FoldingSetNodeID ID;
3735 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3737 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3740 RemoveNodeFromCSEMaps(N);
3741 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3743 CSEMap.InsertNode(N, IP); // Memoize the new node.
3747 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3749 SDOperand Op1, SDOperand Op2) {
3750 SDVTList VTs = getVTList(VT1, VT2);
3751 FoldingSetNodeID ID;
3752 SDOperand Ops[] = { Op1, Op2 };
3753 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3755 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3758 RemoveNodeFromCSEMaps(N);
3759 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3760 CSEMap.InsertNode(N, IP); // Memoize the new node.
3764 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3766 SDOperand Op1, SDOperand Op2,
3768 // If an identical node already exists, use it.
3769 SDVTList VTs = getVTList(VT1, VT2);
3770 SDOperand Ops[] = { Op1, Op2, Op3 };
3771 FoldingSetNodeID ID;
3772 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3774 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3777 RemoveNodeFromCSEMaps(N);
3779 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3780 CSEMap.InsertNode(N, IP); // Memoize the new node.
3785 /// getTargetNode - These are used for target selectors to create a new node
3786 /// with specified return type(s), target opcode, and operands.
3788 /// Note that getTargetNode returns the resultant node. If there is already a
3789 /// node of the specified opcode and operands, it returns that node instead of
3790 /// the current one.
3791 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3792 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3794 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3795 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3797 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3798 SDOperand Op1, SDOperand Op2) {
3799 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3801 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3802 SDOperand Op1, SDOperand Op2,
3804 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3806 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3807 SDOperandPtr Ops, unsigned NumOps) {
3808 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3810 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3811 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3813 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3815 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3816 MVT VT2, SDOperand Op1) {
3817 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3818 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3820 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3821 MVT VT2, SDOperand Op1,
3823 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3824 SDOperand Ops[] = { Op1, Op2 };
3825 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3827 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3828 MVT VT2, SDOperand Op1,
3829 SDOperand Op2, SDOperand Op3) {
3830 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3831 SDOperand Ops[] = { Op1, Op2, Op3 };
3832 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3834 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3835 SDOperandPtr Ops, unsigned NumOps) {
3836 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3837 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3839 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3840 SDOperand Op1, SDOperand Op2) {
3841 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3842 SDOperand Ops[] = { Op1, Op2 };
3843 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3845 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3846 SDOperand Op1, SDOperand Op2,
3848 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3849 SDOperand Ops[] = { Op1, Op2, Op3 };
3850 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3852 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3853 SDOperandPtr Ops, unsigned NumOps) {
3854 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3855 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3857 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3858 MVT VT2, MVT VT3, MVT VT4,
3859 SDOperandPtr Ops, unsigned NumOps) {
3860 std::vector<MVT> VTList;
3861 VTList.push_back(VT1);
3862 VTList.push_back(VT2);
3863 VTList.push_back(VT3);
3864 VTList.push_back(VT4);
3865 const MVT *VTs = getNodeValueTypes(VTList);
3866 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3868 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3869 std::vector<MVT> &ResultTys,
3870 SDOperandPtr Ops, unsigned NumOps) {
3871 const MVT *VTs = getNodeValueTypes(ResultTys);
3872 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3876 /// getNodeIfExists - Get the specified node if it's already available, or
3877 /// else return NULL.
3878 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3879 SDOperandPtr Ops, unsigned NumOps) {
3880 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3881 FoldingSetNodeID ID;
3882 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3884 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3891 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3892 /// This can cause recursive merging of nodes in the DAG.
3894 /// This version assumes From has a single result value.
3896 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3897 DAGUpdateListener *UpdateListener) {
3898 SDNode *From = FromN.Val;
3899 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3900 "Cannot replace with this method!");
3901 assert(From != To.Val && "Cannot replace uses of with self");
3903 while (!From->use_empty()) {
3904 SDNode::use_iterator UI = From->use_begin();
3905 SDNode *U = UI->getUser();
3907 // This node is about to morph, remove its old self from the CSE maps.
3908 RemoveNodeFromCSEMaps(U);
3910 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3911 I != E; ++I, ++operandNum)
3912 if (I->getVal() == From) {
3913 From->removeUser(operandNum, U);
3916 To.Val->addUser(operandNum, U);
3919 // Now that we have modified U, add it back to the CSE maps. If it already
3920 // exists there, recursively merge the results together.
3921 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3922 ReplaceAllUsesWith(U, Existing, UpdateListener);
3923 // U is now dead. Inform the listener if it exists and delete it.
3925 UpdateListener->NodeDeleted(U, Existing);
3926 DeleteNodeNotInCSEMaps(U);
3928 // If the node doesn't already exist, we updated it. Inform a listener if
3931 UpdateListener->NodeUpdated(U);
3936 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3937 /// This can cause recursive merging of nodes in the DAG.
3939 /// This version assumes From/To have matching types and numbers of result
3942 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3943 DAGUpdateListener *UpdateListener) {
3944 assert(From != To && "Cannot replace uses of with self");
3945 assert(From->getNumValues() == To->getNumValues() &&
3946 "Cannot use this version of ReplaceAllUsesWith!");
3947 if (From->getNumValues() == 1) // If possible, use the faster version.
3948 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3951 while (!From->use_empty()) {
3952 SDNode::use_iterator UI = From->use_begin();
3953 SDNode *U = UI->getUser();
3955 // This node is about to morph, remove its old self from the CSE maps.
3956 RemoveNodeFromCSEMaps(U);
3958 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3959 I != E; ++I, ++operandNum)
3960 if (I->getVal() == From) {
3961 From->removeUser(operandNum, U);
3963 To->addUser(operandNum, U);
3966 // Now that we have modified U, add it back to the CSE maps. If it already
3967 // exists there, recursively merge the results together.
3968 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3969 ReplaceAllUsesWith(U, Existing, UpdateListener);
3970 // U is now dead. Inform the listener if it exists and delete it.
3972 UpdateListener->NodeDeleted(U, Existing);
3973 DeleteNodeNotInCSEMaps(U);
3975 // If the node doesn't already exist, we updated it. Inform a listener if
3978 UpdateListener->NodeUpdated(U);
3983 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3984 /// This can cause recursive merging of nodes in the DAG.
3986 /// This version can replace From with any result values. To must match the
3987 /// number and types of values returned by From.
3988 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3990 DAGUpdateListener *UpdateListener) {
3991 if (From->getNumValues() == 1) // Handle the simple case efficiently.
3992 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3994 while (!From->use_empty()) {
3995 SDNode::use_iterator UI = From->use_begin();
3996 SDNode *U = UI->getUser();
3998 // This node is about to morph, remove its old self from the CSE maps.
3999 RemoveNodeFromCSEMaps(U);
4001 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4002 I != E; ++I, ++operandNum)
4003 if (I->getVal() == From) {
4004 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4005 From->removeUser(operandNum, U);
4008 ToOp.Val->addUser(operandNum, U);
4011 // Now that we have modified U, add it back to the CSE maps. If it already
4012 // exists there, recursively merge the results together.
4013 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4014 ReplaceAllUsesWith(U, Existing, UpdateListener);
4015 // U is now dead. Inform the listener if it exists and delete it.
4017 UpdateListener->NodeDeleted(U, Existing);
4018 DeleteNodeNotInCSEMaps(U);
4020 // If the node doesn't already exist, we updated it. Inform a listener if
4023 UpdateListener->NodeUpdated(U);
4029 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4030 /// any deleted nodes from the set passed into its constructor and recursively
4031 /// notifies another update listener if specified.
4032 class ChainedSetUpdaterListener :
4033 public SelectionDAG::DAGUpdateListener {
4034 SmallSetVector<SDNode*, 16> &Set;
4035 SelectionDAG::DAGUpdateListener *Chain;
4037 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4038 SelectionDAG::DAGUpdateListener *chain)
4039 : Set(set), Chain(chain) {}
4041 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4043 if (Chain) Chain->NodeDeleted(N, E);
4045 virtual void NodeUpdated(SDNode *N) {
4046 if (Chain) Chain->NodeUpdated(N);
4051 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4052 /// uses of other values produced by From.Val alone. The Deleted vector is
4053 /// handled the same way as for ReplaceAllUsesWith.
4054 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4055 DAGUpdateListener *UpdateListener){
4056 assert(From != To && "Cannot replace a value with itself");
4058 // Handle the simple, trivial, case efficiently.
4059 if (From.Val->getNumValues() == 1) {
4060 ReplaceAllUsesWith(From, To, UpdateListener);
4064 if (From.use_empty()) return;
4066 // Get all of the users of From.Val. We want these in a nice,
4067 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4068 SmallSetVector<SDNode*, 16> Users;
4069 for (SDNode::use_iterator UI = From.Val->use_begin(),
4070 E = From.Val->use_end(); UI != E; ++UI) {
4071 SDNode *User = UI->getUser();
4072 if (!Users.count(User))
4076 // When one of the recursive merges deletes nodes from the graph, we need to
4077 // make sure that UpdateListener is notified *and* that the node is removed
4078 // from Users if present. CSUL does this.
4079 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4081 while (!Users.empty()) {
4082 // We know that this user uses some value of From. If it is the right
4083 // value, update it.
4084 SDNode *User = Users.back();
4087 // Scan for an operand that matches From.
4088 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4089 for (; Op != E; ++Op)
4090 if (*Op == From) break;
4092 // If there are no matches, the user must use some other result of From.
4093 if (Op == E) continue;
4095 // Okay, we know this user needs to be updated. Remove its old self
4096 // from the CSE maps.
4097 RemoveNodeFromCSEMaps(User);
4099 // Update all operands that match "From" in case there are multiple uses.
4100 for (; Op != E; ++Op) {
4102 From.Val->removeUser(Op-User->op_begin(), User);
4105 To.Val->addUser(Op-User->op_begin(), User);
4109 // Now that we have modified User, add it back to the CSE maps. If it
4110 // already exists there, recursively merge the results together.
4111 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4113 if (UpdateListener) UpdateListener->NodeUpdated(User);
4114 continue; // Continue on to next user.
4117 // If there was already an existing matching node, use ReplaceAllUsesWith
4118 // to replace the dead one with the existing one. This can cause
4119 // recursive merging of other unrelated nodes down the line. The merging
4120 // can cause deletion of nodes that used the old value. To handle this, we
4121 // use CSUL to remove them from the Users set.
4122 ReplaceAllUsesWith(User, Existing, &CSUL);
4124 // User is now dead. Notify a listener if present.
4125 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4126 DeleteNodeNotInCSEMaps(User);
4130 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4131 /// their allnodes order. It returns the maximum id.
4132 unsigned SelectionDAG::AssignNodeIds() {
4134 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4141 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4142 /// based on their topological order. It returns the maximum id and a vector
4143 /// of the SDNodes* in assigned order by reference.
4144 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4145 unsigned DAGSize = AllNodes.size();
4146 std::vector<unsigned> InDegree(DAGSize);
4147 std::vector<SDNode*> Sources;
4149 // Use a two pass approach to avoid using a std::map which is slow.
4151 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4154 unsigned Degree = N->use_size();
4155 InDegree[N->getNodeId()] = Degree;
4157 Sources.push_back(N);
4161 while (!Sources.empty()) {
4162 SDNode *N = Sources.back();
4164 TopOrder.push_back(N);
4165 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4166 SDNode *P = I->getVal();
4167 unsigned Degree = --InDegree[P->getNodeId()];
4169 Sources.push_back(P);
4173 // Second pass, assign the actual topological order as node ids.
4175 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4177 (*TI)->setNodeId(Id++);
4184 //===----------------------------------------------------------------------===//
4186 //===----------------------------------------------------------------------===//
4188 // Out-of-line virtual method to give class a home.
4189 void SDNode::ANCHOR() {}
4190 void UnarySDNode::ANCHOR() {}
4191 void BinarySDNode::ANCHOR() {}
4192 void TernarySDNode::ANCHOR() {}
4193 void HandleSDNode::ANCHOR() {}
4194 void ConstantSDNode::ANCHOR() {}
4195 void ConstantFPSDNode::ANCHOR() {}
4196 void GlobalAddressSDNode::ANCHOR() {}
4197 void FrameIndexSDNode::ANCHOR() {}
4198 void JumpTableSDNode::ANCHOR() {}
4199 void ConstantPoolSDNode::ANCHOR() {}
4200 void BasicBlockSDNode::ANCHOR() {}
4201 void SrcValueSDNode::ANCHOR() {}
4202 void MemOperandSDNode::ANCHOR() {}
4203 void RegisterSDNode::ANCHOR() {}
4204 void DbgStopPointSDNode::ANCHOR() {}
4205 void ExternalSymbolSDNode::ANCHOR() {}
4206 void CondCodeSDNode::ANCHOR() {}
4207 void ARG_FLAGSSDNode::ANCHOR() {}
4208 void VTSDNode::ANCHOR() {}
4209 void MemSDNode::ANCHOR() {}
4210 void LoadSDNode::ANCHOR() {}
4211 void StoreSDNode::ANCHOR() {}
4212 void AtomicSDNode::ANCHOR() {}
4214 HandleSDNode::~HandleSDNode() {
4215 SDVTList VTs = { 0, 0 };
4216 MorphNodeTo(ISD::HANDLENODE, VTs, SDOperandPtr(), 0); // Drops operand uses.
4219 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4221 : SDNode(isa<GlobalVariable>(GA) &&
4222 cast<GlobalVariable>(GA)->isThreadLocal() ?
4224 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4226 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4227 getSDVTList(VT)), Offset(o) {
4228 TheGlobal = const_cast<GlobalValue*>(GA);
4231 /// getMemOperand - Return a MachineMemOperand object describing the memory
4232 /// reference performed by this atomic.
4233 MachineMemOperand AtomicSDNode::getMemOperand() const {
4234 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4235 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4236 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4238 // Check if the atomic references a frame index
4239 const FrameIndexSDNode *FI =
4240 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4241 if (!getSrcValue() && FI)
4242 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4243 FI->getIndex(), Size, getAlignment());
4245 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4246 Size, getAlignment());
4249 /// getMemOperand - Return a MachineMemOperand object describing the memory
4250 /// reference performed by this load or store.
4251 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4252 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4254 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4255 MachineMemOperand::MOStore;
4256 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4258 // Check if the load references a frame index, and does not have
4260 const FrameIndexSDNode *FI =
4261 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4262 if (!getSrcValue() && FI)
4263 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4264 FI->getIndex(), Size, getAlignment());
4266 return MachineMemOperand(getSrcValue(), Flags,
4267 getSrcValueOffset(), Size, getAlignment());
4270 /// Profile - Gather unique data for the node.
4272 void SDNode::Profile(FoldingSetNodeID &ID) {
4273 AddNodeIDNode(ID, this);
4276 /// getValueTypeList - Return a pointer to the specified value type.
4278 const MVT *SDNode::getValueTypeList(MVT VT) {
4279 if (VT.isExtended()) {
4280 static std::set<MVT, MVT::compareRawBits> EVTs;
4281 return &(*EVTs.insert(VT).first);
4283 static MVT VTs[MVT::LAST_VALUETYPE];
4284 VTs[VT.getSimpleVT()] = VT;
4285 return &VTs[VT.getSimpleVT()];
4289 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4290 /// indicated value. This method ignores uses of other values defined by this
4292 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4293 assert(Value < getNumValues() && "Bad value!");
4295 // If there is only one value, this is easy.
4296 if (getNumValues() == 1)
4297 return use_size() == NUses;
4298 if (use_size() < NUses) return false;
4300 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4302 SmallPtrSet<SDNode*, 32> UsersHandled;
4304 // TODO: Only iterate over uses of a given value of the node
4305 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4306 if (*UI == TheValue) {
4313 // Found exactly the right number of uses?
4318 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4319 /// value. This method ignores uses of other values defined by this operation.
4320 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4321 assert(Value < getNumValues() && "Bad value!");
4323 if (use_empty()) return false;
4325 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4327 SmallPtrSet<SDNode*, 32> UsersHandled;
4329 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4330 SDNode *User = UI->getUser();
4331 if (User->getNumOperands() == 1 ||
4332 UsersHandled.insert(User)) // First time we've seen this?
4333 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4334 if (User->getOperand(i) == TheValue) {
4343 /// isOnlyUseOf - Return true if this node is the only use of N.
4345 bool SDNode::isOnlyUseOf(SDNode *N) const {
4347 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4348 SDNode *User = I->getUser();
4358 /// isOperand - Return true if this node is an operand of N.
4360 bool SDOperand::isOperandOf(SDNode *N) const {
4361 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4362 if (*this == N->getOperand(i))
4367 bool SDNode::isOperandOf(SDNode *N) const {
4368 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4369 if (this == N->OperandList[i].getVal())
4374 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4375 /// be a chain) reaches the specified operand without crossing any
4376 /// side-effecting instructions. In practice, this looks through token
4377 /// factors and non-volatile loads. In order to remain efficient, this only
4378 /// looks a couple of nodes in, it does not do an exhaustive search.
4379 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4380 unsigned Depth) const {
4381 if (*this == Dest) return true;
4383 // Don't search too deeply, we just want to be able to see through
4384 // TokenFactor's etc.
4385 if (Depth == 0) return false;
4387 // If this is a token factor, all inputs to the TF happen in parallel. If any
4388 // of the operands of the TF reach dest, then we can do the xform.
4389 if (getOpcode() == ISD::TokenFactor) {
4390 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4391 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4396 // Loads don't have side effects, look through them.
4397 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4398 if (!Ld->isVolatile())
4399 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4405 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4406 SmallPtrSet<SDNode *, 32> &Visited) {
4407 if (found || !Visited.insert(N))
4410 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4411 SDNode *Op = N->getOperand(i).Val;
4416 findPredecessor(Op, P, found, Visited);
4420 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4421 /// is either an operand of N or it can be reached by recursively traversing
4422 /// up the operands.
4423 /// NOTE: this is an expensive method. Use it carefully.
4424 bool SDNode::isPredecessorOf(SDNode *N) const {
4425 SmallPtrSet<SDNode *, 32> Visited;
4427 findPredecessor(N, this, found, Visited);
4431 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4432 assert(Num < NumOperands && "Invalid child # of SDNode!");
4433 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4436 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4437 switch (getOpcode()) {
4439 if (getOpcode() < ISD::BUILTIN_OP_END)
4440 return "<<Unknown DAG Node>>";
4443 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4444 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4445 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4447 TargetLowering &TLI = G->getTargetLoweringInfo();
4449 TLI.getTargetNodeName(getOpcode());
4450 if (Name) return Name;
4453 return "<<Unknown Target Node>>";
4456 case ISD::PREFETCH: return "Prefetch";
4457 case ISD::MEMBARRIER: return "MemBarrier";
4458 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4459 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4460 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4461 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4462 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4463 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4464 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4465 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4466 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4467 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4468 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4469 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4470 case ISD::PCMARKER: return "PCMarker";
4471 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4472 case ISD::SRCVALUE: return "SrcValue";
4473 case ISD::MEMOPERAND: return "MemOperand";
4474 case ISD::EntryToken: return "EntryToken";
4475 case ISD::TokenFactor: return "TokenFactor";
4476 case ISD::AssertSext: return "AssertSext";
4477 case ISD::AssertZext: return "AssertZext";
4479 case ISD::BasicBlock: return "BasicBlock";
4480 case ISD::ARG_FLAGS: return "ArgFlags";
4481 case ISD::VALUETYPE: return "ValueType";
4482 case ISD::Register: return "Register";
4484 case ISD::Constant: return "Constant";
4485 case ISD::ConstantFP: return "ConstantFP";
4486 case ISD::GlobalAddress: return "GlobalAddress";
4487 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4488 case ISD::FrameIndex: return "FrameIndex";
4489 case ISD::JumpTable: return "JumpTable";
4490 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4491 case ISD::RETURNADDR: return "RETURNADDR";
4492 case ISD::FRAMEADDR: return "FRAMEADDR";
4493 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4494 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4495 case ISD::EHSELECTION: return "EHSELECTION";
4496 case ISD::EH_RETURN: return "EH_RETURN";
4497 case ISD::ConstantPool: return "ConstantPool";
4498 case ISD::ExternalSymbol: return "ExternalSymbol";
4499 case ISD::INTRINSIC_WO_CHAIN: {
4500 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4501 return Intrinsic::getName((Intrinsic::ID)IID);
4503 case ISD::INTRINSIC_VOID:
4504 case ISD::INTRINSIC_W_CHAIN: {
4505 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4506 return Intrinsic::getName((Intrinsic::ID)IID);
4509 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4510 case ISD::TargetConstant: return "TargetConstant";
4511 case ISD::TargetConstantFP:return "TargetConstantFP";
4512 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4513 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4514 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4515 case ISD::TargetJumpTable: return "TargetJumpTable";
4516 case ISD::TargetConstantPool: return "TargetConstantPool";
4517 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4519 case ISD::CopyToReg: return "CopyToReg";
4520 case ISD::CopyFromReg: return "CopyFromReg";
4521 case ISD::UNDEF: return "undef";
4522 case ISD::MERGE_VALUES: return "merge_values";
4523 case ISD::INLINEASM: return "inlineasm";
4524 case ISD::LABEL: return "label";
4525 case ISD::DECLARE: return "declare";
4526 case ISD::HANDLENODE: return "handlenode";
4527 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4528 case ISD::CALL: return "call";
4531 case ISD::FABS: return "fabs";
4532 case ISD::FNEG: return "fneg";
4533 case ISD::FSQRT: return "fsqrt";
4534 case ISD::FSIN: return "fsin";
4535 case ISD::FCOS: return "fcos";
4536 case ISD::FPOWI: return "fpowi";
4537 case ISD::FPOW: return "fpow";
4540 case ISD::ADD: return "add";
4541 case ISD::SUB: return "sub";
4542 case ISD::MUL: return "mul";
4543 case ISD::MULHU: return "mulhu";
4544 case ISD::MULHS: return "mulhs";
4545 case ISD::SDIV: return "sdiv";
4546 case ISD::UDIV: return "udiv";
4547 case ISD::SREM: return "srem";
4548 case ISD::UREM: return "urem";
4549 case ISD::SMUL_LOHI: return "smul_lohi";
4550 case ISD::UMUL_LOHI: return "umul_lohi";
4551 case ISD::SDIVREM: return "sdivrem";
4552 case ISD::UDIVREM: return "divrem";
4553 case ISD::AND: return "and";
4554 case ISD::OR: return "or";
4555 case ISD::XOR: return "xor";
4556 case ISD::SHL: return "shl";
4557 case ISD::SRA: return "sra";
4558 case ISD::SRL: return "srl";
4559 case ISD::ROTL: return "rotl";
4560 case ISD::ROTR: return "rotr";
4561 case ISD::FADD: return "fadd";
4562 case ISD::FSUB: return "fsub";
4563 case ISD::FMUL: return "fmul";
4564 case ISD::FDIV: return "fdiv";
4565 case ISD::FREM: return "frem";
4566 case ISD::FCOPYSIGN: return "fcopysign";
4567 case ISD::FGETSIGN: return "fgetsign";
4569 case ISD::SETCC: return "setcc";
4570 case ISD::VSETCC: return "vsetcc";
4571 case ISD::SELECT: return "select";
4572 case ISD::SELECT_CC: return "select_cc";
4573 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4574 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4575 case ISD::CONCAT_VECTORS: return "concat_vectors";
4576 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4577 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4578 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4579 case ISD::CARRY_FALSE: return "carry_false";
4580 case ISD::ADDC: return "addc";
4581 case ISD::ADDE: return "adde";
4582 case ISD::SUBC: return "subc";
4583 case ISD::SUBE: return "sube";
4584 case ISD::SHL_PARTS: return "shl_parts";
4585 case ISD::SRA_PARTS: return "sra_parts";
4586 case ISD::SRL_PARTS: return "srl_parts";
4588 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4589 case ISD::INSERT_SUBREG: return "insert_subreg";
4591 // Conversion operators.
4592 case ISD::SIGN_EXTEND: return "sign_extend";
4593 case ISD::ZERO_EXTEND: return "zero_extend";
4594 case ISD::ANY_EXTEND: return "any_extend";
4595 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4596 case ISD::TRUNCATE: return "truncate";
4597 case ISD::FP_ROUND: return "fp_round";
4598 case ISD::FLT_ROUNDS_: return "flt_rounds";
4599 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4600 case ISD::FP_EXTEND: return "fp_extend";
4602 case ISD::SINT_TO_FP: return "sint_to_fp";
4603 case ISD::UINT_TO_FP: return "uint_to_fp";
4604 case ISD::FP_TO_SINT: return "fp_to_sint";
4605 case ISD::FP_TO_UINT: return "fp_to_uint";
4606 case ISD::BIT_CONVERT: return "bit_convert";
4608 // Control flow instructions
4609 case ISD::BR: return "br";
4610 case ISD::BRIND: return "brind";
4611 case ISD::BR_JT: return "br_jt";
4612 case ISD::BRCOND: return "brcond";
4613 case ISD::BR_CC: return "br_cc";
4614 case ISD::RET: return "ret";
4615 case ISD::CALLSEQ_START: return "callseq_start";
4616 case ISD::CALLSEQ_END: return "callseq_end";
4619 case ISD::LOAD: return "load";
4620 case ISD::STORE: return "store";
4621 case ISD::VAARG: return "vaarg";
4622 case ISD::VACOPY: return "vacopy";
4623 case ISD::VAEND: return "vaend";
4624 case ISD::VASTART: return "vastart";
4625 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4626 case ISD::EXTRACT_ELEMENT: return "extract_element";
4627 case ISD::BUILD_PAIR: return "build_pair";
4628 case ISD::STACKSAVE: return "stacksave";
4629 case ISD::STACKRESTORE: return "stackrestore";
4630 case ISD::TRAP: return "trap";
4633 case ISD::BSWAP: return "bswap";
4634 case ISD::CTPOP: return "ctpop";
4635 case ISD::CTTZ: return "cttz";
4636 case ISD::CTLZ: return "ctlz";
4639 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4640 case ISD::DEBUG_LOC: return "debug_loc";
4643 case ISD::TRAMPOLINE: return "trampoline";
4646 switch (cast<CondCodeSDNode>(this)->get()) {
4647 default: assert(0 && "Unknown setcc condition!");
4648 case ISD::SETOEQ: return "setoeq";
4649 case ISD::SETOGT: return "setogt";
4650 case ISD::SETOGE: return "setoge";
4651 case ISD::SETOLT: return "setolt";
4652 case ISD::SETOLE: return "setole";
4653 case ISD::SETONE: return "setone";
4655 case ISD::SETO: return "seto";
4656 case ISD::SETUO: return "setuo";
4657 case ISD::SETUEQ: return "setue";
4658 case ISD::SETUGT: return "setugt";
4659 case ISD::SETUGE: return "setuge";
4660 case ISD::SETULT: return "setult";
4661 case ISD::SETULE: return "setule";
4662 case ISD::SETUNE: return "setune";
4664 case ISD::SETEQ: return "seteq";
4665 case ISD::SETGT: return "setgt";
4666 case ISD::SETGE: return "setge";
4667 case ISD::SETLT: return "setlt";
4668 case ISD::SETLE: return "setle";
4669 case ISD::SETNE: return "setne";
4674 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4683 return "<post-inc>";
4685 return "<post-dec>";
4689 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4690 std::string S = "< ";
4704 if (getByValAlign())
4705 S += "byval-align:" + utostr(getByValAlign()) + " ";
4707 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4709 S += "byval-size:" + utostr(getByValSize()) + " ";
4713 void SDNode::dump() const { dump(0); }
4714 void SDNode::dump(const SelectionDAG *G) const {
4715 cerr << (void*)this << ": ";
4717 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4719 if (getValueType(i) == MVT::Other)
4722 cerr << getValueType(i).getMVTString();
4724 cerr << " = " << getOperationName(G);
4727 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4728 if (i) cerr << ", ";
4729 cerr << (void*)getOperand(i).Val;
4730 if (unsigned RN = getOperand(i).ResNo)
4734 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4735 SDNode *Mask = getOperand(2).Val;
4737 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4739 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4742 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4747 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4748 cerr << "<" << CSDN->getValue() << ">";
4749 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4750 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4751 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4752 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4753 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4755 cerr << "<APFloat(";
4756 CSDN->getValueAPF().convertToAPInt().dump();
4759 } else if (const GlobalAddressSDNode *GADN =
4760 dyn_cast<GlobalAddressSDNode>(this)) {
4761 int offset = GADN->getOffset();
4763 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4765 cerr << " + " << offset;
4767 cerr << " " << offset;
4768 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4769 cerr << "<" << FIDN->getIndex() << ">";
4770 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4771 cerr << "<" << JTDN->getIndex() << ">";
4772 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4773 int offset = CP->getOffset();
4774 if (CP->isMachineConstantPoolEntry())
4775 cerr << "<" << *CP->getMachineCPVal() << ">";
4777 cerr << "<" << *CP->getConstVal() << ">";
4779 cerr << " + " << offset;
4781 cerr << " " << offset;
4782 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4784 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4786 cerr << LBB->getName() << " ";
4787 cerr << (const void*)BBDN->getBasicBlock() << ">";
4788 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4789 if (G && R->getReg() &&
4790 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4791 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4793 cerr << " #" << R->getReg();
4795 } else if (const ExternalSymbolSDNode *ES =
4796 dyn_cast<ExternalSymbolSDNode>(this)) {
4797 cerr << "'" << ES->getSymbol() << "'";
4798 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4800 cerr << "<" << M->getValue() << ">";
4803 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4804 if (M->MO.getValue())
4805 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4807 cerr << "<null:" << M->MO.getOffset() << ">";
4808 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4809 cerr << N->getArgFlags().getArgFlagsString();
4810 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4811 cerr << ":" << N->getVT().getMVTString();
4813 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4814 const Value *SrcValue = LD->getSrcValue();
4815 int SrcOffset = LD->getSrcValueOffset();
4821 cerr << ":" << SrcOffset << ">";
4824 switch (LD->getExtensionType()) {
4825 default: doExt = false; break;
4827 cerr << " <anyext ";
4837 cerr << LD->getMemoryVT().getMVTString() << ">";
4839 const char *AM = getIndexedModeName(LD->getAddressingMode());
4842 if (LD->isVolatile())
4843 cerr << " <volatile>";
4844 cerr << " alignment=" << LD->getAlignment();
4845 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4846 const Value *SrcValue = ST->getSrcValue();
4847 int SrcOffset = ST->getSrcValueOffset();
4853 cerr << ":" << SrcOffset << ">";
4855 if (ST->isTruncatingStore())
4857 << ST->getMemoryVT().getMVTString() << ">";
4859 const char *AM = getIndexedModeName(ST->getAddressingMode());
4862 if (ST->isVolatile())
4863 cerr << " <volatile>";
4864 cerr << " alignment=" << ST->getAlignment();
4865 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4866 const Value *SrcValue = AT->getSrcValue();
4867 int SrcOffset = AT->getSrcValueOffset();
4873 cerr << ":" << SrcOffset << ">";
4874 if (AT->isVolatile())
4875 cerr << " <volatile>";
4876 cerr << " alignment=" << AT->getAlignment();
4880 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4881 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4882 if (N->getOperand(i).Val->hasOneUse())
4883 DumpNodes(N->getOperand(i).Val, indent+2, G);
4885 cerr << "\n" << std::string(indent+2, ' ')
4886 << (void*)N->getOperand(i).Val << ": <multiple use>";
4889 cerr << "\n" << std::string(indent, ' ');
4893 void SelectionDAG::dump() const {
4894 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4895 std::vector<const SDNode*> Nodes;
4896 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4900 std::sort(Nodes.begin(), Nodes.end());
4902 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4903 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4904 DumpNodes(Nodes[i], 2, this);
4907 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4912 const Type *ConstantPoolSDNode::getType() const {
4913 if (isMachineConstantPoolEntry())
4914 return Val.MachineCPVal->getType();
4915 return Val.ConstVal->getType();