1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/StringExtras.h"
43 /// makeVTList - Return an instance of the SDVTList struct initialized with the
44 /// specified members.
45 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
46 SDVTList Res = {VTs, NumVTs};
50 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
51 switch (VT.getSimpleVT()) {
52 default: assert(0 && "Unknown FP format");
53 case MVT::f32: return &APFloat::IEEEsingle;
54 case MVT::f64: return &APFloat::IEEEdouble;
55 case MVT::f80: return &APFloat::x87DoubleExtended;
56 case MVT::f128: return &APFloat::IEEEquad;
57 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
61 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
63 //===----------------------------------------------------------------------===//
64 // ConstantFPSDNode Class
65 //===----------------------------------------------------------------------===//
67 /// isExactlyValue - We don't rely on operator== working on double values, as
68 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
69 /// As such, this method can be used to do an exact bit-for-bit comparison of
70 /// two floating point values.
71 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
72 return getValueAPF().bitwiseIsEqual(V);
75 bool ConstantFPSDNode::isValueValidForType(MVT VT,
77 assert(VT.isFloatingPoint() && "Can only convert between FP types");
79 // PPC long double cannot be converted to any other type.
80 if (VT == MVT::ppcf128 ||
81 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
84 // convert modifies in place, so make a copy.
85 APFloat Val2 = APFloat(Val);
86 return Val2.convert(*MVTToAPFloatSemantics(VT),
87 APFloat::rmNearestTiesToEven) == APFloat::opOK;
90 //===----------------------------------------------------------------------===//
92 //===----------------------------------------------------------------------===//
94 /// isBuildVectorAllOnes - Return true if the specified node is a
95 /// BUILD_VECTOR where all of the elements are ~0 or undef.
96 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
97 // Look through a bit convert.
98 if (N->getOpcode() == ISD::BIT_CONVERT)
99 N = N->getOperand(0).getNode();
101 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
103 unsigned i = 0, e = N->getNumOperands();
105 // Skip over all of the undef values.
106 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
109 // Do not accept an all-undef vector.
110 if (i == e) return false;
112 // Do not accept build_vectors that aren't all constants or which have non-~0
114 SDValue NotZero = N->getOperand(i);
115 if (isa<ConstantSDNode>(NotZero)) {
116 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
118 } else if (isa<ConstantFPSDNode>(NotZero)) {
119 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
120 convertToAPInt().isAllOnesValue())
125 // Okay, we have at least one ~0 value, check to see if the rest match or are
127 for (++i; i != e; ++i)
128 if (N->getOperand(i) != NotZero &&
129 N->getOperand(i).getOpcode() != ISD::UNDEF)
135 /// isBuildVectorAllZeros - Return true if the specified node is a
136 /// BUILD_VECTOR where all of the elements are 0 or undef.
137 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
138 // Look through a bit convert.
139 if (N->getOpcode() == ISD::BIT_CONVERT)
140 N = N->getOperand(0).getNode();
142 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
144 unsigned i = 0, e = N->getNumOperands();
146 // Skip over all of the undef values.
147 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
150 // Do not accept an all-undef vector.
151 if (i == e) return false;
153 // Do not accept build_vectors that aren't all constants or which have non-~0
155 SDValue Zero = N->getOperand(i);
156 if (isa<ConstantSDNode>(Zero)) {
157 if (!cast<ConstantSDNode>(Zero)->isNullValue())
159 } else if (isa<ConstantFPSDNode>(Zero)) {
160 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
165 // Okay, we have at least one ~0 value, check to see if the rest match or are
167 for (++i; i != e; ++i)
168 if (N->getOperand(i) != Zero &&
169 N->getOperand(i).getOpcode() != ISD::UNDEF)
174 /// isScalarToVector - Return true if the specified node is a
175 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
176 /// element is not an undef.
177 bool ISD::isScalarToVector(const SDNode *N) {
178 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
181 if (N->getOpcode() != ISD::BUILD_VECTOR)
183 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
185 unsigned NumElems = N->getNumOperands();
186 for (unsigned i = 1; i < NumElems; ++i) {
187 SDValue V = N->getOperand(i);
188 if (V.getOpcode() != ISD::UNDEF)
195 /// isDebugLabel - Return true if the specified node represents a debug
196 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
197 bool ISD::isDebugLabel(const SDNode *N) {
199 if (N->getOpcode() == ISD::DBG_LABEL)
201 if (N->isMachineOpcode() &&
202 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
207 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
208 /// when given the operation for (X op Y).
209 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
210 // To perform this operation, we just need to swap the L and G bits of the
212 unsigned OldL = (Operation >> 2) & 1;
213 unsigned OldG = (Operation >> 1) & 1;
214 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
215 (OldL << 1) | // New G bit
216 (OldG << 2)); // New L bit.
219 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
220 /// 'op' is a valid SetCC operation.
221 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
222 unsigned Operation = Op;
224 Operation ^= 7; // Flip L, G, E bits, but not U.
226 Operation ^= 15; // Flip all of the condition bits.
227 if (Operation > ISD::SETTRUE2)
228 Operation &= ~8; // Don't let N and U bits get set.
229 return ISD::CondCode(Operation);
233 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
234 /// signed operation and 2 if the result is an unsigned comparison. Return zero
235 /// if the operation does not depend on the sign of the input (setne and seteq).
236 static int isSignedOp(ISD::CondCode Opcode) {
238 default: assert(0 && "Illegal integer setcc operation!");
240 case ISD::SETNE: return 0;
244 case ISD::SETGE: return 1;
248 case ISD::SETUGE: return 2;
252 /// getSetCCOrOperation - Return the result of a logical OR between different
253 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
254 /// returns SETCC_INVALID if it is not possible to represent the resultant
256 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
258 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
259 // Cannot fold a signed integer setcc with an unsigned integer setcc.
260 return ISD::SETCC_INVALID;
262 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
264 // If the N and U bits get set then the resultant comparison DOES suddenly
265 // care about orderedness, and is true when ordered.
266 if (Op > ISD::SETTRUE2)
267 Op &= ~16; // Clear the U bit if the N bit is set.
269 // Canonicalize illegal integer setcc's.
270 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
273 return ISD::CondCode(Op);
276 /// getSetCCAndOperation - Return the result of a logical AND between different
277 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
278 /// function returns zero if it is not possible to represent the resultant
280 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
282 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
283 // Cannot fold a signed setcc with an unsigned setcc.
284 return ISD::SETCC_INVALID;
286 // Combine all of the condition bits.
287 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
289 // Canonicalize illegal integer setcc's.
293 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
294 case ISD::SETOEQ: // SETEQ & SETU[LG]E
295 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
296 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
297 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
304 const TargetMachine &SelectionDAG::getTarget() const {
305 return MF->getTarget();
308 //===----------------------------------------------------------------------===//
309 // SDNode Profile Support
310 //===----------------------------------------------------------------------===//
312 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
314 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
318 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
319 /// solely with their pointer.
320 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
321 ID.AddPointer(VTList.VTs);
324 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
326 static void AddNodeIDOperands(FoldingSetNodeID &ID,
327 const SDValue *Ops, unsigned NumOps) {
328 for (; NumOps; --NumOps, ++Ops) {
329 ID.AddPointer(Ops->getNode());
330 ID.AddInteger(Ops->getResNo());
334 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
336 static void AddNodeIDOperands(FoldingSetNodeID &ID,
337 const SDUse *Ops, unsigned NumOps) {
338 for (; NumOps; --NumOps, ++Ops) {
339 ID.AddPointer(Ops->getVal());
340 ID.AddInteger(Ops->getSDValue().getResNo());
344 static void AddNodeIDNode(FoldingSetNodeID &ID,
345 unsigned short OpC, SDVTList VTList,
346 const SDValue *OpList, unsigned N) {
347 AddNodeIDOpcode(ID, OpC);
348 AddNodeIDValueTypes(ID, VTList);
349 AddNodeIDOperands(ID, OpList, N);
353 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
355 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
356 AddNodeIDOpcode(ID, N->getOpcode());
357 // Add the return value info.
358 AddNodeIDValueTypes(ID, N->getVTList());
359 // Add the operand info.
360 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
362 // Handle SDNode leafs with special info.
363 switch (N->getOpcode()) {
364 default: break; // Normal nodes don't need extra info.
366 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
368 case ISD::TargetConstant:
370 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
372 case ISD::TargetConstantFP:
373 case ISD::ConstantFP: {
374 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
377 case ISD::TargetGlobalAddress:
378 case ISD::GlobalAddress:
379 case ISD::TargetGlobalTLSAddress:
380 case ISD::GlobalTLSAddress: {
381 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
382 ID.AddPointer(GA->getGlobal());
383 ID.AddInteger(GA->getOffset());
386 case ISD::BasicBlock:
387 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
390 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
392 case ISD::DBG_STOPPOINT: {
393 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
394 ID.AddInteger(DSP->getLine());
395 ID.AddInteger(DSP->getColumn());
396 ID.AddPointer(DSP->getCompileUnit());
400 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
402 case ISD::MEMOPERAND: {
403 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
407 case ISD::FrameIndex:
408 case ISD::TargetFrameIndex:
409 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
412 case ISD::TargetJumpTable:
413 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
415 case ISD::ConstantPool:
416 case ISD::TargetConstantPool: {
417 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
418 ID.AddInteger(CP->getAlignment());
419 ID.AddInteger(CP->getOffset());
420 if (CP->isMachineConstantPoolEntry())
421 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
423 ID.AddPointer(CP->getConstVal());
427 const CallSDNode *Call = cast<CallSDNode>(N);
428 ID.AddInteger(Call->getCallingConv());
429 ID.AddInteger(Call->isVarArg());
433 const LoadSDNode *LD = cast<LoadSDNode>(N);
434 ID.AddInteger(LD->getAddressingMode());
435 ID.AddInteger(LD->getExtensionType());
436 ID.AddInteger(LD->getMemoryVT().getRawBits());
437 ID.AddInteger(LD->getRawFlags());
441 const StoreSDNode *ST = cast<StoreSDNode>(N);
442 ID.AddInteger(ST->getAddressingMode());
443 ID.AddInteger(ST->isTruncatingStore());
444 ID.AddInteger(ST->getMemoryVT().getRawBits());
445 ID.AddInteger(ST->getRawFlags());
448 case ISD::ATOMIC_CMP_SWAP_8:
449 case ISD::ATOMIC_SWAP_8:
450 case ISD::ATOMIC_LOAD_ADD_8:
451 case ISD::ATOMIC_LOAD_SUB_8:
452 case ISD::ATOMIC_LOAD_AND_8:
453 case ISD::ATOMIC_LOAD_OR_8:
454 case ISD::ATOMIC_LOAD_XOR_8:
455 case ISD::ATOMIC_LOAD_NAND_8:
456 case ISD::ATOMIC_LOAD_MIN_8:
457 case ISD::ATOMIC_LOAD_MAX_8:
458 case ISD::ATOMIC_LOAD_UMIN_8:
459 case ISD::ATOMIC_LOAD_UMAX_8:
460 case ISD::ATOMIC_CMP_SWAP_16:
461 case ISD::ATOMIC_SWAP_16:
462 case ISD::ATOMIC_LOAD_ADD_16:
463 case ISD::ATOMIC_LOAD_SUB_16:
464 case ISD::ATOMIC_LOAD_AND_16:
465 case ISD::ATOMIC_LOAD_OR_16:
466 case ISD::ATOMIC_LOAD_XOR_16:
467 case ISD::ATOMIC_LOAD_NAND_16:
468 case ISD::ATOMIC_LOAD_MIN_16:
469 case ISD::ATOMIC_LOAD_MAX_16:
470 case ISD::ATOMIC_LOAD_UMIN_16:
471 case ISD::ATOMIC_LOAD_UMAX_16:
472 case ISD::ATOMIC_CMP_SWAP_32:
473 case ISD::ATOMIC_SWAP_32:
474 case ISD::ATOMIC_LOAD_ADD_32:
475 case ISD::ATOMIC_LOAD_SUB_32:
476 case ISD::ATOMIC_LOAD_AND_32:
477 case ISD::ATOMIC_LOAD_OR_32:
478 case ISD::ATOMIC_LOAD_XOR_32:
479 case ISD::ATOMIC_LOAD_NAND_32:
480 case ISD::ATOMIC_LOAD_MIN_32:
481 case ISD::ATOMIC_LOAD_MAX_32:
482 case ISD::ATOMIC_LOAD_UMIN_32:
483 case ISD::ATOMIC_LOAD_UMAX_32:
484 case ISD::ATOMIC_CMP_SWAP_64:
485 case ISD::ATOMIC_SWAP_64:
486 case ISD::ATOMIC_LOAD_ADD_64:
487 case ISD::ATOMIC_LOAD_SUB_64:
488 case ISD::ATOMIC_LOAD_AND_64:
489 case ISD::ATOMIC_LOAD_OR_64:
490 case ISD::ATOMIC_LOAD_XOR_64:
491 case ISD::ATOMIC_LOAD_NAND_64:
492 case ISD::ATOMIC_LOAD_MIN_64:
493 case ISD::ATOMIC_LOAD_MAX_64:
494 case ISD::ATOMIC_LOAD_UMIN_64:
495 case ISD::ATOMIC_LOAD_UMAX_64: {
496 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
497 ID.AddInteger(AT->getRawFlags());
500 } // end switch (N->getOpcode())
503 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
504 /// the CSE map that carries both alignment and volatility information.
506 static unsigned encodeMemSDNodeFlags(bool isVolatile, unsigned Alignment) {
507 return isVolatile | ((Log2_32(Alignment) + 1) << 1);
510 //===----------------------------------------------------------------------===//
511 // SelectionDAG Class
512 //===----------------------------------------------------------------------===//
514 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
516 void SelectionDAG::RemoveDeadNodes() {
517 // Create a dummy node (which is not added to allnodes), that adds a reference
518 // to the root node, preventing it from being deleted.
519 HandleSDNode Dummy(getRoot());
521 SmallVector<SDNode*, 128> DeadNodes;
523 // Add all obviously-dead nodes to the DeadNodes worklist.
524 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
526 DeadNodes.push_back(I);
528 RemoveDeadNodes(DeadNodes);
530 // If the root changed (e.g. it was a dead load, update the root).
531 setRoot(Dummy.getValue());
534 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
535 /// given list, and any nodes that become unreachable as a result.
536 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
537 DAGUpdateListener *UpdateListener) {
539 // Process the worklist, deleting the nodes and adding their uses to the
541 while (!DeadNodes.empty()) {
542 SDNode *N = DeadNodes.back();
543 DeadNodes.pop_back();
546 UpdateListener->NodeDeleted(N, 0);
548 // Take the node out of the appropriate CSE map.
549 RemoveNodeFromCSEMaps(N);
551 // Next, brutally remove the operand list. This is safe to do, as there are
552 // no cycles in the graph.
553 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
554 SDNode *Operand = I->getVal();
555 Operand->removeUser(std::distance(N->op_begin(), I), N);
557 // Now that we removed this operand, see if there are no uses of it left.
558 if (Operand->use_empty())
559 DeadNodes.push_back(Operand);
561 if (N->OperandsNeedDelete) {
562 delete[] N->OperandList;
567 // Finally, remove N itself.
568 NodeAllocator.Deallocate(AllNodes.remove(N));
572 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
573 SmallVector<SDNode*, 16> DeadNodes(1, N);
574 RemoveDeadNodes(DeadNodes, UpdateListener);
577 void SelectionDAG::DeleteNode(SDNode *N) {
578 assert(N->use_empty() && "Cannot delete a node that is not dead!");
580 // First take this out of the appropriate CSE map.
581 RemoveNodeFromCSEMaps(N);
583 // Finally, remove uses due to operands of this node, remove from the
584 // AllNodes list, and delete the node.
585 DeleteNodeNotInCSEMaps(N);
588 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
590 // Drop all of the operands and decrement used node's use counts.
591 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
592 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
593 if (N->OperandsNeedDelete)
594 delete[] N->OperandList;
596 assert(N != AllNodes.begin());
597 NodeAllocator.Deallocate(AllNodes.remove(N));
600 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
601 /// correspond to it. This is useful when we're about to delete or repurpose
602 /// the node. We don't want future request for structurally identical nodes
603 /// to return N anymore.
604 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
606 switch (N->getOpcode()) {
607 case ISD::EntryToken:
608 assert(0 && "EntryToken should not be in CSEMaps!");
610 case ISD::HANDLENODE: return false; // noop.
612 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
613 "Cond code doesn't exist!");
614 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
615 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
617 case ISD::ExternalSymbol:
618 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
620 case ISD::TargetExternalSymbol:
622 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
624 case ISD::VALUETYPE: {
625 MVT VT = cast<VTSDNode>(N)->getVT();
626 if (VT.isExtended()) {
627 Erased = ExtendedValueTypeNodes.erase(VT);
629 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
630 ValueTypeNodes[VT.getSimpleVT()] = 0;
635 // Remove it from the CSE Map.
636 Erased = CSEMap.RemoveNode(N);
640 // Verify that the node was actually in one of the CSE maps, unless it has a
641 // flag result (which cannot be CSE'd) or is one of the special cases that are
642 // not subject to CSE.
643 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
644 !N->isMachineOpcode() &&
645 N->getOpcode() != ISD::DBG_LABEL &&
646 N->getOpcode() != ISD::DBG_STOPPOINT &&
647 N->getOpcode() != ISD::EH_LABEL &&
648 N->getOpcode() != ISD::DECLARE) {
651 assert(0 && "Node is not in map!");
657 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
658 /// has been taken out and modified in some way. If the specified node already
659 /// exists in the CSE maps, do not modify the maps, but return the existing node
660 /// instead. If it doesn't exist, add it and return null.
662 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
663 assert(N->getNumOperands() && "This is a leaf node!");
665 if (N->getValueType(0) == MVT::Flag)
666 return 0; // Never CSE anything that produces a flag.
668 switch (N->getOpcode()) {
670 case ISD::HANDLENODE:
672 case ISD::DBG_STOPPOINT:
675 return 0; // Never add these nodes.
678 // Check that remaining values produced are not flags.
679 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
680 if (N->getValueType(i) == MVT::Flag)
681 return 0; // Never CSE anything that produces a flag.
683 SDNode *New = CSEMap.GetOrInsertNode(N);
684 if (New != N) return New; // Node already existed.
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, SDValue Op,
694 if (N->getValueType(0) == MVT::Flag)
695 return 0; // Never CSE anything that produces a flag.
697 switch (N->getOpcode()) {
699 case ISD::HANDLENODE:
701 case ISD::DBG_STOPPOINT:
703 return 0; // Never add these nodes.
706 // Check that remaining values produced are not flags.
707 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
708 if (N->getValueType(i) == MVT::Flag)
709 return 0; // Never CSE anything that produces a flag.
711 SDValue Ops[] = { Op };
713 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
714 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
717 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
718 /// were replaced with those specified. If this node is never memoized,
719 /// return null, otherwise return a pointer to the slot it would take. If a
720 /// node already exists with these operands, the slot will be non-null.
721 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
722 SDValue Op1, SDValue Op2,
724 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
726 // Check that remaining values produced are not flags.
727 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
728 if (N->getValueType(i) == MVT::Flag)
729 return 0; // Never CSE anything that produces a flag.
731 SDValue Ops[] = { Op1, Op2 };
733 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
734 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
738 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
739 /// were replaced with those specified. If this node is never memoized,
740 /// return null, otherwise return a pointer to the slot it would take. If a
741 /// node already exists with these operands, the slot will be non-null.
742 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
743 const SDValue *Ops,unsigned NumOps,
745 if (N->getValueType(0) == MVT::Flag)
746 return 0; // Never CSE anything that produces a flag.
748 switch (N->getOpcode()) {
750 case ISD::HANDLENODE:
752 case ISD::DBG_STOPPOINT:
755 return 0; // Never add these nodes.
758 // Check that remaining values produced are not flags.
759 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
760 if (N->getValueType(i) == MVT::Flag)
761 return 0; // Never CSE anything that produces a flag.
764 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
766 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
767 ID.AddInteger(LD->getAddressingMode());
768 ID.AddInteger(LD->getExtensionType());
769 ID.AddInteger(LD->getMemoryVT().getRawBits());
770 ID.AddInteger(LD->getRawFlags());
771 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
772 ID.AddInteger(ST->getAddressingMode());
773 ID.AddInteger(ST->isTruncatingStore());
774 ID.AddInteger(ST->getMemoryVT().getRawBits());
775 ID.AddInteger(ST->getRawFlags());
778 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
781 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
782 void SelectionDAG::VerifyNode(SDNode *N) {
783 switch (N->getOpcode()) {
786 case ISD::BUILD_VECTOR: {
787 assert(N->getNumValues() == 1 && "Too many results for BUILD_VECTOR!");
788 assert(N->getValueType(0).isVector() && "Wrong BUILD_VECTOR return type!");
789 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
790 "Wrong number of BUILD_VECTOR operands!");
791 MVT EltVT = N->getValueType(0).getVectorElementType();
792 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
793 assert(I->getSDValue().getValueType() == EltVT &&
794 "Wrong BUILD_VECTOR operand type!");
800 /// getMVTAlignment - Compute the default alignment value for the
803 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
804 const Type *Ty = VT == MVT::iPTR ?
805 PointerType::get(Type::Int8Ty, 0) :
808 return TLI.getTargetData()->getABITypeAlignment(Ty);
811 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
812 : TLI(tli), FLI(fli),
813 EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
814 Root(getEntryNode()) {
815 AllNodes.push_back(&EntryNode);
818 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi) {
823 SelectionDAG::~SelectionDAG() {
827 void SelectionDAG::allnodes_clear() {
828 assert(&*AllNodes.begin() == &EntryNode);
829 AllNodes.remove(AllNodes.begin());
830 while (!AllNodes.empty()) {
831 SDNode *N = AllNodes.remove(AllNodes.begin());
832 N->SetNextInBucket(0);
833 if (N->OperandsNeedDelete)
834 delete [] N->OperandList;
835 NodeAllocator.Deallocate(N);
839 void SelectionDAG::clear() {
841 OperandAllocator.Reset();
844 ExtendedValueTypeNodes.clear();
845 ExternalSymbols.clear();
846 TargetExternalSymbols.clear();
847 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
848 static_cast<CondCodeSDNode*>(0));
849 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
850 static_cast<SDNode*>(0));
853 AllNodes.push_back(&EntryNode);
854 Root = getEntryNode();
857 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
858 if (Op.getValueType() == VT) return Op;
859 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
861 return getNode(ISD::AND, Op.getValueType(), Op,
862 getConstant(Imm, Op.getValueType()));
865 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
866 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
867 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
870 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
871 return getConstant(*ConstantInt::get(Val), VT, isT);
874 SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
875 assert(VT.isInteger() && "Cannot create FP integer constant!");
877 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
878 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
879 "APInt size does not match type size!");
881 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
883 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
887 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
889 return SDValue(N, 0);
891 N = NodeAllocator.Allocate<ConstantSDNode>();
892 new (N) ConstantSDNode(isT, &Val, EltVT);
893 CSEMap.InsertNode(N, IP);
894 AllNodes.push_back(N);
897 SDValue Result(N, 0);
899 SmallVector<SDValue, 8> Ops;
900 Ops.assign(VT.getVectorNumElements(), Result);
901 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
906 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
907 return getConstant(Val, TLI.getPointerTy(), isTarget);
911 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
912 return getConstantFP(*ConstantFP::get(V), VT, isTarget);
915 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
916 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
919 VT.isVector() ? VT.getVectorElementType() : VT;
921 // Do the map lookup using the actual bit pattern for the floating point
922 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
923 // we don't have issues with SNANs.
924 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
926 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
930 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
932 return SDValue(N, 0);
934 N = NodeAllocator.Allocate<ConstantFPSDNode>();
935 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
936 CSEMap.InsertNode(N, IP);
937 AllNodes.push_back(N);
940 SDValue Result(N, 0);
942 SmallVector<SDValue, 8> Ops;
943 Ops.assign(VT.getVectorNumElements(), Result);
944 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
949 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
951 VT.isVector() ? VT.getVectorElementType() : VT;
953 return getConstantFP(APFloat((float)Val), VT, isTarget);
955 return getConstantFP(APFloat(Val), VT, isTarget);
958 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
963 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
965 // If GV is an alias then use the aliasee for determining thread-localness.
966 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
967 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
970 if (GVar && GVar->isThreadLocal())
971 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
973 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
976 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
978 ID.AddInteger(Offset);
980 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
981 return SDValue(E, 0);
982 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
983 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
984 CSEMap.InsertNode(N, IP);
985 AllNodes.push_back(N);
986 return SDValue(N, 0);
989 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
990 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
992 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
995 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
996 return SDValue(E, 0);
997 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
998 new (N) FrameIndexSDNode(FI, VT, isTarget);
999 CSEMap.InsertNode(N, IP);
1000 AllNodes.push_back(N);
1001 return SDValue(N, 0);
1004 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
1005 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1006 FoldingSetNodeID ID;
1007 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1010 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1011 return SDValue(E, 0);
1012 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1013 new (N) JumpTableSDNode(JTI, VT, isTarget);
1014 CSEMap.InsertNode(N, IP);
1015 AllNodes.push_back(N);
1016 return SDValue(N, 0);
1019 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
1020 unsigned Alignment, int Offset,
1024 TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1025 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1026 FoldingSetNodeID ID;
1027 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1028 ID.AddInteger(Alignment);
1029 ID.AddInteger(Offset);
1032 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1033 return SDValue(E, 0);
1034 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1035 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1036 CSEMap.InsertNode(N, IP);
1037 AllNodes.push_back(N);
1038 return SDValue(N, 0);
1042 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
1043 unsigned Alignment, int Offset,
1047 TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1048 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1049 FoldingSetNodeID ID;
1050 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1051 ID.AddInteger(Alignment);
1052 ID.AddInteger(Offset);
1053 C->AddSelectionDAGCSEId(ID);
1055 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1056 return SDValue(E, 0);
1057 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1058 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1059 CSEMap.InsertNode(N, IP);
1060 AllNodes.push_back(N);
1061 return SDValue(N, 0);
1065 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1066 FoldingSetNodeID ID;
1067 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1070 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1071 return SDValue(E, 0);
1072 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1073 new (N) BasicBlockSDNode(MBB);
1074 CSEMap.InsertNode(N, IP);
1075 AllNodes.push_back(N);
1076 return SDValue(N, 0);
1079 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
1080 FoldingSetNodeID ID;
1081 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
1082 ID.AddInteger(Flags.getRawBits());
1084 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1085 return SDValue(E, 0);
1086 SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
1087 new (N) ARG_FLAGSSDNode(Flags);
1088 CSEMap.InsertNode(N, IP);
1089 AllNodes.push_back(N);
1090 return SDValue(N, 0);
1093 SDValue SelectionDAG::getValueType(MVT VT) {
1094 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1095 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1097 SDNode *&N = VT.isExtended() ?
1098 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1100 if (N) return SDValue(N, 0);
1101 N = NodeAllocator.Allocate<VTSDNode>();
1102 new (N) VTSDNode(VT);
1103 AllNodes.push_back(N);
1104 return SDValue(N, 0);
1107 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1108 SDNode *&N = ExternalSymbols[Sym];
1109 if (N) return SDValue(N, 0);
1110 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1111 new (N) ExternalSymbolSDNode(false, Sym, VT);
1112 AllNodes.push_back(N);
1113 return SDValue(N, 0);
1116 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1117 SDNode *&N = TargetExternalSymbols[Sym];
1118 if (N) return SDValue(N, 0);
1119 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1120 new (N) ExternalSymbolSDNode(true, Sym, VT);
1121 AllNodes.push_back(N);
1122 return SDValue(N, 0);
1125 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1126 if ((unsigned)Cond >= CondCodeNodes.size())
1127 CondCodeNodes.resize(Cond+1);
1129 if (CondCodeNodes[Cond] == 0) {
1130 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1131 new (N) CondCodeSDNode(Cond);
1132 CondCodeNodes[Cond] = N;
1133 AllNodes.push_back(N);
1135 return SDValue(CondCodeNodes[Cond], 0);
1138 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1139 FoldingSetNodeID ID;
1140 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1141 ID.AddInteger(RegNo);
1143 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1144 return SDValue(E, 0);
1145 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1146 new (N) RegisterSDNode(RegNo, VT);
1147 CSEMap.InsertNode(N, IP);
1148 AllNodes.push_back(N);
1149 return SDValue(N, 0);
1152 SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
1153 unsigned Line, unsigned Col,
1154 const CompileUnitDesc *CU) {
1155 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1156 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1157 AllNodes.push_back(N);
1158 return SDValue(N, 0);
1161 SDValue SelectionDAG::getLabel(unsigned Opcode,
1164 FoldingSetNodeID ID;
1165 SDValue Ops[] = { Root };
1166 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1167 ID.AddInteger(LabelID);
1169 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1170 return SDValue(E, 0);
1171 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1172 new (N) LabelSDNode(Opcode, Root, LabelID);
1173 CSEMap.InsertNode(N, IP);
1174 AllNodes.push_back(N);
1175 return SDValue(N, 0);
1178 SDValue SelectionDAG::getSrcValue(const Value *V) {
1179 assert((!V || isa<PointerType>(V->getType())) &&
1180 "SrcValue is not a pointer?");
1182 FoldingSetNodeID ID;
1183 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1187 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1188 return SDValue(E, 0);
1190 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1191 new (N) SrcValueSDNode(V);
1192 CSEMap.InsertNode(N, IP);
1193 AllNodes.push_back(N);
1194 return SDValue(N, 0);
1197 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1198 const Value *v = MO.getValue();
1199 assert((!v || isa<PointerType>(v->getType())) &&
1200 "SrcValue is not a pointer?");
1202 FoldingSetNodeID ID;
1203 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1207 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1208 return SDValue(E, 0);
1210 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1211 new (N) MemOperandSDNode(MO);
1212 CSEMap.InsertNode(N, IP);
1213 AllNodes.push_back(N);
1214 return SDValue(N, 0);
1217 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1218 /// specified value type.
1219 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1220 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1221 unsigned ByteSize = VT.getSizeInBits()/8;
1222 const Type *Ty = VT.getTypeForMVT();
1223 unsigned StackAlign =
1224 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1226 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1227 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1230 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1231 SDValue N2, ISD::CondCode Cond) {
1232 // These setcc operations always fold.
1236 case ISD::SETFALSE2: return getConstant(0, VT);
1238 case ISD::SETTRUE2: return getConstant(1, VT);
1250 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1254 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1255 const APInt &C2 = N2C->getAPIntValue();
1256 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1257 const APInt &C1 = N1C->getAPIntValue();
1260 default: assert(0 && "Unknown integer setcc!");
1261 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1262 case ISD::SETNE: return getConstant(C1 != C2, VT);
1263 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1264 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1265 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1266 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1267 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1268 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1269 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1270 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1274 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1275 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1276 // No compile time operations on this type yet.
1277 if (N1C->getValueType(0) == MVT::ppcf128)
1280 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1283 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1284 return getNode(ISD::UNDEF, VT);
1286 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1287 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1288 return getNode(ISD::UNDEF, VT);
1290 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1291 R==APFloat::cmpLessThan, VT);
1292 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1293 return getNode(ISD::UNDEF, VT);
1295 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1296 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1297 return getNode(ISD::UNDEF, VT);
1299 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1300 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1301 return getNode(ISD::UNDEF, VT);
1303 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1304 R==APFloat::cmpEqual, VT);
1305 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1306 return getNode(ISD::UNDEF, VT);
1308 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1309 R==APFloat::cmpEqual, VT);
1310 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1311 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1312 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1313 R==APFloat::cmpEqual, VT);
1314 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1315 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1316 R==APFloat::cmpLessThan, VT);
1317 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1318 R==APFloat::cmpUnordered, VT);
1319 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1320 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1323 // Ensure that the constant occurs on the RHS.
1324 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1328 // Could not fold it.
1332 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1333 /// use this predicate to simplify operations downstream.
1334 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1335 unsigned BitWidth = Op.getValueSizeInBits();
1336 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1339 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1340 /// this predicate to simplify operations downstream. Mask is known to be zero
1341 /// for bits that V cannot have.
1342 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1343 unsigned Depth) const {
1344 APInt KnownZero, KnownOne;
1345 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1346 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1347 return (KnownZero & Mask) == Mask;
1350 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1351 /// known to be either zero or one and return them in the KnownZero/KnownOne
1352 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1354 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1355 APInt &KnownZero, APInt &KnownOne,
1356 unsigned Depth) const {
1357 unsigned BitWidth = Mask.getBitWidth();
1358 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1359 "Mask size mismatches value type size!");
1361 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1362 if (Depth == 6 || Mask == 0)
1363 return; // Limit search depth.
1365 APInt KnownZero2, KnownOne2;
1367 switch (Op.getOpcode()) {
1369 // We know all of the bits for a constant!
1370 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1371 KnownZero = ~KnownOne & Mask;
1374 // If either the LHS or the RHS are Zero, the result is zero.
1375 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1376 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1377 KnownZero2, KnownOne2, Depth+1);
1378 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1379 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1381 // Output known-1 bits are only known if set in both the LHS & RHS.
1382 KnownOne &= KnownOne2;
1383 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1384 KnownZero |= KnownZero2;
1387 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1388 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1389 KnownZero2, KnownOne2, Depth+1);
1390 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1391 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1393 // Output known-0 bits are only known if clear in both the LHS & RHS.
1394 KnownZero &= KnownZero2;
1395 // Output known-1 are known to be set if set in either the LHS | RHS.
1396 KnownOne |= KnownOne2;
1399 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1400 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1401 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1402 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1404 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1405 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1406 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1407 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1408 KnownZero = KnownZeroOut;
1412 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1413 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1414 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1415 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1416 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1418 // If low bits are zero in either operand, output low known-0 bits.
1419 // Also compute a conserative estimate for high known-0 bits.
1420 // More trickiness is possible, but this is sufficient for the
1421 // interesting case of alignment computation.
1423 unsigned TrailZ = KnownZero.countTrailingOnes() +
1424 KnownZero2.countTrailingOnes();
1425 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1426 KnownZero2.countLeadingOnes(),
1427 BitWidth) - BitWidth;
1429 TrailZ = std::min(TrailZ, BitWidth);
1430 LeadZ = std::min(LeadZ, BitWidth);
1431 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1432 APInt::getHighBitsSet(BitWidth, LeadZ);
1437 // For the purposes of computing leading zeros we can conservatively
1438 // treat a udiv as a logical right shift by the power of 2 known to
1439 // be less than the denominator.
1440 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1441 ComputeMaskedBits(Op.getOperand(0),
1442 AllOnes, KnownZero2, KnownOne2, Depth+1);
1443 unsigned LeadZ = KnownZero2.countLeadingOnes();
1447 ComputeMaskedBits(Op.getOperand(1),
1448 AllOnes, KnownZero2, KnownOne2, Depth+1);
1449 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1450 if (RHSUnknownLeadingOnes != BitWidth)
1451 LeadZ = std::min(BitWidth,
1452 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1454 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1458 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1459 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1460 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1461 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1463 // Only known if known in both the LHS and RHS.
1464 KnownOne &= KnownOne2;
1465 KnownZero &= KnownZero2;
1467 case ISD::SELECT_CC:
1468 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1469 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1470 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1471 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1473 // Only known if known in both the LHS and RHS.
1474 KnownOne &= KnownOne2;
1475 KnownZero &= KnownZero2;
1478 // If we know the result of a setcc has the top bits zero, use this info.
1479 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1481 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1484 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1485 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1486 unsigned ShAmt = SA->getZExtValue();
1488 // If the shift count is an invalid immediate, don't do anything.
1489 if (ShAmt >= BitWidth)
1492 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1493 KnownZero, KnownOne, Depth+1);
1494 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1495 KnownZero <<= ShAmt;
1497 // low bits known zero.
1498 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1502 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1503 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1504 unsigned ShAmt = SA->getZExtValue();
1506 // If the shift count is an invalid immediate, don't do anything.
1507 if (ShAmt >= BitWidth)
1510 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1511 KnownZero, KnownOne, Depth+1);
1512 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1513 KnownZero = KnownZero.lshr(ShAmt);
1514 KnownOne = KnownOne.lshr(ShAmt);
1516 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1517 KnownZero |= HighBits; // High bits known zero.
1521 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1522 unsigned ShAmt = SA->getZExtValue();
1524 // If the shift count is an invalid immediate, don't do anything.
1525 if (ShAmt >= BitWidth)
1528 APInt InDemandedMask = (Mask << ShAmt);
1529 // If any of the demanded bits are produced by the sign extension, we also
1530 // demand the input sign bit.
1531 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1532 if (HighBits.getBoolValue())
1533 InDemandedMask |= APInt::getSignBit(BitWidth);
1535 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1537 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1538 KnownZero = KnownZero.lshr(ShAmt);
1539 KnownOne = KnownOne.lshr(ShAmt);
1541 // Handle the sign bits.
1542 APInt SignBit = APInt::getSignBit(BitWidth);
1543 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1545 if (KnownZero.intersects(SignBit)) {
1546 KnownZero |= HighBits; // New bits are known zero.
1547 } else if (KnownOne.intersects(SignBit)) {
1548 KnownOne |= HighBits; // New bits are known one.
1552 case ISD::SIGN_EXTEND_INREG: {
1553 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1554 unsigned EBits = EVT.getSizeInBits();
1556 // Sign extension. Compute the demanded bits in the result that are not
1557 // present in the input.
1558 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1560 APInt InSignBit = APInt::getSignBit(EBits);
1561 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1563 // If the sign extended bits are demanded, we know that the sign
1565 InSignBit.zext(BitWidth);
1566 if (NewBits.getBoolValue())
1567 InputDemandedBits |= InSignBit;
1569 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1570 KnownZero, KnownOne, Depth+1);
1571 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1573 // If the sign bit of the input is known set or clear, then we know the
1574 // top bits of the result.
1575 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1576 KnownZero |= NewBits;
1577 KnownOne &= ~NewBits;
1578 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1579 KnownOne |= NewBits;
1580 KnownZero &= ~NewBits;
1581 } else { // Input sign bit unknown
1582 KnownZero &= ~NewBits;
1583 KnownOne &= ~NewBits;
1590 unsigned LowBits = Log2_32(BitWidth)+1;
1591 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1596 if (ISD::isZEXTLoad(Op.getNode())) {
1597 LoadSDNode *LD = cast<LoadSDNode>(Op);
1598 MVT VT = LD->getMemoryVT();
1599 unsigned MemBits = VT.getSizeInBits();
1600 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1604 case ISD::ZERO_EXTEND: {
1605 MVT InVT = Op.getOperand(0).getValueType();
1606 unsigned InBits = InVT.getSizeInBits();
1607 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1608 APInt InMask = Mask;
1609 InMask.trunc(InBits);
1610 KnownZero.trunc(InBits);
1611 KnownOne.trunc(InBits);
1612 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1613 KnownZero.zext(BitWidth);
1614 KnownOne.zext(BitWidth);
1615 KnownZero |= NewBits;
1618 case ISD::SIGN_EXTEND: {
1619 MVT InVT = Op.getOperand(0).getValueType();
1620 unsigned InBits = InVT.getSizeInBits();
1621 APInt InSignBit = APInt::getSignBit(InBits);
1622 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1623 APInt InMask = Mask;
1624 InMask.trunc(InBits);
1626 // If any of the sign extended bits are demanded, we know that the sign
1627 // bit is demanded. Temporarily set this bit in the mask for our callee.
1628 if (NewBits.getBoolValue())
1629 InMask |= InSignBit;
1631 KnownZero.trunc(InBits);
1632 KnownOne.trunc(InBits);
1633 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1635 // Note if the sign bit is known to be zero or one.
1636 bool SignBitKnownZero = KnownZero.isNegative();
1637 bool SignBitKnownOne = KnownOne.isNegative();
1638 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1639 "Sign bit can't be known to be both zero and one!");
1641 // If the sign bit wasn't actually demanded by our caller, we don't
1642 // want it set in the KnownZero and KnownOne result values. Reset the
1643 // mask and reapply it to the result values.
1645 InMask.trunc(InBits);
1646 KnownZero &= InMask;
1649 KnownZero.zext(BitWidth);
1650 KnownOne.zext(BitWidth);
1652 // If the sign bit is known zero or one, the top bits match.
1653 if (SignBitKnownZero)
1654 KnownZero |= NewBits;
1655 else if (SignBitKnownOne)
1656 KnownOne |= NewBits;
1659 case ISD::ANY_EXTEND: {
1660 MVT InVT = Op.getOperand(0).getValueType();
1661 unsigned InBits = InVT.getSizeInBits();
1662 APInt InMask = Mask;
1663 InMask.trunc(InBits);
1664 KnownZero.trunc(InBits);
1665 KnownOne.trunc(InBits);
1666 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1667 KnownZero.zext(BitWidth);
1668 KnownOne.zext(BitWidth);
1671 case ISD::TRUNCATE: {
1672 MVT InVT = Op.getOperand(0).getValueType();
1673 unsigned InBits = InVT.getSizeInBits();
1674 APInt InMask = Mask;
1675 InMask.zext(InBits);
1676 KnownZero.zext(InBits);
1677 KnownOne.zext(InBits);
1678 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1679 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1680 KnownZero.trunc(BitWidth);
1681 KnownOne.trunc(BitWidth);
1684 case ISD::AssertZext: {
1685 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1686 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1687 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1689 KnownZero |= (~InMask) & Mask;
1693 // All bits are zero except the low bit.
1694 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1698 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1699 // We know that the top bits of C-X are clear if X contains less bits
1700 // than C (i.e. no wrap-around can happen). For example, 20-X is
1701 // positive if we can prove that X is >= 0 and < 16.
1702 if (CLHS->getAPIntValue().isNonNegative()) {
1703 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1704 // NLZ can't be BitWidth with no sign bit
1705 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1706 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1709 // If all of the MaskV bits are known to be zero, then we know the
1710 // output top bits are zero, because we now know that the output is
1712 if ((KnownZero2 & MaskV) == MaskV) {
1713 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1714 // Top bits known zero.
1715 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1722 // Output known-0 bits are known if clear or set in both the low clear bits
1723 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1724 // low 3 bits clear.
1725 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1726 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1727 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1728 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1730 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1731 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1732 KnownZeroOut = std::min(KnownZeroOut,
1733 KnownZero2.countTrailingOnes());
1735 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1739 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1740 const APInt &RA = Rem->getAPIntValue();
1741 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1742 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1743 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1744 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1746 // If the sign bit of the first operand is zero, the sign bit of
1747 // the result is zero. If the first operand has no one bits below
1748 // the second operand's single 1 bit, its sign will be zero.
1749 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1750 KnownZero2 |= ~LowBits;
1752 KnownZero |= KnownZero2 & Mask;
1754 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1759 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1760 const APInt &RA = Rem->getAPIntValue();
1761 if (RA.isPowerOf2()) {
1762 APInt LowBits = (RA - 1);
1763 APInt Mask2 = LowBits & Mask;
1764 KnownZero |= ~LowBits & Mask;
1765 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1766 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1771 // Since the result is less than or equal to either operand, any leading
1772 // zero bits in either operand must also exist in the result.
1773 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1774 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1776 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1779 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1780 KnownZero2.countLeadingOnes());
1782 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1786 // Allow the target to implement this method for its nodes.
1787 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1788 case ISD::INTRINSIC_WO_CHAIN:
1789 case ISD::INTRINSIC_W_CHAIN:
1790 case ISD::INTRINSIC_VOID:
1791 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1797 /// ComputeNumSignBits - Return the number of times the sign bit of the
1798 /// register is replicated into the other bits. We know that at least 1 bit
1799 /// is always equal to the sign bit (itself), but other cases can give us
1800 /// information. For example, immediately after an "SRA X, 2", we know that
1801 /// the top 3 bits are all equal to each other, so we return 3.
1802 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1803 MVT VT = Op.getValueType();
1804 assert(VT.isInteger() && "Invalid VT!");
1805 unsigned VTBits = VT.getSizeInBits();
1807 unsigned FirstAnswer = 1;
1810 return 1; // Limit search depth.
1812 switch (Op.getOpcode()) {
1814 case ISD::AssertSext:
1815 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1816 return VTBits-Tmp+1;
1817 case ISD::AssertZext:
1818 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1821 case ISD::Constant: {
1822 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1823 // If negative, return # leading ones.
1824 if (Val.isNegative())
1825 return Val.countLeadingOnes();
1827 // Return # leading zeros.
1828 return Val.countLeadingZeros();
1831 case ISD::SIGN_EXTEND:
1832 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1833 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1835 case ISD::SIGN_EXTEND_INREG:
1836 // Max of the input and what this extends.
1837 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1840 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1841 return std::max(Tmp, Tmp2);
1844 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1845 // SRA X, C -> adds C sign bits.
1846 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1847 Tmp += C->getZExtValue();
1848 if (Tmp > VTBits) Tmp = VTBits;
1852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1853 // shl destroys sign bits.
1854 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1855 if (C->getZExtValue() >= VTBits || // Bad shift.
1856 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
1857 return Tmp - C->getZExtValue();
1862 case ISD::XOR: // NOT is handled here.
1863 // Logical binary ops preserve the number of sign bits at the worst.
1864 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1866 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1867 FirstAnswer = std::min(Tmp, Tmp2);
1868 // We computed what we know about the sign bits as our first
1869 // answer. Now proceed to the generic code that uses
1870 // ComputeMaskedBits, and pick whichever answer is better.
1875 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1876 if (Tmp == 1) return 1; // Early out.
1877 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1878 return std::min(Tmp, Tmp2);
1881 // If setcc returns 0/-1, all bits are sign bits.
1882 if (TLI.getSetCCResultContents() ==
1883 TargetLowering::ZeroOrNegativeOneSetCCResult)
1888 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1889 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
1891 // Handle rotate right by N like a rotate left by 32-N.
1892 if (Op.getOpcode() == ISD::ROTR)
1893 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1895 // If we aren't rotating out all of the known-in sign bits, return the
1896 // number that are left. This handles rotl(sext(x), 1) for example.
1897 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1898 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1902 // Add can have at most one carry bit. Thus we know that the output
1903 // is, at worst, one more bit than the inputs.
1904 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1905 if (Tmp == 1) return 1; // Early out.
1907 // Special case decrementing a value (ADD X, -1):
1908 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1909 if (CRHS->isAllOnesValue()) {
1910 APInt KnownZero, KnownOne;
1911 APInt Mask = APInt::getAllOnesValue(VTBits);
1912 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1914 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1916 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1919 // If we are subtracting one from a positive number, there is no carry
1920 // out of the result.
1921 if (KnownZero.isNegative())
1925 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1926 if (Tmp2 == 1) return 1;
1927 return std::min(Tmp, Tmp2)-1;
1931 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1932 if (Tmp2 == 1) return 1;
1935 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1936 if (CLHS->isNullValue()) {
1937 APInt KnownZero, KnownOne;
1938 APInt Mask = APInt::getAllOnesValue(VTBits);
1939 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1940 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1942 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1945 // If the input is known to be positive (the sign bit is known clear),
1946 // the output of the NEG has the same number of sign bits as the input.
1947 if (KnownZero.isNegative())
1950 // Otherwise, we treat this like a SUB.
1953 // Sub can have at most one carry bit. Thus we know that the output
1954 // is, at worst, one more bit than the inputs.
1955 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1956 if (Tmp == 1) return 1; // Early out.
1957 return std::min(Tmp, Tmp2)-1;
1960 // FIXME: it's tricky to do anything useful for this, but it is an important
1961 // case for targets like X86.
1965 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1966 if (Op.getOpcode() == ISD::LOAD) {
1967 LoadSDNode *LD = cast<LoadSDNode>(Op);
1968 unsigned ExtType = LD->getExtensionType();
1971 case ISD::SEXTLOAD: // '17' bits known
1972 Tmp = LD->getMemoryVT().getSizeInBits();
1973 return VTBits-Tmp+1;
1974 case ISD::ZEXTLOAD: // '16' bits known
1975 Tmp = LD->getMemoryVT().getSizeInBits();
1980 // Allow the target to implement this method for its nodes.
1981 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1982 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1983 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1984 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1985 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1986 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1989 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1990 // use this information.
1991 APInt KnownZero, KnownOne;
1992 APInt Mask = APInt::getAllOnesValue(VTBits);
1993 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1995 if (KnownZero.isNegative()) { // sign bit is 0
1997 } else if (KnownOne.isNegative()) { // sign bit is 1;
2004 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2005 // the number of identical bits in the top of the input value.
2007 Mask <<= Mask.getBitWidth()-VTBits;
2008 // Return # leading zeros. We use 'min' here in case Val was zero before
2009 // shifting. We don't want to return '64' as for an i32 "0".
2010 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2014 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2015 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2016 if (!GA) return false;
2017 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2018 if (!GV) return false;
2019 MachineModuleInfo *MMI = getMachineModuleInfo();
2020 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
2024 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2025 /// element of the result of the vector shuffle.
2026 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
2027 MVT VT = N->getValueType(0);
2028 SDValue PermMask = N->getOperand(2);
2029 SDValue Idx = PermMask.getOperand(i);
2030 if (Idx.getOpcode() == ISD::UNDEF)
2031 return getNode(ISD::UNDEF, VT.getVectorElementType());
2032 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
2033 unsigned NumElems = PermMask.getNumOperands();
2034 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2037 if (V.getOpcode() == ISD::BIT_CONVERT) {
2038 V = V.getOperand(0);
2039 if (V.getValueType().getVectorNumElements() != NumElems)
2042 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2043 return (Index == 0) ? V.getOperand(0)
2044 : getNode(ISD::UNDEF, VT.getVectorElementType());
2045 if (V.getOpcode() == ISD::BUILD_VECTOR)
2046 return V.getOperand(Index);
2047 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
2048 return getShuffleScalarElt(V.getNode(), Index);
2053 /// getNode - Gets or creates the specified node.
2055 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
2056 FoldingSetNodeID ID;
2057 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2059 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2060 return SDValue(E, 0);
2061 SDNode *N = NodeAllocator.Allocate<SDNode>();
2062 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
2063 CSEMap.InsertNode(N, IP);
2065 AllNodes.push_back(N);
2069 return SDValue(N, 0);
2072 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
2073 // Constant fold unary operations with an integer constant operand.
2074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2075 const APInt &Val = C->getAPIntValue();
2076 unsigned BitWidth = VT.getSizeInBits();
2079 case ISD::SIGN_EXTEND:
2080 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2081 case ISD::ANY_EXTEND:
2082 case ISD::ZERO_EXTEND:
2084 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2085 case ISD::UINT_TO_FP:
2086 case ISD::SINT_TO_FP: {
2087 const uint64_t zero[] = {0, 0};
2088 // No compile time operations on this type.
2089 if (VT==MVT::ppcf128)
2091 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2092 (void)apf.convertFromAPInt(Val,
2093 Opcode==ISD::SINT_TO_FP,
2094 APFloat::rmNearestTiesToEven);
2095 return getConstantFP(apf, VT);
2097 case ISD::BIT_CONVERT:
2098 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2099 return getConstantFP(Val.bitsToFloat(), VT);
2100 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2101 return getConstantFP(Val.bitsToDouble(), VT);
2104 return getConstant(Val.byteSwap(), VT);
2106 return getConstant(Val.countPopulation(), VT);
2108 return getConstant(Val.countLeadingZeros(), VT);
2110 return getConstant(Val.countTrailingZeros(), VT);
2114 // Constant fold unary operations with a floating point constant operand.
2115 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2116 APFloat V = C->getValueAPF(); // make copy
2117 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2121 return getConstantFP(V, VT);
2124 return getConstantFP(V, VT);
2126 case ISD::FP_EXTEND:
2127 // This can return overflow, underflow, or inexact; we don't care.
2128 // FIXME need to be more flexible about rounding mode.
2129 (void)V.convert(*MVTToAPFloatSemantics(VT),
2130 APFloat::rmNearestTiesToEven);
2131 return getConstantFP(V, VT);
2132 case ISD::FP_TO_SINT:
2133 case ISD::FP_TO_UINT: {
2135 assert(integerPartWidth >= 64);
2136 // FIXME need to be more flexible about rounding mode.
2137 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2138 Opcode==ISD::FP_TO_SINT,
2139 APFloat::rmTowardZero);
2140 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2142 return getConstant(x, VT);
2144 case ISD::BIT_CONVERT:
2145 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2146 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2147 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2148 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2154 unsigned OpOpcode = Operand.getNode()->getOpcode();
2156 case ISD::TokenFactor:
2157 case ISD::CONCAT_VECTORS:
2158 return Operand; // Factor or concat of one node? No need.
2159 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2160 case ISD::FP_EXTEND:
2161 assert(VT.isFloatingPoint() &&
2162 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2163 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2164 if (Operand.getOpcode() == ISD::UNDEF)
2165 return getNode(ISD::UNDEF, VT);
2167 case ISD::SIGN_EXTEND:
2168 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2169 "Invalid SIGN_EXTEND!");
2170 if (Operand.getValueType() == VT) return Operand; // noop extension
2171 assert(Operand.getValueType().bitsLT(VT)
2172 && "Invalid sext node, dst < src!");
2173 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2174 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2176 case ISD::ZERO_EXTEND:
2177 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2178 "Invalid ZERO_EXTEND!");
2179 if (Operand.getValueType() == VT) return Operand; // noop extension
2180 assert(Operand.getValueType().bitsLT(VT)
2181 && "Invalid zext node, dst < src!");
2182 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2183 return getNode(ISD::ZERO_EXTEND, VT, Operand.getNode()->getOperand(0));
2185 case ISD::ANY_EXTEND:
2186 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2187 "Invalid ANY_EXTEND!");
2188 if (Operand.getValueType() == VT) return Operand; // noop extension
2189 assert(Operand.getValueType().bitsLT(VT)
2190 && "Invalid anyext node, dst < src!");
2191 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2192 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2193 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2196 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2197 "Invalid TRUNCATE!");
2198 if (Operand.getValueType() == VT) return Operand; // noop truncate
2199 assert(Operand.getValueType().bitsGT(VT)
2200 && "Invalid truncate node, src < dst!");
2201 if (OpOpcode == ISD::TRUNCATE)
2202 return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
2203 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2204 OpOpcode == ISD::ANY_EXTEND) {
2205 // If the source is smaller than the dest, we still need an extend.
2206 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2207 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2208 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2209 return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
2211 return Operand.getNode()->getOperand(0);
2214 case ISD::BIT_CONVERT:
2215 // Basic sanity checking.
2216 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2217 && "Cannot BIT_CONVERT between types of different sizes!");
2218 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2219 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2220 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2221 if (OpOpcode == ISD::UNDEF)
2222 return getNode(ISD::UNDEF, VT);
2224 case ISD::SCALAR_TO_VECTOR:
2225 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2226 VT.getVectorElementType() == Operand.getValueType() &&
2227 "Illegal SCALAR_TO_VECTOR node!");
2228 if (OpOpcode == ISD::UNDEF)
2229 return getNode(ISD::UNDEF, VT);
2230 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2231 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2232 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2233 Operand.getConstantOperandVal(1) == 0 &&
2234 Operand.getOperand(0).getValueType() == VT)
2235 return Operand.getOperand(0);
2238 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2239 return getNode(ISD::FSUB, VT, Operand.getNode()->getOperand(1),
2240 Operand.getNode()->getOperand(0));
2241 if (OpOpcode == ISD::FNEG) // --X -> X
2242 return Operand.getNode()->getOperand(0);
2245 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2246 return getNode(ISD::FABS, VT, Operand.getNode()->getOperand(0));
2251 SDVTList VTs = getVTList(VT);
2252 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2253 FoldingSetNodeID ID;
2254 SDValue Ops[1] = { Operand };
2255 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2257 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2258 return SDValue(E, 0);
2259 N = NodeAllocator.Allocate<UnarySDNode>();
2260 new (N) UnarySDNode(Opcode, VTs, Operand);
2261 CSEMap.InsertNode(N, IP);
2263 N = NodeAllocator.Allocate<UnarySDNode>();
2264 new (N) UnarySDNode(Opcode, VTs, Operand);
2267 AllNodes.push_back(N);
2271 return SDValue(N, 0);
2274 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2276 ConstantSDNode *Cst1,
2277 ConstantSDNode *Cst2) {
2278 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2281 case ISD::ADD: return getConstant(C1 + C2, VT);
2282 case ISD::SUB: return getConstant(C1 - C2, VT);
2283 case ISD::MUL: return getConstant(C1 * C2, VT);
2285 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2288 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2291 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2294 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2296 case ISD::AND: return getConstant(C1 & C2, VT);
2297 case ISD::OR: return getConstant(C1 | C2, VT);
2298 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2299 case ISD::SHL: return getConstant(C1 << C2, VT);
2300 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2301 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2302 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2303 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2310 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2311 SDValue N1, SDValue N2) {
2312 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2313 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2316 case ISD::TokenFactor:
2317 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2318 N2.getValueType() == MVT::Other && "Invalid token factor!");
2319 // Fold trivial token factors.
2320 if (N1.getOpcode() == ISD::EntryToken) return N2;
2321 if (N2.getOpcode() == ISD::EntryToken) return N1;
2323 case ISD::CONCAT_VECTORS:
2324 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2325 // one big BUILD_VECTOR.
2326 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2327 N2.getOpcode() == ISD::BUILD_VECTOR) {
2328 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2329 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2330 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2334 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2335 N1.getValueType() == VT && "Binary operator types must match!");
2336 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2337 // worth handling here.
2338 if (N2C && N2C->isNullValue())
2340 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2347 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2348 N1.getValueType() == VT && "Binary operator types must match!");
2349 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2350 // it's worth handling here.
2351 if (N2C && N2C->isNullValue())
2358 assert(VT.isInteger() && "This operator does not apply to FP types!");
2368 assert(N1.getValueType() == N2.getValueType() &&
2369 N1.getValueType() == VT && "Binary operator types must match!");
2371 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2372 assert(N1.getValueType() == VT &&
2373 N1.getValueType().isFloatingPoint() &&
2374 N2.getValueType().isFloatingPoint() &&
2375 "Invalid FCOPYSIGN!");
2382 assert(VT == N1.getValueType() &&
2383 "Shift operators return type must be the same as their first arg");
2384 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2385 "Shifts only work on integers");
2387 // Always fold shifts of i1 values so the code generator doesn't need to
2388 // handle them. Since we know the size of the shift has to be less than the
2389 // size of the value, the shift/rotate count is guaranteed to be zero.
2393 case ISD::FP_ROUND_INREG: {
2394 MVT EVT = cast<VTSDNode>(N2)->getVT();
2395 assert(VT == N1.getValueType() && "Not an inreg round!");
2396 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2397 "Cannot FP_ROUND_INREG integer types");
2398 assert(EVT.bitsLE(VT) && "Not rounding down!");
2399 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2403 assert(VT.isFloatingPoint() &&
2404 N1.getValueType().isFloatingPoint() &&
2405 VT.bitsLE(N1.getValueType()) &&
2406 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2407 if (N1.getValueType() == VT) return N1; // noop conversion.
2409 case ISD::AssertSext:
2410 case ISD::AssertZext: {
2411 MVT EVT = cast<VTSDNode>(N2)->getVT();
2412 assert(VT == N1.getValueType() && "Not an inreg extend!");
2413 assert(VT.isInteger() && EVT.isInteger() &&
2414 "Cannot *_EXTEND_INREG FP types");
2415 assert(EVT.bitsLE(VT) && "Not extending!");
2416 if (VT == EVT) return N1; // noop assertion.
2419 case ISD::SIGN_EXTEND_INREG: {
2420 MVT EVT = cast<VTSDNode>(N2)->getVT();
2421 assert(VT == N1.getValueType() && "Not an inreg extend!");
2422 assert(VT.isInteger() && EVT.isInteger() &&
2423 "Cannot *_EXTEND_INREG FP types");
2424 assert(EVT.bitsLE(VT) && "Not extending!");
2425 if (EVT == VT) return N1; // Not actually extending
2428 APInt Val = N1C->getAPIntValue();
2429 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2430 Val <<= Val.getBitWidth()-FromBits;
2431 Val = Val.ashr(Val.getBitWidth()-FromBits);
2432 return getConstant(Val, VT);
2436 case ISD::EXTRACT_VECTOR_ELT:
2437 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2438 if (N1.getOpcode() == ISD::UNDEF)
2439 return getNode(ISD::UNDEF, VT);
2441 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2442 // expanding copies of large vectors from registers.
2444 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2445 N1.getNumOperands() > 0) {
2447 N1.getOperand(0).getValueType().getVectorNumElements();
2448 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2449 N1.getOperand(N2C->getZExtValue() / Factor),
2450 getConstant(N2C->getZExtValue() % Factor,
2451 N2.getValueType()));
2454 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2455 // expanding large vector constants.
2456 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
2457 return N1.getOperand(N2C->getZExtValue());
2459 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2460 // operations are lowered to scalars.
2461 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2462 if (N1.getOperand(2) == N2)
2463 return N1.getOperand(1);
2465 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2468 case ISD::EXTRACT_ELEMENT:
2469 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2470 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2471 (N1.getValueType().isInteger() == VT.isInteger()) &&
2472 "Wrong types for EXTRACT_ELEMENT!");
2474 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2475 // 64-bit integers into 32-bit parts. Instead of building the extract of
2476 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2477 if (N1.getOpcode() == ISD::BUILD_PAIR)
2478 return N1.getOperand(N2C->getZExtValue());
2480 // EXTRACT_ELEMENT of a constant int is also very common.
2481 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2482 unsigned ElementSize = VT.getSizeInBits();
2483 unsigned Shift = ElementSize * N2C->getZExtValue();
2484 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2485 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2488 case ISD::EXTRACT_SUBVECTOR:
2489 if (N1.getValueType() == VT) // Trivial extraction.
2496 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2497 if (SV.getNode()) return SV;
2498 } else { // Cannonicalize constant to RHS if commutative
2499 if (isCommutativeBinOp(Opcode)) {
2500 std::swap(N1C, N2C);
2506 // Constant fold FP operations.
2507 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2508 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2510 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2511 // Cannonicalize constant to RHS if commutative
2512 std::swap(N1CFP, N2CFP);
2514 } else if (N2CFP && VT != MVT::ppcf128) {
2515 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2516 APFloat::opStatus s;
2519 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2520 if (s != APFloat::opInvalidOp)
2521 return getConstantFP(V1, VT);
2524 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2525 if (s!=APFloat::opInvalidOp)
2526 return getConstantFP(V1, VT);
2529 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2530 if (s!=APFloat::opInvalidOp)
2531 return getConstantFP(V1, VT);
2534 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2535 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2536 return getConstantFP(V1, VT);
2539 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2540 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2541 return getConstantFP(V1, VT);
2543 case ISD::FCOPYSIGN:
2545 return getConstantFP(V1, VT);
2551 // Canonicalize an UNDEF to the RHS, even over a constant.
2552 if (N1.getOpcode() == ISD::UNDEF) {
2553 if (isCommutativeBinOp(Opcode)) {
2557 case ISD::FP_ROUND_INREG:
2558 case ISD::SIGN_EXTEND_INREG:
2564 return N1; // fold op(undef, arg2) -> undef
2572 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2573 // For vectors, we can't easily build an all zero vector, just return
2580 // Fold a bunch of operators when the RHS is undef.
2581 if (N2.getOpcode() == ISD::UNDEF) {
2584 if (N1.getOpcode() == ISD::UNDEF)
2585 // Handle undef ^ undef -> 0 special case. This is a common
2587 return getConstant(0, VT);
2602 return N2; // fold op(arg1, undef) -> undef
2608 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2609 // For vectors, we can't easily build an all zero vector, just return
2614 return getConstant(VT.getIntegerVTBitMask(), VT);
2615 // For vectors, we can't easily build an all one vector, just return
2623 // Memoize this node if possible.
2625 SDVTList VTs = getVTList(VT);
2626 if (VT != MVT::Flag) {
2627 SDValue Ops[] = { N1, N2 };
2628 FoldingSetNodeID ID;
2629 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2631 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2632 return SDValue(E, 0);
2633 N = NodeAllocator.Allocate<BinarySDNode>();
2634 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2635 CSEMap.InsertNode(N, IP);
2637 N = NodeAllocator.Allocate<BinarySDNode>();
2638 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2641 AllNodes.push_back(N);
2645 return SDValue(N, 0);
2648 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2649 SDValue N1, SDValue N2, SDValue N3) {
2650 // Perform various simplifications.
2651 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2652 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2654 case ISD::CONCAT_VECTORS:
2655 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2656 // one big BUILD_VECTOR.
2657 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2658 N2.getOpcode() == ISD::BUILD_VECTOR &&
2659 N3.getOpcode() == ISD::BUILD_VECTOR) {
2660 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2661 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2662 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2663 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2667 // Use FoldSetCC to simplify SETCC's.
2668 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2669 if (Simp.getNode()) return Simp;
2674 if (N1C->getZExtValue())
2675 return N2; // select true, X, Y -> X
2677 return N3; // select false, X, Y -> Y
2680 if (N2 == N3) return N2; // select C, X, X -> X
2684 if (N2C->getZExtValue()) // Unconditional branch
2685 return getNode(ISD::BR, MVT::Other, N1, N3);
2687 return N1; // Never-taken branch
2690 case ISD::VECTOR_SHUFFLE:
2691 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2692 VT.isVector() && N3.getValueType().isVector() &&
2693 N3.getOpcode() == ISD::BUILD_VECTOR &&
2694 VT.getVectorNumElements() == N3.getNumOperands() &&
2695 "Illegal VECTOR_SHUFFLE node!");
2697 case ISD::BIT_CONVERT:
2698 // Fold bit_convert nodes from a type to themselves.
2699 if (N1.getValueType() == VT)
2704 // Memoize node if it doesn't produce a flag.
2706 SDVTList VTs = getVTList(VT);
2707 if (VT != MVT::Flag) {
2708 SDValue Ops[] = { N1, N2, N3 };
2709 FoldingSetNodeID ID;
2710 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2712 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2713 return SDValue(E, 0);
2714 N = NodeAllocator.Allocate<TernarySDNode>();
2715 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2716 CSEMap.InsertNode(N, IP);
2718 N = NodeAllocator.Allocate<TernarySDNode>();
2719 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2721 AllNodes.push_back(N);
2725 return SDValue(N, 0);
2728 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2729 SDValue N1, SDValue N2, SDValue N3,
2731 SDValue Ops[] = { N1, N2, N3, N4 };
2732 return getNode(Opcode, VT, Ops, 4);
2735 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2736 SDValue N1, SDValue N2, SDValue N3,
2737 SDValue N4, SDValue N5) {
2738 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2739 return getNode(Opcode, VT, Ops, 5);
2742 /// getMemsetValue - Vectorized representation of the memset value
2744 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
2745 unsigned NumBits = VT.isVector() ?
2746 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2747 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2748 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
2750 for (unsigned i = NumBits; i > 8; i >>= 1) {
2751 Val = (Val << Shift) | Val;
2755 return DAG.getConstant(Val, VT);
2756 return DAG.getConstantFP(APFloat(Val), VT);
2759 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2761 for (unsigned i = NumBits; i > 8; i >>= 1) {
2762 Value = DAG.getNode(ISD::OR, VT,
2763 DAG.getNode(ISD::SHL, VT, Value,
2764 DAG.getConstant(Shift, MVT::i8)), Value);
2771 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2772 /// used when a memcpy is turned into a memset when the source is a constant
2774 static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2775 const TargetLowering &TLI,
2776 std::string &Str, unsigned Offset) {
2777 // Handle vector with all elements zero.
2780 return DAG.getConstant(0, VT);
2781 unsigned NumElts = VT.getVectorNumElements();
2782 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2783 return DAG.getNode(ISD::BIT_CONVERT, VT,
2784 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2787 assert(!VT.isVector() && "Can't handle vector type here!");
2788 unsigned NumBits = VT.getSizeInBits();
2789 unsigned MSB = NumBits / 8;
2791 if (TLI.isLittleEndian())
2792 Offset = Offset + MSB - 1;
2793 for (unsigned i = 0; i != MSB; ++i) {
2794 Val = (Val << 8) | (unsigned char)Str[Offset];
2795 Offset += TLI.isLittleEndian() ? -1 : 1;
2797 return DAG.getConstant(Val, VT);
2800 /// getMemBasePlusOffset - Returns base and offset node for the
2802 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2803 SelectionDAG &DAG) {
2804 MVT VT = Base.getValueType();
2805 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2808 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2810 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
2811 unsigned SrcDelta = 0;
2812 GlobalAddressSDNode *G = NULL;
2813 if (Src.getOpcode() == ISD::GlobalAddress)
2814 G = cast<GlobalAddressSDNode>(Src);
2815 else if (Src.getOpcode() == ISD::ADD &&
2816 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2817 Src.getOperand(1).getOpcode() == ISD::Constant) {
2818 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2819 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
2824 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2825 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2831 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2832 /// to replace the memset / memcpy is below the threshold. It also returns the
2833 /// types of the sequence of memory ops to perform memset / memcpy.
2835 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2836 SDValue Dst, SDValue Src,
2837 unsigned Limit, uint64_t Size, unsigned &Align,
2838 std::string &Str, bool &isSrcStr,
2840 const TargetLowering &TLI) {
2841 isSrcStr = isMemSrcFromString(Src, Str);
2842 bool isSrcConst = isa<ConstantSDNode>(Src);
2843 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2844 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2845 if (VT != MVT::iAny) {
2846 unsigned NewAlign = (unsigned)
2847 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2848 // If source is a string constant, this will require an unaligned load.
2849 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2850 if (Dst.getOpcode() != ISD::FrameIndex) {
2851 // Can't change destination alignment. It requires a unaligned store.
2855 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2856 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2857 if (MFI->isFixedObjectIndex(FI)) {
2858 // Can't change destination alignment. It requires a unaligned store.
2862 // Give the stack frame object a larger alignment if needed.
2863 if (MFI->getObjectAlignment(FI) < NewAlign)
2864 MFI->setObjectAlignment(FI, NewAlign);
2871 if (VT == MVT::iAny) {
2875 switch (Align & 7) {
2876 case 0: VT = MVT::i64; break;
2877 case 4: VT = MVT::i32; break;
2878 case 2: VT = MVT::i16; break;
2879 default: VT = MVT::i8; break;
2884 while (!TLI.isTypeLegal(LVT))
2885 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2886 assert(LVT.isInteger());
2892 unsigned NumMemOps = 0;
2894 unsigned VTSize = VT.getSizeInBits() / 8;
2895 while (VTSize > Size) {
2896 // For now, only use non-vector load / store's for the left-over pieces.
2897 if (VT.isVector()) {
2899 while (!TLI.isTypeLegal(VT))
2900 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2901 VTSize = VT.getSizeInBits() / 8;
2903 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2908 if (++NumMemOps > Limit)
2910 MemOps.push_back(VT);
2917 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
2918 SDValue Chain, SDValue Dst,
2919 SDValue Src, uint64_t Size,
2920 unsigned Align, bool AlwaysInline,
2921 const Value *DstSV, uint64_t DstSVOff,
2922 const Value *SrcSV, uint64_t SrcSVOff){
2923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2925 // Expand memcpy to a series of load and store ops if the size operand falls
2926 // below a certain threshold.
2927 std::vector<MVT> MemOps;
2928 uint64_t Limit = -1;
2930 Limit = TLI.getMaxStoresPerMemcpy();
2931 unsigned DstAlign = Align; // Destination alignment can change.
2934 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2935 Str, CopyFromStr, DAG, TLI))
2939 bool isZeroStr = CopyFromStr && Str.empty();
2940 SmallVector<SDValue, 8> OutChains;
2941 unsigned NumMemOps = MemOps.size();
2942 uint64_t SrcOff = 0, DstOff = 0;
2943 for (unsigned i = 0; i < NumMemOps; i++) {
2945 unsigned VTSize = VT.getSizeInBits() / 8;
2946 SDValue Value, Store;
2948 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2949 // It's unlikely a store of a vector immediate can be done in a single
2950 // instruction. It would require a load from a constantpool first.
2951 // We also handle store a vector with all zero's.
2952 // FIXME: Handle other cases where store of vector immediate is done in
2953 // a single instruction.
2954 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2955 Store = DAG.getStore(Chain, Value,
2956 getMemBasePlusOffset(Dst, DstOff, DAG),
2957 DstSV, DstSVOff + DstOff, false, DstAlign);
2959 Value = DAG.getLoad(VT, Chain,
2960 getMemBasePlusOffset(Src, SrcOff, DAG),
2961 SrcSV, SrcSVOff + SrcOff, false, Align);
2962 Store = DAG.getStore(Chain, Value,
2963 getMemBasePlusOffset(Dst, DstOff, DAG),
2964 DstSV, DstSVOff + DstOff, false, DstAlign);
2966 OutChains.push_back(Store);
2971 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2972 &OutChains[0], OutChains.size());
2975 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
2976 SDValue Chain, SDValue Dst,
2977 SDValue Src, uint64_t Size,
2978 unsigned Align, bool AlwaysInline,
2979 const Value *DstSV, uint64_t DstSVOff,
2980 const Value *SrcSV, uint64_t SrcSVOff){
2981 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2983 // Expand memmove to a series of load and store ops if the size operand falls
2984 // below a certain threshold.
2985 std::vector<MVT> MemOps;
2986 uint64_t Limit = -1;
2988 Limit = TLI.getMaxStoresPerMemmove();
2989 unsigned DstAlign = Align; // Destination alignment can change.
2992 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2993 Str, CopyFromStr, DAG, TLI))
2996 uint64_t SrcOff = 0, DstOff = 0;
2998 SmallVector<SDValue, 8> LoadValues;
2999 SmallVector<SDValue, 8> LoadChains;
3000 SmallVector<SDValue, 8> OutChains;
3001 unsigned NumMemOps = MemOps.size();
3002 for (unsigned i = 0; i < NumMemOps; i++) {
3004 unsigned VTSize = VT.getSizeInBits() / 8;
3005 SDValue Value, Store;
3007 Value = DAG.getLoad(VT, Chain,
3008 getMemBasePlusOffset(Src, SrcOff, DAG),
3009 SrcSV, SrcSVOff + SrcOff, false, Align);
3010 LoadValues.push_back(Value);
3011 LoadChains.push_back(Value.getValue(1));
3014 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3015 &LoadChains[0], LoadChains.size());
3017 for (unsigned i = 0; i < NumMemOps; i++) {
3019 unsigned VTSize = VT.getSizeInBits() / 8;
3020 SDValue Value, Store;
3022 Store = DAG.getStore(Chain, LoadValues[i],
3023 getMemBasePlusOffset(Dst, DstOff, DAG),
3024 DstSV, DstSVOff + DstOff, false, DstAlign);
3025 OutChains.push_back(Store);
3029 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3030 &OutChains[0], OutChains.size());
3033 static SDValue getMemsetStores(SelectionDAG &DAG,
3034 SDValue Chain, SDValue Dst,
3035 SDValue Src, uint64_t Size,
3037 const Value *DstSV, uint64_t DstSVOff) {
3038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3040 // Expand memset to a series of load/store ops if the size operand
3041 // falls below a certain threshold.
3042 std::vector<MVT> MemOps;
3045 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3046 Size, Align, Str, CopyFromStr, DAG, TLI))
3049 SmallVector<SDValue, 8> OutChains;
3050 uint64_t DstOff = 0;
3052 unsigned NumMemOps = MemOps.size();
3053 for (unsigned i = 0; i < NumMemOps; i++) {
3055 unsigned VTSize = VT.getSizeInBits() / 8;
3056 SDValue Value = getMemsetValue(Src, VT, DAG);
3057 SDValue Store = DAG.getStore(Chain, Value,
3058 getMemBasePlusOffset(Dst, DstOff, DAG),
3059 DstSV, DstSVOff + DstOff);
3060 OutChains.push_back(Store);
3064 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3065 &OutChains[0], OutChains.size());
3068 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
3069 SDValue Src, SDValue Size,
3070 unsigned Align, bool AlwaysInline,
3071 const Value *DstSV, uint64_t DstSVOff,
3072 const Value *SrcSV, uint64_t SrcSVOff) {
3074 // Check to see if we should lower the memcpy to loads and stores first.
3075 // For cases within the target-specified limits, this is the best choice.
3076 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3078 // Memcpy with size zero? Just return the original chain.
3079 if (ConstantSize->isNullValue())
3083 getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3084 ConstantSize->getZExtValue(),
3085 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3086 if (Result.getNode())
3090 // Then check to see if we should lower the memcpy with target-specific
3091 // code. If the target chooses to do this, this is the next best.
3093 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
3095 DstSV, DstSVOff, SrcSV, SrcSVOff);
3096 if (Result.getNode())
3099 // If we really need inline code and the target declined to provide it,
3100 // use a (potentially long) sequence of loads and stores.
3102 assert(ConstantSize && "AlwaysInline requires a constant size!");
3103 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3104 ConstantSize->getZExtValue(), Align, true,
3105 DstSV, DstSVOff, SrcSV, SrcSVOff);
3108 // Emit a library call.
3109 TargetLowering::ArgListTy Args;
3110 TargetLowering::ArgListEntry Entry;
3111 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3112 Entry.Node = Dst; Args.push_back(Entry);
3113 Entry.Node = Src; Args.push_back(Entry);
3114 Entry.Node = Size; Args.push_back(Entry);
3115 std::pair<SDValue,SDValue> CallResult =
3116 TLI.LowerCallTo(Chain, Type::VoidTy,
3117 false, false, false, false, CallingConv::C, false,
3118 getExternalSymbol("memcpy", TLI.getPointerTy()),
3120 return CallResult.second;
3123 SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
3124 SDValue Src, SDValue Size,
3126 const Value *DstSV, uint64_t DstSVOff,
3127 const Value *SrcSV, uint64_t SrcSVOff) {
3129 // Check to see if we should lower the memmove to loads and stores first.
3130 // For cases within the target-specified limits, this is the best choice.
3131 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3133 // Memmove with size zero? Just return the original chain.
3134 if (ConstantSize->isNullValue())
3138 getMemmoveLoadsAndStores(*this, Chain, Dst, Src,
3139 ConstantSize->getZExtValue(),
3140 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3141 if (Result.getNode())
3145 // Then check to see if we should lower the memmove with target-specific
3146 // code. If the target chooses to do this, this is the next best.
3148 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3149 DstSV, DstSVOff, SrcSV, SrcSVOff);
3150 if (Result.getNode())
3153 // Emit a library call.
3154 TargetLowering::ArgListTy Args;
3155 TargetLowering::ArgListEntry Entry;
3156 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3157 Entry.Node = Dst; Args.push_back(Entry);
3158 Entry.Node = Src; Args.push_back(Entry);
3159 Entry.Node = Size; Args.push_back(Entry);
3160 std::pair<SDValue,SDValue> CallResult =
3161 TLI.LowerCallTo(Chain, Type::VoidTy,
3162 false, false, false, false, CallingConv::C, false,
3163 getExternalSymbol("memmove", TLI.getPointerTy()),
3165 return CallResult.second;
3168 SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
3169 SDValue Src, SDValue Size,
3171 const Value *DstSV, uint64_t DstSVOff) {
3173 // Check to see if we should lower the memset to stores first.
3174 // For cases within the target-specified limits, this is the best choice.
3175 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3177 // Memset with size zero? Just return the original chain.
3178 if (ConstantSize->isNullValue())
3182 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getZExtValue(),
3183 Align, DstSV, DstSVOff);
3184 if (Result.getNode())
3188 // Then check to see if we should lower the memset with target-specific
3189 // code. If the target chooses to do this, this is the next best.
3191 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3193 if (Result.getNode())
3196 // Emit a library call.
3197 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3198 TargetLowering::ArgListTy Args;
3199 TargetLowering::ArgListEntry Entry;
3200 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3201 Args.push_back(Entry);
3202 // Extend or truncate the argument to be an i32 value for the call.
3203 if (Src.getValueType().bitsGT(MVT::i32))
3204 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3206 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3207 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3208 Args.push_back(Entry);
3209 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3210 Args.push_back(Entry);
3211 std::pair<SDValue,SDValue> CallResult =
3212 TLI.LowerCallTo(Chain, Type::VoidTy,
3213 false, false, false, false, CallingConv::C, false,
3214 getExternalSymbol("memset", TLI.getPointerTy()),
3216 return CallResult.second;
3219 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3220 SDValue Ptr, SDValue Cmp,
3221 SDValue Swp, const Value* PtrVal,
3222 unsigned Alignment) {
3223 assert((Opcode == ISD::ATOMIC_CMP_SWAP_8 ||
3224 Opcode == ISD::ATOMIC_CMP_SWAP_16 ||
3225 Opcode == ISD::ATOMIC_CMP_SWAP_32 ||
3226 Opcode == ISD::ATOMIC_CMP_SWAP_64) && "Invalid Atomic Op");
3227 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3229 MVT VT = Cmp.getValueType();
3231 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3232 Alignment = getMVTAlignment(VT);
3234 SDVTList VTs = getVTList(VT, MVT::Other);
3235 FoldingSetNodeID ID;
3236 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3237 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3239 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3240 return SDValue(E, 0);
3241 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3242 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3243 CSEMap.InsertNode(N, IP);
3244 AllNodes.push_back(N);
3245 return SDValue(N, 0);
3248 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3249 SDValue Ptr, SDValue Val,
3250 const Value* PtrVal,
3251 unsigned Alignment) {
3252 assert((Opcode == ISD::ATOMIC_LOAD_ADD_8 ||
3253 Opcode == ISD::ATOMIC_LOAD_SUB_8 ||
3254 Opcode == ISD::ATOMIC_LOAD_AND_8 ||
3255 Opcode == ISD::ATOMIC_LOAD_OR_8 ||
3256 Opcode == ISD::ATOMIC_LOAD_XOR_8 ||
3257 Opcode == ISD::ATOMIC_LOAD_NAND_8 ||
3258 Opcode == ISD::ATOMIC_LOAD_MIN_8 ||
3259 Opcode == ISD::ATOMIC_LOAD_MAX_8 ||
3260 Opcode == ISD::ATOMIC_LOAD_UMIN_8 ||
3261 Opcode == ISD::ATOMIC_LOAD_UMAX_8 ||
3262 Opcode == ISD::ATOMIC_SWAP_8 ||
3263 Opcode == ISD::ATOMIC_LOAD_ADD_16 ||
3264 Opcode == ISD::ATOMIC_LOAD_SUB_16 ||
3265 Opcode == ISD::ATOMIC_LOAD_AND_16 ||
3266 Opcode == ISD::ATOMIC_LOAD_OR_16 ||
3267 Opcode == ISD::ATOMIC_LOAD_XOR_16 ||
3268 Opcode == ISD::ATOMIC_LOAD_NAND_16 ||
3269 Opcode == ISD::ATOMIC_LOAD_MIN_16 ||
3270 Opcode == ISD::ATOMIC_LOAD_MAX_16 ||
3271 Opcode == ISD::ATOMIC_LOAD_UMIN_16 ||
3272 Opcode == ISD::ATOMIC_LOAD_UMAX_16 ||
3273 Opcode == ISD::ATOMIC_SWAP_16 ||
3274 Opcode == ISD::ATOMIC_LOAD_ADD_32 ||
3275 Opcode == ISD::ATOMIC_LOAD_SUB_32 ||
3276 Opcode == ISD::ATOMIC_LOAD_AND_32 ||
3277 Opcode == ISD::ATOMIC_LOAD_OR_32 ||
3278 Opcode == ISD::ATOMIC_LOAD_XOR_32 ||
3279 Opcode == ISD::ATOMIC_LOAD_NAND_32 ||
3280 Opcode == ISD::ATOMIC_LOAD_MIN_32 ||
3281 Opcode == ISD::ATOMIC_LOAD_MAX_32 ||
3282 Opcode == ISD::ATOMIC_LOAD_UMIN_32 ||
3283 Opcode == ISD::ATOMIC_LOAD_UMAX_32 ||
3284 Opcode == ISD::ATOMIC_SWAP_32 ||
3285 Opcode == ISD::ATOMIC_LOAD_ADD_64 ||
3286 Opcode == ISD::ATOMIC_LOAD_SUB_64 ||
3287 Opcode == ISD::ATOMIC_LOAD_AND_64 ||
3288 Opcode == ISD::ATOMIC_LOAD_OR_64 ||
3289 Opcode == ISD::ATOMIC_LOAD_XOR_64 ||
3290 Opcode == ISD::ATOMIC_LOAD_NAND_64 ||
3291 Opcode == ISD::ATOMIC_LOAD_MIN_64 ||
3292 Opcode == ISD::ATOMIC_LOAD_MAX_64 ||
3293 Opcode == ISD::ATOMIC_LOAD_UMIN_64 ||
3294 Opcode == ISD::ATOMIC_LOAD_UMAX_64 ||
3295 Opcode == ISD::ATOMIC_SWAP_64) && "Invalid Atomic Op");
3297 MVT VT = Val.getValueType();
3299 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3300 Alignment = getMVTAlignment(VT);
3302 SDVTList VTs = getVTList(VT, MVT::Other);
3303 FoldingSetNodeID ID;
3304 SDValue Ops[] = {Chain, Ptr, Val};
3305 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3307 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3308 return SDValue(E, 0);
3309 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3310 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3311 CSEMap.InsertNode(N, IP);
3312 AllNodes.push_back(N);
3313 return SDValue(N, 0);
3316 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3317 /// Allowed to return something different (and simpler) if Simplify is true.
3318 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3320 if (Simplify && NumOps == 1)
3323 SmallVector<MVT, 4> VTs;
3324 VTs.reserve(NumOps);
3325 for (unsigned i = 0; i < NumOps; ++i)
3326 VTs.push_back(Ops[i].getValueType());
3327 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3331 SelectionDAG::getCall(unsigned CallingConv, bool IsVarArgs, bool IsTailCall,
3332 bool IsInreg, SDVTList VTs,
3333 const SDValue *Operands, unsigned NumOperands) {
3334 // Do not include isTailCall in the folding set profile.
3335 FoldingSetNodeID ID;
3336 AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3337 ID.AddInteger(CallingConv);
3338 ID.AddInteger(IsVarArgs);
3340 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3341 // Instead of including isTailCall in the folding set, we just
3342 // set the flag of the existing node.
3344 cast<CallSDNode>(E)->setNotTailCall();
3345 return SDValue(E, 0);
3347 SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3348 new (N) CallSDNode(CallingConv, IsVarArgs, IsTailCall, IsInreg,
3349 VTs, Operands, NumOperands);
3350 CSEMap.InsertNode(N, IP);
3351 AllNodes.push_back(N);
3352 return SDValue(N, 0);
3356 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3357 MVT VT, SDValue Chain,
3358 SDValue Ptr, SDValue Offset,
3359 const Value *SV, int SVOffset, MVT EVT,
3360 bool isVolatile, unsigned Alignment) {
3361 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3362 Alignment = getMVTAlignment(VT);
3365 ExtType = ISD::NON_EXTLOAD;
3366 } else if (ExtType == ISD::NON_EXTLOAD) {
3367 assert(VT == EVT && "Non-extending load from different memory type!");
3371 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3372 "Invalid vector extload!");
3374 assert(EVT.bitsLT(VT) &&
3375 "Should only be an extending load, not truncating!");
3376 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3377 "Cannot sign/zero extend a FP/Vector load!");
3378 assert(VT.isInteger() == EVT.isInteger() &&
3379 "Cannot convert from FP to Int or Int -> FP!");
3382 bool Indexed = AM != ISD::UNINDEXED;
3383 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3384 "Unindexed load with an offset!");
3386 SDVTList VTs = Indexed ?
3387 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3388 SDValue Ops[] = { Chain, Ptr, Offset };
3389 FoldingSetNodeID ID;
3390 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3392 ID.AddInteger(ExtType);
3393 ID.AddInteger(EVT.getRawBits());
3394 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3396 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3397 return SDValue(E, 0);
3398 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3399 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3400 Alignment, isVolatile);
3401 CSEMap.InsertNode(N, IP);
3402 AllNodes.push_back(N);
3403 return SDValue(N, 0);
3406 SDValue SelectionDAG::getLoad(MVT VT,
3407 SDValue Chain, SDValue Ptr,
3408 const Value *SV, int SVOffset,
3409 bool isVolatile, unsigned Alignment) {
3410 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3411 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3412 SV, SVOffset, VT, isVolatile, Alignment);
3415 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3416 SDValue Chain, SDValue Ptr,
3418 int SVOffset, MVT EVT,
3419 bool isVolatile, unsigned Alignment) {
3420 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3421 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3422 SV, SVOffset, EVT, isVolatile, Alignment);
3426 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
3427 SDValue Offset, ISD::MemIndexedMode AM) {
3428 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3429 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3430 "Load is already a indexed load!");
3431 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3432 LD->getChain(), Base, Offset, LD->getSrcValue(),
3433 LD->getSrcValueOffset(), LD->getMemoryVT(),
3434 LD->isVolatile(), LD->getAlignment());
3437 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3438 SDValue Ptr, const Value *SV, int SVOffset,
3439 bool isVolatile, unsigned Alignment) {
3440 MVT VT = Val.getValueType();
3442 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3443 Alignment = getMVTAlignment(VT);
3445 SDVTList VTs = getVTList(MVT::Other);
3446 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3447 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3448 FoldingSetNodeID ID;
3449 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3450 ID.AddInteger(ISD::UNINDEXED);
3451 ID.AddInteger(false);
3452 ID.AddInteger(VT.getRawBits());
3453 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3455 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3456 return SDValue(E, 0);
3457 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3458 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3459 VT, SV, SVOffset, Alignment, isVolatile);
3460 CSEMap.InsertNode(N, IP);
3461 AllNodes.push_back(N);
3462 return SDValue(N, 0);
3465 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
3466 SDValue Ptr, const Value *SV,
3467 int SVOffset, MVT SVT,
3468 bool isVolatile, unsigned Alignment) {
3469 MVT VT = Val.getValueType();
3472 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3474 assert(VT.bitsGT(SVT) && "Not a truncation?");
3475 assert(VT.isInteger() == SVT.isInteger() &&
3476 "Can't do FP-INT conversion!");
3478 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3479 Alignment = getMVTAlignment(VT);
3481 SDVTList VTs = getVTList(MVT::Other);
3482 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3483 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3484 FoldingSetNodeID ID;
3485 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3486 ID.AddInteger(ISD::UNINDEXED);
3488 ID.AddInteger(SVT.getRawBits());
3489 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3491 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3492 return SDValue(E, 0);
3493 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3494 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3495 SVT, SV, SVOffset, Alignment, isVolatile);
3496 CSEMap.InsertNode(N, IP);
3497 AllNodes.push_back(N);
3498 return SDValue(N, 0);
3502 SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
3503 SDValue Offset, ISD::MemIndexedMode AM) {
3504 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3505 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3506 "Store is already a indexed store!");
3507 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3508 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3509 FoldingSetNodeID ID;
3510 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3512 ID.AddInteger(ST->isTruncatingStore());
3513 ID.AddInteger(ST->getMemoryVT().getRawBits());
3514 ID.AddInteger(ST->getRawFlags());
3516 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3517 return SDValue(E, 0);
3518 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3519 new (N) StoreSDNode(Ops, VTs, AM,
3520 ST->isTruncatingStore(), ST->getMemoryVT(),
3521 ST->getSrcValue(), ST->getSrcValueOffset(),
3522 ST->getAlignment(), ST->isVolatile());
3523 CSEMap.InsertNode(N, IP);
3524 AllNodes.push_back(N);
3525 return SDValue(N, 0);
3528 SDValue SelectionDAG::getVAArg(MVT VT,
3529 SDValue Chain, SDValue Ptr,
3531 SDValue Ops[] = { Chain, Ptr, SV };
3532 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3535 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3536 const SDUse *Ops, unsigned NumOps) {
3538 case 0: return getNode(Opcode, VT);
3539 case 1: return getNode(Opcode, VT, Ops[0]);
3540 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3541 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3545 // Copy from an SDUse array into an SDValue array for use with
3546 // the regular getNode logic.
3547 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3548 return getNode(Opcode, VT, &NewOps[0], NumOps);
3551 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3552 const SDValue *Ops, unsigned NumOps) {
3554 case 0: return getNode(Opcode, VT);
3555 case 1: return getNode(Opcode, VT, Ops[0]);
3556 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3557 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3563 case ISD::SELECT_CC: {
3564 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3565 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3566 "LHS and RHS of condition must have same type!");
3567 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3568 "True and False arms of SelectCC must have same type!");
3569 assert(Ops[2].getValueType() == VT &&
3570 "select_cc node must be of same type as true and false value!");
3574 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3575 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3576 "LHS/RHS of comparison should match types!");
3583 SDVTList VTs = getVTList(VT);
3584 if (VT != MVT::Flag) {
3585 FoldingSetNodeID ID;
3586 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3588 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3589 return SDValue(E, 0);
3590 N = NodeAllocator.Allocate<SDNode>();
3591 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3592 CSEMap.InsertNode(N, IP);
3594 N = NodeAllocator.Allocate<SDNode>();
3595 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3597 AllNodes.push_back(N);
3601 return SDValue(N, 0);
3604 SDValue SelectionDAG::getNode(unsigned Opcode,
3605 const std::vector<MVT> &ResultTys,
3606 const SDValue *Ops, unsigned NumOps) {
3607 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3611 SDValue SelectionDAG::getNode(unsigned Opcode,
3612 const MVT *VTs, unsigned NumVTs,
3613 const SDValue *Ops, unsigned NumOps) {
3615 return getNode(Opcode, VTs[0], Ops, NumOps);
3616 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3619 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3620 const SDValue *Ops, unsigned NumOps) {
3621 if (VTList.NumVTs == 1)
3622 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3625 // FIXME: figure out how to safely handle things like
3626 // int foo(int x) { return 1 << (x & 255); }
3627 // int bar() { return foo(256); }
3629 case ISD::SRA_PARTS:
3630 case ISD::SRL_PARTS:
3631 case ISD::SHL_PARTS:
3632 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3633 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3634 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3635 else if (N3.getOpcode() == ISD::AND)
3636 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3637 // If the and is only masking out bits that cannot effect the shift,
3638 // eliminate the and.
3639 unsigned NumBits = VT.getSizeInBits()*2;
3640 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3641 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3647 // Memoize the node unless it returns a flag.
3649 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3650 FoldingSetNodeID ID;
3651 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3653 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3654 return SDValue(E, 0);
3656 N = NodeAllocator.Allocate<UnarySDNode>();
3657 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3658 } else if (NumOps == 2) {
3659 N = NodeAllocator.Allocate<BinarySDNode>();
3660 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3661 } else if (NumOps == 3) {
3662 N = NodeAllocator.Allocate<TernarySDNode>();
3663 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3665 N = NodeAllocator.Allocate<SDNode>();
3666 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3668 CSEMap.InsertNode(N, IP);
3671 N = NodeAllocator.Allocate<UnarySDNode>();
3672 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3673 } else if (NumOps == 2) {
3674 N = NodeAllocator.Allocate<BinarySDNode>();
3675 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3676 } else if (NumOps == 3) {
3677 N = NodeAllocator.Allocate<TernarySDNode>();
3678 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3680 N = NodeAllocator.Allocate<SDNode>();
3681 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3684 AllNodes.push_back(N);
3688 return SDValue(N, 0);
3691 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3692 return getNode(Opcode, VTList, 0, 0);
3695 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3697 SDValue Ops[] = { N1 };
3698 return getNode(Opcode, VTList, Ops, 1);
3701 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3702 SDValue N1, SDValue N2) {
3703 SDValue Ops[] = { N1, N2 };
3704 return getNode(Opcode, VTList, Ops, 2);
3707 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3708 SDValue N1, SDValue N2, SDValue N3) {
3709 SDValue Ops[] = { N1, N2, N3 };
3710 return getNode(Opcode, VTList, Ops, 3);
3713 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3714 SDValue N1, SDValue N2, SDValue N3,
3716 SDValue Ops[] = { N1, N2, N3, N4 };
3717 return getNode(Opcode, VTList, Ops, 4);
3720 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3721 SDValue N1, SDValue N2, SDValue N3,
3722 SDValue N4, SDValue N5) {
3723 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3724 return getNode(Opcode, VTList, Ops, 5);
3727 SDVTList SelectionDAG::getVTList(MVT VT) {
3728 return makeVTList(SDNode::getValueTypeList(VT), 1);
3731 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3732 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3733 E = VTList.rend(); I != E; ++I)
3734 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
3737 MVT *Array = Allocator.Allocate<MVT>(2);
3740 SDVTList Result = makeVTList(Array, 2);
3741 VTList.push_back(Result);
3745 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
3746 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3747 E = VTList.rend(); I != E; ++I)
3748 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
3752 MVT *Array = Allocator.Allocate<MVT>(3);
3756 SDVTList Result = makeVTList(Array, 3);
3757 VTList.push_back(Result);
3761 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3763 case 0: assert(0 && "Cannot have nodes without results!");
3764 case 1: return getVTList(VTs[0]);
3765 case 2: return getVTList(VTs[0], VTs[1]);
3766 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3770 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3771 E = VTList.rend(); I != E; ++I) {
3772 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
3775 bool NoMatch = false;
3776 for (unsigned i = 2; i != NumVTs; ++i)
3777 if (VTs[i] != I->VTs[i]) {
3785 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
3786 std::copy(VTs, VTs+NumVTs, Array);
3787 SDVTList Result = makeVTList(Array, NumVTs);
3788 VTList.push_back(Result);
3793 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3794 /// specified operands. If the resultant node already exists in the DAG,
3795 /// this does not modify the specified node, instead it returns the node that
3796 /// already exists. If the resultant node does not exist in the DAG, the
3797 /// input node is returned. As a degenerate case, if you specify the same
3798 /// input operands as the node already has, the input node is returned.
3799 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
3800 SDNode *N = InN.getNode();
3801 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3803 // Check to see if there is no change.
3804 if (Op == N->getOperand(0)) return InN;
3806 // See if the modified node already exists.
3807 void *InsertPos = 0;
3808 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3809 return SDValue(Existing, InN.getResNo());
3811 // Nope it doesn't. Remove the node from its current place in the maps.
3813 if (!RemoveNodeFromCSEMaps(N))
3816 // Now we update the operands.
3817 N->OperandList[0].getVal()->removeUser(0, N);
3818 N->OperandList[0] = Op;
3819 N->OperandList[0].setUser(N);
3820 Op.getNode()->addUser(0, N);
3822 // If this gets put into a CSE map, add it.
3823 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3827 SDValue SelectionDAG::
3828 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
3829 SDNode *N = InN.getNode();
3830 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3832 // Check to see if there is no change.
3833 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3834 return InN; // No operands changed, just return the input node.
3836 // See if the modified node already exists.
3837 void *InsertPos = 0;
3838 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3839 return SDValue(Existing, InN.getResNo());
3841 // Nope it doesn't. Remove the node from its current place in the maps.
3843 if (!RemoveNodeFromCSEMaps(N))
3846 // Now we update the operands.
3847 if (N->OperandList[0] != Op1) {
3848 N->OperandList[0].getVal()->removeUser(0, N);
3849 N->OperandList[0] = Op1;
3850 N->OperandList[0].setUser(N);
3851 Op1.getNode()->addUser(0, N);
3853 if (N->OperandList[1] != Op2) {
3854 N->OperandList[1].getVal()->removeUser(1, N);
3855 N->OperandList[1] = Op2;
3856 N->OperandList[1].setUser(N);
3857 Op2.getNode()->addUser(1, N);
3860 // If this gets put into a CSE map, add it.
3861 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3865 SDValue SelectionDAG::
3866 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
3867 SDValue Ops[] = { Op1, Op2, Op3 };
3868 return UpdateNodeOperands(N, Ops, 3);
3871 SDValue SelectionDAG::
3872 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3873 SDValue Op3, SDValue Op4) {
3874 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
3875 return UpdateNodeOperands(N, Ops, 4);
3878 SDValue SelectionDAG::
3879 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3880 SDValue Op3, SDValue Op4, SDValue Op5) {
3881 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3882 return UpdateNodeOperands(N, Ops, 5);
3885 SDValue SelectionDAG::
3886 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
3887 SDNode *N = InN.getNode();
3888 assert(N->getNumOperands() == NumOps &&
3889 "Update with wrong number of operands");
3891 // Check to see if there is no change.
3892 bool AnyChange = false;
3893 for (unsigned i = 0; i != NumOps; ++i) {
3894 if (Ops[i] != N->getOperand(i)) {
3900 // No operands changed, just return the input node.
3901 if (!AnyChange) return InN;
3903 // See if the modified node already exists.
3904 void *InsertPos = 0;
3905 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3906 return SDValue(Existing, InN.getResNo());
3908 // Nope it doesn't. Remove the node from its current place in the maps.
3910 if (!RemoveNodeFromCSEMaps(N))
3913 // Now we update the operands.
3914 for (unsigned i = 0; i != NumOps; ++i) {
3915 if (N->OperandList[i] != Ops[i]) {
3916 N->OperandList[i].getVal()->removeUser(i, N);
3917 N->OperandList[i] = Ops[i];
3918 N->OperandList[i].setUser(N);
3919 Ops[i].getNode()->addUser(i, N);
3923 // If this gets put into a CSE map, add it.
3924 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3928 /// DropOperands - Release the operands and set this node to have
3930 void SDNode::DropOperands() {
3931 // Unlike the code in MorphNodeTo that does this, we don't need to
3932 // watch for dead nodes here.
3933 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3934 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3939 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
3942 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3944 SDVTList VTs = getVTList(VT);
3945 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
3948 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3949 MVT VT, SDValue Op1) {
3950 SDVTList VTs = getVTList(VT);
3951 SDValue Ops[] = { Op1 };
3952 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3955 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3956 MVT VT, SDValue Op1,
3958 SDVTList VTs = getVTList(VT);
3959 SDValue Ops[] = { Op1, Op2 };
3960 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3963 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3964 MVT VT, SDValue Op1,
3965 SDValue Op2, SDValue Op3) {
3966 SDVTList VTs = getVTList(VT);
3967 SDValue Ops[] = { Op1, Op2, Op3 };
3968 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3971 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3972 MVT VT, const SDValue *Ops,
3974 SDVTList VTs = getVTList(VT);
3975 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3978 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3979 MVT VT1, MVT VT2, const SDValue *Ops,
3981 SDVTList VTs = getVTList(VT1, VT2);
3982 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3985 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3987 SDVTList VTs = getVTList(VT1, VT2);
3988 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
3991 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3992 MVT VT1, MVT VT2, MVT VT3,
3993 const SDValue *Ops, unsigned NumOps) {
3994 SDVTList VTs = getVTList(VT1, VT2, VT3);
3995 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3998 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4001 SDVTList VTs = getVTList(VT1, VT2);
4002 SDValue Ops[] = { Op1 };
4003 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4006 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4008 SDValue Op1, SDValue Op2) {
4009 SDVTList VTs = getVTList(VT1, VT2);
4010 SDValue Ops[] = { Op1, Op2 };
4011 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4014 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4016 SDValue Op1, SDValue Op2,
4018 SDVTList VTs = getVTList(VT1, VT2);
4019 SDValue Ops[] = { Op1, Op2, Op3 };
4020 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4023 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4024 SDVTList VTs, const SDValue *Ops,
4026 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4029 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4031 SDVTList VTs = getVTList(VT);
4032 return MorphNodeTo(N, Opc, VTs, 0, 0);
4035 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4036 MVT VT, SDValue Op1) {
4037 SDVTList VTs = getVTList(VT);
4038 SDValue Ops[] = { Op1 };
4039 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4042 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4043 MVT VT, SDValue Op1,
4045 SDVTList VTs = getVTList(VT);
4046 SDValue Ops[] = { Op1, Op2 };
4047 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4050 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4051 MVT VT, SDValue Op1,
4052 SDValue Op2, SDValue Op3) {
4053 SDVTList VTs = getVTList(VT);
4054 SDValue Ops[] = { Op1, Op2, Op3 };
4055 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4058 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4059 MVT VT, const SDValue *Ops,
4061 SDVTList VTs = getVTList(VT);
4062 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4065 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4066 MVT VT1, MVT VT2, const SDValue *Ops,
4068 SDVTList VTs = getVTList(VT1, VT2);
4069 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4072 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4074 SDVTList VTs = getVTList(VT1, VT2);
4075 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4078 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4079 MVT VT1, MVT VT2, MVT VT3,
4080 const SDValue *Ops, unsigned NumOps) {
4081 SDVTList VTs = getVTList(VT1, VT2, VT3);
4082 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4085 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4088 SDVTList VTs = getVTList(VT1, VT2);
4089 SDValue Ops[] = { Op1 };
4090 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4093 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4095 SDValue Op1, SDValue Op2) {
4096 SDVTList VTs = getVTList(VT1, VT2);
4097 SDValue Ops[] = { Op1, Op2 };
4098 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4101 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4103 SDValue Op1, SDValue Op2,
4105 SDVTList VTs = getVTList(VT1, VT2);
4106 SDValue Ops[] = { Op1, Op2, Op3 };
4107 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4110 /// MorphNodeTo - These *mutate* the specified node to have the specified
4111 /// return type, opcode, and operands.
4113 /// Note that MorphNodeTo returns the resultant node. If there is already a
4114 /// node of the specified opcode and operands, it returns that node instead of
4115 /// the current one.
4117 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4118 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4119 /// node, and because it doesn't require CSE recalculation for any of
4120 /// the node's users.
4122 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4123 SDVTList VTs, const SDValue *Ops,
4125 // If an identical node already exists, use it.
4127 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4128 FoldingSetNodeID ID;
4129 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4130 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4134 if (!RemoveNodeFromCSEMaps(N))
4137 // Start the morphing.
4139 N->ValueList = VTs.VTs;
4140 N->NumValues = VTs.NumVTs;
4142 // Clear the operands list, updating used nodes to remove this from their
4143 // use list. Keep track of any operands that become dead as a result.
4144 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4145 for (SDNode::op_iterator B = N->op_begin(), I = B, E = N->op_end();
4147 SDNode *Used = I->getVal();
4148 Used->removeUser(std::distance(B, I), N);
4149 if (Used->use_empty())
4150 DeadNodeSet.insert(Used);
4153 // If NumOps is larger than the # of operands we currently have, reallocate
4154 // the operand list.
4155 if (NumOps > N->NumOperands) {
4156 if (N->OperandsNeedDelete)
4157 delete[] N->OperandList;
4158 if (N->isMachineOpcode()) {
4159 // We're creating a final node that will live unmorphed for the
4160 // remainder of the current SelectionDAG iteration, so we can allocate
4161 // the operands directly out of a pool with no recycling metadata.
4162 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4163 N->OperandsNeedDelete = false;
4165 N->OperandList = new SDUse[NumOps];
4166 N->OperandsNeedDelete = true;
4170 // Assign the new operands.
4171 N->NumOperands = NumOps;
4172 for (unsigned i = 0, e = NumOps; i != e; ++i) {
4173 N->OperandList[i] = Ops[i];
4174 N->OperandList[i].setUser(N);
4175 SDNode *ToUse = N->OperandList[i].getVal();
4176 ToUse->addUser(i, N);
4179 // Delete any nodes that are still dead after adding the uses for the
4181 SmallVector<SDNode *, 16> DeadNodes;
4182 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4183 E = DeadNodeSet.end(); I != E; ++I)
4184 if ((*I)->use_empty())
4185 DeadNodes.push_back(*I);
4186 RemoveDeadNodes(DeadNodes);
4189 CSEMap.InsertNode(N, IP); // Memoize the new node.
4194 /// getTargetNode - These are used for target selectors to create a new node
4195 /// with specified return type(s), target opcode, and operands.
4197 /// Note that getTargetNode returns the resultant node. If there is already a
4198 /// node of the specified opcode and operands, it returns that node instead of
4199 /// the current one.
4200 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4201 return getNode(~Opcode, VT).getNode();
4203 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4204 return getNode(~Opcode, VT, Op1).getNode();
4206 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4207 SDValue Op1, SDValue Op2) {
4208 return getNode(~Opcode, VT, Op1, Op2).getNode();
4210 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4211 SDValue Op1, SDValue Op2,
4213 return getNode(~Opcode, VT, Op1, Op2, Op3).getNode();
4215 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4216 const SDValue *Ops, unsigned NumOps) {
4217 return getNode(~Opcode, VT, Ops, NumOps).getNode();
4219 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4220 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4222 return getNode(~Opcode, VTs, 2, &Op, 0).getNode();
4224 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4225 MVT VT2, SDValue Op1) {
4226 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4227 return getNode(~Opcode, VTs, 2, &Op1, 1).getNode();
4229 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4230 MVT VT2, SDValue Op1,
4232 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4233 SDValue Ops[] = { Op1, Op2 };
4234 return getNode(~Opcode, VTs, 2, Ops, 2).getNode();
4236 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4237 MVT VT2, SDValue Op1,
4238 SDValue Op2, SDValue Op3) {
4239 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4240 SDValue Ops[] = { Op1, Op2, Op3 };
4241 return getNode(~Opcode, VTs, 2, Ops, 3).getNode();
4243 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4244 const SDValue *Ops, unsigned NumOps) {
4245 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4246 return getNode(~Opcode, VTs, 2, Ops, NumOps).getNode();
4248 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4249 SDValue Op1, SDValue Op2) {
4250 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4251 SDValue Ops[] = { Op1, Op2 };
4252 return getNode(~Opcode, VTs, 3, Ops, 2).getNode();
4254 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4255 SDValue Op1, SDValue Op2,
4257 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4258 SDValue Ops[] = { Op1, Op2, Op3 };
4259 return getNode(~Opcode, VTs, 3, Ops, 3).getNode();
4261 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4262 const SDValue *Ops, unsigned NumOps) {
4263 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4264 return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
4266 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4267 MVT VT2, MVT VT3, MVT VT4,
4268 const SDValue *Ops, unsigned NumOps) {
4269 std::vector<MVT> VTList;
4270 VTList.push_back(VT1);
4271 VTList.push_back(VT2);
4272 VTList.push_back(VT3);
4273 VTList.push_back(VT4);
4274 const MVT *VTs = getNodeValueTypes(VTList);
4275 return getNode(~Opcode, VTs, 4, Ops, NumOps).getNode();
4277 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4278 const std::vector<MVT> &ResultTys,
4279 const SDValue *Ops, unsigned NumOps) {
4280 const MVT *VTs = getNodeValueTypes(ResultTys);
4281 return getNode(~Opcode, VTs, ResultTys.size(),
4282 Ops, NumOps).getNode();
4285 /// getNodeIfExists - Get the specified node if it's already available, or
4286 /// else return NULL.
4287 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4288 const SDValue *Ops, unsigned NumOps) {
4289 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4290 FoldingSetNodeID ID;
4291 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4293 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4300 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4301 /// This can cause recursive merging of nodes in the DAG.
4303 /// This version assumes From has a single result value.
4305 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4306 DAGUpdateListener *UpdateListener) {
4307 SDNode *From = FromN.getNode();
4308 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4309 "Cannot replace with this method!");
4310 assert(From != To.getNode() && "Cannot replace uses of with self");
4312 while (!From->use_empty()) {
4313 SDNode::use_iterator UI = From->use_begin();
4316 // This node is about to morph, remove its old self from the CSE maps.
4317 RemoveNodeFromCSEMaps(U);
4319 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4320 I != E; ++I, ++operandNum)
4321 if (I->getVal() == From) {
4322 From->removeUser(operandNum, U);
4325 To.getNode()->addUser(operandNum, U);
4328 // Now that we have modified U, add it back to the CSE maps. If it already
4329 // exists there, recursively merge the results together.
4330 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4331 ReplaceAllUsesWith(U, Existing, UpdateListener);
4332 // U is now dead. Inform the listener if it exists and delete it.
4334 UpdateListener->NodeDeleted(U, Existing);
4335 DeleteNodeNotInCSEMaps(U);
4337 // If the node doesn't already exist, we updated it. Inform a listener if
4340 UpdateListener->NodeUpdated(U);
4345 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4346 /// This can cause recursive merging of nodes in the DAG.
4348 /// This version assumes From/To have matching types and numbers of result
4351 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4352 DAGUpdateListener *UpdateListener) {
4353 assert(From->getVTList().VTs == To->getVTList().VTs &&
4354 From->getNumValues() == To->getNumValues() &&
4355 "Cannot use this version of ReplaceAllUsesWith!");
4357 // Handle the trivial case.
4361 while (!From->use_empty()) {
4362 SDNode::use_iterator UI = From->use_begin();
4365 // This node is about to morph, remove its old self from the CSE maps.
4366 RemoveNodeFromCSEMaps(U);
4368 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4369 I != E; ++I, ++operandNum)
4370 if (I->getVal() == From) {
4371 From->removeUser(operandNum, U);
4372 I->getSDValue().setNode(To);
4373 To->addUser(operandNum, U);
4376 // Now that we have modified U, add it back to the CSE maps. If it already
4377 // exists there, recursively merge the results together.
4378 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4379 ReplaceAllUsesWith(U, Existing, UpdateListener);
4380 // U is now dead. Inform the listener if it exists and delete it.
4382 UpdateListener->NodeDeleted(U, Existing);
4383 DeleteNodeNotInCSEMaps(U);
4385 // If the node doesn't already exist, we updated it. Inform a listener if
4388 UpdateListener->NodeUpdated(U);
4393 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4394 /// This can cause recursive merging of nodes in the DAG.
4396 /// This version can replace From with any result values. To must match the
4397 /// number and types of values returned by From.
4398 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4400 DAGUpdateListener *UpdateListener) {
4401 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4402 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4404 while (!From->use_empty()) {
4405 SDNode::use_iterator UI = From->use_begin();
4408 // This node is about to morph, remove its old self from the CSE maps.
4409 RemoveNodeFromCSEMaps(U);
4411 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4412 I != E; ++I, ++operandNum)
4413 if (I->getVal() == From) {
4414 const SDValue &ToOp = To[I->getSDValue().getResNo()];
4415 From->removeUser(operandNum, U);
4418 ToOp.getNode()->addUser(operandNum, U);
4421 // Now that we have modified U, add it back to the CSE maps. If it already
4422 // exists there, recursively merge the results together.
4423 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4424 ReplaceAllUsesWith(U, Existing, UpdateListener);
4425 // U is now dead. Inform the listener if it exists and delete it.
4427 UpdateListener->NodeDeleted(U, Existing);
4428 DeleteNodeNotInCSEMaps(U);
4430 // If the node doesn't already exist, we updated it. Inform a listener if
4433 UpdateListener->NodeUpdated(U);
4438 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4439 /// uses of other values produced by From.getVal() alone. The Deleted vector is
4440 /// handled the same way as for ReplaceAllUsesWith.
4441 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4442 DAGUpdateListener *UpdateListener){
4443 // Handle the really simple, really trivial case efficiently.
4444 if (From == To) return;
4446 // Handle the simple, trivial, case efficiently.
4447 if (From.getNode()->getNumValues() == 1) {
4448 ReplaceAllUsesWith(From, To, UpdateListener);
4452 // Get all of the users of From.getNode(). We want these in a nice,
4453 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4454 SmallSetVector<SDNode*, 16> Users(From.getNode()->use_begin(), From.getNode()->use_end());
4456 while (!Users.empty()) {
4457 // We know that this user uses some value of From. If it is the right
4458 // value, update it.
4459 SDNode *User = Users.back();
4462 // Scan for an operand that matches From.
4463 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4464 for (; Op != E; ++Op)
4465 if (*Op == From) break;
4467 // If there are no matches, the user must use some other result of From.
4468 if (Op == E) continue;
4470 // Okay, we know this user needs to be updated. Remove its old self
4471 // from the CSE maps.
4472 RemoveNodeFromCSEMaps(User);
4474 // Update all operands that match "From" in case there are multiple uses.
4475 for (; Op != E; ++Op) {
4477 From.getNode()->removeUser(Op-User->op_begin(), User);
4480 To.getNode()->addUser(Op-User->op_begin(), User);
4484 // Now that we have modified User, add it back to the CSE maps. If it
4485 // already exists there, recursively merge the results together.
4486 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4488 if (UpdateListener) UpdateListener->NodeUpdated(User);
4489 continue; // Continue on to next user.
4492 // If there was already an existing matching node, use ReplaceAllUsesWith
4493 // to replace the dead one with the existing one. This can cause
4494 // recursive merging of other unrelated nodes down the line.
4495 ReplaceAllUsesWith(User, Existing, UpdateListener);
4497 // User is now dead. Notify a listener if present.
4498 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4499 DeleteNodeNotInCSEMaps(User);
4503 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4504 /// uses of other values produced by From.getVal() alone. The same value may
4505 /// appear in both the From and To list. The Deleted vector is
4506 /// handled the same way as for ReplaceAllUsesWith.
4507 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4510 DAGUpdateListener *UpdateListener){
4511 // Handle the simple, trivial case efficiently.
4513 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4515 SmallVector<std::pair<SDNode *, unsigned>, 16> Users;
4516 for (unsigned i = 0; i != Num; ++i)
4517 for (SDNode::use_iterator UI = From[i].getNode()->use_begin(),
4518 E = From[i].getNode()->use_end(); UI != E; ++UI)
4519 Users.push_back(std::make_pair(*UI, i));
4521 while (!Users.empty()) {
4522 // We know that this user uses some value of From. If it is the right
4523 // value, update it.
4524 SDNode *User = Users.back().first;
4525 unsigned i = Users.back().second;
4528 // Scan for an operand that matches From.
4529 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4530 for (; Op != E; ++Op)
4531 if (*Op == From[i]) break;
4533 // If there are no matches, the user must use some other result of From.
4534 if (Op == E) continue;
4536 // Okay, we know this user needs to be updated. Remove its old self
4537 // from the CSE maps.
4538 RemoveNodeFromCSEMaps(User);
4540 // Update all operands that match "From" in case there are multiple uses.
4541 for (; Op != E; ++Op) {
4542 if (*Op == From[i]) {
4543 From[i].getNode()->removeUser(Op-User->op_begin(), User);
4546 To[i].getNode()->addUser(Op-User->op_begin(), User);
4550 // Now that we have modified User, add it back to the CSE maps. If it
4551 // already exists there, recursively merge the results together.
4552 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4554 if (UpdateListener) UpdateListener->NodeUpdated(User);
4555 continue; // Continue on to next user.
4558 // If there was already an existing matching node, use ReplaceAllUsesWith
4559 // to replace the dead one with the existing one. This can cause
4560 // recursive merging of other unrelated nodes down the line.
4561 ReplaceAllUsesWith(User, Existing, UpdateListener);
4563 // User is now dead. Notify a listener if present.
4564 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4565 DeleteNodeNotInCSEMaps(User);
4569 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4570 /// based on their topological order. It returns the maximum id and a vector
4571 /// of the SDNodes* in assigned order by reference.
4572 unsigned SelectionDAG::AssignTopologicalOrder() {
4574 unsigned DAGSize = 0;
4576 // SortedPos tracks the progress of the algorithm. Nodes before it are
4577 // sorted, nodes after it are unsorted. When the algorithm completes
4578 // it is at the end of the list.
4579 allnodes_iterator SortedPos = allnodes_begin();
4581 // Visit all the nodes. Add nodes with no operands to the TopOrder result
4582 // array immediately. Annotate nodes that do have operands with their
4583 // operand count. Before we do this, the Node Id fields of the nodes
4584 // may contain arbitrary values. After, the Node Id fields for nodes
4585 // before SortedPos will contain the topological sort index, and the
4586 // Node Id fields for nodes At SortedPos and after will contain the
4587 // count of outstanding operands.
4588 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
4590 unsigned Degree = N->getNumOperands();
4592 // A node with no uses, add it to the result array immediately.
4593 N->setNodeId(DAGSize++);
4594 allnodes_iterator Q = N;
4596 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
4599 // Temporarily use the Node Id as scratch space for the degree count.
4600 N->setNodeId(Degree);
4604 // Visit all the nodes. As we iterate, moves nodes into sorted order,
4605 // such that by the time the end is reached all nodes will be sorted.
4606 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
4608 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4611 unsigned Degree = P->getNodeId();
4614 // All of P's operands are sorted, so P may sorted now.
4615 P->setNodeId(DAGSize++);
4617 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
4620 // Update P's outstanding operand count.
4621 P->setNodeId(Degree);
4626 assert(SortedPos == AllNodes.end() &&
4627 "Topological sort incomplete!");
4628 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
4629 "First node in topological sort is not the entry token!");
4630 assert(AllNodes.front().getNodeId() == 0 &&
4631 "First node in topological sort has non-zero id!");
4632 assert(AllNodes.front().getNumOperands() == 0 &&
4633 "First node in topological sort has operands!");
4634 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
4635 "Last node in topologic sort has unexpected id!");
4636 assert(AllNodes.back().use_empty() &&
4637 "Last node in topologic sort has users!");
4638 assert(DAGSize == allnodes_size() && "TopOrder result count mismatch!");
4644 //===----------------------------------------------------------------------===//
4646 //===----------------------------------------------------------------------===//
4648 // Out-of-line virtual method to give class a home.
4649 void SDNode::ANCHOR() {}
4650 void UnarySDNode::ANCHOR() {}
4651 void BinarySDNode::ANCHOR() {}
4652 void TernarySDNode::ANCHOR() {}
4653 void HandleSDNode::ANCHOR() {}
4654 void ConstantSDNode::ANCHOR() {}
4655 void ConstantFPSDNode::ANCHOR() {}
4656 void GlobalAddressSDNode::ANCHOR() {}
4657 void FrameIndexSDNode::ANCHOR() {}
4658 void JumpTableSDNode::ANCHOR() {}
4659 void ConstantPoolSDNode::ANCHOR() {}
4660 void BasicBlockSDNode::ANCHOR() {}
4661 void SrcValueSDNode::ANCHOR() {}
4662 void MemOperandSDNode::ANCHOR() {}
4663 void RegisterSDNode::ANCHOR() {}
4664 void DbgStopPointSDNode::ANCHOR() {}
4665 void LabelSDNode::ANCHOR() {}
4666 void ExternalSymbolSDNode::ANCHOR() {}
4667 void CondCodeSDNode::ANCHOR() {}
4668 void ARG_FLAGSSDNode::ANCHOR() {}
4669 void VTSDNode::ANCHOR() {}
4670 void MemSDNode::ANCHOR() {}
4671 void LoadSDNode::ANCHOR() {}
4672 void StoreSDNode::ANCHOR() {}
4673 void AtomicSDNode::ANCHOR() {}
4674 void CallSDNode::ANCHOR() {}
4676 HandleSDNode::~HandleSDNode() {
4680 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4682 : SDNode(isa<GlobalVariable>(GA) &&
4683 cast<GlobalVariable>(GA)->isThreadLocal() ?
4685 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4687 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4688 getSDVTList(VT)), Offset(o) {
4689 TheGlobal = const_cast<GlobalValue*>(GA);
4692 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
4693 const Value *srcValue, int SVO,
4694 unsigned alignment, bool vol)
4695 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4696 Flags(encodeMemSDNodeFlags(vol, alignment)) {
4698 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4699 assert(getAlignment() == alignment && "Alignment representation error!");
4700 assert(isVolatile() == vol && "Volatile representation error!");
4703 /// getMemOperand - Return a MachineMemOperand object describing the memory
4704 /// reference performed by this memory reference.
4705 MachineMemOperand MemSDNode::getMemOperand() const {
4707 if (isa<LoadSDNode>(this))
4708 Flags = MachineMemOperand::MOLoad;
4709 else if (isa<StoreSDNode>(this))
4710 Flags = MachineMemOperand::MOStore;
4712 assert(isa<AtomicSDNode>(this) && "Unknown MemSDNode opcode!");
4713 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4716 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4717 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4719 // Check if the memory reference references a frame index
4720 const FrameIndexSDNode *FI =
4721 dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
4722 if (!getSrcValue() && FI)
4723 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
4724 Flags, 0, Size, getAlignment());
4726 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4727 Size, getAlignment());
4730 /// Profile - Gather unique data for the node.
4732 void SDNode::Profile(FoldingSetNodeID &ID) const {
4733 AddNodeIDNode(ID, this);
4736 /// getValueTypeList - Return a pointer to the specified value type.
4738 const MVT *SDNode::getValueTypeList(MVT VT) {
4739 if (VT.isExtended()) {
4740 static std::set<MVT, MVT::compareRawBits> EVTs;
4741 return &(*EVTs.insert(VT).first);
4743 static MVT VTs[MVT::LAST_VALUETYPE];
4744 VTs[VT.getSimpleVT()] = VT;
4745 return &VTs[VT.getSimpleVT()];
4749 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4750 /// indicated value. This method ignores uses of other values defined by this
4752 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4753 assert(Value < getNumValues() && "Bad value!");
4755 // TODO: Only iterate over uses of a given value of the node
4756 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4757 if (UI.getUse().getSDValue().getResNo() == Value) {
4764 // Found exactly the right number of uses?
4769 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4770 /// value. This method ignores uses of other values defined by this operation.
4771 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4772 assert(Value < getNumValues() && "Bad value!");
4774 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
4775 if (UI.getUse().getSDValue().getResNo() == Value)
4782 /// isOnlyUserOf - Return true if this node is the only use of N.
4784 bool SDNode::isOnlyUserOf(SDNode *N) const {
4786 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4797 /// isOperand - Return true if this node is an operand of N.
4799 bool SDValue::isOperandOf(SDNode *N) const {
4800 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4801 if (*this == N->getOperand(i))
4806 bool SDNode::isOperandOf(SDNode *N) const {
4807 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4808 if (this == N->OperandList[i].getVal())
4813 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4814 /// be a chain) reaches the specified operand without crossing any
4815 /// side-effecting instructions. In practice, this looks through token
4816 /// factors and non-volatile loads. In order to remain efficient, this only
4817 /// looks a couple of nodes in, it does not do an exhaustive search.
4818 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
4819 unsigned Depth) const {
4820 if (*this == Dest) return true;
4822 // Don't search too deeply, we just want to be able to see through
4823 // TokenFactor's etc.
4824 if (Depth == 0) return false;
4826 // If this is a token factor, all inputs to the TF happen in parallel. If any
4827 // of the operands of the TF reach dest, then we can do the xform.
4828 if (getOpcode() == ISD::TokenFactor) {
4829 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4830 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4835 // Loads don't have side effects, look through them.
4836 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4837 if (!Ld->isVolatile())
4838 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4844 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4845 SmallPtrSet<SDNode *, 32> &Visited) {
4846 if (found || !Visited.insert(N))
4849 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4850 SDNode *Op = N->getOperand(i).getNode();
4855 findPredecessor(Op, P, found, Visited);
4859 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4860 /// is either an operand of N or it can be reached by recursively traversing
4861 /// up the operands.
4862 /// NOTE: this is an expensive method. Use it carefully.
4863 bool SDNode::isPredecessorOf(SDNode *N) const {
4864 SmallPtrSet<SDNode *, 32> Visited;
4866 findPredecessor(N, this, found, Visited);
4870 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4871 assert(Num < NumOperands && "Invalid child # of SDNode!");
4872 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
4875 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4876 switch (getOpcode()) {
4878 if (getOpcode() < ISD::BUILTIN_OP_END)
4879 return "<<Unknown DAG Node>>";
4880 if (isMachineOpcode()) {
4882 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4883 if (getMachineOpcode() < TII->getNumOpcodes())
4884 return TII->get(getMachineOpcode()).getName();
4885 return "<<Unknown Machine Node>>";
4888 TargetLowering &TLI = G->getTargetLoweringInfo();
4889 const char *Name = TLI.getTargetNodeName(getOpcode());
4890 if (Name) return Name;
4891 return "<<Unknown Target Node>>";
4893 return "<<Unknown Node>>";
4896 case ISD::DELETED_NODE:
4897 return "<<Deleted Node!>>";
4899 case ISD::PREFETCH: return "Prefetch";
4900 case ISD::MEMBARRIER: return "MemBarrier";
4901 case ISD::ATOMIC_CMP_SWAP_8: return "AtomicCmpSwap8";
4902 case ISD::ATOMIC_SWAP_8: return "AtomicSwap8";
4903 case ISD::ATOMIC_LOAD_ADD_8: return "AtomicLoadAdd8";
4904 case ISD::ATOMIC_LOAD_SUB_8: return "AtomicLoadSub8";
4905 case ISD::ATOMIC_LOAD_AND_8: return "AtomicLoadAnd8";
4906 case ISD::ATOMIC_LOAD_OR_8: return "AtomicLoadOr8";
4907 case ISD::ATOMIC_LOAD_XOR_8: return "AtomicLoadXor8";
4908 case ISD::ATOMIC_LOAD_NAND_8: return "AtomicLoadNand8";
4909 case ISD::ATOMIC_LOAD_MIN_8: return "AtomicLoadMin8";
4910 case ISD::ATOMIC_LOAD_MAX_8: return "AtomicLoadMax8";
4911 case ISD::ATOMIC_LOAD_UMIN_8: return "AtomicLoadUMin8";
4912 case ISD::ATOMIC_LOAD_UMAX_8: return "AtomicLoadUMax8";
4913 case ISD::ATOMIC_CMP_SWAP_16: return "AtomicCmpSwap16";
4914 case ISD::ATOMIC_SWAP_16: return "AtomicSwap16";
4915 case ISD::ATOMIC_LOAD_ADD_16: return "AtomicLoadAdd16";
4916 case ISD::ATOMIC_LOAD_SUB_16: return "AtomicLoadSub16";
4917 case ISD::ATOMIC_LOAD_AND_16: return "AtomicLoadAnd16";
4918 case ISD::ATOMIC_LOAD_OR_16: return "AtomicLoadOr16";
4919 case ISD::ATOMIC_LOAD_XOR_16: return "AtomicLoadXor16";
4920 case ISD::ATOMIC_LOAD_NAND_16: return "AtomicLoadNand16";
4921 case ISD::ATOMIC_LOAD_MIN_16: return "AtomicLoadMin16";
4922 case ISD::ATOMIC_LOAD_MAX_16: return "AtomicLoadMax16";
4923 case ISD::ATOMIC_LOAD_UMIN_16: return "AtomicLoadUMin16";
4924 case ISD::ATOMIC_LOAD_UMAX_16: return "AtomicLoadUMax16";
4925 case ISD::ATOMIC_CMP_SWAP_32: return "AtomicCmpSwap32";
4926 case ISD::ATOMIC_SWAP_32: return "AtomicSwap32";
4927 case ISD::ATOMIC_LOAD_ADD_32: return "AtomicLoadAdd32";
4928 case ISD::ATOMIC_LOAD_SUB_32: return "AtomicLoadSub32";
4929 case ISD::ATOMIC_LOAD_AND_32: return "AtomicLoadAnd32";
4930 case ISD::ATOMIC_LOAD_OR_32: return "AtomicLoadOr32";
4931 case ISD::ATOMIC_LOAD_XOR_32: return "AtomicLoadXor32";
4932 case ISD::ATOMIC_LOAD_NAND_32: return "AtomicLoadNand32";
4933 case ISD::ATOMIC_LOAD_MIN_32: return "AtomicLoadMin32";
4934 case ISD::ATOMIC_LOAD_MAX_32: return "AtomicLoadMax32";
4935 case ISD::ATOMIC_LOAD_UMIN_32: return "AtomicLoadUMin32";
4936 case ISD::ATOMIC_LOAD_UMAX_32: return "AtomicLoadUMax32";
4937 case ISD::ATOMIC_CMP_SWAP_64: return "AtomicCmpSwap64";
4938 case ISD::ATOMIC_SWAP_64: return "AtomicSwap64";
4939 case ISD::ATOMIC_LOAD_ADD_64: return "AtomicLoadAdd64";
4940 case ISD::ATOMIC_LOAD_SUB_64: return "AtomicLoadSub64";
4941 case ISD::ATOMIC_LOAD_AND_64: return "AtomicLoadAnd64";
4942 case ISD::ATOMIC_LOAD_OR_64: return "AtomicLoadOr64";
4943 case ISD::ATOMIC_LOAD_XOR_64: return "AtomicLoadXor64";
4944 case ISD::ATOMIC_LOAD_NAND_64: return "AtomicLoadNand64";
4945 case ISD::ATOMIC_LOAD_MIN_64: return "AtomicLoadMin64";
4946 case ISD::ATOMIC_LOAD_MAX_64: return "AtomicLoadMax64";
4947 case ISD::ATOMIC_LOAD_UMIN_64: return "AtomicLoadUMin64";
4948 case ISD::ATOMIC_LOAD_UMAX_64: return "AtomicLoadUMax64";
4949 case ISD::PCMARKER: return "PCMarker";
4950 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4951 case ISD::SRCVALUE: return "SrcValue";
4952 case ISD::MEMOPERAND: return "MemOperand";
4953 case ISD::EntryToken: return "EntryToken";
4954 case ISD::TokenFactor: return "TokenFactor";
4955 case ISD::AssertSext: return "AssertSext";
4956 case ISD::AssertZext: return "AssertZext";
4958 case ISD::BasicBlock: return "BasicBlock";
4959 case ISD::ARG_FLAGS: return "ArgFlags";
4960 case ISD::VALUETYPE: return "ValueType";
4961 case ISD::Register: return "Register";
4963 case ISD::Constant: return "Constant";
4964 case ISD::ConstantFP: return "ConstantFP";
4965 case ISD::GlobalAddress: return "GlobalAddress";
4966 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4967 case ISD::FrameIndex: return "FrameIndex";
4968 case ISD::JumpTable: return "JumpTable";
4969 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4970 case ISD::RETURNADDR: return "RETURNADDR";
4971 case ISD::FRAMEADDR: return "FRAMEADDR";
4972 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4973 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4974 case ISD::EHSELECTION: return "EHSELECTION";
4975 case ISD::EH_RETURN: return "EH_RETURN";
4976 case ISD::ConstantPool: return "ConstantPool";
4977 case ISD::ExternalSymbol: return "ExternalSymbol";
4978 case ISD::INTRINSIC_WO_CHAIN: {
4979 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
4980 return Intrinsic::getName((Intrinsic::ID)IID);
4982 case ISD::INTRINSIC_VOID:
4983 case ISD::INTRINSIC_W_CHAIN: {
4984 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
4985 return Intrinsic::getName((Intrinsic::ID)IID);
4988 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4989 case ISD::TargetConstant: return "TargetConstant";
4990 case ISD::TargetConstantFP:return "TargetConstantFP";
4991 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4992 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4993 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4994 case ISD::TargetJumpTable: return "TargetJumpTable";
4995 case ISD::TargetConstantPool: return "TargetConstantPool";
4996 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4998 case ISD::CopyToReg: return "CopyToReg";
4999 case ISD::CopyFromReg: return "CopyFromReg";
5000 case ISD::UNDEF: return "undef";
5001 case ISD::MERGE_VALUES: return "merge_values";
5002 case ISD::INLINEASM: return "inlineasm";
5003 case ISD::DBG_LABEL: return "dbg_label";
5004 case ISD::EH_LABEL: return "eh_label";
5005 case ISD::DECLARE: return "declare";
5006 case ISD::HANDLENODE: return "handlenode";
5007 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
5008 case ISD::CALL: return "call";
5011 case ISD::FABS: return "fabs";
5012 case ISD::FNEG: return "fneg";
5013 case ISD::FSQRT: return "fsqrt";
5014 case ISD::FSIN: return "fsin";
5015 case ISD::FCOS: return "fcos";
5016 case ISD::FPOWI: return "fpowi";
5017 case ISD::FPOW: return "fpow";
5018 case ISD::FTRUNC: return "ftrunc";
5019 case ISD::FFLOOR: return "ffloor";
5020 case ISD::FCEIL: return "fceil";
5021 case ISD::FRINT: return "frint";
5022 case ISD::FNEARBYINT: return "fnearbyint";
5025 case ISD::ADD: return "add";
5026 case ISD::SUB: return "sub";
5027 case ISD::MUL: return "mul";
5028 case ISD::MULHU: return "mulhu";
5029 case ISD::MULHS: return "mulhs";
5030 case ISD::SDIV: return "sdiv";
5031 case ISD::UDIV: return "udiv";
5032 case ISD::SREM: return "srem";
5033 case ISD::UREM: return "urem";
5034 case ISD::SMUL_LOHI: return "smul_lohi";
5035 case ISD::UMUL_LOHI: return "umul_lohi";
5036 case ISD::SDIVREM: return "sdivrem";
5037 case ISD::UDIVREM: return "udivrem";
5038 case ISD::AND: return "and";
5039 case ISD::OR: return "or";
5040 case ISD::XOR: return "xor";
5041 case ISD::SHL: return "shl";
5042 case ISD::SRA: return "sra";
5043 case ISD::SRL: return "srl";
5044 case ISD::ROTL: return "rotl";
5045 case ISD::ROTR: return "rotr";
5046 case ISD::FADD: return "fadd";
5047 case ISD::FSUB: return "fsub";
5048 case ISD::FMUL: return "fmul";
5049 case ISD::FDIV: return "fdiv";
5050 case ISD::FREM: return "frem";
5051 case ISD::FCOPYSIGN: return "fcopysign";
5052 case ISD::FGETSIGN: return "fgetsign";
5054 case ISD::SETCC: return "setcc";
5055 case ISD::VSETCC: return "vsetcc";
5056 case ISD::SELECT: return "select";
5057 case ISD::SELECT_CC: return "select_cc";
5058 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5059 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5060 case ISD::CONCAT_VECTORS: return "concat_vectors";
5061 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5062 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5063 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5064 case ISD::CARRY_FALSE: return "carry_false";
5065 case ISD::ADDC: return "addc";
5066 case ISD::ADDE: return "adde";
5067 case ISD::SUBC: return "subc";
5068 case ISD::SUBE: return "sube";
5069 case ISD::SHL_PARTS: return "shl_parts";
5070 case ISD::SRA_PARTS: return "sra_parts";
5071 case ISD::SRL_PARTS: return "srl_parts";
5073 case ISD::EXTRACT_SUBREG: return "extract_subreg";
5074 case ISD::INSERT_SUBREG: return "insert_subreg";
5076 // Conversion operators.
5077 case ISD::SIGN_EXTEND: return "sign_extend";
5078 case ISD::ZERO_EXTEND: return "zero_extend";
5079 case ISD::ANY_EXTEND: return "any_extend";
5080 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5081 case ISD::TRUNCATE: return "truncate";
5082 case ISD::FP_ROUND: return "fp_round";
5083 case ISD::FLT_ROUNDS_: return "flt_rounds";
5084 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5085 case ISD::FP_EXTEND: return "fp_extend";
5087 case ISD::SINT_TO_FP: return "sint_to_fp";
5088 case ISD::UINT_TO_FP: return "uint_to_fp";
5089 case ISD::FP_TO_SINT: return "fp_to_sint";
5090 case ISD::FP_TO_UINT: return "fp_to_uint";
5091 case ISD::BIT_CONVERT: return "bit_convert";
5093 // Control flow instructions
5094 case ISD::BR: return "br";
5095 case ISD::BRIND: return "brind";
5096 case ISD::BR_JT: return "br_jt";
5097 case ISD::BRCOND: return "brcond";
5098 case ISD::BR_CC: return "br_cc";
5099 case ISD::RET: return "ret";
5100 case ISD::CALLSEQ_START: return "callseq_start";
5101 case ISD::CALLSEQ_END: return "callseq_end";
5104 case ISD::LOAD: return "load";
5105 case ISD::STORE: return "store";
5106 case ISD::VAARG: return "vaarg";
5107 case ISD::VACOPY: return "vacopy";
5108 case ISD::VAEND: return "vaend";
5109 case ISD::VASTART: return "vastart";
5110 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5111 case ISD::EXTRACT_ELEMENT: return "extract_element";
5112 case ISD::BUILD_PAIR: return "build_pair";
5113 case ISD::STACKSAVE: return "stacksave";
5114 case ISD::STACKRESTORE: return "stackrestore";
5115 case ISD::TRAP: return "trap";
5118 case ISD::BSWAP: return "bswap";
5119 case ISD::CTPOP: return "ctpop";
5120 case ISD::CTTZ: return "cttz";
5121 case ISD::CTLZ: return "ctlz";
5124 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5125 case ISD::DEBUG_LOC: return "debug_loc";
5128 case ISD::TRAMPOLINE: return "trampoline";
5131 switch (cast<CondCodeSDNode>(this)->get()) {
5132 default: assert(0 && "Unknown setcc condition!");
5133 case ISD::SETOEQ: return "setoeq";
5134 case ISD::SETOGT: return "setogt";
5135 case ISD::SETOGE: return "setoge";
5136 case ISD::SETOLT: return "setolt";
5137 case ISD::SETOLE: return "setole";
5138 case ISD::SETONE: return "setone";
5140 case ISD::SETO: return "seto";
5141 case ISD::SETUO: return "setuo";
5142 case ISD::SETUEQ: return "setue";
5143 case ISD::SETUGT: return "setugt";
5144 case ISD::SETUGE: return "setuge";
5145 case ISD::SETULT: return "setult";
5146 case ISD::SETULE: return "setule";
5147 case ISD::SETUNE: return "setune";
5149 case ISD::SETEQ: return "seteq";
5150 case ISD::SETGT: return "setgt";
5151 case ISD::SETGE: return "setge";
5152 case ISD::SETLT: return "setlt";
5153 case ISD::SETLE: return "setle";
5154 case ISD::SETNE: return "setne";
5159 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5168 return "<post-inc>";
5170 return "<post-dec>";
5174 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5175 std::string S = "< ";
5189 if (getByValAlign())
5190 S += "byval-align:" + utostr(getByValAlign()) + " ";
5192 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5194 S += "byval-size:" + utostr(getByValSize()) + " ";
5198 void SDNode::dump() const { dump(0); }
5199 void SDNode::dump(const SelectionDAG *G) const {
5204 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5205 OS << (void*)this << ": ";
5207 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5209 if (getValueType(i) == MVT::Other)
5212 OS << getValueType(i).getMVTString();
5214 OS << " = " << getOperationName(G);
5217 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5219 OS << (void*)getOperand(i).getNode();
5220 if (unsigned RN = getOperand(i).getResNo())
5224 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5225 SDNode *Mask = getOperand(2).getNode();
5227 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
5229 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
5232 OS << cast<ConstantSDNode>(Mask->getOperand(i))->getZExtValue();
5237 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5238 OS << '<' << CSDN->getAPIntValue() << '>';
5239 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5240 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5241 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5242 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5243 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5246 CSDN->getValueAPF().convertToAPInt().dump();
5249 } else if (const GlobalAddressSDNode *GADN =
5250 dyn_cast<GlobalAddressSDNode>(this)) {
5251 int offset = GADN->getOffset();
5253 WriteAsOperand(OS, GADN->getGlobal());
5256 OS << " + " << offset;
5258 OS << " " << offset;
5259 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5260 OS << "<" << FIDN->getIndex() << ">";
5261 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5262 OS << "<" << JTDN->getIndex() << ">";
5263 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5264 int offset = CP->getOffset();
5265 if (CP->isMachineConstantPoolEntry())
5266 OS << "<" << *CP->getMachineCPVal() << ">";
5268 OS << "<" << *CP->getConstVal() << ">";
5270 OS << " + " << offset;
5272 OS << " " << offset;
5273 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5275 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5277 OS << LBB->getName() << " ";
5278 OS << (const void*)BBDN->getBasicBlock() << ">";
5279 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5280 if (G && R->getReg() &&
5281 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5282 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5284 OS << " #" << R->getReg();
5286 } else if (const ExternalSymbolSDNode *ES =
5287 dyn_cast<ExternalSymbolSDNode>(this)) {
5288 OS << "'" << ES->getSymbol() << "'";
5289 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5291 OS << "<" << M->getValue() << ">";
5294 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5295 if (M->MO.getValue())
5296 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5298 OS << "<null:" << M->MO.getOffset() << ">";
5299 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5300 OS << N->getArgFlags().getArgFlagsString();
5301 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5302 OS << ":" << N->getVT().getMVTString();
5304 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5305 const Value *SrcValue = LD->getSrcValue();
5306 int SrcOffset = LD->getSrcValueOffset();
5312 OS << ":" << SrcOffset << ">";
5315 switch (LD->getExtensionType()) {
5316 default: doExt = false; break;
5317 case ISD::EXTLOAD: OS << " <anyext "; break;
5318 case ISD::SEXTLOAD: OS << " <sext "; break;
5319 case ISD::ZEXTLOAD: OS << " <zext "; break;
5322 OS << LD->getMemoryVT().getMVTString() << ">";
5324 const char *AM = getIndexedModeName(LD->getAddressingMode());
5327 if (LD->isVolatile())
5328 OS << " <volatile>";
5329 OS << " alignment=" << LD->getAlignment();
5330 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5331 const Value *SrcValue = ST->getSrcValue();
5332 int SrcOffset = ST->getSrcValueOffset();
5338 OS << ":" << SrcOffset << ">";
5340 if (ST->isTruncatingStore())
5341 OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
5343 const char *AM = getIndexedModeName(ST->getAddressingMode());
5346 if (ST->isVolatile())
5347 OS << " <volatile>";
5348 OS << " alignment=" << ST->getAlignment();
5349 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5350 const Value *SrcValue = AT->getSrcValue();
5351 int SrcOffset = AT->getSrcValueOffset();
5357 OS << ":" << SrcOffset << ">";
5358 if (AT->isVolatile())
5359 OS << " <volatile>";
5360 OS << " alignment=" << AT->getAlignment();
5364 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5365 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5366 if (N->getOperand(i).getNode()->hasOneUse())
5367 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5369 cerr << "\n" << std::string(indent+2, ' ')
5370 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5373 cerr << "\n" << std::string(indent, ' ');
5377 void SelectionDAG::dump() const {
5378 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5380 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5382 const SDNode *N = I;
5383 if (!N->hasOneUse() && N != getRoot().getNode())
5384 DumpNodes(N, 2, this);
5387 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5392 const Type *ConstantPoolSDNode::getType() const {
5393 if (isMachineConstantPoolEntry())
5394 return Val.MachineCPVal->getType();
5395 return Val.ConstVal->getType();