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/TargetOptions.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/System/Mutex.h"
38 #include "llvm/ADT/SetVector.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/StringExtras.h"
47 /// makeVTList - Return an instance of the SDVTList struct initialized with the
48 /// specified members.
49 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
50 SDVTList Res = {VTs, NumVTs};
54 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
55 switch (VT.getSimpleVT()) {
56 default: assert(0 && "Unknown FP format");
57 case MVT::f32: return &APFloat::IEEEsingle;
58 case MVT::f64: return &APFloat::IEEEdouble;
59 case MVT::f80: return &APFloat::x87DoubleExtended;
60 case MVT::f128: return &APFloat::IEEEquad;
61 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
65 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
67 //===----------------------------------------------------------------------===//
68 // ConstantFPSDNode Class
69 //===----------------------------------------------------------------------===//
71 /// isExactlyValue - We don't rely on operator== working on double values, as
72 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
73 /// As such, this method can be used to do an exact bit-for-bit comparison of
74 /// two floating point values.
75 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
76 return getValueAPF().bitwiseIsEqual(V);
79 bool ConstantFPSDNode::isValueValidForType(MVT VT,
81 assert(VT.isFloatingPoint() && "Can only convert between FP types");
83 // PPC long double cannot be converted to any other type.
84 if (VT == MVT::ppcf128 ||
85 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
88 // convert modifies in place, so make a copy.
89 APFloat Val2 = APFloat(Val);
91 (void) Val2.convert(*MVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
96 //===----------------------------------------------------------------------===//
98 //===----------------------------------------------------------------------===//
100 /// isBuildVectorAllOnes - Return true if the specified node is a
101 /// BUILD_VECTOR where all of the elements are ~0 or undef.
102 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
103 // Look through a bit convert.
104 if (N->getOpcode() == ISD::BIT_CONVERT)
105 N = N->getOperand(0).getNode();
107 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
109 unsigned i = 0, e = N->getNumOperands();
111 // Skip over all of the undef values.
112 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
115 // Do not accept an all-undef vector.
116 if (i == e) return false;
118 // Do not accept build_vectors that aren't all constants or which have non-~0
120 SDValue NotZero = N->getOperand(i);
121 if (isa<ConstantSDNode>(NotZero)) {
122 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
124 } else if (isa<ConstantFPSDNode>(NotZero)) {
125 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
126 bitcastToAPInt().isAllOnesValue())
131 // Okay, we have at least one ~0 value, check to see if the rest match or are
133 for (++i; i != e; ++i)
134 if (N->getOperand(i) != NotZero &&
135 N->getOperand(i).getOpcode() != ISD::UNDEF)
141 /// isBuildVectorAllZeros - Return true if the specified node is a
142 /// BUILD_VECTOR where all of the elements are 0 or undef.
143 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
144 // Look through a bit convert.
145 if (N->getOpcode() == ISD::BIT_CONVERT)
146 N = N->getOperand(0).getNode();
148 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
150 unsigned i = 0, e = N->getNumOperands();
152 // Skip over all of the undef values.
153 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
156 // Do not accept an all-undef vector.
157 if (i == e) return false;
159 // Do not accept build_vectors that aren't all constants or which have non-0
161 SDValue Zero = N->getOperand(i);
162 if (isa<ConstantSDNode>(Zero)) {
163 if (!cast<ConstantSDNode>(Zero)->isNullValue())
165 } else if (isa<ConstantFPSDNode>(Zero)) {
166 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
171 // Okay, we have at least one 0 value, check to see if the rest match or are
173 for (++i; i != e; ++i)
174 if (N->getOperand(i) != Zero &&
175 N->getOperand(i).getOpcode() != ISD::UNDEF)
180 /// isScalarToVector - Return true if the specified node is a
181 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
182 /// element is not an undef.
183 bool ISD::isScalarToVector(const SDNode *N) {
184 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
187 if (N->getOpcode() != ISD::BUILD_VECTOR)
189 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
191 unsigned NumElems = N->getNumOperands();
192 for (unsigned i = 1; i < NumElems; ++i) {
193 SDValue V = N->getOperand(i);
194 if (V.getOpcode() != ISD::UNDEF)
201 /// isDebugLabel - Return true if the specified node represents a debug
202 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
203 bool ISD::isDebugLabel(const SDNode *N) {
205 if (N->getOpcode() == ISD::DBG_LABEL)
207 if (N->isMachineOpcode() &&
208 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
213 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
214 /// when given the operation for (X op Y).
215 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
216 // To perform this operation, we just need to swap the L and G bits of the
218 unsigned OldL = (Operation >> 2) & 1;
219 unsigned OldG = (Operation >> 1) & 1;
220 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
221 (OldL << 1) | // New G bit
222 (OldG << 2)); // New L bit.
225 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
226 /// 'op' is a valid SetCC operation.
227 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
228 unsigned Operation = Op;
230 Operation ^= 7; // Flip L, G, E bits, but not U.
232 Operation ^= 15; // Flip all of the condition bits.
234 if (Operation > ISD::SETTRUE2)
235 Operation &= ~8; // Don't let N and U bits get set.
237 return ISD::CondCode(Operation);
241 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
242 /// signed operation and 2 if the result is an unsigned comparison. Return zero
243 /// if the operation does not depend on the sign of the input (setne and seteq).
244 static int isSignedOp(ISD::CondCode Opcode) {
246 default: assert(0 && "Illegal integer setcc operation!");
248 case ISD::SETNE: return 0;
252 case ISD::SETGE: return 1;
256 case ISD::SETUGE: return 2;
260 /// getSetCCOrOperation - Return the result of a logical OR between different
261 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
262 /// returns SETCC_INVALID if it is not possible to represent the resultant
264 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
266 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
267 // Cannot fold a signed integer setcc with an unsigned integer setcc.
268 return ISD::SETCC_INVALID;
270 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
272 // If the N and U bits get set then the resultant comparison DOES suddenly
273 // care about orderedness, and is true when ordered.
274 if (Op > ISD::SETTRUE2)
275 Op &= ~16; // Clear the U bit if the N bit is set.
277 // Canonicalize illegal integer setcc's.
278 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
281 return ISD::CondCode(Op);
284 /// getSetCCAndOperation - Return the result of a logical AND between different
285 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
286 /// function returns zero if it is not possible to represent the resultant
288 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
290 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
291 // Cannot fold a signed setcc with an unsigned setcc.
292 return ISD::SETCC_INVALID;
294 // Combine all of the condition bits.
295 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
297 // Canonicalize illegal integer setcc's.
301 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
302 case ISD::SETOEQ: // SETEQ & SETU[LG]E
303 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
304 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
305 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
312 const TargetMachine &SelectionDAG::getTarget() const {
313 return MF->getTarget();
316 //===----------------------------------------------------------------------===//
317 // SDNode Profile Support
318 //===----------------------------------------------------------------------===//
320 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
322 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
326 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
327 /// solely with their pointer.
328 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
329 ID.AddPointer(VTList.VTs);
332 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
334 static void AddNodeIDOperands(FoldingSetNodeID &ID,
335 const SDValue *Ops, unsigned NumOps) {
336 for (; NumOps; --NumOps, ++Ops) {
337 ID.AddPointer(Ops->getNode());
338 ID.AddInteger(Ops->getResNo());
342 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
344 static void AddNodeIDOperands(FoldingSetNodeID &ID,
345 const SDUse *Ops, unsigned NumOps) {
346 for (; NumOps; --NumOps, ++Ops) {
347 ID.AddPointer(Ops->getNode());
348 ID.AddInteger(Ops->getResNo());
352 static void AddNodeIDNode(FoldingSetNodeID &ID,
353 unsigned short OpC, SDVTList VTList,
354 const SDValue *OpList, unsigned N) {
355 AddNodeIDOpcode(ID, OpC);
356 AddNodeIDValueTypes(ID, VTList);
357 AddNodeIDOperands(ID, OpList, N);
360 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
362 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
363 switch (N->getOpcode()) {
364 case ISD::TargetExternalSymbol:
365 case ISD::ExternalSymbol:
366 assert(0 && "Should only be used on nodes with operands");
367 default: break; // Normal nodes don't need extra info.
369 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
371 case ISD::TargetConstant:
373 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
375 case ISD::TargetConstantFP:
376 case ISD::ConstantFP: {
377 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
380 case ISD::TargetGlobalAddress:
381 case ISD::GlobalAddress:
382 case ISD::TargetGlobalTLSAddress:
383 case ISD::GlobalTLSAddress: {
384 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
385 ID.AddPointer(GA->getGlobal());
386 ID.AddInteger(GA->getOffset());
387 ID.AddInteger(GA->getTargetFlags());
390 case ISD::BasicBlock:
391 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
394 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
396 case ISD::DBG_STOPPOINT: {
397 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
398 ID.AddInteger(DSP->getLine());
399 ID.AddInteger(DSP->getColumn());
400 ID.AddPointer(DSP->getCompileUnit());
404 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
406 case ISD::MEMOPERAND: {
407 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
411 case ISD::FrameIndex:
412 case ISD::TargetFrameIndex:
413 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
416 case ISD::TargetJumpTable:
417 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
419 case ISD::ConstantPool:
420 case ISD::TargetConstantPool: {
421 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
422 ID.AddInteger(CP->getAlignment());
423 ID.AddInteger(CP->getOffset());
424 if (CP->isMachineConstantPoolEntry())
425 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
427 ID.AddPointer(CP->getConstVal());
431 const CallSDNode *Call = cast<CallSDNode>(N);
432 ID.AddInteger(Call->getCallingConv());
433 ID.AddInteger(Call->isVarArg());
437 const LoadSDNode *LD = cast<LoadSDNode>(N);
438 ID.AddInteger(LD->getMemoryVT().getRawBits());
439 ID.AddInteger(LD->getRawSubclassData());
443 const StoreSDNode *ST = cast<StoreSDNode>(N);
444 ID.AddInteger(ST->getMemoryVT().getRawBits());
445 ID.AddInteger(ST->getRawSubclassData());
448 case ISD::ATOMIC_CMP_SWAP:
449 case ISD::ATOMIC_SWAP:
450 case ISD::ATOMIC_LOAD_ADD:
451 case ISD::ATOMIC_LOAD_SUB:
452 case ISD::ATOMIC_LOAD_AND:
453 case ISD::ATOMIC_LOAD_OR:
454 case ISD::ATOMIC_LOAD_XOR:
455 case ISD::ATOMIC_LOAD_NAND:
456 case ISD::ATOMIC_LOAD_MIN:
457 case ISD::ATOMIC_LOAD_MAX:
458 case ISD::ATOMIC_LOAD_UMIN:
459 case ISD::ATOMIC_LOAD_UMAX: {
460 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
461 ID.AddInteger(AT->getMemoryVT().getRawBits());
462 ID.AddInteger(AT->getRawSubclassData());
465 case ISD::VECTOR_SHUFFLE: {
466 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
467 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
469 ID.AddInteger(SVN->getMaskElt(i));
472 } // end switch (N->getOpcode())
475 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
477 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
478 AddNodeIDOpcode(ID, N->getOpcode());
479 // Add the return value info.
480 AddNodeIDValueTypes(ID, N->getVTList());
481 // Add the operand info.
482 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
484 // Handle SDNode leafs with special info.
485 AddNodeIDCustom(ID, N);
488 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
489 /// the CSE map that carries alignment, volatility, indexing mode, and
490 /// extension/truncation information.
492 static inline unsigned
493 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM,
494 bool isVolatile, unsigned Alignment) {
495 assert((ConvType & 3) == ConvType &&
496 "ConvType may not require more than 2 bits!");
497 assert((AM & 7) == AM &&
498 "AM may not require more than 3 bits!");
502 ((Log2_32(Alignment) + 1) << 6);
505 //===----------------------------------------------------------------------===//
506 // SelectionDAG Class
507 //===----------------------------------------------------------------------===//
509 /// doNotCSE - Return true if CSE should not be performed for this node.
510 static bool doNotCSE(SDNode *N) {
511 if (N->getValueType(0) == MVT::Flag)
512 return true; // Never CSE anything that produces a flag.
514 switch (N->getOpcode()) {
516 case ISD::HANDLENODE:
518 case ISD::DBG_STOPPOINT:
521 return true; // Never CSE these nodes.
524 // Check that remaining values produced are not flags.
525 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
526 if (N->getValueType(i) == MVT::Flag)
527 return true; // Never CSE anything that produces a flag.
532 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
534 void SelectionDAG::RemoveDeadNodes() {
535 // Create a dummy node (which is not added to allnodes), that adds a reference
536 // to the root node, preventing it from being deleted.
537 HandleSDNode Dummy(getRoot());
539 SmallVector<SDNode*, 128> DeadNodes;
541 // Add all obviously-dead nodes to the DeadNodes worklist.
542 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
544 DeadNodes.push_back(I);
546 RemoveDeadNodes(DeadNodes);
548 // If the root changed (e.g. it was a dead load, update the root).
549 setRoot(Dummy.getValue());
552 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
553 /// given list, and any nodes that become unreachable as a result.
554 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
555 DAGUpdateListener *UpdateListener) {
557 // Process the worklist, deleting the nodes and adding their uses to the
559 while (!DeadNodes.empty()) {
560 SDNode *N = DeadNodes.pop_back_val();
563 UpdateListener->NodeDeleted(N, 0);
565 // Take the node out of the appropriate CSE map.
566 RemoveNodeFromCSEMaps(N);
568 // Next, brutally remove the operand list. This is safe to do, as there are
569 // no cycles in the graph.
570 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
572 SDNode *Operand = Use.getNode();
575 // Now that we removed this operand, see if there are no uses of it left.
576 if (Operand->use_empty())
577 DeadNodes.push_back(Operand);
584 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
585 SmallVector<SDNode*, 16> DeadNodes(1, N);
586 RemoveDeadNodes(DeadNodes, UpdateListener);
589 void SelectionDAG::DeleteNode(SDNode *N) {
590 // First take this out of the appropriate CSE map.
591 RemoveNodeFromCSEMaps(N);
593 // Finally, remove uses due to operands of this node, remove from the
594 // AllNodes list, and delete the node.
595 DeleteNodeNotInCSEMaps(N);
598 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
599 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
600 assert(N->use_empty() && "Cannot delete a node that is not dead!");
602 // Drop all of the operands and decrement used node's use counts.
608 void SelectionDAG::DeallocateNode(SDNode *N) {
609 if (N->OperandsNeedDelete)
610 delete[] N->OperandList;
612 // Set the opcode to DELETED_NODE to help catch bugs when node
613 // memory is reallocated.
614 N->NodeType = ISD::DELETED_NODE;
616 NodeAllocator.Deallocate(AllNodes.remove(N));
619 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
620 /// correspond to it. This is useful when we're about to delete or repurpose
621 /// the node. We don't want future request for structurally identical nodes
622 /// to return N anymore.
623 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
625 switch (N->getOpcode()) {
626 case ISD::EntryToken:
627 assert(0 && "EntryToken should not be in CSEMaps!");
629 case ISD::HANDLENODE: return false; // noop.
631 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
632 "Cond code doesn't exist!");
633 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
634 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
636 case ISD::ExternalSymbol:
637 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
639 case ISD::TargetExternalSymbol: {
640 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
641 Erased = TargetExternalSymbols.erase(
642 std::pair<std::string,unsigned char>(ESN->getSymbol(),
643 ESN->getTargetFlags()));
646 case ISD::VALUETYPE: {
647 MVT VT = cast<VTSDNode>(N)->getVT();
648 if (VT.isExtended()) {
649 Erased = ExtendedValueTypeNodes.erase(VT);
651 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
652 ValueTypeNodes[VT.getSimpleVT()] = 0;
657 // Remove it from the CSE Map.
658 Erased = CSEMap.RemoveNode(N);
662 // Verify that the node was actually in one of the CSE maps, unless it has a
663 // flag result (which cannot be CSE'd) or is one of the special cases that are
664 // not subject to CSE.
665 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
666 !N->isMachineOpcode() && !doNotCSE(N)) {
669 assert(0 && "Node is not in map!");
675 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
676 /// maps and modified in place. Add it back to the CSE maps, unless an identical
677 /// node already exists, in which case transfer all its users to the existing
678 /// node. This transfer can potentially trigger recursive merging.
681 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
682 DAGUpdateListener *UpdateListener) {
683 // For node types that aren't CSE'd, just act as if no identical node
686 SDNode *Existing = CSEMap.GetOrInsertNode(N);
688 // If there was already an existing matching node, use ReplaceAllUsesWith
689 // to replace the dead one with the existing one. This can cause
690 // recursive merging of other unrelated nodes down the line.
691 ReplaceAllUsesWith(N, Existing, UpdateListener);
693 // N is now dead. Inform the listener if it exists and delete it.
695 UpdateListener->NodeDeleted(N, Existing);
696 DeleteNodeNotInCSEMaps(N);
701 // If the node doesn't already exist, we updated it. Inform a listener if
704 UpdateListener->NodeUpdated(N);
707 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
708 /// were replaced with those specified. If this node is never memoized,
709 /// return null, otherwise return a pointer to the slot it would take. If a
710 /// node already exists with these operands, the slot will be non-null.
711 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
716 SDValue Ops[] = { Op };
718 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
719 AddNodeIDCustom(ID, N);
720 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
723 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
724 /// were replaced with those specified. If this node is never memoized,
725 /// return null, otherwise return a pointer to the slot it would take. If a
726 /// node already exists with these operands, the slot will be non-null.
727 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
728 SDValue Op1, SDValue Op2,
733 SDValue Ops[] = { Op1, Op2 };
735 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
736 AddNodeIDCustom(ID, N);
737 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
741 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
742 /// were replaced with those specified. If this node is never memoized,
743 /// return null, otherwise return a pointer to the slot it would take. If a
744 /// node already exists with these operands, the slot will be non-null.
745 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
746 const SDValue *Ops,unsigned NumOps,
752 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
753 AddNodeIDCustom(ID, N);
754 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
757 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
758 void SelectionDAG::VerifyNode(SDNode *N) {
759 switch (N->getOpcode()) {
762 case ISD::BUILD_PAIR: {
763 MVT VT = N->getValueType(0);
764 assert(N->getNumValues() == 1 && "Too many results!");
765 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
766 "Wrong return type!");
767 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
768 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
769 "Mismatched operand types!");
770 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
771 "Wrong operand type!");
772 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
773 "Wrong return type size");
776 case ISD::BUILD_VECTOR: {
777 assert(N->getNumValues() == 1 && "Too many results!");
778 assert(N->getValueType(0).isVector() && "Wrong return type!");
779 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
780 "Wrong number of operands!");
781 MVT EltVT = N->getValueType(0).getVectorElementType();
782 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
783 assert((I->getValueType() == EltVT ||
784 (EltVT.isInteger() && I->getValueType().isInteger() &&
785 EltVT.bitsLE(I->getValueType()))) &&
786 "Wrong operand type!");
792 /// getMVTAlignment - Compute the default alignment value for the
795 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
796 const Type *Ty = VT == MVT::iPTR ?
797 PointerType::get(Type::Int8Ty, 0) :
800 return TLI.getTargetData()->getABITypeAlignment(Ty);
803 // EntryNode could meaningfully have debug info if we can find it...
804 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
805 : TLI(tli), FLI(fli), DW(0),
806 EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
807 getVTList(MVT::Other)), Root(getEntryNode()) {
808 AllNodes.push_back(&EntryNode);
811 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
818 SelectionDAG::~SelectionDAG() {
822 void SelectionDAG::allnodes_clear() {
823 assert(&*AllNodes.begin() == &EntryNode);
824 AllNodes.remove(AllNodes.begin());
825 while (!AllNodes.empty())
826 DeallocateNode(AllNodes.begin());
829 void SelectionDAG::clear() {
831 OperandAllocator.Reset();
834 ExtendedValueTypeNodes.clear();
835 ExternalSymbols.clear();
836 TargetExternalSymbols.clear();
837 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
838 static_cast<CondCodeSDNode*>(0));
839 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
840 static_cast<SDNode*>(0));
842 EntryNode.UseList = 0;
843 AllNodes.push_back(&EntryNode);
844 Root = getEntryNode();
847 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, MVT VT) {
848 if (Op.getValueType() == VT) return Op;
849 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
851 return getNode(ISD::AND, DL, Op.getValueType(), Op,
852 getConstant(Imm, Op.getValueType()));
855 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
857 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, MVT VT) {
858 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
860 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
861 return getNode(ISD::XOR, DL, VT, Val, NegOne);
864 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
865 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
866 assert((EltVT.getSizeInBits() >= 64 ||
867 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
868 "getConstant with a uint64_t value that doesn't fit in the type!");
869 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
872 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
873 return getConstant(*ConstantInt::get(Val), VT, isT);
876 SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
877 assert(VT.isInteger() && "Cannot create FP integer constant!");
879 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
880 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
881 "APInt size does not match type size!");
883 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
885 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
889 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
891 return SDValue(N, 0);
893 N = NodeAllocator.Allocate<ConstantSDNode>();
894 new (N) ConstantSDNode(isT, &Val, EltVT);
895 CSEMap.InsertNode(N, IP);
896 AllNodes.push_back(N);
899 SDValue Result(N, 0);
901 SmallVector<SDValue, 8> Ops;
902 Ops.assign(VT.getVectorNumElements(), Result);
903 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
904 VT, &Ops[0], Ops.size());
909 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
910 return getConstant(Val, TLI.getPointerTy(), isTarget);
914 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
915 return getConstantFP(*ConstantFP::get(V), VT, isTarget);
918 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
919 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
922 VT.isVector() ? VT.getVectorElementType() : VT;
924 // Do the map lookup using the actual bit pattern for the floating point
925 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
926 // we don't have issues with SNANs.
927 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
929 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
933 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
935 return SDValue(N, 0);
937 N = NodeAllocator.Allocate<ConstantFPSDNode>();
938 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
939 CSEMap.InsertNode(N, IP);
940 AllNodes.push_back(N);
943 SDValue Result(N, 0);
945 SmallVector<SDValue, 8> Ops;
946 Ops.assign(VT.getVectorNumElements(), Result);
947 // FIXME DebugLoc info might be appropriate here
948 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
949 VT, &Ops[0], Ops.size());
954 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
956 VT.isVector() ? VT.getVectorElementType() : VT;
958 return getConstantFP(APFloat((float)Val), VT, isTarget);
960 return getConstantFP(APFloat(Val), VT, isTarget);
963 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
964 MVT VT, int64_t Offset,
966 unsigned char TargetFlags) {
967 assert((TargetFlags == 0 || isTargetGA) &&
968 "Cannot set target flags on target-independent globals");
970 // Truncate (with sign-extension) the offset value to the pointer size.
971 unsigned BitWidth = TLI.getPointerTy().getSizeInBits();
973 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
975 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
977 // If GV is an alias then use the aliasee for determining thread-localness.
978 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
979 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
983 if (GVar && GVar->isThreadLocal())
984 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
986 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
989 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
991 ID.AddInteger(Offset);
992 ID.AddInteger(TargetFlags);
994 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
995 return SDValue(E, 0);
996 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
997 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset, TargetFlags);
998 CSEMap.InsertNode(N, IP);
999 AllNodes.push_back(N);
1000 return SDValue(N, 0);
1003 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
1004 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1005 FoldingSetNodeID ID;
1006 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1009 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1010 return SDValue(E, 0);
1011 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
1012 new (N) FrameIndexSDNode(FI, VT, isTarget);
1013 CSEMap.InsertNode(N, IP);
1014 AllNodes.push_back(N);
1015 return SDValue(N, 0);
1018 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
1019 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1020 FoldingSetNodeID ID;
1021 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1024 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1025 return SDValue(E, 0);
1026 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1027 new (N) JumpTableSDNode(JTI, VT, isTarget);
1028 CSEMap.InsertNode(N, IP);
1029 AllNodes.push_back(N);
1030 return SDValue(N, 0);
1033 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
1034 unsigned Alignment, int Offset,
1037 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1038 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1039 FoldingSetNodeID ID;
1040 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1041 ID.AddInteger(Alignment);
1042 ID.AddInteger(Offset);
1045 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1046 return SDValue(E, 0);
1047 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1048 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1049 CSEMap.InsertNode(N, IP);
1050 AllNodes.push_back(N);
1051 return SDValue(N, 0);
1055 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
1056 unsigned Alignment, int Offset,
1059 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1060 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1061 FoldingSetNodeID ID;
1062 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1063 ID.AddInteger(Alignment);
1064 ID.AddInteger(Offset);
1065 C->AddSelectionDAGCSEId(ID);
1067 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1068 return SDValue(E, 0);
1069 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1070 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1071 CSEMap.InsertNode(N, IP);
1072 AllNodes.push_back(N);
1073 return SDValue(N, 0);
1076 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1077 FoldingSetNodeID ID;
1078 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1081 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1082 return SDValue(E, 0);
1083 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1084 new (N) BasicBlockSDNode(MBB);
1085 CSEMap.InsertNode(N, IP);
1086 AllNodes.push_back(N);
1087 return SDValue(N, 0);
1090 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
1091 FoldingSetNodeID ID;
1092 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
1093 ID.AddInteger(Flags.getRawBits());
1095 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1096 return SDValue(E, 0);
1097 SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
1098 new (N) ARG_FLAGSSDNode(Flags);
1099 CSEMap.InsertNode(N, IP);
1100 AllNodes.push_back(N);
1101 return SDValue(N, 0);
1104 SDValue SelectionDAG::getValueType(MVT VT) {
1105 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1106 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1108 SDNode *&N = VT.isExtended() ?
1109 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1111 if (N) return SDValue(N, 0);
1112 N = NodeAllocator.Allocate<VTSDNode>();
1113 new (N) VTSDNode(VT);
1114 AllNodes.push_back(N);
1115 return SDValue(N, 0);
1118 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1119 SDNode *&N = ExternalSymbols[Sym];
1120 if (N) return SDValue(N, 0);
1121 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1122 new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
1123 AllNodes.push_back(N);
1124 return SDValue(N, 0);
1127 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT,
1128 unsigned char TargetFlags) {
1130 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1132 if (N) return SDValue(N, 0);
1133 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1134 new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1135 AllNodes.push_back(N);
1136 return SDValue(N, 0);
1139 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1140 if ((unsigned)Cond >= CondCodeNodes.size())
1141 CondCodeNodes.resize(Cond+1);
1143 if (CondCodeNodes[Cond] == 0) {
1144 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1145 new (N) CondCodeSDNode(Cond);
1146 CondCodeNodes[Cond] = N;
1147 AllNodes.push_back(N);
1149 return SDValue(CondCodeNodes[Cond], 0);
1152 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1153 // the shuffle mask M that point at N1 to point at N2, and indices that point
1154 // N2 to point at N1.
1155 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1157 int NElts = M.size();
1158 for (int i = 0; i != NElts; ++i) {
1166 SDValue SelectionDAG::getVectorShuffle(MVT VT, DebugLoc dl, SDValue N1,
1167 SDValue N2, const int *Mask) {
1168 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1169 assert(VT.isVector() && N1.getValueType().isVector() &&
1170 "Vector Shuffle VTs must be a vectors");
1171 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1172 && "Vector Shuffle VTs must have same element type");
1174 // Canonicalize shuffle undef, undef -> undef
1175 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1178 // Validate that all indices in Mask are within the range of the elements
1179 // input to the shuffle.
1180 unsigned NElts = VT.getVectorNumElements();
1181 SmallVector<int, 8> MaskVec;
1182 for (unsigned i = 0; i != NElts; ++i) {
1183 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1184 MaskVec.push_back(Mask[i]);
1187 // Canonicalize shuffle v, v -> v, undef
1190 for (unsigned i = 0; i != NElts; ++i)
1191 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1194 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1195 if (N1.getOpcode() == ISD::UNDEF)
1196 commuteShuffle(N1, N2, MaskVec);
1198 // Canonicalize all index into lhs, -> shuffle lhs, undef
1199 // Canonicalize all index into rhs, -> shuffle rhs, undef
1200 bool AllLHS = true, AllRHS = true;
1201 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1202 for (unsigned i = 0; i != NElts; ++i) {
1203 if (MaskVec[i] >= (int)NElts) {
1208 } else if (MaskVec[i] >= 0) {
1212 if (AllLHS && AllRHS)
1213 return getUNDEF(VT);
1214 if (AllLHS && !N2Undef)
1218 commuteShuffle(N1, N2, MaskVec);
1221 // If Identity shuffle, or all shuffle in to undef, return that node.
1222 bool AllUndef = true;
1223 bool Identity = true;
1224 for (unsigned i = 0; i != NElts; ++i) {
1225 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1226 if (MaskVec[i] >= 0) AllUndef = false;
1231 return getUNDEF(VT);
1233 FoldingSetNodeID ID;
1234 SDValue Ops[2] = { N1, N2 };
1235 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1236 for (unsigned i = 0; i != NElts; ++i)
1237 ID.AddInteger(MaskVec[i]);
1240 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1241 return SDValue(E, 0);
1243 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1244 // SDNode doesn't have access to it. This memory will be "leaked" when
1245 // the node is deallocated, but recovered when the NodeAllocator is released.
1246 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1247 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1249 ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
1250 new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1251 CSEMap.InsertNode(N, IP);
1252 AllNodes.push_back(N);
1253 return SDValue(N, 0);
1256 SDValue SelectionDAG::getConvertRndSat(MVT VT, DebugLoc dl,
1257 SDValue Val, SDValue DTy,
1258 SDValue STy, SDValue Rnd, SDValue Sat,
1259 ISD::CvtCode Code) {
1260 // If the src and dest types are the same and the conversion is between
1261 // integer types of the same sign or two floats, no conversion is necessary.
1263 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1266 FoldingSetNodeID ID;
1268 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1269 return SDValue(E, 0);
1270 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1271 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1272 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
1273 CSEMap.InsertNode(N, IP);
1274 AllNodes.push_back(N);
1275 return SDValue(N, 0);
1278 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1279 FoldingSetNodeID ID;
1280 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1281 ID.AddInteger(RegNo);
1283 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1284 return SDValue(E, 0);
1285 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1286 new (N) RegisterSDNode(RegNo, VT);
1287 CSEMap.InsertNode(N, IP);
1288 AllNodes.push_back(N);
1289 return SDValue(N, 0);
1292 SDValue SelectionDAG::getDbgStopPoint(DebugLoc DL, SDValue Root,
1293 unsigned Line, unsigned Col,
1295 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1296 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1298 AllNodes.push_back(N);
1299 return SDValue(N, 0);
1302 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1305 FoldingSetNodeID ID;
1306 SDValue Ops[] = { Root };
1307 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1308 ID.AddInteger(LabelID);
1310 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1311 return SDValue(E, 0);
1312 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1313 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1314 CSEMap.InsertNode(N, IP);
1315 AllNodes.push_back(N);
1316 return SDValue(N, 0);
1319 SDValue SelectionDAG::getSrcValue(const Value *V) {
1320 assert((!V || isa<PointerType>(V->getType())) &&
1321 "SrcValue is not a pointer?");
1323 FoldingSetNodeID ID;
1324 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1328 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1329 return SDValue(E, 0);
1331 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1332 new (N) SrcValueSDNode(V);
1333 CSEMap.InsertNode(N, IP);
1334 AllNodes.push_back(N);
1335 return SDValue(N, 0);
1338 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1340 const Value *v = MO.getValue();
1341 assert((!v || isa<PointerType>(v->getType())) &&
1342 "SrcValue is not a pointer?");
1345 FoldingSetNodeID ID;
1346 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1350 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1351 return SDValue(E, 0);
1353 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1354 new (N) MemOperandSDNode(MO);
1355 CSEMap.InsertNode(N, IP);
1356 AllNodes.push_back(N);
1357 return SDValue(N, 0);
1360 /// getShiftAmountOperand - Return the specified value casted to
1361 /// the target's desired shift amount type.
1362 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1363 MVT OpTy = Op.getValueType();
1364 MVT ShTy = TLI.getShiftAmountTy();
1365 if (OpTy == ShTy || OpTy.isVector()) return Op;
1367 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1368 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1371 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1372 /// specified value type.
1373 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1374 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1375 unsigned ByteSize = VT.getStoreSizeInBits()/8;
1376 const Type *Ty = VT.getTypeForMVT();
1377 unsigned StackAlign =
1378 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1380 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1381 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1384 /// CreateStackTemporary - Create a stack temporary suitable for holding
1385 /// either of the specified value types.
1386 SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) {
1387 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1388 VT2.getStoreSizeInBits())/8;
1389 const Type *Ty1 = VT1.getTypeForMVT();
1390 const Type *Ty2 = VT2.getTypeForMVT();
1391 const TargetData *TD = TLI.getTargetData();
1392 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1393 TD->getPrefTypeAlignment(Ty2));
1395 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1396 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
1397 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1400 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1401 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1402 // These setcc operations always fold.
1406 case ISD::SETFALSE2: return getConstant(0, VT);
1408 case ISD::SETTRUE2: return getConstant(1, VT);
1420 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1424 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1425 const APInt &C2 = N2C->getAPIntValue();
1426 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1427 const APInt &C1 = N1C->getAPIntValue();
1430 default: assert(0 && "Unknown integer setcc!");
1431 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1432 case ISD::SETNE: return getConstant(C1 != C2, VT);
1433 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1434 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1435 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1436 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1437 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1438 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1439 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1440 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1444 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1445 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1446 // No compile time operations on this type yet.
1447 if (N1C->getValueType(0) == MVT::ppcf128)
1450 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1453 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1454 return getUNDEF(VT);
1456 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1457 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1458 return getUNDEF(VT);
1460 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1461 R==APFloat::cmpLessThan, VT);
1462 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1463 return getUNDEF(VT);
1465 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1466 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1467 return getUNDEF(VT);
1469 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1470 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1471 return getUNDEF(VT);
1473 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1474 R==APFloat::cmpEqual, VT);
1475 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1476 return getUNDEF(VT);
1478 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1479 R==APFloat::cmpEqual, VT);
1480 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1481 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1482 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1483 R==APFloat::cmpEqual, VT);
1484 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1485 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1486 R==APFloat::cmpLessThan, VT);
1487 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1488 R==APFloat::cmpUnordered, VT);
1489 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1490 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1493 // Ensure that the constant occurs on the RHS.
1494 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1498 // Could not fold it.
1502 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1503 /// use this predicate to simplify operations downstream.
1504 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1505 unsigned BitWidth = Op.getValueSizeInBits();
1506 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1509 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1510 /// this predicate to simplify operations downstream. Mask is known to be zero
1511 /// for bits that V cannot have.
1512 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1513 unsigned Depth) const {
1514 APInt KnownZero, KnownOne;
1515 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1516 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1517 return (KnownZero & Mask) == Mask;
1520 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1521 /// known to be either zero or one and return them in the KnownZero/KnownOne
1522 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1524 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1525 APInt &KnownZero, APInt &KnownOne,
1526 unsigned Depth) const {
1527 unsigned BitWidth = Mask.getBitWidth();
1528 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1529 "Mask size mismatches value type size!");
1531 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1532 if (Depth == 6 || Mask == 0)
1533 return; // Limit search depth.
1535 APInt KnownZero2, KnownOne2;
1537 switch (Op.getOpcode()) {
1539 // We know all of the bits for a constant!
1540 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1541 KnownZero = ~KnownOne & Mask;
1544 // If either the LHS or the RHS are Zero, the result is zero.
1545 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1546 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1547 KnownZero2, KnownOne2, Depth+1);
1548 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1549 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1551 // Output known-1 bits are only known if set in both the LHS & RHS.
1552 KnownOne &= KnownOne2;
1553 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1554 KnownZero |= KnownZero2;
1557 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1558 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1559 KnownZero2, KnownOne2, Depth+1);
1560 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1561 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1563 // Output known-0 bits are only known if clear in both the LHS & RHS.
1564 KnownZero &= KnownZero2;
1565 // Output known-1 are known to be set if set in either the LHS | RHS.
1566 KnownOne |= KnownOne2;
1569 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1570 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1571 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1572 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1574 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1575 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1576 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1577 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1578 KnownZero = KnownZeroOut;
1582 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1583 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1584 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1585 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1586 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1588 // If low bits are zero in either operand, output low known-0 bits.
1589 // Also compute a conserative estimate for high known-0 bits.
1590 // More trickiness is possible, but this is sufficient for the
1591 // interesting case of alignment computation.
1593 unsigned TrailZ = KnownZero.countTrailingOnes() +
1594 KnownZero2.countTrailingOnes();
1595 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1596 KnownZero2.countLeadingOnes(),
1597 BitWidth) - BitWidth;
1599 TrailZ = std::min(TrailZ, BitWidth);
1600 LeadZ = std::min(LeadZ, BitWidth);
1601 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1602 APInt::getHighBitsSet(BitWidth, LeadZ);
1607 // For the purposes of computing leading zeros we can conservatively
1608 // treat a udiv as a logical right shift by the power of 2 known to
1609 // be less than the denominator.
1610 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1611 ComputeMaskedBits(Op.getOperand(0),
1612 AllOnes, KnownZero2, KnownOne2, Depth+1);
1613 unsigned LeadZ = KnownZero2.countLeadingOnes();
1617 ComputeMaskedBits(Op.getOperand(1),
1618 AllOnes, KnownZero2, KnownOne2, Depth+1);
1619 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1620 if (RHSUnknownLeadingOnes != BitWidth)
1621 LeadZ = std::min(BitWidth,
1622 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1624 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1628 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1629 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1630 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1631 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1633 // Only known if known in both the LHS and RHS.
1634 KnownOne &= KnownOne2;
1635 KnownZero &= KnownZero2;
1637 case ISD::SELECT_CC:
1638 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1639 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1640 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1641 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1643 // Only known if known in both the LHS and RHS.
1644 KnownOne &= KnownOne2;
1645 KnownZero &= KnownZero2;
1653 if (Op.getResNo() != 1)
1655 // The boolean result conforms to getBooleanContents. Fall through.
1657 // If we know the result of a setcc has the top bits zero, use this info.
1658 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1660 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1663 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1664 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1665 unsigned ShAmt = SA->getZExtValue();
1667 // If the shift count is an invalid immediate, don't do anything.
1668 if (ShAmt >= BitWidth)
1671 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1672 KnownZero, KnownOne, Depth+1);
1673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1674 KnownZero <<= ShAmt;
1676 // low bits known zero.
1677 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1681 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1682 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1683 unsigned ShAmt = SA->getZExtValue();
1685 // If the shift count is an invalid immediate, don't do anything.
1686 if (ShAmt >= BitWidth)
1689 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1690 KnownZero, KnownOne, Depth+1);
1691 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1692 KnownZero = KnownZero.lshr(ShAmt);
1693 KnownOne = KnownOne.lshr(ShAmt);
1695 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1696 KnownZero |= HighBits; // High bits known zero.
1700 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1701 unsigned ShAmt = SA->getZExtValue();
1703 // If the shift count is an invalid immediate, don't do anything.
1704 if (ShAmt >= BitWidth)
1707 APInt InDemandedMask = (Mask << ShAmt);
1708 // If any of the demanded bits are produced by the sign extension, we also
1709 // demand the input sign bit.
1710 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1711 if (HighBits.getBoolValue())
1712 InDemandedMask |= APInt::getSignBit(BitWidth);
1714 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1716 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1717 KnownZero = KnownZero.lshr(ShAmt);
1718 KnownOne = KnownOne.lshr(ShAmt);
1720 // Handle the sign bits.
1721 APInt SignBit = APInt::getSignBit(BitWidth);
1722 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1724 if (KnownZero.intersects(SignBit)) {
1725 KnownZero |= HighBits; // New bits are known zero.
1726 } else if (KnownOne.intersects(SignBit)) {
1727 KnownOne |= HighBits; // New bits are known one.
1731 case ISD::SIGN_EXTEND_INREG: {
1732 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1733 unsigned EBits = EVT.getSizeInBits();
1735 // Sign extension. Compute the demanded bits in the result that are not
1736 // present in the input.
1737 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1739 APInt InSignBit = APInt::getSignBit(EBits);
1740 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1742 // If the sign extended bits are demanded, we know that the sign
1744 InSignBit.zext(BitWidth);
1745 if (NewBits.getBoolValue())
1746 InputDemandedBits |= InSignBit;
1748 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1749 KnownZero, KnownOne, Depth+1);
1750 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1752 // If the sign bit of the input is known set or clear, then we know the
1753 // top bits of the result.
1754 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1755 KnownZero |= NewBits;
1756 KnownOne &= ~NewBits;
1757 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1758 KnownOne |= NewBits;
1759 KnownZero &= ~NewBits;
1760 } else { // Input sign bit unknown
1761 KnownZero &= ~NewBits;
1762 KnownOne &= ~NewBits;
1769 unsigned LowBits = Log2_32(BitWidth)+1;
1770 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1775 if (ISD::isZEXTLoad(Op.getNode())) {
1776 LoadSDNode *LD = cast<LoadSDNode>(Op);
1777 MVT VT = LD->getMemoryVT();
1778 unsigned MemBits = VT.getSizeInBits();
1779 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1783 case ISD::ZERO_EXTEND: {
1784 MVT InVT = Op.getOperand(0).getValueType();
1785 unsigned InBits = InVT.getSizeInBits();
1786 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1787 APInt InMask = Mask;
1788 InMask.trunc(InBits);
1789 KnownZero.trunc(InBits);
1790 KnownOne.trunc(InBits);
1791 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1792 KnownZero.zext(BitWidth);
1793 KnownOne.zext(BitWidth);
1794 KnownZero |= NewBits;
1797 case ISD::SIGN_EXTEND: {
1798 MVT InVT = Op.getOperand(0).getValueType();
1799 unsigned InBits = InVT.getSizeInBits();
1800 APInt InSignBit = APInt::getSignBit(InBits);
1801 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1802 APInt InMask = Mask;
1803 InMask.trunc(InBits);
1805 // If any of the sign extended bits are demanded, we know that the sign
1806 // bit is demanded. Temporarily set this bit in the mask for our callee.
1807 if (NewBits.getBoolValue())
1808 InMask |= InSignBit;
1810 KnownZero.trunc(InBits);
1811 KnownOne.trunc(InBits);
1812 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1814 // Note if the sign bit is known to be zero or one.
1815 bool SignBitKnownZero = KnownZero.isNegative();
1816 bool SignBitKnownOne = KnownOne.isNegative();
1817 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1818 "Sign bit can't be known to be both zero and one!");
1820 // If the sign bit wasn't actually demanded by our caller, we don't
1821 // want it set in the KnownZero and KnownOne result values. Reset the
1822 // mask and reapply it to the result values.
1824 InMask.trunc(InBits);
1825 KnownZero &= InMask;
1828 KnownZero.zext(BitWidth);
1829 KnownOne.zext(BitWidth);
1831 // If the sign bit is known zero or one, the top bits match.
1832 if (SignBitKnownZero)
1833 KnownZero |= NewBits;
1834 else if (SignBitKnownOne)
1835 KnownOne |= NewBits;
1838 case ISD::ANY_EXTEND: {
1839 MVT InVT = Op.getOperand(0).getValueType();
1840 unsigned InBits = InVT.getSizeInBits();
1841 APInt InMask = Mask;
1842 InMask.trunc(InBits);
1843 KnownZero.trunc(InBits);
1844 KnownOne.trunc(InBits);
1845 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1846 KnownZero.zext(BitWidth);
1847 KnownOne.zext(BitWidth);
1850 case ISD::TRUNCATE: {
1851 MVT InVT = Op.getOperand(0).getValueType();
1852 unsigned InBits = InVT.getSizeInBits();
1853 APInt InMask = Mask;
1854 InMask.zext(InBits);
1855 KnownZero.zext(InBits);
1856 KnownOne.zext(InBits);
1857 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1859 KnownZero.trunc(BitWidth);
1860 KnownOne.trunc(BitWidth);
1863 case ISD::AssertZext: {
1864 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1865 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1866 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1868 KnownZero |= (~InMask) & Mask;
1872 // All bits are zero except the low bit.
1873 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1877 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1878 // We know that the top bits of C-X are clear if X contains less bits
1879 // than C (i.e. no wrap-around can happen). For example, 20-X is
1880 // positive if we can prove that X is >= 0 and < 16.
1881 if (CLHS->getAPIntValue().isNonNegative()) {
1882 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1883 // NLZ can't be BitWidth with no sign bit
1884 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1885 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1888 // If all of the MaskV bits are known to be zero, then we know the
1889 // output top bits are zero, because we now know that the output is
1891 if ((KnownZero2 & MaskV) == MaskV) {
1892 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1893 // Top bits known zero.
1894 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1901 // Output known-0 bits are known if clear or set in both the low clear bits
1902 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1903 // low 3 bits clear.
1904 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1905 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1906 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1907 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1909 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1910 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1911 KnownZeroOut = std::min(KnownZeroOut,
1912 KnownZero2.countTrailingOnes());
1914 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1918 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1919 const APInt &RA = Rem->getAPIntValue();
1920 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1921 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1922 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1923 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1925 // If the sign bit of the first operand is zero, the sign bit of
1926 // the result is zero. If the first operand has no one bits below
1927 // the second operand's single 1 bit, its sign will be zero.
1928 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1929 KnownZero2 |= ~LowBits;
1931 KnownZero |= KnownZero2 & Mask;
1933 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1938 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1939 const APInt &RA = Rem->getAPIntValue();
1940 if (RA.isPowerOf2()) {
1941 APInt LowBits = (RA - 1);
1942 APInt Mask2 = LowBits & Mask;
1943 KnownZero |= ~LowBits & Mask;
1944 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1945 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1950 // Since the result is less than or equal to either operand, any leading
1951 // zero bits in either operand must also exist in the result.
1952 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1953 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1955 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1958 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1959 KnownZero2.countLeadingOnes());
1961 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1965 // Allow the target to implement this method for its nodes.
1966 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1967 case ISD::INTRINSIC_WO_CHAIN:
1968 case ISD::INTRINSIC_W_CHAIN:
1969 case ISD::INTRINSIC_VOID:
1970 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1976 /// ComputeNumSignBits - Return the number of times the sign bit of the
1977 /// register is replicated into the other bits. We know that at least 1 bit
1978 /// is always equal to the sign bit (itself), but other cases can give us
1979 /// information. For example, immediately after an "SRA X, 2", we know that
1980 /// the top 3 bits are all equal to each other, so we return 3.
1981 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1982 MVT VT = Op.getValueType();
1983 assert(VT.isInteger() && "Invalid VT!");
1984 unsigned VTBits = VT.getSizeInBits();
1986 unsigned FirstAnswer = 1;
1989 return 1; // Limit search depth.
1991 switch (Op.getOpcode()) {
1993 case ISD::AssertSext:
1994 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1995 return VTBits-Tmp+1;
1996 case ISD::AssertZext:
1997 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2000 case ISD::Constant: {
2001 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2002 // If negative, return # leading ones.
2003 if (Val.isNegative())
2004 return Val.countLeadingOnes();
2006 // Return # leading zeros.
2007 return Val.countLeadingZeros();
2010 case ISD::SIGN_EXTEND:
2011 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
2012 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2014 case ISD::SIGN_EXTEND_INREG:
2015 // Max of the input and what this extends.
2016 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2019 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2020 return std::max(Tmp, Tmp2);
2023 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2024 // SRA X, C -> adds C sign bits.
2025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2026 Tmp += C->getZExtValue();
2027 if (Tmp > VTBits) Tmp = VTBits;
2031 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2032 // shl destroys sign bits.
2033 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2034 if (C->getZExtValue() >= VTBits || // Bad shift.
2035 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2036 return Tmp - C->getZExtValue();
2041 case ISD::XOR: // NOT is handled here.
2042 // Logical binary ops preserve the number of sign bits at the worst.
2043 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2045 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2046 FirstAnswer = std::min(Tmp, Tmp2);
2047 // We computed what we know about the sign bits as our first
2048 // answer. Now proceed to the generic code that uses
2049 // ComputeMaskedBits, and pick whichever answer is better.
2054 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2055 if (Tmp == 1) return 1; // Early out.
2056 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2057 return std::min(Tmp, Tmp2);
2065 if (Op.getResNo() != 1)
2067 // The boolean result conforms to getBooleanContents. Fall through.
2069 // If setcc returns 0/-1, all bits are sign bits.
2070 if (TLI.getBooleanContents() ==
2071 TargetLowering::ZeroOrNegativeOneBooleanContent)
2076 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2077 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2079 // Handle rotate right by N like a rotate left by 32-N.
2080 if (Op.getOpcode() == ISD::ROTR)
2081 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2083 // If we aren't rotating out all of the known-in sign bits, return the
2084 // number that are left. This handles rotl(sext(x), 1) for example.
2085 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2086 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2090 // Add can have at most one carry bit. Thus we know that the output
2091 // is, at worst, one more bit than the inputs.
2092 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2093 if (Tmp == 1) return 1; // Early out.
2095 // Special case decrementing a value (ADD X, -1):
2096 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2097 if (CRHS->isAllOnesValue()) {
2098 APInt KnownZero, KnownOne;
2099 APInt Mask = APInt::getAllOnesValue(VTBits);
2100 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2102 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2104 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2107 // If we are subtracting one from a positive number, there is no carry
2108 // out of the result.
2109 if (KnownZero.isNegative())
2113 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2114 if (Tmp2 == 1) return 1;
2115 return std::min(Tmp, Tmp2)-1;
2119 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2120 if (Tmp2 == 1) return 1;
2123 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2124 if (CLHS->isNullValue()) {
2125 APInt KnownZero, KnownOne;
2126 APInt Mask = APInt::getAllOnesValue(VTBits);
2127 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2128 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2130 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2133 // If the input is known to be positive (the sign bit is known clear),
2134 // the output of the NEG has the same number of sign bits as the input.
2135 if (KnownZero.isNegative())
2138 // Otherwise, we treat this like a SUB.
2141 // Sub can have at most one carry bit. Thus we know that the output
2142 // is, at worst, one more bit than the inputs.
2143 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2144 if (Tmp == 1) return 1; // Early out.
2145 return std::min(Tmp, Tmp2)-1;
2148 // FIXME: it's tricky to do anything useful for this, but it is an important
2149 // case for targets like X86.
2153 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2154 if (Op.getOpcode() == ISD::LOAD) {
2155 LoadSDNode *LD = cast<LoadSDNode>(Op);
2156 unsigned ExtType = LD->getExtensionType();
2159 case ISD::SEXTLOAD: // '17' bits known
2160 Tmp = LD->getMemoryVT().getSizeInBits();
2161 return VTBits-Tmp+1;
2162 case ISD::ZEXTLOAD: // '16' bits known
2163 Tmp = LD->getMemoryVT().getSizeInBits();
2168 // Allow the target to implement this method for its nodes.
2169 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2170 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2171 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2172 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2173 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2174 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2177 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2178 // use this information.
2179 APInt KnownZero, KnownOne;
2180 APInt Mask = APInt::getAllOnesValue(VTBits);
2181 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2183 if (KnownZero.isNegative()) { // sign bit is 0
2185 } else if (KnownOne.isNegative()) { // sign bit is 1;
2192 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2193 // the number of identical bits in the top of the input value.
2195 Mask <<= Mask.getBitWidth()-VTBits;
2196 // Return # leading zeros. We use 'min' here in case Val was zero before
2197 // shifting. We don't want to return '64' as for an i32 "0".
2198 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2202 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2203 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2204 if (!GA) return false;
2205 if (GA->getOffset() != 0) return false;
2206 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2207 if (!GV) return false;
2208 MachineModuleInfo *MMI = getMachineModuleInfo();
2209 return MMI && MMI->hasDebugInfo();
2213 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2214 /// element of the result of the vector shuffle.
2215 SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
2217 MVT VT = N->getValueType(0);
2218 DebugLoc dl = N->getDebugLoc();
2219 if (N->getMaskElt(i) < 0)
2220 return getUNDEF(VT.getVectorElementType());
2221 unsigned Index = N->getMaskElt(i);
2222 unsigned NumElems = VT.getVectorNumElements();
2223 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2226 if (V.getOpcode() == ISD::BIT_CONVERT) {
2227 V = V.getOperand(0);
2228 MVT VVT = V.getValueType();
2229 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
2232 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2233 return (Index == 0) ? V.getOperand(0)
2234 : getUNDEF(VT.getVectorElementType());
2235 if (V.getOpcode() == ISD::BUILD_VECTOR)
2236 return V.getOperand(Index);
2237 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
2238 return getShuffleScalarElt(SVN, Index);
2243 /// getNode - Gets or creates the specified node.
2245 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT) {
2246 FoldingSetNodeID ID;
2247 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2249 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2250 return SDValue(E, 0);
2251 SDNode *N = NodeAllocator.Allocate<SDNode>();
2252 new (N) SDNode(Opcode, DL, getVTList(VT));
2253 CSEMap.InsertNode(N, IP);
2255 AllNodes.push_back(N);
2259 return SDValue(N, 0);
2262 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2263 MVT VT, SDValue Operand) {
2264 // Constant fold unary operations with an integer constant operand.
2265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2266 const APInt &Val = C->getAPIntValue();
2267 unsigned BitWidth = VT.getSizeInBits();
2270 case ISD::SIGN_EXTEND:
2271 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2272 case ISD::ANY_EXTEND:
2273 case ISD::ZERO_EXTEND:
2275 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2276 case ISD::UINT_TO_FP:
2277 case ISD::SINT_TO_FP: {
2278 const uint64_t zero[] = {0, 0};
2279 // No compile time operations on this type.
2280 if (VT==MVT::ppcf128)
2282 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2283 (void)apf.convertFromAPInt(Val,
2284 Opcode==ISD::SINT_TO_FP,
2285 APFloat::rmNearestTiesToEven);
2286 return getConstantFP(apf, VT);
2288 case ISD::BIT_CONVERT:
2289 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2290 return getConstantFP(Val.bitsToFloat(), VT);
2291 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2292 return getConstantFP(Val.bitsToDouble(), VT);
2295 return getConstant(Val.byteSwap(), VT);
2297 return getConstant(Val.countPopulation(), VT);
2299 return getConstant(Val.countLeadingZeros(), VT);
2301 return getConstant(Val.countTrailingZeros(), VT);
2305 // Constant fold unary operations with a floating point constant operand.
2306 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2307 APFloat V = C->getValueAPF(); // make copy
2308 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2312 return getConstantFP(V, VT);
2315 return getConstantFP(V, VT);
2317 case ISD::FP_EXTEND: {
2319 // This can return overflow, underflow, or inexact; we don't care.
2320 // FIXME need to be more flexible about rounding mode.
2321 (void)V.convert(*MVTToAPFloatSemantics(VT),
2322 APFloat::rmNearestTiesToEven, &ignored);
2323 return getConstantFP(V, VT);
2325 case ISD::FP_TO_SINT:
2326 case ISD::FP_TO_UINT: {
2329 assert(integerPartWidth >= 64);
2330 // FIXME need to be more flexible about rounding mode.
2331 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2332 Opcode==ISD::FP_TO_SINT,
2333 APFloat::rmTowardZero, &ignored);
2334 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2336 APInt api(VT.getSizeInBits(), 2, x);
2337 return getConstant(api, VT);
2339 case ISD::BIT_CONVERT:
2340 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2341 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2342 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2343 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2349 unsigned OpOpcode = Operand.getNode()->getOpcode();
2351 case ISD::TokenFactor:
2352 case ISD::MERGE_VALUES:
2353 case ISD::CONCAT_VECTORS:
2354 return Operand; // Factor, merge or concat of one node? No need.
2355 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2356 case ISD::FP_EXTEND:
2357 assert(VT.isFloatingPoint() &&
2358 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2359 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2360 if (Operand.getOpcode() == ISD::UNDEF)
2361 return getUNDEF(VT);
2363 case ISD::SIGN_EXTEND:
2364 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2365 "Invalid SIGN_EXTEND!");
2366 if (Operand.getValueType() == VT) return Operand; // noop extension
2367 assert(Operand.getValueType().bitsLT(VT)
2368 && "Invalid sext node, dst < src!");
2369 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2370 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2372 case ISD::ZERO_EXTEND:
2373 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2374 "Invalid ZERO_EXTEND!");
2375 if (Operand.getValueType() == VT) return Operand; // noop extension
2376 assert(Operand.getValueType().bitsLT(VT)
2377 && "Invalid zext node, dst < src!");
2378 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2379 return getNode(ISD::ZERO_EXTEND, DL, VT,
2380 Operand.getNode()->getOperand(0));
2382 case ISD::ANY_EXTEND:
2383 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2384 "Invalid ANY_EXTEND!");
2385 if (Operand.getValueType() == VT) return Operand; // noop extension
2386 assert(Operand.getValueType().bitsLT(VT)
2387 && "Invalid anyext node, dst < src!");
2388 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2389 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2390 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2393 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2394 "Invalid TRUNCATE!");
2395 if (Operand.getValueType() == VT) return Operand; // noop truncate
2396 assert(Operand.getValueType().bitsGT(VT)
2397 && "Invalid truncate node, src < dst!");
2398 if (OpOpcode == ISD::TRUNCATE)
2399 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2400 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2401 OpOpcode == ISD::ANY_EXTEND) {
2402 // If the source is smaller than the dest, we still need an extend.
2403 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2404 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2405 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2406 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2408 return Operand.getNode()->getOperand(0);
2411 case ISD::BIT_CONVERT:
2412 // Basic sanity checking.
2413 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2414 && "Cannot BIT_CONVERT between types of different sizes!");
2415 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2416 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2417 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2418 if (OpOpcode == ISD::UNDEF)
2419 return getUNDEF(VT);
2421 case ISD::SCALAR_TO_VECTOR:
2422 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2423 (VT.getVectorElementType() == Operand.getValueType() ||
2424 (VT.getVectorElementType().isInteger() &&
2425 Operand.getValueType().isInteger() &&
2426 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2427 "Illegal SCALAR_TO_VECTOR node!");
2428 if (OpOpcode == ISD::UNDEF)
2429 return getUNDEF(VT);
2430 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2431 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2432 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2433 Operand.getConstantOperandVal(1) == 0 &&
2434 Operand.getOperand(0).getValueType() == VT)
2435 return Operand.getOperand(0);
2438 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2439 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2440 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2441 Operand.getNode()->getOperand(0));
2442 if (OpOpcode == ISD::FNEG) // --X -> X
2443 return Operand.getNode()->getOperand(0);
2446 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2447 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2452 SDVTList VTs = getVTList(VT);
2453 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2454 FoldingSetNodeID ID;
2455 SDValue Ops[1] = { Operand };
2456 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2458 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2459 return SDValue(E, 0);
2460 N = NodeAllocator.Allocate<UnarySDNode>();
2461 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2462 CSEMap.InsertNode(N, IP);
2464 N = NodeAllocator.Allocate<UnarySDNode>();
2465 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2468 AllNodes.push_back(N);
2472 return SDValue(N, 0);
2475 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2477 ConstantSDNode *Cst1,
2478 ConstantSDNode *Cst2) {
2479 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2482 case ISD::ADD: return getConstant(C1 + C2, VT);
2483 case ISD::SUB: return getConstant(C1 - C2, VT);
2484 case ISD::MUL: return getConstant(C1 * C2, VT);
2486 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2489 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2492 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2495 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2497 case ISD::AND: return getConstant(C1 & C2, VT);
2498 case ISD::OR: return getConstant(C1 | C2, VT);
2499 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2500 case ISD::SHL: return getConstant(C1 << C2, VT);
2501 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2502 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2503 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2504 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2511 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2512 SDValue N1, SDValue N2) {
2513 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2514 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2517 case ISD::TokenFactor:
2518 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2519 N2.getValueType() == MVT::Other && "Invalid token factor!");
2520 // Fold trivial token factors.
2521 if (N1.getOpcode() == ISD::EntryToken) return N2;
2522 if (N2.getOpcode() == ISD::EntryToken) return N1;
2523 if (N1 == N2) return N1;
2525 case ISD::CONCAT_VECTORS:
2526 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2527 // one big BUILD_VECTOR.
2528 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2529 N2.getOpcode() == ISD::BUILD_VECTOR) {
2530 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2531 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2532 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2536 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2537 N1.getValueType() == VT && "Binary operator types must match!");
2538 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2539 // worth handling here.
2540 if (N2C && N2C->isNullValue())
2542 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2549 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2550 N1.getValueType() == VT && "Binary operator types must match!");
2551 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2552 // it's worth handling here.
2553 if (N2C && N2C->isNullValue())
2563 assert(VT.isInteger() && "This operator does not apply to FP types!");
2571 if (Opcode == ISD::FADD) {
2573 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2574 if (CFP->getValueAPF().isZero())
2577 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2578 if (CFP->getValueAPF().isZero())
2580 } else if (Opcode == ISD::FSUB) {
2582 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2583 if (CFP->getValueAPF().isZero())
2587 assert(N1.getValueType() == N2.getValueType() &&
2588 N1.getValueType() == VT && "Binary operator types must match!");
2590 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2591 assert(N1.getValueType() == VT &&
2592 N1.getValueType().isFloatingPoint() &&
2593 N2.getValueType().isFloatingPoint() &&
2594 "Invalid FCOPYSIGN!");
2601 assert(VT == N1.getValueType() &&
2602 "Shift operators return type must be the same as their first arg");
2603 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2604 "Shifts only work on integers");
2606 // Always fold shifts of i1 values so the code generator doesn't need to
2607 // handle them. Since we know the size of the shift has to be less than the
2608 // size of the value, the shift/rotate count is guaranteed to be zero.
2612 case ISD::FP_ROUND_INREG: {
2613 MVT EVT = cast<VTSDNode>(N2)->getVT();
2614 assert(VT == N1.getValueType() && "Not an inreg round!");
2615 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2616 "Cannot FP_ROUND_INREG integer types");
2617 assert(EVT.bitsLE(VT) && "Not rounding down!");
2618 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2622 assert(VT.isFloatingPoint() &&
2623 N1.getValueType().isFloatingPoint() &&
2624 VT.bitsLE(N1.getValueType()) &&
2625 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2626 if (N1.getValueType() == VT) return N1; // noop conversion.
2628 case ISD::AssertSext:
2629 case ISD::AssertZext: {
2630 MVT EVT = cast<VTSDNode>(N2)->getVT();
2631 assert(VT == N1.getValueType() && "Not an inreg extend!");
2632 assert(VT.isInteger() && EVT.isInteger() &&
2633 "Cannot *_EXTEND_INREG FP types");
2634 assert(EVT.bitsLE(VT) && "Not extending!");
2635 if (VT == EVT) return N1; // noop assertion.
2638 case ISD::SIGN_EXTEND_INREG: {
2639 MVT EVT = cast<VTSDNode>(N2)->getVT();
2640 assert(VT == N1.getValueType() && "Not an inreg extend!");
2641 assert(VT.isInteger() && EVT.isInteger() &&
2642 "Cannot *_EXTEND_INREG FP types");
2643 assert(EVT.bitsLE(VT) && "Not extending!");
2644 if (EVT == VT) return N1; // Not actually extending
2647 APInt Val = N1C->getAPIntValue();
2648 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2649 Val <<= Val.getBitWidth()-FromBits;
2650 Val = Val.ashr(Val.getBitWidth()-FromBits);
2651 return getConstant(Val, VT);
2655 case ISD::EXTRACT_VECTOR_ELT:
2656 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2657 if (N1.getOpcode() == ISD::UNDEF)
2658 return getUNDEF(VT);
2660 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2661 // expanding copies of large vectors from registers.
2663 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2664 N1.getNumOperands() > 0) {
2666 N1.getOperand(0).getValueType().getVectorNumElements();
2667 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2668 N1.getOperand(N2C->getZExtValue() / Factor),
2669 getConstant(N2C->getZExtValue() % Factor,
2670 N2.getValueType()));
2673 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2674 // expanding large vector constants.
2675 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2676 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2677 if (Elt.getValueType() != VT) {
2678 // If the vector element type is not legal, the BUILD_VECTOR operands
2679 // are promoted and implicitly truncated. Make that explicit here.
2680 assert(VT.isInteger() && Elt.getValueType().isInteger() &&
2681 VT.bitsLE(Elt.getValueType()) &&
2682 "Bad type for BUILD_VECTOR operand");
2683 Elt = getNode(ISD::TRUNCATE, DL, VT, Elt);
2688 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2689 // operations are lowered to scalars.
2690 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2691 // If the indices are the same, return the inserted element.
2692 if (N1.getOperand(2) == N2)
2693 return N1.getOperand(1);
2694 // If the indices are known different, extract the element from
2695 // the original vector.
2696 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2697 isa<ConstantSDNode>(N2))
2698 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2701 case ISD::EXTRACT_ELEMENT:
2702 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2703 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2704 (N1.getValueType().isInteger() == VT.isInteger()) &&
2705 "Wrong types for EXTRACT_ELEMENT!");
2707 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2708 // 64-bit integers into 32-bit parts. Instead of building the extract of
2709 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2710 if (N1.getOpcode() == ISD::BUILD_PAIR)
2711 return N1.getOperand(N2C->getZExtValue());
2713 // EXTRACT_ELEMENT of a constant int is also very common.
2714 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2715 unsigned ElementSize = VT.getSizeInBits();
2716 unsigned Shift = ElementSize * N2C->getZExtValue();
2717 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2718 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2721 case ISD::EXTRACT_SUBVECTOR:
2722 if (N1.getValueType() == VT) // Trivial extraction.
2729 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2730 if (SV.getNode()) return SV;
2731 } else { // Cannonicalize constant to RHS if commutative
2732 if (isCommutativeBinOp(Opcode)) {
2733 std::swap(N1C, N2C);
2739 // Constant fold FP operations.
2740 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2741 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2743 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2744 // Cannonicalize constant to RHS if commutative
2745 std::swap(N1CFP, N2CFP);
2747 } else if (N2CFP && VT != MVT::ppcf128) {
2748 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2749 APFloat::opStatus s;
2752 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2753 if (s != APFloat::opInvalidOp)
2754 return getConstantFP(V1, VT);
2757 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2758 if (s!=APFloat::opInvalidOp)
2759 return getConstantFP(V1, VT);
2762 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2763 if (s!=APFloat::opInvalidOp)
2764 return getConstantFP(V1, VT);
2767 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2768 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2769 return getConstantFP(V1, VT);
2772 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2773 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2774 return getConstantFP(V1, VT);
2776 case ISD::FCOPYSIGN:
2778 return getConstantFP(V1, VT);
2784 // Canonicalize an UNDEF to the RHS, even over a constant.
2785 if (N1.getOpcode() == ISD::UNDEF) {
2786 if (isCommutativeBinOp(Opcode)) {
2790 case ISD::FP_ROUND_INREG:
2791 case ISD::SIGN_EXTEND_INREG:
2797 return N1; // fold op(undef, arg2) -> undef
2805 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2806 // For vectors, we can't easily build an all zero vector, just return
2813 // Fold a bunch of operators when the RHS is undef.
2814 if (N2.getOpcode() == ISD::UNDEF) {
2817 if (N1.getOpcode() == ISD::UNDEF)
2818 // Handle undef ^ undef -> 0 special case. This is a common
2820 return getConstant(0, VT);
2830 return N2; // fold op(arg1, undef) -> undef
2844 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2845 // For vectors, we can't easily build an all zero vector, just return
2850 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2851 // For vectors, we can't easily build an all one vector, just return
2859 // Memoize this node if possible.
2861 SDVTList VTs = getVTList(VT);
2862 if (VT != MVT::Flag) {
2863 SDValue Ops[] = { N1, N2 };
2864 FoldingSetNodeID ID;
2865 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2867 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2868 return SDValue(E, 0);
2869 N = NodeAllocator.Allocate<BinarySDNode>();
2870 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2871 CSEMap.InsertNode(N, IP);
2873 N = NodeAllocator.Allocate<BinarySDNode>();
2874 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2877 AllNodes.push_back(N);
2881 return SDValue(N, 0);
2884 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2885 SDValue N1, SDValue N2, SDValue N3) {
2886 // Perform various simplifications.
2887 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2888 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2890 case ISD::CONCAT_VECTORS:
2891 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2892 // one big BUILD_VECTOR.
2893 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2894 N2.getOpcode() == ISD::BUILD_VECTOR &&
2895 N3.getOpcode() == ISD::BUILD_VECTOR) {
2896 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2897 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2898 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2899 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2903 // Use FoldSetCC to simplify SETCC's.
2904 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
2905 if (Simp.getNode()) return Simp;
2910 if (N1C->getZExtValue())
2911 return N2; // select true, X, Y -> X
2913 return N3; // select false, X, Y -> Y
2916 if (N2 == N3) return N2; // select C, X, X -> X
2920 if (N2C->getZExtValue()) // Unconditional branch
2921 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
2923 return N1; // Never-taken branch
2926 case ISD::VECTOR_SHUFFLE:
2927 assert(0 && "should use getVectorShuffle constructor!");
2929 case ISD::BIT_CONVERT:
2930 // Fold bit_convert nodes from a type to themselves.
2931 if (N1.getValueType() == VT)
2936 // Memoize node if it doesn't produce a flag.
2938 SDVTList VTs = getVTList(VT);
2939 if (VT != MVT::Flag) {
2940 SDValue Ops[] = { N1, N2, N3 };
2941 FoldingSetNodeID ID;
2942 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2944 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2945 return SDValue(E, 0);
2946 N = NodeAllocator.Allocate<TernarySDNode>();
2947 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2948 CSEMap.InsertNode(N, IP);
2950 N = NodeAllocator.Allocate<TernarySDNode>();
2951 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2953 AllNodes.push_back(N);
2957 return SDValue(N, 0);
2960 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2961 SDValue N1, SDValue N2, SDValue N3,
2963 SDValue Ops[] = { N1, N2, N3, N4 };
2964 return getNode(Opcode, DL, VT, Ops, 4);
2967 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2968 SDValue N1, SDValue N2, SDValue N3,
2969 SDValue N4, SDValue N5) {
2970 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2971 return getNode(Opcode, DL, VT, Ops, 5);
2974 /// getMemsetValue - Vectorized representation of the memset value
2976 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG,
2978 unsigned NumBits = VT.isVector() ?
2979 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2980 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2981 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
2983 for (unsigned i = NumBits; i > 8; i >>= 1) {
2984 Val = (Val << Shift) | Val;
2988 return DAG.getConstant(Val, VT);
2989 return DAG.getConstantFP(APFloat(Val), VT);
2992 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2993 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
2995 for (unsigned i = NumBits; i > 8; i >>= 1) {
2996 Value = DAG.getNode(ISD::OR, dl, VT,
2997 DAG.getNode(ISD::SHL, dl, VT, Value,
2998 DAG.getConstant(Shift,
2999 TLI.getShiftAmountTy())),
3007 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3008 /// used when a memcpy is turned into a memset when the source is a constant
3010 static SDValue getMemsetStringVal(MVT VT, DebugLoc dl, SelectionDAG &DAG,
3011 const TargetLowering &TLI,
3012 std::string &Str, unsigned Offset) {
3013 // Handle vector with all elements zero.
3016 return DAG.getConstant(0, VT);
3017 unsigned NumElts = VT.getVectorNumElements();
3018 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3019 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3020 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
3023 assert(!VT.isVector() && "Can't handle vector type here!");
3024 unsigned NumBits = VT.getSizeInBits();
3025 unsigned MSB = NumBits / 8;
3027 if (TLI.isLittleEndian())
3028 Offset = Offset + MSB - 1;
3029 for (unsigned i = 0; i != MSB; ++i) {
3030 Val = (Val << 8) | (unsigned char)Str[Offset];
3031 Offset += TLI.isLittleEndian() ? -1 : 1;
3033 return DAG.getConstant(Val, VT);
3036 /// getMemBasePlusOffset - Returns base and offset node for the
3038 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3039 SelectionDAG &DAG) {
3040 MVT VT = Base.getValueType();
3041 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3042 VT, Base, DAG.getConstant(Offset, VT));
3045 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3047 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3048 unsigned SrcDelta = 0;
3049 GlobalAddressSDNode *G = NULL;
3050 if (Src.getOpcode() == ISD::GlobalAddress)
3051 G = cast<GlobalAddressSDNode>(Src);
3052 else if (Src.getOpcode() == ISD::ADD &&
3053 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3054 Src.getOperand(1).getOpcode() == ISD::Constant) {
3055 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3056 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3061 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3062 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3068 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3069 /// to replace the memset / memcpy is below the threshold. It also returns the
3070 /// types of the sequence of memory ops to perform memset / memcpy.
3072 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
3073 SDValue Dst, SDValue Src,
3074 unsigned Limit, uint64_t Size, unsigned &Align,
3075 std::string &Str, bool &isSrcStr,
3077 const TargetLowering &TLI) {
3078 isSrcStr = isMemSrcFromString(Src, Str);
3079 bool isSrcConst = isa<ConstantSDNode>(Src);
3080 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
3081 MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3082 if (VT != MVT::iAny) {
3083 unsigned NewAlign = (unsigned)
3084 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
3085 // If source is a string constant, this will require an unaligned load.
3086 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3087 if (Dst.getOpcode() != ISD::FrameIndex) {
3088 // Can't change destination alignment. It requires a unaligned store.
3092 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3093 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3094 if (MFI->isFixedObjectIndex(FI)) {
3095 // Can't change destination alignment. It requires a unaligned store.
3099 // Give the stack frame object a larger alignment if needed.
3100 if (MFI->getObjectAlignment(FI) < NewAlign)
3101 MFI->setObjectAlignment(FI, NewAlign);
3108 if (VT == MVT::iAny) {
3112 switch (Align & 7) {
3113 case 0: VT = MVT::i64; break;
3114 case 4: VT = MVT::i32; break;
3115 case 2: VT = MVT::i16; break;
3116 default: VT = MVT::i8; break;
3121 while (!TLI.isTypeLegal(LVT))
3122 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
3123 assert(LVT.isInteger());
3129 unsigned NumMemOps = 0;
3131 unsigned VTSize = VT.getSizeInBits() / 8;
3132 while (VTSize > Size) {
3133 // For now, only use non-vector load / store's for the left-over pieces.
3134 if (VT.isVector()) {
3136 while (!TLI.isTypeLegal(VT))
3137 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
3138 VTSize = VT.getSizeInBits() / 8;
3140 // This can result in a type that is not legal on the target, e.g.
3141 // 1 or 2 bytes on PPC.
3142 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
3147 if (++NumMemOps > Limit)
3149 MemOps.push_back(VT);
3156 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3157 SDValue Chain, SDValue Dst,
3158 SDValue Src, uint64_t Size,
3159 unsigned Align, bool AlwaysInline,
3160 const Value *DstSV, uint64_t DstSVOff,
3161 const Value *SrcSV, uint64_t SrcSVOff){
3162 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3164 // Expand memcpy to a series of load and store ops if the size operand falls
3165 // below a certain threshold.
3166 std::vector<MVT> MemOps;
3167 uint64_t Limit = -1ULL;
3169 Limit = TLI.getMaxStoresPerMemcpy();
3170 unsigned DstAlign = Align; // Destination alignment can change.
3173 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3174 Str, CopyFromStr, DAG, TLI))
3178 bool isZeroStr = CopyFromStr && Str.empty();
3179 SmallVector<SDValue, 8> OutChains;
3180 unsigned NumMemOps = MemOps.size();
3181 uint64_t SrcOff = 0, DstOff = 0;
3182 for (unsigned i = 0; i < NumMemOps; i++) {
3184 unsigned VTSize = VT.getSizeInBits() / 8;
3185 SDValue Value, Store;
3187 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3188 // It's unlikely a store of a vector immediate can be done in a single
3189 // instruction. It would require a load from a constantpool first.
3190 // We also handle store a vector with all zero's.
3191 // FIXME: Handle other cases where store of vector immediate is done in
3192 // a single instruction.
3193 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3194 Store = DAG.getStore(Chain, dl, Value,
3195 getMemBasePlusOffset(Dst, DstOff, DAG),
3196 DstSV, DstSVOff + DstOff, false, DstAlign);
3198 // The type might not be legal for the target. This should only happen
3199 // if the type is smaller than a legal type, as on PPC, so the right
3200 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3201 // to Load/Store if NVT==VT.
3202 // FIXME does the case above also need this?
3203 MVT NVT = TLI.getTypeToTransformTo(VT);
3204 assert(NVT.bitsGE(VT));
3205 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3206 getMemBasePlusOffset(Src, SrcOff, DAG),
3207 SrcSV, SrcSVOff + SrcOff, VT, false, Align);
3208 Store = DAG.getTruncStore(Chain, dl, Value,
3209 getMemBasePlusOffset(Dst, DstOff, DAG),
3210 DstSV, DstSVOff + DstOff, VT, false, DstAlign);
3212 OutChains.push_back(Store);
3217 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3218 &OutChains[0], OutChains.size());
3221 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3222 SDValue Chain, SDValue Dst,
3223 SDValue Src, uint64_t Size,
3224 unsigned Align, bool AlwaysInline,
3225 const Value *DstSV, uint64_t DstSVOff,
3226 const Value *SrcSV, uint64_t SrcSVOff){
3227 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3229 // Expand memmove to a series of load and store ops if the size operand falls
3230 // below a certain threshold.
3231 std::vector<MVT> MemOps;
3232 uint64_t Limit = -1ULL;
3234 Limit = TLI.getMaxStoresPerMemmove();
3235 unsigned DstAlign = Align; // Destination alignment can change.
3238 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3239 Str, CopyFromStr, DAG, TLI))
3242 uint64_t SrcOff = 0, DstOff = 0;
3244 SmallVector<SDValue, 8> LoadValues;
3245 SmallVector<SDValue, 8> LoadChains;
3246 SmallVector<SDValue, 8> OutChains;
3247 unsigned NumMemOps = MemOps.size();
3248 for (unsigned i = 0; i < NumMemOps; i++) {
3250 unsigned VTSize = VT.getSizeInBits() / 8;
3251 SDValue Value, Store;
3253 Value = DAG.getLoad(VT, dl, Chain,
3254 getMemBasePlusOffset(Src, SrcOff, DAG),
3255 SrcSV, SrcSVOff + SrcOff, false, Align);
3256 LoadValues.push_back(Value);
3257 LoadChains.push_back(Value.getValue(1));
3260 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3261 &LoadChains[0], LoadChains.size());
3263 for (unsigned i = 0; i < NumMemOps; i++) {
3265 unsigned VTSize = VT.getSizeInBits() / 8;
3266 SDValue Value, Store;
3268 Store = DAG.getStore(Chain, dl, LoadValues[i],
3269 getMemBasePlusOffset(Dst, DstOff, DAG),
3270 DstSV, DstSVOff + DstOff, false, DstAlign);
3271 OutChains.push_back(Store);
3275 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3276 &OutChains[0], OutChains.size());
3279 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3280 SDValue Chain, SDValue Dst,
3281 SDValue Src, uint64_t Size,
3283 const Value *DstSV, uint64_t DstSVOff) {
3284 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3286 // Expand memset to a series of load/store ops if the size operand
3287 // falls below a certain threshold.
3288 std::vector<MVT> MemOps;
3291 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3292 Size, Align, Str, CopyFromStr, DAG, TLI))
3295 SmallVector<SDValue, 8> OutChains;
3296 uint64_t DstOff = 0;
3298 unsigned NumMemOps = MemOps.size();
3299 for (unsigned i = 0; i < NumMemOps; i++) {
3301 unsigned VTSize = VT.getSizeInBits() / 8;
3302 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3303 SDValue Store = DAG.getStore(Chain, dl, Value,
3304 getMemBasePlusOffset(Dst, DstOff, DAG),
3305 DstSV, DstSVOff + DstOff);
3306 OutChains.push_back(Store);
3310 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3311 &OutChains[0], OutChains.size());
3314 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3315 SDValue Src, SDValue Size,
3316 unsigned Align, bool AlwaysInline,
3317 const Value *DstSV, uint64_t DstSVOff,
3318 const Value *SrcSV, uint64_t SrcSVOff) {
3320 // Check to see if we should lower the memcpy to loads and stores first.
3321 // For cases within the target-specified limits, this is the best choice.
3322 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3324 // Memcpy with size zero? Just return the original chain.
3325 if (ConstantSize->isNullValue())
3329 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3330 ConstantSize->getZExtValue(),
3331 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3332 if (Result.getNode())
3336 // Then check to see if we should lower the memcpy with target-specific
3337 // code. If the target chooses to do this, this is the next best.
3339 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3341 DstSV, DstSVOff, SrcSV, SrcSVOff);
3342 if (Result.getNode())
3345 // If we really need inline code and the target declined to provide it,
3346 // use a (potentially long) sequence of loads and stores.
3348 assert(ConstantSize && "AlwaysInline requires a constant size!");
3349 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3350 ConstantSize->getZExtValue(), Align, true,
3351 DstSV, DstSVOff, SrcSV, SrcSVOff);
3354 // Emit a library call.
3355 TargetLowering::ArgListTy Args;
3356 TargetLowering::ArgListEntry Entry;
3357 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3358 Entry.Node = Dst; Args.push_back(Entry);
3359 Entry.Node = Src; Args.push_back(Entry);
3360 Entry.Node = Size; Args.push_back(Entry);
3361 // FIXME: pass in DebugLoc
3362 std::pair<SDValue,SDValue> CallResult =
3363 TLI.LowerCallTo(Chain, Type::VoidTy,
3364 false, false, false, false, CallingConv::C, false,
3365 getExternalSymbol("memcpy", TLI.getPointerTy()),
3367 return CallResult.second;
3370 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3371 SDValue Src, SDValue Size,
3373 const Value *DstSV, uint64_t DstSVOff,
3374 const Value *SrcSV, uint64_t SrcSVOff) {
3376 // Check to see if we should lower the memmove to loads and stores first.
3377 // For cases within the target-specified limits, this is the best choice.
3378 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3380 // Memmove with size zero? Just return the original chain.
3381 if (ConstantSize->isNullValue())
3385 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3386 ConstantSize->getZExtValue(),
3387 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3388 if (Result.getNode())
3392 // Then check to see if we should lower the memmove with target-specific
3393 // code. If the target chooses to do this, this is the next best.
3395 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3396 DstSV, DstSVOff, SrcSV, SrcSVOff);
3397 if (Result.getNode())
3400 // Emit a library call.
3401 TargetLowering::ArgListTy Args;
3402 TargetLowering::ArgListEntry Entry;
3403 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3404 Entry.Node = Dst; Args.push_back(Entry);
3405 Entry.Node = Src; Args.push_back(Entry);
3406 Entry.Node = Size; Args.push_back(Entry);
3407 // FIXME: pass in DebugLoc
3408 std::pair<SDValue,SDValue> CallResult =
3409 TLI.LowerCallTo(Chain, Type::VoidTy,
3410 false, false, false, false, CallingConv::C, false,
3411 getExternalSymbol("memmove", TLI.getPointerTy()),
3413 return CallResult.second;
3416 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3417 SDValue Src, SDValue Size,
3419 const Value *DstSV, uint64_t DstSVOff) {
3421 // Check to see if we should lower the memset to stores first.
3422 // For cases within the target-specified limits, this is the best choice.
3423 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3425 // Memset with size zero? Just return the original chain.
3426 if (ConstantSize->isNullValue())
3430 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3431 Align, DstSV, DstSVOff);
3432 if (Result.getNode())
3436 // Then check to see if we should lower the memset with target-specific
3437 // code. If the target chooses to do this, this is the next best.
3439 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3441 if (Result.getNode())
3444 // Emit a library call.
3445 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3446 TargetLowering::ArgListTy Args;
3447 TargetLowering::ArgListEntry Entry;
3448 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3449 Args.push_back(Entry);
3450 // Extend or truncate the argument to be an i32 value for the call.
3451 if (Src.getValueType().bitsGT(MVT::i32))
3452 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3454 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3455 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3456 Args.push_back(Entry);
3457 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3458 Args.push_back(Entry);
3459 // FIXME: pass in DebugLoc
3460 std::pair<SDValue,SDValue> CallResult =
3461 TLI.LowerCallTo(Chain, Type::VoidTy,
3462 false, false, false, false, CallingConv::C, false,
3463 getExternalSymbol("memset", TLI.getPointerTy()),
3465 return CallResult.second;
3468 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
3470 SDValue Ptr, SDValue Cmp,
3471 SDValue Swp, const Value* PtrVal,
3472 unsigned Alignment) {
3473 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3474 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3476 MVT VT = Cmp.getValueType();
3478 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3479 Alignment = getMVTAlignment(MemVT);
3481 SDVTList VTs = getVTList(VT, MVT::Other);
3482 FoldingSetNodeID ID;
3483 ID.AddInteger(MemVT.getRawBits());
3484 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3485 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3487 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3488 return SDValue(E, 0);
3489 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3490 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3491 Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3492 CSEMap.InsertNode(N, IP);
3493 AllNodes.push_back(N);
3494 return SDValue(N, 0);
3497 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
3499 SDValue Ptr, SDValue Val,
3500 const Value* PtrVal,
3501 unsigned Alignment) {
3502 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3503 Opcode == ISD::ATOMIC_LOAD_SUB ||
3504 Opcode == ISD::ATOMIC_LOAD_AND ||
3505 Opcode == ISD::ATOMIC_LOAD_OR ||
3506 Opcode == ISD::ATOMIC_LOAD_XOR ||
3507 Opcode == ISD::ATOMIC_LOAD_NAND ||
3508 Opcode == ISD::ATOMIC_LOAD_MIN ||
3509 Opcode == ISD::ATOMIC_LOAD_MAX ||
3510 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3511 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3512 Opcode == ISD::ATOMIC_SWAP) &&
3513 "Invalid Atomic Op");
3515 MVT VT = Val.getValueType();
3517 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3518 Alignment = getMVTAlignment(MemVT);
3520 SDVTList VTs = getVTList(VT, MVT::Other);
3521 FoldingSetNodeID ID;
3522 ID.AddInteger(MemVT.getRawBits());
3523 SDValue Ops[] = {Chain, Ptr, Val};
3524 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3526 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3527 return SDValue(E, 0);
3528 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3529 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3530 Chain, Ptr, Val, PtrVal, Alignment);
3531 CSEMap.InsertNode(N, IP);
3532 AllNodes.push_back(N);
3533 return SDValue(N, 0);
3536 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3537 /// Allowed to return something different (and simpler) if Simplify is true.
3538 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3543 SmallVector<MVT, 4> VTs;
3544 VTs.reserve(NumOps);
3545 for (unsigned i = 0; i < NumOps; ++i)
3546 VTs.push_back(Ops[i].getValueType());
3547 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3552 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3553 const MVT *VTs, unsigned NumVTs,
3554 const SDValue *Ops, unsigned NumOps,
3555 MVT MemVT, const Value *srcValue, int SVOff,
3556 unsigned Align, bool Vol,
3557 bool ReadMem, bool WriteMem) {
3558 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3559 MemVT, srcValue, SVOff, Align, Vol,
3564 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3565 const SDValue *Ops, unsigned NumOps,
3566 MVT MemVT, const Value *srcValue, int SVOff,
3567 unsigned Align, bool Vol,
3568 bool ReadMem, bool WriteMem) {
3569 // Memoize the node unless it returns a flag.
3570 MemIntrinsicSDNode *N;
3571 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3572 FoldingSetNodeID ID;
3573 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3575 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3576 return SDValue(E, 0);
3578 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3579 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3580 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3581 CSEMap.InsertNode(N, IP);
3583 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3584 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3585 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3587 AllNodes.push_back(N);
3588 return SDValue(N, 0);
3592 SelectionDAG::getCall(unsigned CallingConv, DebugLoc dl, bool IsVarArgs,
3593 bool IsTailCall, bool IsInreg, SDVTList VTs,
3594 const SDValue *Operands, unsigned NumOperands) {
3595 // Do not include isTailCall in the folding set profile.
3596 FoldingSetNodeID ID;
3597 AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3598 ID.AddInteger(CallingConv);
3599 ID.AddInteger(IsVarArgs);
3601 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3602 // Instead of including isTailCall in the folding set, we just
3603 // set the flag of the existing node.
3605 cast<CallSDNode>(E)->setNotTailCall();
3606 return SDValue(E, 0);
3608 SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3609 new (N) CallSDNode(CallingConv, dl, IsVarArgs, IsTailCall, IsInreg,
3610 VTs, Operands, NumOperands);
3611 CSEMap.InsertNode(N, IP);
3612 AllNodes.push_back(N);
3613 return SDValue(N, 0);
3617 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3618 ISD::LoadExtType ExtType, MVT VT, SDValue Chain,
3619 SDValue Ptr, SDValue Offset,
3620 const Value *SV, int SVOffset, MVT EVT,
3621 bool isVolatile, unsigned Alignment) {
3622 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3623 Alignment = getMVTAlignment(VT);
3626 ExtType = ISD::NON_EXTLOAD;
3627 } else if (ExtType == ISD::NON_EXTLOAD) {
3628 assert(VT == EVT && "Non-extending load from different memory type!");
3632 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3633 "Invalid vector extload!");
3635 assert(EVT.bitsLT(VT) &&
3636 "Should only be an extending load, not truncating!");
3637 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3638 "Cannot sign/zero extend a FP/Vector load!");
3639 assert(VT.isInteger() == EVT.isInteger() &&
3640 "Cannot convert from FP to Int or Int -> FP!");
3643 bool Indexed = AM != ISD::UNINDEXED;
3644 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3645 "Unindexed load with an offset!");
3647 SDVTList VTs = Indexed ?
3648 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3649 SDValue Ops[] = { Chain, Ptr, Offset };
3650 FoldingSetNodeID ID;
3651 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3652 ID.AddInteger(EVT.getRawBits());
3653 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
3655 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3656 return SDValue(E, 0);
3657 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3658 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset,
3659 Alignment, isVolatile);
3660 CSEMap.InsertNode(N, IP);
3661 AllNodes.push_back(N);
3662 return SDValue(N, 0);
3665 SDValue SelectionDAG::getLoad(MVT VT, DebugLoc dl,
3666 SDValue Chain, SDValue Ptr,
3667 const Value *SV, int SVOffset,
3668 bool isVolatile, unsigned Alignment) {
3669 SDValue Undef = getUNDEF(Ptr.getValueType());
3670 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3671 SV, SVOffset, VT, isVolatile, Alignment);
3674 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, MVT VT,
3675 SDValue Chain, SDValue Ptr,
3677 int SVOffset, MVT EVT,
3678 bool isVolatile, unsigned Alignment) {
3679 SDValue Undef = getUNDEF(Ptr.getValueType());
3680 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3681 SV, SVOffset, EVT, isVolatile, Alignment);
3685 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3686 SDValue Offset, ISD::MemIndexedMode AM) {
3687 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3688 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3689 "Load is already a indexed load!");
3690 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3691 LD->getChain(), Base, Offset, LD->getSrcValue(),
3692 LD->getSrcValueOffset(), LD->getMemoryVT(),
3693 LD->isVolatile(), LD->getAlignment());
3696 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3697 SDValue Ptr, const Value *SV, int SVOffset,
3698 bool isVolatile, unsigned Alignment) {
3699 MVT VT = Val.getValueType();
3701 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3702 Alignment = getMVTAlignment(VT);
3704 SDVTList VTs = getVTList(MVT::Other);
3705 SDValue Undef = getUNDEF(Ptr.getValueType());
3706 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3707 FoldingSetNodeID ID;
3708 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3709 ID.AddInteger(VT.getRawBits());
3710 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
3711 isVolatile, Alignment));
3713 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3714 return SDValue(E, 0);
3715 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3716 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false,
3717 VT, SV, SVOffset, Alignment, isVolatile);
3718 CSEMap.InsertNode(N, IP);
3719 AllNodes.push_back(N);
3720 return SDValue(N, 0);
3723 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3724 SDValue Ptr, const Value *SV,
3725 int SVOffset, MVT SVT,
3726 bool isVolatile, unsigned Alignment) {
3727 MVT VT = Val.getValueType();
3730 return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3732 assert(VT.bitsGT(SVT) && "Not a truncation?");
3733 assert(VT.isInteger() == SVT.isInteger() &&
3734 "Can't do FP-INT conversion!");
3736 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3737 Alignment = getMVTAlignment(VT);
3739 SDVTList VTs = getVTList(MVT::Other);
3740 SDValue Undef = getUNDEF(Ptr.getValueType());
3741 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3742 FoldingSetNodeID ID;
3743 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3744 ID.AddInteger(SVT.getRawBits());
3745 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED,
3746 isVolatile, Alignment));
3748 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3749 return SDValue(E, 0);
3750 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3751 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true,
3752 SVT, SV, SVOffset, Alignment, isVolatile);
3753 CSEMap.InsertNode(N, IP);
3754 AllNodes.push_back(N);
3755 return SDValue(N, 0);
3759 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
3760 SDValue Offset, ISD::MemIndexedMode AM) {
3761 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3762 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3763 "Store is already a indexed store!");
3764 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3765 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3766 FoldingSetNodeID ID;
3767 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3768 ID.AddInteger(ST->getMemoryVT().getRawBits());
3769 ID.AddInteger(ST->getRawSubclassData());
3771 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3772 return SDValue(E, 0);
3773 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3774 new (N) StoreSDNode(Ops, dl, VTs, AM,
3775 ST->isTruncatingStore(), ST->getMemoryVT(),
3776 ST->getSrcValue(), ST->getSrcValueOffset(),
3777 ST->getAlignment(), ST->isVolatile());
3778 CSEMap.InsertNode(N, IP);
3779 AllNodes.push_back(N);
3780 return SDValue(N, 0);
3783 SDValue SelectionDAG::getVAArg(MVT VT, DebugLoc dl,
3784 SDValue Chain, SDValue Ptr,
3786 SDValue Ops[] = { Chain, Ptr, SV };
3787 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
3790 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
3791 const SDUse *Ops, unsigned NumOps) {
3793 case 0: return getNode(Opcode, DL, VT);
3794 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3795 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3796 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3800 // Copy from an SDUse array into an SDValue array for use with
3801 // the regular getNode logic.
3802 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3803 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
3806 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
3807 const SDValue *Ops, unsigned NumOps) {
3809 case 0: return getNode(Opcode, DL, VT);
3810 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3811 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3812 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3818 case ISD::SELECT_CC: {
3819 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3820 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3821 "LHS and RHS of condition must have same type!");
3822 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3823 "True and False arms of SelectCC must have same type!");
3824 assert(Ops[2].getValueType() == VT &&
3825 "select_cc node must be of same type as true and false value!");
3829 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3830 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3831 "LHS/RHS of comparison should match types!");
3838 SDVTList VTs = getVTList(VT);
3840 if (VT != MVT::Flag) {
3841 FoldingSetNodeID ID;
3842 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3845 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3846 return SDValue(E, 0);
3848 N = NodeAllocator.Allocate<SDNode>();
3849 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3850 CSEMap.InsertNode(N, IP);
3852 N = NodeAllocator.Allocate<SDNode>();
3853 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3856 AllNodes.push_back(N);
3860 return SDValue(N, 0);
3863 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
3864 const std::vector<MVT> &ResultTys,
3865 const SDValue *Ops, unsigned NumOps) {
3866 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
3870 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
3871 const MVT *VTs, unsigned NumVTs,
3872 const SDValue *Ops, unsigned NumOps) {
3874 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
3875 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
3878 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3879 const SDValue *Ops, unsigned NumOps) {
3880 if (VTList.NumVTs == 1)
3881 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
3884 // FIXME: figure out how to safely handle things like
3885 // int foo(int x) { return 1 << (x & 255); }
3886 // int bar() { return foo(256); }
3888 case ISD::SRA_PARTS:
3889 case ISD::SRL_PARTS:
3890 case ISD::SHL_PARTS:
3891 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3892 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3893 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
3894 else if (N3.getOpcode() == ISD::AND)
3895 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3896 // If the and is only masking out bits that cannot effect the shift,
3897 // eliminate the and.
3898 unsigned NumBits = VT.getSizeInBits()*2;
3899 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3900 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
3906 // Memoize the node unless it returns a flag.
3908 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3909 FoldingSetNodeID ID;
3910 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3912 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3913 return SDValue(E, 0);
3915 N = NodeAllocator.Allocate<UnarySDNode>();
3916 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
3917 } else if (NumOps == 2) {
3918 N = NodeAllocator.Allocate<BinarySDNode>();
3919 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
3920 } else if (NumOps == 3) {
3921 N = NodeAllocator.Allocate<TernarySDNode>();
3922 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
3924 N = NodeAllocator.Allocate<SDNode>();
3925 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
3927 CSEMap.InsertNode(N, IP);
3930 N = NodeAllocator.Allocate<UnarySDNode>();
3931 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
3932 } else if (NumOps == 2) {
3933 N = NodeAllocator.Allocate<BinarySDNode>();
3934 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
3935 } else if (NumOps == 3) {
3936 N = NodeAllocator.Allocate<TernarySDNode>();
3937 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
3939 N = NodeAllocator.Allocate<SDNode>();
3940 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
3943 AllNodes.push_back(N);
3947 return SDValue(N, 0);
3950 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
3951 return getNode(Opcode, DL, VTList, 0, 0);
3954 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3956 SDValue Ops[] = { N1 };
3957 return getNode(Opcode, DL, VTList, Ops, 1);
3960 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3961 SDValue N1, SDValue N2) {
3962 SDValue Ops[] = { N1, N2 };
3963 return getNode(Opcode, DL, VTList, Ops, 2);
3966 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3967 SDValue N1, SDValue N2, SDValue N3) {
3968 SDValue Ops[] = { N1, N2, N3 };
3969 return getNode(Opcode, DL, VTList, Ops, 3);
3972 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3973 SDValue N1, SDValue N2, SDValue N3,
3975 SDValue Ops[] = { N1, N2, N3, N4 };
3976 return getNode(Opcode, DL, VTList, Ops, 4);
3979 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3980 SDValue N1, SDValue N2, SDValue N3,
3981 SDValue N4, SDValue N5) {
3982 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3983 return getNode(Opcode, DL, VTList, Ops, 5);
3986 SDVTList SelectionDAG::getVTList(MVT VT) {
3987 return makeVTList(SDNode::getValueTypeList(VT), 1);
3990 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3991 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3992 E = VTList.rend(); I != E; ++I)
3993 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
3996 MVT *Array = Allocator.Allocate<MVT>(2);
3999 SDVTList Result = makeVTList(Array, 2);
4000 VTList.push_back(Result);
4004 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
4005 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4006 E = VTList.rend(); I != E; ++I)
4007 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4011 MVT *Array = Allocator.Allocate<MVT>(3);
4015 SDVTList Result = makeVTList(Array, 3);
4016 VTList.push_back(Result);
4020 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) {
4021 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4022 E = VTList.rend(); I != E; ++I)
4023 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4024 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4027 MVT *Array = Allocator.Allocate<MVT>(3);
4032 SDVTList Result = makeVTList(Array, 4);
4033 VTList.push_back(Result);
4037 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
4039 case 0: assert(0 && "Cannot have nodes without results!");
4040 case 1: return getVTList(VTs[0]);
4041 case 2: return getVTList(VTs[0], VTs[1]);
4042 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4046 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4047 E = VTList.rend(); I != E; ++I) {
4048 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4051 bool NoMatch = false;
4052 for (unsigned i = 2; i != NumVTs; ++i)
4053 if (VTs[i] != I->VTs[i]) {
4061 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
4062 std::copy(VTs, VTs+NumVTs, Array);
4063 SDVTList Result = makeVTList(Array, NumVTs);
4064 VTList.push_back(Result);
4069 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4070 /// specified operands. If the resultant node already exists in the DAG,
4071 /// this does not modify the specified node, instead it returns the node that
4072 /// already exists. If the resultant node does not exist in the DAG, the
4073 /// input node is returned. As a degenerate case, if you specify the same
4074 /// input operands as the node already has, the input node is returned.
4075 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4076 SDNode *N = InN.getNode();
4077 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4079 // Check to see if there is no change.
4080 if (Op == N->getOperand(0)) return InN;
4082 // See if the modified node already exists.
4083 void *InsertPos = 0;
4084 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4085 return SDValue(Existing, InN.getResNo());
4087 // Nope it doesn't. Remove the node from its current place in the maps.
4089 if (!RemoveNodeFromCSEMaps(N))
4092 // Now we update the operands.
4093 N->OperandList[0].set(Op);
4095 // If this gets put into a CSE map, add it.
4096 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4100 SDValue SelectionDAG::
4101 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4102 SDNode *N = InN.getNode();
4103 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4105 // Check to see if there is no change.
4106 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4107 return InN; // No operands changed, just return the input node.
4109 // See if the modified node already exists.
4110 void *InsertPos = 0;
4111 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4112 return SDValue(Existing, InN.getResNo());
4114 // Nope it doesn't. Remove the node from its current place in the maps.
4116 if (!RemoveNodeFromCSEMaps(N))
4119 // Now we update the operands.
4120 if (N->OperandList[0] != Op1)
4121 N->OperandList[0].set(Op1);
4122 if (N->OperandList[1] != Op2)
4123 N->OperandList[1].set(Op2);
4125 // If this gets put into a CSE map, add it.
4126 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4130 SDValue SelectionDAG::
4131 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4132 SDValue Ops[] = { Op1, Op2, Op3 };
4133 return UpdateNodeOperands(N, Ops, 3);
4136 SDValue SelectionDAG::
4137 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4138 SDValue Op3, SDValue Op4) {
4139 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4140 return UpdateNodeOperands(N, Ops, 4);
4143 SDValue SelectionDAG::
4144 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4145 SDValue Op3, SDValue Op4, SDValue Op5) {
4146 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4147 return UpdateNodeOperands(N, Ops, 5);
4150 SDValue SelectionDAG::
4151 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4152 SDNode *N = InN.getNode();
4153 assert(N->getNumOperands() == NumOps &&
4154 "Update with wrong number of operands");
4156 // Check to see if there is no change.
4157 bool AnyChange = false;
4158 for (unsigned i = 0; i != NumOps; ++i) {
4159 if (Ops[i] != N->getOperand(i)) {
4165 // No operands changed, just return the input node.
4166 if (!AnyChange) return InN;
4168 // See if the modified node already exists.
4169 void *InsertPos = 0;
4170 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4171 return SDValue(Existing, InN.getResNo());
4173 // Nope it doesn't. Remove the node from its current place in the maps.
4175 if (!RemoveNodeFromCSEMaps(N))
4178 // Now we update the operands.
4179 for (unsigned i = 0; i != NumOps; ++i)
4180 if (N->OperandList[i] != Ops[i])
4181 N->OperandList[i].set(Ops[i]);
4183 // If this gets put into a CSE map, add it.
4184 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4188 /// DropOperands - Release the operands and set this node to have
4190 void SDNode::DropOperands() {
4191 // Unlike the code in MorphNodeTo that does this, we don't need to
4192 // watch for dead nodes here.
4193 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4199 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4202 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4204 SDVTList VTs = getVTList(VT);
4205 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4208 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4209 MVT VT, SDValue Op1) {
4210 SDVTList VTs = getVTList(VT);
4211 SDValue Ops[] = { Op1 };
4212 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4215 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4216 MVT VT, SDValue Op1,
4218 SDVTList VTs = getVTList(VT);
4219 SDValue Ops[] = { Op1, Op2 };
4220 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4223 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4224 MVT VT, SDValue Op1,
4225 SDValue Op2, SDValue Op3) {
4226 SDVTList VTs = getVTList(VT);
4227 SDValue Ops[] = { Op1, Op2, Op3 };
4228 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4231 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4232 MVT VT, const SDValue *Ops,
4234 SDVTList VTs = getVTList(VT);
4235 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4238 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4239 MVT VT1, MVT VT2, const SDValue *Ops,
4241 SDVTList VTs = getVTList(VT1, VT2);
4242 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4245 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4247 SDVTList VTs = getVTList(VT1, VT2);
4248 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4251 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4252 MVT VT1, MVT VT2, MVT VT3,
4253 const SDValue *Ops, unsigned NumOps) {
4254 SDVTList VTs = getVTList(VT1, VT2, VT3);
4255 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4258 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4259 MVT VT1, MVT VT2, MVT VT3, MVT VT4,
4260 const SDValue *Ops, unsigned NumOps) {
4261 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4262 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4265 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4268 SDVTList VTs = getVTList(VT1, VT2);
4269 SDValue Ops[] = { Op1 };
4270 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4273 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4275 SDValue Op1, SDValue Op2) {
4276 SDVTList VTs = getVTList(VT1, VT2);
4277 SDValue Ops[] = { Op1, Op2 };
4278 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4281 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4283 SDValue Op1, SDValue Op2,
4285 SDVTList VTs = getVTList(VT1, VT2);
4286 SDValue Ops[] = { Op1, Op2, Op3 };
4287 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4290 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4291 MVT VT1, MVT VT2, MVT VT3,
4292 SDValue Op1, SDValue Op2,
4294 SDVTList VTs = getVTList(VT1, VT2, VT3);
4295 SDValue Ops[] = { Op1, Op2, Op3 };
4296 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4299 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4300 SDVTList VTs, const SDValue *Ops,
4302 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4305 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4307 SDVTList VTs = getVTList(VT);
4308 return MorphNodeTo(N, Opc, VTs, 0, 0);
4311 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4312 MVT VT, SDValue Op1) {
4313 SDVTList VTs = getVTList(VT);
4314 SDValue Ops[] = { Op1 };
4315 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4318 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4319 MVT VT, SDValue Op1,
4321 SDVTList VTs = getVTList(VT);
4322 SDValue Ops[] = { Op1, Op2 };
4323 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4326 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4327 MVT VT, SDValue Op1,
4328 SDValue Op2, SDValue Op3) {
4329 SDVTList VTs = getVTList(VT);
4330 SDValue Ops[] = { Op1, Op2, Op3 };
4331 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4334 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4335 MVT VT, const SDValue *Ops,
4337 SDVTList VTs = getVTList(VT);
4338 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4341 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4342 MVT VT1, MVT VT2, const SDValue *Ops,
4344 SDVTList VTs = getVTList(VT1, VT2);
4345 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4348 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4350 SDVTList VTs = getVTList(VT1, VT2);
4351 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4354 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4355 MVT VT1, MVT VT2, MVT VT3,
4356 const SDValue *Ops, unsigned NumOps) {
4357 SDVTList VTs = getVTList(VT1, VT2, VT3);
4358 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4361 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4364 SDVTList VTs = getVTList(VT1, VT2);
4365 SDValue Ops[] = { Op1 };
4366 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4369 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4371 SDValue Op1, SDValue Op2) {
4372 SDVTList VTs = getVTList(VT1, VT2);
4373 SDValue Ops[] = { Op1, Op2 };
4374 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4377 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4379 SDValue Op1, SDValue Op2,
4381 SDVTList VTs = getVTList(VT1, VT2);
4382 SDValue Ops[] = { Op1, Op2, Op3 };
4383 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4386 /// MorphNodeTo - These *mutate* the specified node to have the specified
4387 /// return type, opcode, and operands.
4389 /// Note that MorphNodeTo returns the resultant node. If there is already a
4390 /// node of the specified opcode and operands, it returns that node instead of
4391 /// the current one. Note that the DebugLoc need not be the same.
4393 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4394 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4395 /// node, and because it doesn't require CSE recalculation for any of
4396 /// the node's users.
4398 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4399 SDVTList VTs, const SDValue *Ops,
4401 // If an identical node already exists, use it.
4403 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4404 FoldingSetNodeID ID;
4405 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4406 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4410 if (!RemoveNodeFromCSEMaps(N))
4413 // Start the morphing.
4415 N->ValueList = VTs.VTs;
4416 N->NumValues = VTs.NumVTs;
4418 // Clear the operands list, updating used nodes to remove this from their
4419 // use list. Keep track of any operands that become dead as a result.
4420 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4421 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4423 SDNode *Used = Use.getNode();
4425 if (Used->use_empty())
4426 DeadNodeSet.insert(Used);
4429 // If NumOps is larger than the # of operands we currently have, reallocate
4430 // the operand list.
4431 if (NumOps > N->NumOperands) {
4432 if (N->OperandsNeedDelete)
4433 delete[] N->OperandList;
4435 if (N->isMachineOpcode()) {
4436 // We're creating a final node that will live unmorphed for the
4437 // remainder of the current SelectionDAG iteration, so we can allocate
4438 // the operands directly out of a pool with no recycling metadata.
4439 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4440 N->OperandsNeedDelete = false;
4442 N->OperandList = new SDUse[NumOps];
4443 N->OperandsNeedDelete = true;
4447 // Assign the new operands.
4448 N->NumOperands = NumOps;
4449 for (unsigned i = 0, e = NumOps; i != e; ++i) {
4450 N->OperandList[i].setUser(N);
4451 N->OperandList[i].setInitial(Ops[i]);
4454 // Delete any nodes that are still dead after adding the uses for the
4456 SmallVector<SDNode *, 16> DeadNodes;
4457 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4458 E = DeadNodeSet.end(); I != E; ++I)
4459 if ((*I)->use_empty())
4460 DeadNodes.push_back(*I);
4461 RemoveDeadNodes(DeadNodes);
4464 CSEMap.InsertNode(N, IP); // Memoize the new node.
4469 /// getTargetNode - These are used for target selectors to create a new node
4470 /// with specified return type(s), target opcode, and operands.
4472 /// Note that getTargetNode returns the resultant node. If there is already a
4473 /// node of the specified opcode and operands, it returns that node instead of
4474 /// the current one.
4475 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT) {
4476 return getNode(~Opcode, dl, VT).getNode();
4479 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4481 return getNode(~Opcode, dl, VT, Op1).getNode();
4484 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4485 SDValue Op1, SDValue Op2) {
4486 return getNode(~Opcode, dl, VT, Op1, Op2).getNode();
4489 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4490 SDValue Op1, SDValue Op2,
4492 return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode();
4495 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4496 const SDValue *Ops, unsigned NumOps) {
4497 return getNode(~Opcode, dl, VT, Ops, NumOps).getNode();
4500 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4502 SDVTList VTs = getVTList(VT1, VT2);
4504 return getNode(~Opcode, dl, VTs, &Op, 0).getNode();
4507 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4508 MVT VT2, SDValue Op1) {
4509 SDVTList VTs = getVTList(VT1, VT2);
4510 return getNode(~Opcode, dl, VTs, &Op1, 1).getNode();
4513 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4514 MVT VT2, SDValue Op1,
4516 SDVTList VTs = getVTList(VT1, VT2);
4517 SDValue Ops[] = { Op1, Op2 };
4518 return getNode(~Opcode, dl, VTs, Ops, 2).getNode();
4521 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4522 MVT VT2, SDValue Op1,
4523 SDValue Op2, SDValue Op3) {
4524 SDVTList VTs = getVTList(VT1, VT2);
4525 SDValue Ops[] = { Op1, Op2, Op3 };
4526 return getNode(~Opcode, dl, VTs, Ops, 3).getNode();
4529 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4531 const SDValue *Ops, unsigned NumOps) {
4532 SDVTList VTs = getVTList(VT1, VT2);
4533 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
4536 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4537 MVT VT1, MVT VT2, MVT VT3,
4538 SDValue Op1, SDValue Op2) {
4539 SDVTList VTs = getVTList(VT1, VT2, VT3);
4540 SDValue Ops[] = { Op1, Op2 };
4541 return getNode(~Opcode, dl, VTs, Ops, 2).getNode();
4544 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4545 MVT VT1, MVT VT2, MVT VT3,
4546 SDValue Op1, SDValue Op2,
4548 SDVTList VTs = getVTList(VT1, VT2, VT3);
4549 SDValue Ops[] = { Op1, Op2, Op3 };
4550 return getNode(~Opcode, dl, VTs, Ops, 3).getNode();
4553 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4554 MVT VT1, MVT VT2, MVT VT3,
4555 const SDValue *Ops, unsigned NumOps) {
4556 SDVTList VTs = getVTList(VT1, VT2, VT3);
4557 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
4560 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4561 MVT VT2, MVT VT3, MVT VT4,
4562 const SDValue *Ops, unsigned NumOps) {
4563 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4564 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
4567 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4568 const std::vector<MVT> &ResultTys,
4569 const SDValue *Ops, unsigned NumOps) {
4570 return getNode(~Opcode, dl, ResultTys, Ops, NumOps).getNode();
4573 /// getNodeIfExists - Get the specified node if it's already available, or
4574 /// else return NULL.
4575 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4576 const SDValue *Ops, unsigned NumOps) {
4577 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4578 FoldingSetNodeID ID;
4579 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4581 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4587 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4588 /// This can cause recursive merging of nodes in the DAG.
4590 /// This version assumes From has a single result value.
4592 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4593 DAGUpdateListener *UpdateListener) {
4594 SDNode *From = FromN.getNode();
4595 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4596 "Cannot replace with this method!");
4597 assert(From != To.getNode() && "Cannot replace uses of with self");
4599 // Iterate over all the existing uses of From. New uses will be added
4600 // to the beginning of the use list, which we avoid visiting.
4601 // This specifically avoids visiting uses of From that arise while the
4602 // replacement is happening, because any such uses would be the result
4603 // of CSE: If an existing node looks like From after one of its operands
4604 // is replaced by To, we don't want to replace of all its users with To
4605 // too. See PR3018 for more info.
4606 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4610 // This node is about to morph, remove its old self from the CSE maps.
4611 RemoveNodeFromCSEMaps(User);
4613 // A user can appear in a use list multiple times, and when this
4614 // happens the uses are usually next to each other in the list.
4615 // To help reduce the number of CSE recomputations, process all
4616 // the uses of this user that we can find this way.
4618 SDUse &Use = UI.getUse();
4621 } while (UI != UE && *UI == User);
4623 // Now that we have modified User, add it back to the CSE maps. If it
4624 // already exists there, recursively merge the results together.
4625 AddModifiedNodeToCSEMaps(User, UpdateListener);
4629 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4630 /// This can cause recursive merging of nodes in the DAG.
4632 /// This version assumes that for each value of From, there is a
4633 /// corresponding value in To in the same position with the same type.
4635 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4636 DAGUpdateListener *UpdateListener) {
4638 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
4639 assert((!From->hasAnyUseOfValue(i) ||
4640 From->getValueType(i) == To->getValueType(i)) &&
4641 "Cannot use this version of ReplaceAllUsesWith!");
4644 // Handle the trivial case.
4648 // Iterate over just the existing users of From. See the comments in
4649 // the ReplaceAllUsesWith above.
4650 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4654 // This node is about to morph, remove its old self from the CSE maps.
4655 RemoveNodeFromCSEMaps(User);
4657 // A user can appear in a use list multiple times, and when this
4658 // happens the uses are usually next to each other in the list.
4659 // To help reduce the number of CSE recomputations, process all
4660 // the uses of this user that we can find this way.
4662 SDUse &Use = UI.getUse();
4665 } while (UI != UE && *UI == User);
4667 // Now that we have modified User, add it back to the CSE maps. If it
4668 // already exists there, recursively merge the results together.
4669 AddModifiedNodeToCSEMaps(User, UpdateListener);
4673 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4674 /// This can cause recursive merging of nodes in the DAG.
4676 /// This version can replace From with any result values. To must match the
4677 /// number and types of values returned by From.
4678 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4680 DAGUpdateListener *UpdateListener) {
4681 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4682 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4684 // Iterate over just the existing users of From. See the comments in
4685 // the ReplaceAllUsesWith above.
4686 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4690 // This node is about to morph, remove its old self from the CSE maps.
4691 RemoveNodeFromCSEMaps(User);
4693 // A user can appear in a use list multiple times, and when this
4694 // happens the uses are usually next to each other in the list.
4695 // To help reduce the number of CSE recomputations, process all
4696 // the uses of this user that we can find this way.
4698 SDUse &Use = UI.getUse();
4699 const SDValue &ToOp = To[Use.getResNo()];
4702 } while (UI != UE && *UI == User);
4704 // Now that we have modified User, add it back to the CSE maps. If it
4705 // already exists there, recursively merge the results together.
4706 AddModifiedNodeToCSEMaps(User, UpdateListener);
4710 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4711 /// uses of other values produced by From.getNode() alone. The Deleted
4712 /// vector is handled the same way as for ReplaceAllUsesWith.
4713 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4714 DAGUpdateListener *UpdateListener){
4715 // Handle the really simple, really trivial case efficiently.
4716 if (From == To) return;
4718 // Handle the simple, trivial, case efficiently.
4719 if (From.getNode()->getNumValues() == 1) {
4720 ReplaceAllUsesWith(From, To, UpdateListener);
4724 // Iterate over just the existing users of From. See the comments in
4725 // the ReplaceAllUsesWith above.
4726 SDNode::use_iterator UI = From.getNode()->use_begin(),
4727 UE = From.getNode()->use_end();
4730 bool UserRemovedFromCSEMaps = false;
4732 // A user can appear in a use list multiple times, and when this
4733 // happens the uses are usually next to each other in the list.
4734 // To help reduce the number of CSE recomputations, process all
4735 // the uses of this user that we can find this way.
4737 SDUse &Use = UI.getUse();
4739 // Skip uses of different values from the same node.
4740 if (Use.getResNo() != From.getResNo()) {
4745 // If this node hasn't been modified yet, it's still in the CSE maps,
4746 // so remove its old self from the CSE maps.
4747 if (!UserRemovedFromCSEMaps) {
4748 RemoveNodeFromCSEMaps(User);
4749 UserRemovedFromCSEMaps = true;
4754 } while (UI != UE && *UI == User);
4756 // We are iterating over all uses of the From node, so if a use
4757 // doesn't use the specific value, no changes are made.
4758 if (!UserRemovedFromCSEMaps)
4761 // Now that we have modified User, add it back to the CSE maps. If it
4762 // already exists there, recursively merge the results together.
4763 AddModifiedNodeToCSEMaps(User, UpdateListener);
4768 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
4769 /// to record information about a use.
4776 /// operator< - Sort Memos by User.
4777 bool operator<(const UseMemo &L, const UseMemo &R) {
4778 return (intptr_t)L.User < (intptr_t)R.User;
4782 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4783 /// uses of other values produced by From.getNode() alone. The same value
4784 /// may appear in both the From and To list. The Deleted vector is
4785 /// handled the same way as for ReplaceAllUsesWith.
4786 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4789 DAGUpdateListener *UpdateListener){
4790 // Handle the simple, trivial case efficiently.
4792 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4794 // Read up all the uses and make records of them. This helps
4795 // processing new uses that are introduced during the
4796 // replacement process.
4797 SmallVector<UseMemo, 4> Uses;
4798 for (unsigned i = 0; i != Num; ++i) {
4799 unsigned FromResNo = From[i].getResNo();
4800 SDNode *FromNode = From[i].getNode();
4801 for (SDNode::use_iterator UI = FromNode->use_begin(),
4802 E = FromNode->use_end(); UI != E; ++UI) {
4803 SDUse &Use = UI.getUse();
4804 if (Use.getResNo() == FromResNo) {
4805 UseMemo Memo = { *UI, i, &Use };
4806 Uses.push_back(Memo);
4811 // Sort the uses, so that all the uses from a given User are together.
4812 std::sort(Uses.begin(), Uses.end());
4814 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
4815 UseIndex != UseIndexEnd; ) {
4816 // We know that this user uses some value of From. If it is the right
4817 // value, update it.
4818 SDNode *User = Uses[UseIndex].User;
4820 // This node is about to morph, remove its old self from the CSE maps.
4821 RemoveNodeFromCSEMaps(User);
4823 // The Uses array is sorted, so all the uses for a given User
4824 // are next to each other in the list.
4825 // To help reduce the number of CSE recomputations, process all
4826 // the uses of this user that we can find this way.
4828 unsigned i = Uses[UseIndex].Index;
4829 SDUse &Use = *Uses[UseIndex].Use;
4833 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
4835 // Now that we have modified User, add it back to the CSE maps. If it
4836 // already exists there, recursively merge the results together.
4837 AddModifiedNodeToCSEMaps(User, UpdateListener);
4841 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4842 /// based on their topological order. It returns the maximum id and a vector
4843 /// of the SDNodes* in assigned order by reference.
4844 unsigned SelectionDAG::AssignTopologicalOrder() {
4846 unsigned DAGSize = 0;
4848 // SortedPos tracks the progress of the algorithm. Nodes before it are
4849 // sorted, nodes after it are unsorted. When the algorithm completes
4850 // it is at the end of the list.
4851 allnodes_iterator SortedPos = allnodes_begin();
4853 // Visit all the nodes. Move nodes with no operands to the front of
4854 // the list immediately. Annotate nodes that do have operands with their
4855 // operand count. Before we do this, the Node Id fields of the nodes
4856 // may contain arbitrary values. After, the Node Id fields for nodes
4857 // before SortedPos will contain the topological sort index, and the
4858 // Node Id fields for nodes At SortedPos and after will contain the
4859 // count of outstanding operands.
4860 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
4862 unsigned Degree = N->getNumOperands();
4864 // A node with no uses, add it to the result array immediately.
4865 N->setNodeId(DAGSize++);
4866 allnodes_iterator Q = N;
4868 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
4871 // Temporarily use the Node Id as scratch space for the degree count.
4872 N->setNodeId(Degree);
4876 // Visit all the nodes. As we iterate, moves nodes into sorted order,
4877 // such that by the time the end is reached all nodes will be sorted.
4878 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
4880 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4883 unsigned Degree = P->getNodeId();
4886 // All of P's operands are sorted, so P may sorted now.
4887 P->setNodeId(DAGSize++);
4889 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
4892 // Update P's outstanding operand count.
4893 P->setNodeId(Degree);
4898 assert(SortedPos == AllNodes.end() &&
4899 "Topological sort incomplete!");
4900 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
4901 "First node in topological sort is not the entry token!");
4902 assert(AllNodes.front().getNodeId() == 0 &&
4903 "First node in topological sort has non-zero id!");
4904 assert(AllNodes.front().getNumOperands() == 0 &&
4905 "First node in topological sort has operands!");
4906 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
4907 "Last node in topologic sort has unexpected id!");
4908 assert(AllNodes.back().use_empty() &&
4909 "Last node in topologic sort has users!");
4910 assert(DAGSize == allnodes_size() && "Node count mismatch!");
4916 //===----------------------------------------------------------------------===//
4918 //===----------------------------------------------------------------------===//
4920 HandleSDNode::~HandleSDNode() {
4924 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4925 MVT VT, int64_t o, unsigned char TF)
4926 : SDNode(isa<GlobalVariable>(GA) &&
4927 cast<GlobalVariable>(GA)->isThreadLocal() ?
4929 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4931 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4932 DebugLoc::getUnknownLoc(), getSDVTList(VT)),
4933 Offset(o), TargetFlags(TF) {
4934 TheGlobal = const_cast<GlobalValue*>(GA);
4937 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, MVT memvt,
4938 const Value *srcValue, int SVO,
4939 unsigned alignment, bool vol)
4940 : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
4941 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
4942 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4943 assert(getAlignment() == alignment && "Alignment representation error!");
4944 assert(isVolatile() == vol && "Volatile representation error!");
4947 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
4949 unsigned NumOps, MVT memvt, const Value *srcValue,
4950 int SVO, unsigned alignment, bool vol)
4951 : SDNode(Opc, dl, VTs, Ops, NumOps),
4952 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
4953 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
4954 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4955 assert(getAlignment() == alignment && "Alignment representation error!");
4956 assert(isVolatile() == vol && "Volatile representation error!");
4959 /// getMemOperand - Return a MachineMemOperand object describing the memory
4960 /// reference performed by this memory reference.
4961 MachineMemOperand MemSDNode::getMemOperand() const {
4963 if (isa<LoadSDNode>(this))
4964 Flags = MachineMemOperand::MOLoad;
4965 else if (isa<StoreSDNode>(this))
4966 Flags = MachineMemOperand::MOStore;
4967 else if (isa<AtomicSDNode>(this)) {
4968 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4971 const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
4972 assert(MemIntrinNode && "Unknown MemSDNode opcode!");
4973 if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
4974 if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
4977 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4978 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4980 // Check if the memory reference references a frame index
4981 const FrameIndexSDNode *FI =
4982 dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
4983 if (!getSrcValue() && FI)
4984 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
4985 Flags, 0, Size, getAlignment());
4987 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4988 Size, getAlignment());
4991 /// Profile - Gather unique data for the node.
4993 void SDNode::Profile(FoldingSetNodeID &ID) const {
4994 AddNodeIDNode(ID, this);
4997 static ManagedStatic<std::set<MVT, MVT::compareRawBits> > EVTs;
4998 static MVT VTs[MVT::LAST_VALUETYPE];
4999 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5001 /// getValueTypeList - Return a pointer to the specified value type.
5003 const MVT *SDNode::getValueTypeList(MVT VT) {
5004 sys::SmartScopedLock<true> Lock(&*VTMutex);
5005 if (VT.isExtended()) {
5006 return &(*EVTs->insert(VT).first);
5008 VTs[VT.getSimpleVT()] = VT;
5009 return &VTs[VT.getSimpleVT()];
5013 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5014 /// indicated value. This method ignores uses of other values defined by this
5016 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5017 assert(Value < getNumValues() && "Bad value!");
5019 // TODO: Only iterate over uses of a given value of the node
5020 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5021 if (UI.getUse().getResNo() == Value) {
5028 // Found exactly the right number of uses?
5033 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5034 /// value. This method ignores uses of other values defined by this operation.
5035 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5036 assert(Value < getNumValues() && "Bad value!");
5038 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5039 if (UI.getUse().getResNo() == Value)
5046 /// isOnlyUserOf - Return true if this node is the only use of N.
5048 bool SDNode::isOnlyUserOf(SDNode *N) const {
5050 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5061 /// isOperand - Return true if this node is an operand of N.
5063 bool SDValue::isOperandOf(SDNode *N) const {
5064 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5065 if (*this == N->getOperand(i))
5070 bool SDNode::isOperandOf(SDNode *N) const {
5071 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5072 if (this == N->OperandList[i].getNode())
5077 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5078 /// be a chain) reaches the specified operand without crossing any
5079 /// side-effecting instructions. In practice, this looks through token
5080 /// factors and non-volatile loads. In order to remain efficient, this only
5081 /// looks a couple of nodes in, it does not do an exhaustive search.
5082 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5083 unsigned Depth) const {
5084 if (*this == Dest) return true;
5086 // Don't search too deeply, we just want to be able to see through
5087 // TokenFactor's etc.
5088 if (Depth == 0) return false;
5090 // If this is a token factor, all inputs to the TF happen in parallel. If any
5091 // of the operands of the TF reach dest, then we can do the xform.
5092 if (getOpcode() == ISD::TokenFactor) {
5093 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5094 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5099 // Loads don't have side effects, look through them.
5100 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5101 if (!Ld->isVolatile())
5102 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5108 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
5109 SmallPtrSet<SDNode *, 32> &Visited) {
5110 if (found || !Visited.insert(N))
5113 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
5114 SDNode *Op = N->getOperand(i).getNode();
5119 findPredecessor(Op, P, found, Visited);
5123 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5124 /// is either an operand of N or it can be reached by recursively traversing
5125 /// up the operands.
5126 /// NOTE: this is an expensive method. Use it carefully.
5127 bool SDNode::isPredecessorOf(SDNode *N) const {
5128 SmallPtrSet<SDNode *, 32> Visited;
5130 findPredecessor(N, this, found, Visited);
5134 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5135 assert(Num < NumOperands && "Invalid child # of SDNode!");
5136 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5139 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5140 switch (getOpcode()) {
5142 if (getOpcode() < ISD::BUILTIN_OP_END)
5143 return "<<Unknown DAG Node>>";
5144 if (isMachineOpcode()) {
5146 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5147 if (getMachineOpcode() < TII->getNumOpcodes())
5148 return TII->get(getMachineOpcode()).getName();
5149 return "<<Unknown Machine Node>>";
5152 const TargetLowering &TLI = G->getTargetLoweringInfo();
5153 const char *Name = TLI.getTargetNodeName(getOpcode());
5154 if (Name) return Name;
5155 return "<<Unknown Target Node>>";
5157 return "<<Unknown Node>>";
5160 case ISD::DELETED_NODE:
5161 return "<<Deleted Node!>>";
5163 case ISD::PREFETCH: return "Prefetch";
5164 case ISD::MEMBARRIER: return "MemBarrier";
5165 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5166 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5167 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5168 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5169 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5170 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5171 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5172 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5173 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5174 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5175 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5176 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5177 case ISD::PCMARKER: return "PCMarker";
5178 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5179 case ISD::SRCVALUE: return "SrcValue";
5180 case ISD::MEMOPERAND: return "MemOperand";
5181 case ISD::EntryToken: return "EntryToken";
5182 case ISD::TokenFactor: return "TokenFactor";
5183 case ISD::AssertSext: return "AssertSext";
5184 case ISD::AssertZext: return "AssertZext";
5186 case ISD::BasicBlock: return "BasicBlock";
5187 case ISD::ARG_FLAGS: return "ArgFlags";
5188 case ISD::VALUETYPE: return "ValueType";
5189 case ISD::Register: return "Register";
5191 case ISD::Constant: return "Constant";
5192 case ISD::ConstantFP: return "ConstantFP";
5193 case ISD::GlobalAddress: return "GlobalAddress";
5194 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5195 case ISD::FrameIndex: return "FrameIndex";
5196 case ISD::JumpTable: return "JumpTable";
5197 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5198 case ISD::RETURNADDR: return "RETURNADDR";
5199 case ISD::FRAMEADDR: return "FRAMEADDR";
5200 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5201 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5202 case ISD::EHSELECTION: return "EHSELECTION";
5203 case ISD::EH_RETURN: return "EH_RETURN";
5204 case ISD::ConstantPool: return "ConstantPool";
5205 case ISD::ExternalSymbol: return "ExternalSymbol";
5206 case ISD::INTRINSIC_WO_CHAIN: {
5207 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
5208 return Intrinsic::getName((Intrinsic::ID)IID);
5210 case ISD::INTRINSIC_VOID:
5211 case ISD::INTRINSIC_W_CHAIN: {
5212 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
5213 return Intrinsic::getName((Intrinsic::ID)IID);
5216 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5217 case ISD::TargetConstant: return "TargetConstant";
5218 case ISD::TargetConstantFP:return "TargetConstantFP";
5219 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5220 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5221 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5222 case ISD::TargetJumpTable: return "TargetJumpTable";
5223 case ISD::TargetConstantPool: return "TargetConstantPool";
5224 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5226 case ISD::CopyToReg: return "CopyToReg";
5227 case ISD::CopyFromReg: return "CopyFromReg";
5228 case ISD::UNDEF: return "undef";
5229 case ISD::MERGE_VALUES: return "merge_values";
5230 case ISD::INLINEASM: return "inlineasm";
5231 case ISD::DBG_LABEL: return "dbg_label";
5232 case ISD::EH_LABEL: return "eh_label";
5233 case ISD::DECLARE: return "declare";
5234 case ISD::HANDLENODE: return "handlenode";
5235 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
5236 case ISD::CALL: return "call";
5239 case ISD::FABS: return "fabs";
5240 case ISD::FNEG: return "fneg";
5241 case ISD::FSQRT: return "fsqrt";
5242 case ISD::FSIN: return "fsin";
5243 case ISD::FCOS: return "fcos";
5244 case ISD::FPOWI: return "fpowi";
5245 case ISD::FPOW: return "fpow";
5246 case ISD::FTRUNC: return "ftrunc";
5247 case ISD::FFLOOR: return "ffloor";
5248 case ISD::FCEIL: return "fceil";
5249 case ISD::FRINT: return "frint";
5250 case ISD::FNEARBYINT: return "fnearbyint";
5253 case ISD::ADD: return "add";
5254 case ISD::SUB: return "sub";
5255 case ISD::MUL: return "mul";
5256 case ISD::MULHU: return "mulhu";
5257 case ISD::MULHS: return "mulhs";
5258 case ISD::SDIV: return "sdiv";
5259 case ISD::UDIV: return "udiv";
5260 case ISD::SREM: return "srem";
5261 case ISD::UREM: return "urem";
5262 case ISD::SMUL_LOHI: return "smul_lohi";
5263 case ISD::UMUL_LOHI: return "umul_lohi";
5264 case ISD::SDIVREM: return "sdivrem";
5265 case ISD::UDIVREM: return "udivrem";
5266 case ISD::AND: return "and";
5267 case ISD::OR: return "or";
5268 case ISD::XOR: return "xor";
5269 case ISD::SHL: return "shl";
5270 case ISD::SRA: return "sra";
5271 case ISD::SRL: return "srl";
5272 case ISD::ROTL: return "rotl";
5273 case ISD::ROTR: return "rotr";
5274 case ISD::FADD: return "fadd";
5275 case ISD::FSUB: return "fsub";
5276 case ISD::FMUL: return "fmul";
5277 case ISD::FDIV: return "fdiv";
5278 case ISD::FREM: return "frem";
5279 case ISD::FCOPYSIGN: return "fcopysign";
5280 case ISD::FGETSIGN: return "fgetsign";
5282 case ISD::SETCC: return "setcc";
5283 case ISD::VSETCC: return "vsetcc";
5284 case ISD::SELECT: return "select";
5285 case ISD::SELECT_CC: return "select_cc";
5286 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5287 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5288 case ISD::CONCAT_VECTORS: return "concat_vectors";
5289 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5290 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5291 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5292 case ISD::CARRY_FALSE: return "carry_false";
5293 case ISD::ADDC: return "addc";
5294 case ISD::ADDE: return "adde";
5295 case ISD::SADDO: return "saddo";
5296 case ISD::UADDO: return "uaddo";
5297 case ISD::SSUBO: return "ssubo";
5298 case ISD::USUBO: return "usubo";
5299 case ISD::SMULO: return "smulo";
5300 case ISD::UMULO: return "umulo";
5301 case ISD::SUBC: return "subc";
5302 case ISD::SUBE: return "sube";
5303 case ISD::SHL_PARTS: return "shl_parts";
5304 case ISD::SRA_PARTS: return "sra_parts";
5305 case ISD::SRL_PARTS: return "srl_parts";
5307 // Conversion operators.
5308 case ISD::SIGN_EXTEND: return "sign_extend";
5309 case ISD::ZERO_EXTEND: return "zero_extend";
5310 case ISD::ANY_EXTEND: return "any_extend";
5311 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5312 case ISD::TRUNCATE: return "truncate";
5313 case ISD::FP_ROUND: return "fp_round";
5314 case ISD::FLT_ROUNDS_: return "flt_rounds";
5315 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5316 case ISD::FP_EXTEND: return "fp_extend";
5318 case ISD::SINT_TO_FP: return "sint_to_fp";
5319 case ISD::UINT_TO_FP: return "uint_to_fp";
5320 case ISD::FP_TO_SINT: return "fp_to_sint";
5321 case ISD::FP_TO_UINT: return "fp_to_uint";
5322 case ISD::BIT_CONVERT: return "bit_convert";
5324 case ISD::CONVERT_RNDSAT: {
5325 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5326 default: assert(0 && "Unknown cvt code!");
5327 case ISD::CVT_FF: return "cvt_ff";
5328 case ISD::CVT_FS: return "cvt_fs";
5329 case ISD::CVT_FU: return "cvt_fu";
5330 case ISD::CVT_SF: return "cvt_sf";
5331 case ISD::CVT_UF: return "cvt_uf";
5332 case ISD::CVT_SS: return "cvt_ss";
5333 case ISD::CVT_SU: return "cvt_su";
5334 case ISD::CVT_US: return "cvt_us";
5335 case ISD::CVT_UU: return "cvt_uu";
5339 // Control flow instructions
5340 case ISD::BR: return "br";
5341 case ISD::BRIND: return "brind";
5342 case ISD::BR_JT: return "br_jt";
5343 case ISD::BRCOND: return "brcond";
5344 case ISD::BR_CC: return "br_cc";
5345 case ISD::RET: return "ret";
5346 case ISD::CALLSEQ_START: return "callseq_start";
5347 case ISD::CALLSEQ_END: return "callseq_end";
5350 case ISD::LOAD: return "load";
5351 case ISD::STORE: return "store";
5352 case ISD::VAARG: return "vaarg";
5353 case ISD::VACOPY: return "vacopy";
5354 case ISD::VAEND: return "vaend";
5355 case ISD::VASTART: return "vastart";
5356 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5357 case ISD::EXTRACT_ELEMENT: return "extract_element";
5358 case ISD::BUILD_PAIR: return "build_pair";
5359 case ISD::STACKSAVE: return "stacksave";
5360 case ISD::STACKRESTORE: return "stackrestore";
5361 case ISD::TRAP: return "trap";
5364 case ISD::BSWAP: return "bswap";
5365 case ISD::CTPOP: return "ctpop";
5366 case ISD::CTTZ: return "cttz";
5367 case ISD::CTLZ: return "ctlz";
5370 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5371 case ISD::DEBUG_LOC: return "debug_loc";
5374 case ISD::TRAMPOLINE: return "trampoline";
5377 switch (cast<CondCodeSDNode>(this)->get()) {
5378 default: assert(0 && "Unknown setcc condition!");
5379 case ISD::SETOEQ: return "setoeq";
5380 case ISD::SETOGT: return "setogt";
5381 case ISD::SETOGE: return "setoge";
5382 case ISD::SETOLT: return "setolt";
5383 case ISD::SETOLE: return "setole";
5384 case ISD::SETONE: return "setone";
5386 case ISD::SETO: return "seto";
5387 case ISD::SETUO: return "setuo";
5388 case ISD::SETUEQ: return "setue";
5389 case ISD::SETUGT: return "setugt";
5390 case ISD::SETUGE: return "setuge";
5391 case ISD::SETULT: return "setult";
5392 case ISD::SETULE: return "setule";
5393 case ISD::SETUNE: return "setune";
5395 case ISD::SETEQ: return "seteq";
5396 case ISD::SETGT: return "setgt";
5397 case ISD::SETGE: return "setge";
5398 case ISD::SETLT: return "setlt";
5399 case ISD::SETLE: return "setle";
5400 case ISD::SETNE: return "setne";
5405 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5414 return "<post-inc>";
5416 return "<post-dec>";
5420 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5421 std::string S = "< ";
5435 if (getByValAlign())
5436 S += "byval-align:" + utostr(getByValAlign()) + " ";
5438 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5440 S += "byval-size:" + utostr(getByValSize()) + " ";
5444 void SDNode::dump() const { dump(0); }
5445 void SDNode::dump(const SelectionDAG *G) const {
5449 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5450 OS << (void*)this << ": ";
5452 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5454 if (getValueType(i) == MVT::Other)
5457 OS << getValueType(i).getMVTString();
5459 OS << " = " << getOperationName(G);
5462 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5463 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5464 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(this);
5466 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5467 int Idx = SVN->getMaskElt(i);
5477 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5478 OS << '<' << CSDN->getAPIntValue() << '>';
5479 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5480 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5481 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5482 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5483 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5486 CSDN->getValueAPF().bitcastToAPInt().dump();
5489 } else if (const GlobalAddressSDNode *GADN =
5490 dyn_cast<GlobalAddressSDNode>(this)) {
5491 int64_t offset = GADN->getOffset();
5493 WriteAsOperand(OS, GADN->getGlobal());
5496 OS << " + " << offset;
5498 OS << " " << offset;
5499 if (unsigned char TF = GADN->getTargetFlags())
5500 OS << " [TF=" << TF << ']';
5501 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5502 OS << "<" << FIDN->getIndex() << ">";
5503 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5504 OS << "<" << JTDN->getIndex() << ">";
5505 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5506 int offset = CP->getOffset();
5507 if (CP->isMachineConstantPoolEntry())
5508 OS << "<" << *CP->getMachineCPVal() << ">";
5510 OS << "<" << *CP->getConstVal() << ">";
5512 OS << " + " << offset;
5514 OS << " " << offset;
5515 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5517 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5519 OS << LBB->getName() << " ";
5520 OS << (const void*)BBDN->getBasicBlock() << ">";
5521 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5522 if (G && R->getReg() &&
5523 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5524 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5526 OS << " #" << R->getReg();
5528 } else if (const ExternalSymbolSDNode *ES =
5529 dyn_cast<ExternalSymbolSDNode>(this)) {
5530 OS << "'" << ES->getSymbol() << "'";
5531 if (unsigned char TF = GADN->getTargetFlags())
5532 OS << " [TF=" << TF << ']';
5533 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5535 OS << "<" << M->getValue() << ">";
5538 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5539 if (M->MO.getValue())
5540 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5542 OS << "<null:" << M->MO.getOffset() << ">";
5543 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5544 OS << N->getArgFlags().getArgFlagsString();
5545 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5546 OS << ":" << N->getVT().getMVTString();
5548 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5549 const Value *SrcValue = LD->getSrcValue();
5550 int SrcOffset = LD->getSrcValueOffset();
5556 OS << ":" << SrcOffset << ">";
5559 switch (LD->getExtensionType()) {
5560 default: doExt = false; break;
5561 case ISD::EXTLOAD: OS << " <anyext "; break;
5562 case ISD::SEXTLOAD: OS << " <sext "; break;
5563 case ISD::ZEXTLOAD: OS << " <zext "; break;
5566 OS << LD->getMemoryVT().getMVTString() << ">";
5568 const char *AM = getIndexedModeName(LD->getAddressingMode());
5571 if (LD->isVolatile())
5572 OS << " <volatile>";
5573 OS << " alignment=" << LD->getAlignment();
5574 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5575 const Value *SrcValue = ST->getSrcValue();
5576 int SrcOffset = ST->getSrcValueOffset();
5582 OS << ":" << SrcOffset << ">";
5584 if (ST->isTruncatingStore())
5585 OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
5587 const char *AM = getIndexedModeName(ST->getAddressingMode());
5590 if (ST->isVolatile())
5591 OS << " <volatile>";
5592 OS << " alignment=" << ST->getAlignment();
5593 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5594 const Value *SrcValue = AT->getSrcValue();
5595 int SrcOffset = AT->getSrcValueOffset();
5601 OS << ":" << SrcOffset << ">";
5602 if (AT->isVolatile())
5603 OS << " <volatile>";
5604 OS << " alignment=" << AT->getAlignment();
5608 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5611 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5613 OS << (void*)getOperand(i).getNode();
5614 if (unsigned RN = getOperand(i).getResNo())
5617 print_details(OS, G);
5620 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5621 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5622 if (N->getOperand(i).getNode()->hasOneUse())
5623 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5625 cerr << "\n" << std::string(indent+2, ' ')
5626 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5629 cerr << "\n" << std::string(indent, ' ');
5633 void SelectionDAG::dump() const {
5634 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5636 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5638 const SDNode *N = I;
5639 if (!N->hasOneUse() && N != getRoot().getNode())
5640 DumpNodes(N, 2, this);
5643 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5648 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
5650 print_details(OS, G);
5653 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
5654 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
5655 const SelectionDAG *G, VisitedSDNodeSet &once) {
5656 if (!once.insert(N)) // If we've been here before, return now.
5658 // Dump the current SDNode, but don't end the line yet.
5659 OS << std::string(indent, ' ');
5661 // Having printed this SDNode, walk the children:
5662 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5663 const SDNode *child = N->getOperand(i).getNode();
5666 if (child->getNumOperands() == 0) {
5667 // This child has no grandchildren; print it inline right here.
5668 child->printr(OS, G);
5670 } else { // Just the address. FIXME: also print the child's opcode
5672 if (unsigned RN = N->getOperand(i).getResNo())
5677 // Dump children that have grandchildren on their own line(s).
5678 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5679 const SDNode *child = N->getOperand(i).getNode();
5680 DumpNodesr(OS, child, indent+2, G, once);
5684 void SDNode::dumpr() const {
5685 VisitedSDNodeSet once;
5686 DumpNodesr(errs(), this, 0, 0, once);
5690 // getAddressSpace - Return the address space this GlobalAddress belongs to.
5691 unsigned GlobalAddressSDNode::getAddressSpace() const {
5692 return getGlobal()->getType()->getAddressSpace();
5696 const Type *ConstantPoolSDNode::getType() const {
5697 if (isMachineConstantPoolEntry())
5698 return Val.MachineCPVal->getType();
5699 return Val.ConstVal->getType();
5702 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
5704 unsigned &SplatBitSize,
5706 unsigned MinSplatBits) {
5707 MVT VT = getValueType(0);
5708 assert(VT.isVector() && "Expected a vector type");
5709 unsigned sz = VT.getSizeInBits();
5710 if (MinSplatBits > sz)
5713 SplatValue = APInt(sz, 0);
5714 SplatUndef = APInt(sz, 0);
5716 // Get the bits. Bits with undefined values (when the corresponding element
5717 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
5718 // in SplatValue. If any of the values are not constant, give up and return
5720 unsigned int nOps = getNumOperands();
5721 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
5722 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
5723 for (unsigned i = 0; i < nOps; ++i) {
5724 SDValue OpVal = getOperand(i);
5725 unsigned BitPos = i * EltBitSize;
5727 if (OpVal.getOpcode() == ISD::UNDEF)
5728 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos +EltBitSize);
5729 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
5730 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
5731 zextOrTrunc(sz) << BitPos);
5732 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
5733 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
5738 // The build_vector is all constants or undefs. Find the smallest element
5739 // size that splats the vector.
5741 HasAnyUndefs = (SplatUndef != 0);
5744 unsigned HalfSize = sz / 2;
5745 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
5746 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
5747 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
5748 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
5750 // If the two halves do not match (ignoring undef bits), stop here.
5751 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
5752 MinSplatBits > HalfSize)
5755 SplatValue = HighValue | LowValue;
5756 SplatUndef = HighUndef & LowUndef;
5765 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, MVT VT) {
5766 // Find the first non-undef value in the shuffle mask.
5768 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
5771 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
5773 // Make sure all remaining elements are either undef or the same as the first
5775 for (int Idx = Mask[i]; i != e; ++i)
5776 if (Mask[i] >= 0 && Mask[i] != Idx)