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/Function.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetIntrinsicInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/System/Mutex.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/ADT/StringExtras.h"
50 /// makeVTList - Return an instance of the SDVTList struct initialized with the
51 /// specified members.
52 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
53 SDVTList Res = {VTs, NumVTs};
57 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
58 switch (VT.getSimpleVT().SimpleTy) {
59 default: llvm_unreachable("Unknown FP format");
60 case MVT::f32: return &APFloat::IEEEsingle;
61 case MVT::f64: return &APFloat::IEEEdouble;
62 case MVT::f80: return &APFloat::x87DoubleExtended;
63 case MVT::f128: return &APFloat::IEEEquad;
64 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
68 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
70 //===----------------------------------------------------------------------===//
71 // ConstantFPSDNode Class
72 //===----------------------------------------------------------------------===//
74 /// isExactlyValue - We don't rely on operator== working on double values, as
75 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
76 /// As such, this method can be used to do an exact bit-for-bit comparison of
77 /// two floating point values.
78 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
79 return getValueAPF().bitwiseIsEqual(V);
82 bool ConstantFPSDNode::isValueValidForType(EVT VT,
84 assert(VT.isFloatingPoint() && "Can only convert between FP types");
86 // PPC long double cannot be converted to any other type.
87 if (VT == MVT::ppcf128 ||
88 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
91 // convert modifies in place, so make a copy.
92 APFloat Val2 = APFloat(Val);
94 (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
99 //===----------------------------------------------------------------------===//
101 //===----------------------------------------------------------------------===//
103 /// isBuildVectorAllOnes - Return true if the specified node is a
104 /// BUILD_VECTOR where all of the elements are ~0 or undef.
105 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
106 // Look through a bit convert.
107 if (N->getOpcode() == ISD::BIT_CONVERT)
108 N = N->getOperand(0).getNode();
110 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
112 unsigned i = 0, e = N->getNumOperands();
114 // Skip over all of the undef values.
115 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
118 // Do not accept an all-undef vector.
119 if (i == e) return false;
121 // Do not accept build_vectors that aren't all constants or which have non-~0
123 SDValue NotZero = N->getOperand(i);
124 if (isa<ConstantSDNode>(NotZero)) {
125 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
127 } else if (isa<ConstantFPSDNode>(NotZero)) {
128 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
129 bitcastToAPInt().isAllOnesValue())
134 // Okay, we have at least one ~0 value, check to see if the rest match or are
136 for (++i; i != e; ++i)
137 if (N->getOperand(i) != NotZero &&
138 N->getOperand(i).getOpcode() != ISD::UNDEF)
144 /// isBuildVectorAllZeros - Return true if the specified node is a
145 /// BUILD_VECTOR where all of the elements are 0 or undef.
146 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
147 // Look through a bit convert.
148 if (N->getOpcode() == ISD::BIT_CONVERT)
149 N = N->getOperand(0).getNode();
151 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
153 unsigned i = 0, e = N->getNumOperands();
155 // Skip over all of the undef values.
156 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
159 // Do not accept an all-undef vector.
160 if (i == e) return false;
162 // Do not accept build_vectors that aren't all constants or which have non-0
164 SDValue Zero = N->getOperand(i);
165 if (isa<ConstantSDNode>(Zero)) {
166 if (!cast<ConstantSDNode>(Zero)->isNullValue())
168 } else if (isa<ConstantFPSDNode>(Zero)) {
169 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
174 // Okay, we have at least one 0 value, check to see if the rest match or are
176 for (++i; i != e; ++i)
177 if (N->getOperand(i) != Zero &&
178 N->getOperand(i).getOpcode() != ISD::UNDEF)
183 /// isScalarToVector - Return true if the specified node is a
184 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
185 /// element is not an undef.
186 bool ISD::isScalarToVector(const SDNode *N) {
187 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
190 if (N->getOpcode() != ISD::BUILD_VECTOR)
192 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
194 unsigned NumElems = N->getNumOperands();
195 for (unsigned i = 1; i < NumElems; ++i) {
196 SDValue V = N->getOperand(i);
197 if (V.getOpcode() != ISD::UNDEF)
204 /// isDebugLabel - Return true if the specified node represents a debug
205 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
206 bool ISD::isDebugLabel(const SDNode *N) {
208 if (N->getOpcode() == ISD::DBG_LABEL)
210 if (N->isMachineOpcode() &&
211 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
216 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
217 /// when given the operation for (X op Y).
218 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
219 // To perform this operation, we just need to swap the L and G bits of the
221 unsigned OldL = (Operation >> 2) & 1;
222 unsigned OldG = (Operation >> 1) & 1;
223 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
224 (OldL << 1) | // New G bit
225 (OldG << 2)); // New L bit.
228 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
229 /// 'op' is a valid SetCC operation.
230 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
231 unsigned Operation = Op;
233 Operation ^= 7; // Flip L, G, E bits, but not U.
235 Operation ^= 15; // Flip all of the condition bits.
237 if (Operation > ISD::SETTRUE2)
238 Operation &= ~8; // Don't let N and U bits get set.
240 return ISD::CondCode(Operation);
244 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
245 /// signed operation and 2 if the result is an unsigned comparison. Return zero
246 /// if the operation does not depend on the sign of the input (setne and seteq).
247 static int isSignedOp(ISD::CondCode Opcode) {
249 default: llvm_unreachable("Illegal integer setcc operation!");
251 case ISD::SETNE: return 0;
255 case ISD::SETGE: return 1;
259 case ISD::SETUGE: return 2;
263 /// getSetCCOrOperation - Return the result of a logical OR between different
264 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
265 /// returns SETCC_INVALID if it is not possible to represent the resultant
267 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
269 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
270 // Cannot fold a signed integer setcc with an unsigned integer setcc.
271 return ISD::SETCC_INVALID;
273 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
275 // If the N and U bits get set then the resultant comparison DOES suddenly
276 // care about orderedness, and is true when ordered.
277 if (Op > ISD::SETTRUE2)
278 Op &= ~16; // Clear the U bit if the N bit is set.
280 // Canonicalize illegal integer setcc's.
281 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
284 return ISD::CondCode(Op);
287 /// getSetCCAndOperation - Return the result of a logical AND between different
288 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
289 /// function returns zero if it is not possible to represent the resultant
291 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
293 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
294 // Cannot fold a signed setcc with an unsigned setcc.
295 return ISD::SETCC_INVALID;
297 // Combine all of the condition bits.
298 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
300 // Canonicalize illegal integer setcc's.
304 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
305 case ISD::SETOEQ: // SETEQ & SETU[LG]E
306 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
307 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
308 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
315 const TargetMachine &SelectionDAG::getTarget() const {
316 return MF->getTarget();
319 //===----------------------------------------------------------------------===//
320 // SDNode Profile Support
321 //===----------------------------------------------------------------------===//
323 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
325 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
329 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
330 /// solely with their pointer.
331 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
332 ID.AddPointer(VTList.VTs);
335 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
337 static void AddNodeIDOperands(FoldingSetNodeID &ID,
338 const SDValue *Ops, unsigned NumOps) {
339 for (; NumOps; --NumOps, ++Ops) {
340 ID.AddPointer(Ops->getNode());
341 ID.AddInteger(Ops->getResNo());
345 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
347 static void AddNodeIDOperands(FoldingSetNodeID &ID,
348 const SDUse *Ops, unsigned NumOps) {
349 for (; NumOps; --NumOps, ++Ops) {
350 ID.AddPointer(Ops->getNode());
351 ID.AddInteger(Ops->getResNo());
355 static void AddNodeIDNode(FoldingSetNodeID &ID,
356 unsigned short OpC, SDVTList VTList,
357 const SDValue *OpList, unsigned N) {
358 AddNodeIDOpcode(ID, OpC);
359 AddNodeIDValueTypes(ID, VTList);
360 AddNodeIDOperands(ID, OpList, N);
363 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
365 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
366 switch (N->getOpcode()) {
367 case ISD::TargetExternalSymbol:
368 case ISD::ExternalSymbol:
369 llvm_unreachable("Should only be used on nodes with operands");
370 default: break; // Normal nodes don't need extra info.
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::FrameIndex:
407 case ISD::TargetFrameIndex:
408 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
411 case ISD::TargetJumpTable:
412 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
413 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
415 case ISD::ConstantPool:
416 case ISD::TargetConstantPool: {
417 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
418 ID.AddInteger(CP->getAlignment());
419 ID.AddInteger(CP->getOffset());
420 if (CP->isMachineConstantPoolEntry())
421 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
423 ID.AddPointer(CP->getConstVal());
424 ID.AddInteger(CP->getTargetFlags());
428 const LoadSDNode *LD = cast<LoadSDNode>(N);
429 ID.AddInteger(LD->getMemoryVT().getRawBits());
430 ID.AddInteger(LD->getRawSubclassData());
434 const StoreSDNode *ST = cast<StoreSDNode>(N);
435 ID.AddInteger(ST->getMemoryVT().getRawBits());
436 ID.AddInteger(ST->getRawSubclassData());
439 case ISD::ATOMIC_CMP_SWAP:
440 case ISD::ATOMIC_SWAP:
441 case ISD::ATOMIC_LOAD_ADD:
442 case ISD::ATOMIC_LOAD_SUB:
443 case ISD::ATOMIC_LOAD_AND:
444 case ISD::ATOMIC_LOAD_OR:
445 case ISD::ATOMIC_LOAD_XOR:
446 case ISD::ATOMIC_LOAD_NAND:
447 case ISD::ATOMIC_LOAD_MIN:
448 case ISD::ATOMIC_LOAD_MAX:
449 case ISD::ATOMIC_LOAD_UMIN:
450 case ISD::ATOMIC_LOAD_UMAX: {
451 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
452 ID.AddInteger(AT->getMemoryVT().getRawBits());
453 ID.AddInteger(AT->getRawSubclassData());
456 case ISD::VECTOR_SHUFFLE: {
457 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
458 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
460 ID.AddInteger(SVN->getMaskElt(i));
463 case ISD::TargetBlockAddress:
464 case ISD::BlockAddress: {
465 ID.AddPointer(cast<BlockAddressSDNode>(N));
468 } // end switch (N->getOpcode())
471 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
473 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
474 AddNodeIDOpcode(ID, N->getOpcode());
475 // Add the return value info.
476 AddNodeIDValueTypes(ID, N->getVTList());
477 // Add the operand info.
478 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
480 // Handle SDNode leafs with special info.
481 AddNodeIDCustom(ID, N);
484 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
485 /// the CSE map that carries volatility, indexing mode, and
486 /// extension/truncation information.
488 static inline unsigned
489 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile) {
490 assert((ConvType & 3) == ConvType &&
491 "ConvType may not require more than 2 bits!");
492 assert((AM & 7) == AM &&
493 "AM may not require more than 3 bits!");
499 //===----------------------------------------------------------------------===//
500 // SelectionDAG Class
501 //===----------------------------------------------------------------------===//
503 /// doNotCSE - Return true if CSE should not be performed for this node.
504 static bool doNotCSE(SDNode *N) {
505 if (N->getValueType(0) == MVT::Flag)
506 return true; // Never CSE anything that produces a flag.
508 switch (N->getOpcode()) {
510 case ISD::HANDLENODE:
512 case ISD::DBG_STOPPOINT:
514 return true; // Never CSE these nodes.
517 // Check that remaining values produced are not flags.
518 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
519 if (N->getValueType(i) == MVT::Flag)
520 return true; // Never CSE anything that produces a flag.
525 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
527 void SelectionDAG::RemoveDeadNodes() {
528 // Create a dummy node (which is not added to allnodes), that adds a reference
529 // to the root node, preventing it from being deleted.
530 HandleSDNode Dummy(getRoot());
532 SmallVector<SDNode*, 128> DeadNodes;
534 // Add all obviously-dead nodes to the DeadNodes worklist.
535 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
537 DeadNodes.push_back(I);
539 RemoveDeadNodes(DeadNodes);
541 // If the root changed (e.g. it was a dead load, update the root).
542 setRoot(Dummy.getValue());
545 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
546 /// given list, and any nodes that become unreachable as a result.
547 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
548 DAGUpdateListener *UpdateListener) {
550 // Process the worklist, deleting the nodes and adding their uses to the
552 while (!DeadNodes.empty()) {
553 SDNode *N = DeadNodes.pop_back_val();
556 UpdateListener->NodeDeleted(N, 0);
558 // Take the node out of the appropriate CSE map.
559 RemoveNodeFromCSEMaps(N);
561 // Next, brutally remove the operand list. This is safe to do, as there are
562 // no cycles in the graph.
563 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
565 SDNode *Operand = Use.getNode();
568 // Now that we removed this operand, see if there are no uses of it left.
569 if (Operand->use_empty())
570 DeadNodes.push_back(Operand);
577 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
578 SmallVector<SDNode*, 16> DeadNodes(1, N);
579 RemoveDeadNodes(DeadNodes, UpdateListener);
582 void SelectionDAG::DeleteNode(SDNode *N) {
583 // First take this out of the appropriate CSE map.
584 RemoveNodeFromCSEMaps(N);
586 // Finally, remove uses due to operands of this node, remove from the
587 // AllNodes list, and delete the node.
588 DeleteNodeNotInCSEMaps(N);
591 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
592 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
593 assert(N->use_empty() && "Cannot delete a node that is not dead!");
595 // Drop all of the operands and decrement used node's use counts.
601 void SelectionDAG::DeallocateNode(SDNode *N) {
602 if (N->OperandsNeedDelete)
603 delete[] N->OperandList;
605 // Set the opcode to DELETED_NODE to help catch bugs when node
606 // memory is reallocated.
607 N->NodeType = ISD::DELETED_NODE;
609 NodeAllocator.Deallocate(AllNodes.remove(N));
612 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
613 /// correspond to it. This is useful when we're about to delete or repurpose
614 /// the node. We don't want future request for structurally identical nodes
615 /// to return N anymore.
616 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
618 switch (N->getOpcode()) {
619 case ISD::EntryToken:
620 llvm_unreachable("EntryToken should not be in CSEMaps!");
622 case ISD::HANDLENODE: return false; // noop.
624 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
625 "Cond code doesn't exist!");
626 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
627 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
629 case ISD::ExternalSymbol:
630 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
632 case ISD::TargetExternalSymbol: {
633 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
634 Erased = TargetExternalSymbols.erase(
635 std::pair<std::string,unsigned char>(ESN->getSymbol(),
636 ESN->getTargetFlags()));
639 case ISD::VALUETYPE: {
640 EVT VT = cast<VTSDNode>(N)->getVT();
641 if (VT.isExtended()) {
642 Erased = ExtendedValueTypeNodes.erase(VT);
644 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
645 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
650 // Remove it from the CSE Map.
651 Erased = CSEMap.RemoveNode(N);
655 // Verify that the node was actually in one of the CSE maps, unless it has a
656 // flag result (which cannot be CSE'd) or is one of the special cases that are
657 // not subject to CSE.
658 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
659 !N->isMachineOpcode() && !doNotCSE(N)) {
662 llvm_unreachable("Node is not in map!");
668 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
669 /// maps and modified in place. Add it back to the CSE maps, unless an identical
670 /// node already exists, in which case transfer all its users to the existing
671 /// node. This transfer can potentially trigger recursive merging.
674 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
675 DAGUpdateListener *UpdateListener) {
676 // For node types that aren't CSE'd, just act as if no identical node
679 SDNode *Existing = CSEMap.GetOrInsertNode(N);
681 // If there was already an existing matching node, use ReplaceAllUsesWith
682 // to replace the dead one with the existing one. This can cause
683 // recursive merging of other unrelated nodes down the line.
684 ReplaceAllUsesWith(N, Existing, UpdateListener);
686 // N is now dead. Inform the listener if it exists and delete it.
688 UpdateListener->NodeDeleted(N, Existing);
689 DeleteNodeNotInCSEMaps(N);
694 // If the node doesn't already exist, we updated it. Inform a listener if
697 UpdateListener->NodeUpdated(N);
700 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
701 /// were replaced with those specified. If this node is never memoized,
702 /// return null, otherwise return a pointer to the slot it would take. If a
703 /// node already exists with these operands, the slot will be non-null.
704 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
709 SDValue Ops[] = { Op };
711 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
712 AddNodeIDCustom(ID, N);
713 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
716 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
717 /// were replaced with those specified. If this node is never memoized,
718 /// return null, otherwise return a pointer to the slot it would take. If a
719 /// node already exists with these operands, the slot will be non-null.
720 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
721 SDValue Op1, SDValue Op2,
726 SDValue Ops[] = { Op1, Op2 };
728 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
729 AddNodeIDCustom(ID, N);
730 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
734 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
735 /// were replaced with those specified. If this node is never memoized,
736 /// return null, otherwise return a pointer to the slot it would take. If a
737 /// node already exists with these operands, the slot will be non-null.
738 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
739 const SDValue *Ops,unsigned NumOps,
745 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
746 AddNodeIDCustom(ID, N);
747 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
750 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
751 void SelectionDAG::VerifyNode(SDNode *N) {
752 switch (N->getOpcode()) {
755 case ISD::BUILD_PAIR: {
756 EVT VT = N->getValueType(0);
757 assert(N->getNumValues() == 1 && "Too many results!");
758 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
759 "Wrong return type!");
760 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
761 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
762 "Mismatched operand types!");
763 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
764 "Wrong operand type!");
765 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
766 "Wrong return type size");
769 case ISD::BUILD_VECTOR: {
770 assert(N->getNumValues() == 1 && "Too many results!");
771 assert(N->getValueType(0).isVector() && "Wrong return type!");
772 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
773 "Wrong number of operands!");
774 EVT EltVT = N->getValueType(0).getVectorElementType();
775 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
776 assert((I->getValueType() == EltVT ||
777 (EltVT.isInteger() && I->getValueType().isInteger() &&
778 EltVT.bitsLE(I->getValueType()))) &&
779 "Wrong operand type!");
785 /// getEVTAlignment - Compute the default alignment value for the
788 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
789 const Type *Ty = VT == MVT::iPTR ?
790 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
791 VT.getTypeForEVT(*getContext());
793 return TLI.getTargetData()->getABITypeAlignment(Ty);
796 // EntryNode could meaningfully have debug info if we can find it...
797 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
798 : TLI(tli), FLI(fli), DW(0),
799 EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
800 getVTList(MVT::Other)), Root(getEntryNode()) {
801 AllNodes.push_back(&EntryNode);
804 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
809 Context = &mf.getFunction()->getContext();
812 SelectionDAG::~SelectionDAG() {
816 void SelectionDAG::allnodes_clear() {
817 assert(&*AllNodes.begin() == &EntryNode);
818 AllNodes.remove(AllNodes.begin());
819 while (!AllNodes.empty())
820 DeallocateNode(AllNodes.begin());
823 void SelectionDAG::clear() {
825 OperandAllocator.Reset();
828 ExtendedValueTypeNodes.clear();
829 ExternalSymbols.clear();
830 TargetExternalSymbols.clear();
831 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
832 static_cast<CondCodeSDNode*>(0));
833 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
834 static_cast<SDNode*>(0));
836 EntryNode.UseList = 0;
837 AllNodes.push_back(&EntryNode);
838 Root = getEntryNode();
841 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
842 return VT.bitsGT(Op.getValueType()) ?
843 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
844 getNode(ISD::TRUNCATE, DL, VT, Op);
847 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
848 return VT.bitsGT(Op.getValueType()) ?
849 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
850 getNode(ISD::TRUNCATE, DL, VT, Op);
853 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
854 if (Op.getValueType() == VT) return Op;
855 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
857 return getNode(ISD::AND, DL, Op.getValueType(), Op,
858 getConstant(Imm, Op.getValueType()));
861 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
863 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
864 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
866 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
867 return getNode(ISD::XOR, DL, VT, Val, NegOne);
870 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
871 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
872 assert((EltVT.getSizeInBits() >= 64 ||
873 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
874 "getConstant with a uint64_t value that doesn't fit in the type!");
875 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
878 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
879 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
882 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
883 assert(VT.isInteger() && "Cannot create FP integer constant!");
885 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
886 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
887 "APInt size does not match type size!");
889 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
891 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
895 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
897 return SDValue(N, 0);
899 N = NodeAllocator.Allocate<ConstantSDNode>();
900 new (N) ConstantSDNode(isT, &Val, EltVT);
901 CSEMap.InsertNode(N, IP);
902 AllNodes.push_back(N);
905 SDValue Result(N, 0);
907 SmallVector<SDValue, 8> Ops;
908 Ops.assign(VT.getVectorNumElements(), Result);
909 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
910 VT, &Ops[0], Ops.size());
915 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
916 return getConstant(Val, TLI.getPointerTy(), isTarget);
920 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
921 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
924 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
925 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
928 VT.isVector() ? VT.getVectorElementType() : VT;
930 // Do the map lookup using the actual bit pattern for the floating point
931 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
932 // we don't have issues with SNANs.
933 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
935 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
939 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
941 return SDValue(N, 0);
943 N = NodeAllocator.Allocate<ConstantFPSDNode>();
944 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
945 CSEMap.InsertNode(N, IP);
946 AllNodes.push_back(N);
949 SDValue Result(N, 0);
951 SmallVector<SDValue, 8> Ops;
952 Ops.assign(VT.getVectorNumElements(), Result);
953 // FIXME DebugLoc info might be appropriate here
954 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
955 VT, &Ops[0], Ops.size());
960 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
962 VT.isVector() ? VT.getVectorElementType() : VT;
964 return getConstantFP(APFloat((float)Val), VT, isTarget);
966 return getConstantFP(APFloat(Val), VT, isTarget);
969 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
970 EVT VT, int64_t Offset,
972 unsigned char TargetFlags) {
973 assert((TargetFlags == 0 || isTargetGA) &&
974 "Cannot set target flags on target-independent globals");
976 // Truncate (with sign-extension) the offset value to the pointer size.
977 EVT PTy = TLI.getPointerTy();
978 unsigned BitWidth = PTy.getSizeInBits();
980 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
982 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
984 // If GV is an alias then use the aliasee for determining thread-localness.
985 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
986 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
990 if (GVar && GVar->isThreadLocal())
991 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
993 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
996 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
998 ID.AddInteger(Offset);
999 ID.AddInteger(TargetFlags);
1001 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1002 return SDValue(E, 0);
1003 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
1004 new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags);
1005 CSEMap.InsertNode(N, IP);
1006 AllNodes.push_back(N);
1007 return SDValue(N, 0);
1010 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1011 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1012 FoldingSetNodeID ID;
1013 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1016 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1017 return SDValue(E, 0);
1018 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
1019 new (N) FrameIndexSDNode(FI, VT, isTarget);
1020 CSEMap.InsertNode(N, IP);
1021 AllNodes.push_back(N);
1022 return SDValue(N, 0);
1025 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1026 unsigned char TargetFlags) {
1027 assert((TargetFlags == 0 || isTarget) &&
1028 "Cannot set target flags on target-independent jump tables");
1029 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1030 FoldingSetNodeID ID;
1031 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1033 ID.AddInteger(TargetFlags);
1035 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1036 return SDValue(E, 0);
1037 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1038 new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags);
1039 CSEMap.InsertNode(N, IP);
1040 AllNodes.push_back(N);
1041 return SDValue(N, 0);
1044 SDValue SelectionDAG::getConstantPool(Constant *C, EVT VT,
1045 unsigned Alignment, int Offset,
1047 unsigned char TargetFlags) {
1048 assert((TargetFlags == 0 || isTarget) &&
1049 "Cannot set target flags on target-independent globals");
1051 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1052 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1053 FoldingSetNodeID ID;
1054 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1055 ID.AddInteger(Alignment);
1056 ID.AddInteger(Offset);
1058 ID.AddInteger(TargetFlags);
1060 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1061 return SDValue(E, 0);
1062 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1063 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1064 CSEMap.InsertNode(N, IP);
1065 AllNodes.push_back(N);
1066 return SDValue(N, 0);
1070 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1071 unsigned Alignment, int Offset,
1073 unsigned char TargetFlags) {
1074 assert((TargetFlags == 0 || isTarget) &&
1075 "Cannot set target flags on target-independent globals");
1077 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1078 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1079 FoldingSetNodeID ID;
1080 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1081 ID.AddInteger(Alignment);
1082 ID.AddInteger(Offset);
1083 C->AddSelectionDAGCSEId(ID);
1084 ID.AddInteger(TargetFlags);
1086 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1087 return SDValue(E, 0);
1088 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1089 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1090 CSEMap.InsertNode(N, IP);
1091 AllNodes.push_back(N);
1092 return SDValue(N, 0);
1095 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1096 FoldingSetNodeID ID;
1097 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1100 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1101 return SDValue(E, 0);
1102 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1103 new (N) BasicBlockSDNode(MBB);
1104 CSEMap.InsertNode(N, IP);
1105 AllNodes.push_back(N);
1106 return SDValue(N, 0);
1109 SDValue SelectionDAG::getValueType(EVT VT) {
1110 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1111 ValueTypeNodes.size())
1112 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1114 SDNode *&N = VT.isExtended() ?
1115 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1117 if (N) return SDValue(N, 0);
1118 N = NodeAllocator.Allocate<VTSDNode>();
1119 new (N) VTSDNode(VT);
1120 AllNodes.push_back(N);
1121 return SDValue(N, 0);
1124 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1125 SDNode *&N = ExternalSymbols[Sym];
1126 if (N) return SDValue(N, 0);
1127 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1128 new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
1129 AllNodes.push_back(N);
1130 return SDValue(N, 0);
1133 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1134 unsigned char TargetFlags) {
1136 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1138 if (N) return SDValue(N, 0);
1139 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1140 new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1141 AllNodes.push_back(N);
1142 return SDValue(N, 0);
1145 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1146 if ((unsigned)Cond >= CondCodeNodes.size())
1147 CondCodeNodes.resize(Cond+1);
1149 if (CondCodeNodes[Cond] == 0) {
1150 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1151 new (N) CondCodeSDNode(Cond);
1152 CondCodeNodes[Cond] = N;
1153 AllNodes.push_back(N);
1155 return SDValue(CondCodeNodes[Cond], 0);
1158 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1159 // the shuffle mask M that point at N1 to point at N2, and indices that point
1160 // N2 to point at N1.
1161 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1163 int NElts = M.size();
1164 for (int i = 0; i != NElts; ++i) {
1172 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1173 SDValue N2, const int *Mask) {
1174 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1175 assert(VT.isVector() && N1.getValueType().isVector() &&
1176 "Vector Shuffle VTs must be a vectors");
1177 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1178 && "Vector Shuffle VTs must have same element type");
1180 // Canonicalize shuffle undef, undef -> undef
1181 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1182 return getUNDEF(VT);
1184 // Validate that all indices in Mask are within the range of the elements
1185 // input to the shuffle.
1186 unsigned NElts = VT.getVectorNumElements();
1187 SmallVector<int, 8> MaskVec;
1188 for (unsigned i = 0; i != NElts; ++i) {
1189 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1190 MaskVec.push_back(Mask[i]);
1193 // Canonicalize shuffle v, v -> v, undef
1196 for (unsigned i = 0; i != NElts; ++i)
1197 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1200 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1201 if (N1.getOpcode() == ISD::UNDEF)
1202 commuteShuffle(N1, N2, MaskVec);
1204 // Canonicalize all index into lhs, -> shuffle lhs, undef
1205 // Canonicalize all index into rhs, -> shuffle rhs, undef
1206 bool AllLHS = true, AllRHS = true;
1207 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1208 for (unsigned i = 0; i != NElts; ++i) {
1209 if (MaskVec[i] >= (int)NElts) {
1214 } else if (MaskVec[i] >= 0) {
1218 if (AllLHS && AllRHS)
1219 return getUNDEF(VT);
1220 if (AllLHS && !N2Undef)
1224 commuteShuffle(N1, N2, MaskVec);
1227 // If Identity shuffle, or all shuffle in to undef, return that node.
1228 bool AllUndef = true;
1229 bool Identity = true;
1230 for (unsigned i = 0; i != NElts; ++i) {
1231 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1232 if (MaskVec[i] >= 0) AllUndef = false;
1234 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1237 return getUNDEF(VT);
1239 FoldingSetNodeID ID;
1240 SDValue Ops[2] = { N1, N2 };
1241 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1242 for (unsigned i = 0; i != NElts; ++i)
1243 ID.AddInteger(MaskVec[i]);
1246 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1247 return SDValue(E, 0);
1249 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1250 // SDNode doesn't have access to it. This memory will be "leaked" when
1251 // the node is deallocated, but recovered when the NodeAllocator is released.
1252 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1253 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1255 ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
1256 new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1257 CSEMap.InsertNode(N, IP);
1258 AllNodes.push_back(N);
1259 return SDValue(N, 0);
1262 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1263 SDValue Val, SDValue DTy,
1264 SDValue STy, SDValue Rnd, SDValue Sat,
1265 ISD::CvtCode Code) {
1266 // If the src and dest types are the same and the conversion is between
1267 // integer types of the same sign or two floats, no conversion is necessary.
1269 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1272 FoldingSetNodeID ID;
1273 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1274 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1276 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1277 return SDValue(E, 0);
1278 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1279 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
1280 CSEMap.InsertNode(N, IP);
1281 AllNodes.push_back(N);
1282 return SDValue(N, 0);
1285 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1286 FoldingSetNodeID ID;
1287 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1288 ID.AddInteger(RegNo);
1290 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1291 return SDValue(E, 0);
1292 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1293 new (N) RegisterSDNode(RegNo, VT);
1294 CSEMap.InsertNode(N, IP);
1295 AllNodes.push_back(N);
1296 return SDValue(N, 0);
1299 SDValue SelectionDAG::getDbgStopPoint(DebugLoc DL, SDValue Root,
1300 unsigned Line, unsigned Col,
1302 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1303 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1305 AllNodes.push_back(N);
1306 return SDValue(N, 0);
1309 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1312 FoldingSetNodeID ID;
1313 SDValue Ops[] = { Root };
1314 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1315 ID.AddInteger(LabelID);
1317 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1318 return SDValue(E, 0);
1319 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1320 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1321 CSEMap.InsertNode(N, IP);
1322 AllNodes.push_back(N);
1323 return SDValue(N, 0);
1326 SDValue SelectionDAG::getBlockAddress(BlockAddress *BA, DebugLoc DL,
1328 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1330 FoldingSetNodeID ID;
1331 AddNodeIDNode(ID, Opc, getVTList(TLI.getPointerTy()), 0, 0);
1334 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1335 return SDValue(E, 0);
1336 SDNode *N = NodeAllocator.Allocate<BlockAddressSDNode>();
1337 new (N) BlockAddressSDNode(Opc, DL, TLI.getPointerTy(), BA);
1338 CSEMap.InsertNode(N, IP);
1339 AllNodes.push_back(N);
1340 return SDValue(N, 0);
1343 SDValue SelectionDAG::getSrcValue(const Value *V) {
1344 assert((!V || isa<PointerType>(V->getType())) &&
1345 "SrcValue is not a pointer?");
1347 FoldingSetNodeID ID;
1348 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1352 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1353 return SDValue(E, 0);
1355 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1356 new (N) SrcValueSDNode(V);
1357 CSEMap.InsertNode(N, IP);
1358 AllNodes.push_back(N);
1359 return SDValue(N, 0);
1362 /// getShiftAmountOperand - Return the specified value casted to
1363 /// the target's desired shift amount type.
1364 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1365 EVT OpTy = Op.getValueType();
1366 MVT ShTy = TLI.getShiftAmountTy();
1367 if (OpTy == ShTy || OpTy.isVector()) return Op;
1369 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1370 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1373 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1374 /// specified value type.
1375 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1376 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1377 unsigned ByteSize = VT.getStoreSize();
1378 const Type *Ty = VT.getTypeForEVT(*getContext());
1379 unsigned StackAlign =
1380 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1382 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1383 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1386 /// CreateStackTemporary - Create a stack temporary suitable for holding
1387 /// either of the specified value types.
1388 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1389 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1390 VT2.getStoreSizeInBits())/8;
1391 const Type *Ty1 = VT1.getTypeForEVT(*getContext());
1392 const Type *Ty2 = VT2.getTypeForEVT(*getContext());
1393 const TargetData *TD = TLI.getTargetData();
1394 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1395 TD->getPrefTypeAlignment(Ty2));
1397 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1398 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1399 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1402 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1403 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1404 // These setcc operations always fold.
1408 case ISD::SETFALSE2: return getConstant(0, VT);
1410 case ISD::SETTRUE2: return getConstant(1, VT);
1422 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1426 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1427 const APInt &C2 = N2C->getAPIntValue();
1428 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1429 const APInt &C1 = N1C->getAPIntValue();
1432 default: llvm_unreachable("Unknown integer setcc!");
1433 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1434 case ISD::SETNE: return getConstant(C1 != C2, VT);
1435 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1436 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1437 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1438 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1439 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1440 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1441 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1442 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1446 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1447 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1448 // No compile time operations on this type yet.
1449 if (N1C->getValueType(0) == MVT::ppcf128)
1452 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1455 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1456 return getUNDEF(VT);
1458 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1459 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1460 return getUNDEF(VT);
1462 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1463 R==APFloat::cmpLessThan, VT);
1464 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1465 return getUNDEF(VT);
1467 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1468 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1469 return getUNDEF(VT);
1471 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1472 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1473 return getUNDEF(VT);
1475 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1476 R==APFloat::cmpEqual, VT);
1477 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1478 return getUNDEF(VT);
1480 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1481 R==APFloat::cmpEqual, VT);
1482 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1483 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1484 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1485 R==APFloat::cmpEqual, VT);
1486 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1487 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1488 R==APFloat::cmpLessThan, VT);
1489 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1490 R==APFloat::cmpUnordered, VT);
1491 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1492 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1495 // Ensure that the constant occurs on the RHS.
1496 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1500 // Could not fold it.
1504 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1505 /// use this predicate to simplify operations downstream.
1506 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1507 // This predicate is not safe for vector operations.
1508 if (Op.getValueType().isVector())
1511 unsigned BitWidth = Op.getValueSizeInBits();
1512 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1515 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1516 /// this predicate to simplify operations downstream. Mask is known to be zero
1517 /// for bits that V cannot have.
1518 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1519 unsigned Depth) const {
1520 APInt KnownZero, KnownOne;
1521 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1522 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1523 return (KnownZero & Mask) == Mask;
1526 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1527 /// known to be either zero or one and return them in the KnownZero/KnownOne
1528 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1530 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1531 APInt &KnownZero, APInt &KnownOne,
1532 unsigned Depth) const {
1533 unsigned BitWidth = Mask.getBitWidth();
1534 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1535 "Mask size mismatches value type size!");
1537 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1538 if (Depth == 6 || Mask == 0)
1539 return; // Limit search depth.
1541 APInt KnownZero2, KnownOne2;
1543 switch (Op.getOpcode()) {
1545 // We know all of the bits for a constant!
1546 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1547 KnownZero = ~KnownOne & Mask;
1550 // If either the LHS or the RHS are Zero, the result is zero.
1551 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1552 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1553 KnownZero2, KnownOne2, Depth+1);
1554 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1555 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1557 // Output known-1 bits are only known if set in both the LHS & RHS.
1558 KnownOne &= KnownOne2;
1559 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1560 KnownZero |= KnownZero2;
1563 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1564 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1565 KnownZero2, KnownOne2, Depth+1);
1566 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1567 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1569 // Output known-0 bits are only known if clear in both the LHS & RHS.
1570 KnownZero &= KnownZero2;
1571 // Output known-1 are known to be set if set in either the LHS | RHS.
1572 KnownOne |= KnownOne2;
1575 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1576 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1577 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1578 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1580 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1581 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1582 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1583 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1584 KnownZero = KnownZeroOut;
1588 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1589 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1590 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1591 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1592 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1594 // If low bits are zero in either operand, output low known-0 bits.
1595 // Also compute a conserative estimate for high known-0 bits.
1596 // More trickiness is possible, but this is sufficient for the
1597 // interesting case of alignment computation.
1599 unsigned TrailZ = KnownZero.countTrailingOnes() +
1600 KnownZero2.countTrailingOnes();
1601 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1602 KnownZero2.countLeadingOnes(),
1603 BitWidth) - BitWidth;
1605 TrailZ = std::min(TrailZ, BitWidth);
1606 LeadZ = std::min(LeadZ, BitWidth);
1607 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1608 APInt::getHighBitsSet(BitWidth, LeadZ);
1613 // For the purposes of computing leading zeros we can conservatively
1614 // treat a udiv as a logical right shift by the power of 2 known to
1615 // be less than the denominator.
1616 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1617 ComputeMaskedBits(Op.getOperand(0),
1618 AllOnes, KnownZero2, KnownOne2, Depth+1);
1619 unsigned LeadZ = KnownZero2.countLeadingOnes();
1623 ComputeMaskedBits(Op.getOperand(1),
1624 AllOnes, KnownZero2, KnownOne2, Depth+1);
1625 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1626 if (RHSUnknownLeadingOnes != BitWidth)
1627 LeadZ = std::min(BitWidth,
1628 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1630 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1634 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1635 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1636 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1637 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1639 // Only known if known in both the LHS and RHS.
1640 KnownOne &= KnownOne2;
1641 KnownZero &= KnownZero2;
1643 case ISD::SELECT_CC:
1644 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1645 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1646 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1647 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1649 // Only known if known in both the LHS and RHS.
1650 KnownOne &= KnownOne2;
1651 KnownZero &= KnownZero2;
1659 if (Op.getResNo() != 1)
1661 // The boolean result conforms to getBooleanContents. Fall through.
1663 // If we know the result of a setcc has the top bits zero, use this info.
1664 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1666 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1669 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1670 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1671 unsigned ShAmt = SA->getZExtValue();
1673 // If the shift count is an invalid immediate, don't do anything.
1674 if (ShAmt >= BitWidth)
1677 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1678 KnownZero, KnownOne, Depth+1);
1679 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1680 KnownZero <<= ShAmt;
1682 // low bits known zero.
1683 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1687 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1688 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1689 unsigned ShAmt = SA->getZExtValue();
1691 // If the shift count is an invalid immediate, don't do anything.
1692 if (ShAmt >= BitWidth)
1695 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1696 KnownZero, KnownOne, Depth+1);
1697 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1698 KnownZero = KnownZero.lshr(ShAmt);
1699 KnownOne = KnownOne.lshr(ShAmt);
1701 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1702 KnownZero |= HighBits; // High bits known zero.
1706 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1707 unsigned ShAmt = SA->getZExtValue();
1709 // If the shift count is an invalid immediate, don't do anything.
1710 if (ShAmt >= BitWidth)
1713 APInt InDemandedMask = (Mask << ShAmt);
1714 // If any of the demanded bits are produced by the sign extension, we also
1715 // demand the input sign bit.
1716 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1717 if (HighBits.getBoolValue())
1718 InDemandedMask |= APInt::getSignBit(BitWidth);
1720 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1722 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1723 KnownZero = KnownZero.lshr(ShAmt);
1724 KnownOne = KnownOne.lshr(ShAmt);
1726 // Handle the sign bits.
1727 APInt SignBit = APInt::getSignBit(BitWidth);
1728 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1730 if (KnownZero.intersects(SignBit)) {
1731 KnownZero |= HighBits; // New bits are known zero.
1732 } else if (KnownOne.intersects(SignBit)) {
1733 KnownOne |= HighBits; // New bits are known one.
1737 case ISD::SIGN_EXTEND_INREG: {
1738 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1739 unsigned EBits = EVT.getSizeInBits();
1741 // Sign extension. Compute the demanded bits in the result that are not
1742 // present in the input.
1743 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1745 APInt InSignBit = APInt::getSignBit(EBits);
1746 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1748 // If the sign extended bits are demanded, we know that the sign
1750 InSignBit.zext(BitWidth);
1751 if (NewBits.getBoolValue())
1752 InputDemandedBits |= InSignBit;
1754 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1755 KnownZero, KnownOne, Depth+1);
1756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1758 // If the sign bit of the input is known set or clear, then we know the
1759 // top bits of the result.
1760 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1761 KnownZero |= NewBits;
1762 KnownOne &= ~NewBits;
1763 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1764 KnownOne |= NewBits;
1765 KnownZero &= ~NewBits;
1766 } else { // Input sign bit unknown
1767 KnownZero &= ~NewBits;
1768 KnownOne &= ~NewBits;
1775 unsigned LowBits = Log2_32(BitWidth)+1;
1776 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1781 if (ISD::isZEXTLoad(Op.getNode())) {
1782 LoadSDNode *LD = cast<LoadSDNode>(Op);
1783 EVT VT = LD->getMemoryVT();
1784 unsigned MemBits = VT.getSizeInBits();
1785 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1789 case ISD::ZERO_EXTEND: {
1790 EVT InVT = Op.getOperand(0).getValueType();
1791 unsigned InBits = InVT.getSizeInBits();
1792 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1793 APInt InMask = Mask;
1794 InMask.trunc(InBits);
1795 KnownZero.trunc(InBits);
1796 KnownOne.trunc(InBits);
1797 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1798 KnownZero.zext(BitWidth);
1799 KnownOne.zext(BitWidth);
1800 KnownZero |= NewBits;
1803 case ISD::SIGN_EXTEND: {
1804 EVT InVT = Op.getOperand(0).getValueType();
1805 unsigned InBits = InVT.getSizeInBits();
1806 APInt InSignBit = APInt::getSignBit(InBits);
1807 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1808 APInt InMask = Mask;
1809 InMask.trunc(InBits);
1811 // If any of the sign extended bits are demanded, we know that the sign
1812 // bit is demanded. Temporarily set this bit in the mask for our callee.
1813 if (NewBits.getBoolValue())
1814 InMask |= InSignBit;
1816 KnownZero.trunc(InBits);
1817 KnownOne.trunc(InBits);
1818 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1820 // Note if the sign bit is known to be zero or one.
1821 bool SignBitKnownZero = KnownZero.isNegative();
1822 bool SignBitKnownOne = KnownOne.isNegative();
1823 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1824 "Sign bit can't be known to be both zero and one!");
1826 // If the sign bit wasn't actually demanded by our caller, we don't
1827 // want it set in the KnownZero and KnownOne result values. Reset the
1828 // mask and reapply it to the result values.
1830 InMask.trunc(InBits);
1831 KnownZero &= InMask;
1834 KnownZero.zext(BitWidth);
1835 KnownOne.zext(BitWidth);
1837 // If the sign bit is known zero or one, the top bits match.
1838 if (SignBitKnownZero)
1839 KnownZero |= NewBits;
1840 else if (SignBitKnownOne)
1841 KnownOne |= NewBits;
1844 case ISD::ANY_EXTEND: {
1845 EVT InVT = Op.getOperand(0).getValueType();
1846 unsigned InBits = InVT.getSizeInBits();
1847 APInt InMask = Mask;
1848 InMask.trunc(InBits);
1849 KnownZero.trunc(InBits);
1850 KnownOne.trunc(InBits);
1851 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1852 KnownZero.zext(BitWidth);
1853 KnownOne.zext(BitWidth);
1856 case ISD::TRUNCATE: {
1857 EVT InVT = Op.getOperand(0).getValueType();
1858 unsigned InBits = InVT.getSizeInBits();
1859 APInt InMask = Mask;
1860 InMask.zext(InBits);
1861 KnownZero.zext(InBits);
1862 KnownOne.zext(InBits);
1863 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1864 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1865 KnownZero.trunc(BitWidth);
1866 KnownOne.trunc(BitWidth);
1869 case ISD::AssertZext: {
1870 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1871 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1872 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1874 KnownZero |= (~InMask) & Mask;
1878 // All bits are zero except the low bit.
1879 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1883 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1884 // We know that the top bits of C-X are clear if X contains less bits
1885 // than C (i.e. no wrap-around can happen). For example, 20-X is
1886 // positive if we can prove that X is >= 0 and < 16.
1887 if (CLHS->getAPIntValue().isNonNegative()) {
1888 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1889 // NLZ can't be BitWidth with no sign bit
1890 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1891 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1894 // If all of the MaskV bits are known to be zero, then we know the
1895 // output top bits are zero, because we now know that the output is
1897 if ((KnownZero2 & MaskV) == MaskV) {
1898 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1899 // Top bits known zero.
1900 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1907 // Output known-0 bits are known if clear or set in both the low clear bits
1908 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1909 // low 3 bits clear.
1910 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1911 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1912 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1913 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1915 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1916 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1917 KnownZeroOut = std::min(KnownZeroOut,
1918 KnownZero2.countTrailingOnes());
1920 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1924 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1925 const APInt &RA = Rem->getAPIntValue();
1926 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1927 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1928 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1929 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1931 // If the sign bit of the first operand is zero, the sign bit of
1932 // the result is zero. If the first operand has no one bits below
1933 // the second operand's single 1 bit, its sign will be zero.
1934 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1935 KnownZero2 |= ~LowBits;
1937 KnownZero |= KnownZero2 & Mask;
1939 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1944 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1945 const APInt &RA = Rem->getAPIntValue();
1946 if (RA.isPowerOf2()) {
1947 APInt LowBits = (RA - 1);
1948 APInt Mask2 = LowBits & Mask;
1949 KnownZero |= ~LowBits & Mask;
1950 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1951 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1956 // Since the result is less than or equal to either operand, any leading
1957 // zero bits in either operand must also exist in the result.
1958 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1959 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1961 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1964 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1965 KnownZero2.countLeadingOnes());
1967 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1971 // Allow the target to implement this method for its nodes.
1972 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1973 case ISD::INTRINSIC_WO_CHAIN:
1974 case ISD::INTRINSIC_W_CHAIN:
1975 case ISD::INTRINSIC_VOID:
1976 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
1983 /// ComputeNumSignBits - Return the number of times the sign bit of the
1984 /// register is replicated into the other bits. We know that at least 1 bit
1985 /// is always equal to the sign bit (itself), but other cases can give us
1986 /// information. For example, immediately after an "SRA X, 2", we know that
1987 /// the top 3 bits are all equal to each other, so we return 3.
1988 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1989 EVT VT = Op.getValueType();
1990 assert(VT.isInteger() && "Invalid VT!");
1991 unsigned VTBits = VT.getSizeInBits();
1993 unsigned FirstAnswer = 1;
1996 return 1; // Limit search depth.
1998 switch (Op.getOpcode()) {
2000 case ISD::AssertSext:
2001 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2002 return VTBits-Tmp+1;
2003 case ISD::AssertZext:
2004 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2007 case ISD::Constant: {
2008 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2009 // If negative, return # leading ones.
2010 if (Val.isNegative())
2011 return Val.countLeadingOnes();
2013 // Return # leading zeros.
2014 return Val.countLeadingZeros();
2017 case ISD::SIGN_EXTEND:
2018 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
2019 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2021 case ISD::SIGN_EXTEND_INREG:
2022 // Max of the input and what this extends.
2023 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2026 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2027 return std::max(Tmp, Tmp2);
2030 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2031 // SRA X, C -> adds C sign bits.
2032 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2033 Tmp += C->getZExtValue();
2034 if (Tmp > VTBits) Tmp = VTBits;
2038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2039 // shl destroys sign bits.
2040 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2041 if (C->getZExtValue() >= VTBits || // Bad shift.
2042 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2043 return Tmp - C->getZExtValue();
2048 case ISD::XOR: // NOT is handled here.
2049 // Logical binary ops preserve the number of sign bits at the worst.
2050 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2052 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2053 FirstAnswer = std::min(Tmp, Tmp2);
2054 // We computed what we know about the sign bits as our first
2055 // answer. Now proceed to the generic code that uses
2056 // ComputeMaskedBits, and pick whichever answer is better.
2061 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2062 if (Tmp == 1) return 1; // Early out.
2063 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2064 return std::min(Tmp, Tmp2);
2072 if (Op.getResNo() != 1)
2074 // The boolean result conforms to getBooleanContents. Fall through.
2076 // If setcc returns 0/-1, all bits are sign bits.
2077 if (TLI.getBooleanContents() ==
2078 TargetLowering::ZeroOrNegativeOneBooleanContent)
2083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2084 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2086 // Handle rotate right by N like a rotate left by 32-N.
2087 if (Op.getOpcode() == ISD::ROTR)
2088 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2090 // If we aren't rotating out all of the known-in sign bits, return the
2091 // number that are left. This handles rotl(sext(x), 1) for example.
2092 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2093 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2097 // Add can have at most one carry bit. Thus we know that the output
2098 // is, at worst, one more bit than the inputs.
2099 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2100 if (Tmp == 1) return 1; // Early out.
2102 // Special case decrementing a value (ADD X, -1):
2103 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2104 if (CRHS->isAllOnesValue()) {
2105 APInt KnownZero, KnownOne;
2106 APInt Mask = APInt::getAllOnesValue(VTBits);
2107 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2109 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2111 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2114 // If we are subtracting one from a positive number, there is no carry
2115 // out of the result.
2116 if (KnownZero.isNegative())
2120 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2121 if (Tmp2 == 1) return 1;
2122 return std::min(Tmp, Tmp2)-1;
2126 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2127 if (Tmp2 == 1) return 1;
2130 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2131 if (CLHS->isNullValue()) {
2132 APInt KnownZero, KnownOne;
2133 APInt Mask = APInt::getAllOnesValue(VTBits);
2134 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2135 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2137 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2140 // If the input is known to be positive (the sign bit is known clear),
2141 // the output of the NEG has the same number of sign bits as the input.
2142 if (KnownZero.isNegative())
2145 // Otherwise, we treat this like a SUB.
2148 // Sub can have at most one carry bit. Thus we know that the output
2149 // is, at worst, one more bit than the inputs.
2150 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2151 if (Tmp == 1) return 1; // Early out.
2152 return std::min(Tmp, Tmp2)-1;
2155 // FIXME: it's tricky to do anything useful for this, but it is an important
2156 // case for targets like X86.
2160 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2161 if (Op.getOpcode() == ISD::LOAD) {
2162 LoadSDNode *LD = cast<LoadSDNode>(Op);
2163 unsigned ExtType = LD->getExtensionType();
2166 case ISD::SEXTLOAD: // '17' bits known
2167 Tmp = LD->getMemoryVT().getSizeInBits();
2168 return VTBits-Tmp+1;
2169 case ISD::ZEXTLOAD: // '16' bits known
2170 Tmp = LD->getMemoryVT().getSizeInBits();
2175 // Allow the target to implement this method for its nodes.
2176 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2177 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2178 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2179 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2180 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2181 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2184 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2185 // use this information.
2186 APInt KnownZero, KnownOne;
2187 APInt Mask = APInt::getAllOnesValue(VTBits);
2188 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2190 if (KnownZero.isNegative()) { // sign bit is 0
2192 } else if (KnownOne.isNegative()) { // sign bit is 1;
2199 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2200 // the number of identical bits in the top of the input value.
2202 Mask <<= Mask.getBitWidth()-VTBits;
2203 // Return # leading zeros. We use 'min' here in case Val was zero before
2204 // shifting. We don't want to return '64' as for an i32 "0".
2205 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2208 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2209 // If we're told that NaNs won't happen, assume they won't.
2210 if (FiniteOnlyFPMath())
2213 // If the value is a constant, we can obviously see if it is a NaN or not.
2214 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2215 return !C->getValueAPF().isNaN();
2217 // TODO: Recognize more cases here.
2222 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2223 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2224 if (!GA) return false;
2225 if (GA->getOffset() != 0) return false;
2226 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2227 if (!GV) return false;
2228 MachineModuleInfo *MMI = getMachineModuleInfo();
2229 return MMI && MMI->hasDebugInfo();
2233 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2234 /// element of the result of the vector shuffle.
2235 SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
2237 EVT VT = N->getValueType(0);
2238 DebugLoc dl = N->getDebugLoc();
2239 if (N->getMaskElt(i) < 0)
2240 return getUNDEF(VT.getVectorElementType());
2241 unsigned Index = N->getMaskElt(i);
2242 unsigned NumElems = VT.getVectorNumElements();
2243 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2246 if (V.getOpcode() == ISD::BIT_CONVERT) {
2247 V = V.getOperand(0);
2248 EVT VVT = V.getValueType();
2249 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
2252 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2253 return (Index == 0) ? V.getOperand(0)
2254 : getUNDEF(VT.getVectorElementType());
2255 if (V.getOpcode() == ISD::BUILD_VECTOR)
2256 return V.getOperand(Index);
2257 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
2258 return getShuffleScalarElt(SVN, Index);
2263 /// getNode - Gets or creates the specified node.
2265 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2266 FoldingSetNodeID ID;
2267 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2269 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2270 return SDValue(E, 0);
2271 SDNode *N = NodeAllocator.Allocate<SDNode>();
2272 new (N) SDNode(Opcode, DL, getVTList(VT));
2273 CSEMap.InsertNode(N, IP);
2275 AllNodes.push_back(N);
2279 return SDValue(N, 0);
2282 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2283 EVT VT, SDValue Operand) {
2284 // Constant fold unary operations with an integer constant operand.
2285 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2286 const APInt &Val = C->getAPIntValue();
2287 unsigned BitWidth = VT.getSizeInBits();
2290 case ISD::SIGN_EXTEND:
2291 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2292 case ISD::ANY_EXTEND:
2293 case ISD::ZERO_EXTEND:
2295 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2296 case ISD::UINT_TO_FP:
2297 case ISD::SINT_TO_FP: {
2298 const uint64_t zero[] = {0, 0};
2299 // No compile time operations on this type.
2300 if (VT==MVT::ppcf128)
2302 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2303 (void)apf.convertFromAPInt(Val,
2304 Opcode==ISD::SINT_TO_FP,
2305 APFloat::rmNearestTiesToEven);
2306 return getConstantFP(apf, VT);
2308 case ISD::BIT_CONVERT:
2309 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2310 return getConstantFP(Val.bitsToFloat(), VT);
2311 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2312 return getConstantFP(Val.bitsToDouble(), VT);
2315 return getConstant(Val.byteSwap(), VT);
2317 return getConstant(Val.countPopulation(), VT);
2319 return getConstant(Val.countLeadingZeros(), VT);
2321 return getConstant(Val.countTrailingZeros(), VT);
2325 // Constant fold unary operations with a floating point constant operand.
2326 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2327 APFloat V = C->getValueAPF(); // make copy
2328 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2332 return getConstantFP(V, VT);
2335 return getConstantFP(V, VT);
2337 case ISD::FP_EXTEND: {
2339 // This can return overflow, underflow, or inexact; we don't care.
2340 // FIXME need to be more flexible about rounding mode.
2341 (void)V.convert(*EVTToAPFloatSemantics(VT),
2342 APFloat::rmNearestTiesToEven, &ignored);
2343 return getConstantFP(V, VT);
2345 case ISD::FP_TO_SINT:
2346 case ISD::FP_TO_UINT: {
2349 assert(integerPartWidth >= 64);
2350 // FIXME need to be more flexible about rounding mode.
2351 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2352 Opcode==ISD::FP_TO_SINT,
2353 APFloat::rmTowardZero, &ignored);
2354 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2356 APInt api(VT.getSizeInBits(), 2, x);
2357 return getConstant(api, VT);
2359 case ISD::BIT_CONVERT:
2360 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2361 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2362 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2363 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2369 unsigned OpOpcode = Operand.getNode()->getOpcode();
2371 case ISD::TokenFactor:
2372 case ISD::MERGE_VALUES:
2373 case ISD::CONCAT_VECTORS:
2374 return Operand; // Factor, merge or concat of one node? No need.
2375 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2376 case ISD::FP_EXTEND:
2377 assert(VT.isFloatingPoint() &&
2378 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2379 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2380 if (Operand.getOpcode() == ISD::UNDEF)
2381 return getUNDEF(VT);
2383 case ISD::SIGN_EXTEND:
2384 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2385 "Invalid SIGN_EXTEND!");
2386 if (Operand.getValueType() == VT) return Operand; // noop extension
2387 assert(Operand.getValueType().bitsLT(VT)
2388 && "Invalid sext node, dst < src!");
2389 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2390 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2392 case ISD::ZERO_EXTEND:
2393 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2394 "Invalid ZERO_EXTEND!");
2395 if (Operand.getValueType() == VT) return Operand; // noop extension
2396 assert(Operand.getValueType().bitsLT(VT)
2397 && "Invalid zext node, dst < src!");
2398 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2399 return getNode(ISD::ZERO_EXTEND, DL, VT,
2400 Operand.getNode()->getOperand(0));
2402 case ISD::ANY_EXTEND:
2403 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2404 "Invalid ANY_EXTEND!");
2405 if (Operand.getValueType() == VT) return Operand; // noop extension
2406 assert(Operand.getValueType().bitsLT(VT)
2407 && "Invalid anyext node, dst < src!");
2408 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2409 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2410 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2413 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2414 "Invalid TRUNCATE!");
2415 if (Operand.getValueType() == VT) return Operand; // noop truncate
2416 assert(Operand.getValueType().bitsGT(VT)
2417 && "Invalid truncate node, src < dst!");
2418 if (OpOpcode == ISD::TRUNCATE)
2419 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2420 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2421 OpOpcode == ISD::ANY_EXTEND) {
2422 // If the source is smaller than the dest, we still need an extend.
2423 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2424 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2425 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2426 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2428 return Operand.getNode()->getOperand(0);
2431 case ISD::BIT_CONVERT:
2432 // Basic sanity checking.
2433 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2434 && "Cannot BIT_CONVERT between types of different sizes!");
2435 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2436 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2437 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2438 if (OpOpcode == ISD::UNDEF)
2439 return getUNDEF(VT);
2441 case ISD::SCALAR_TO_VECTOR:
2442 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2443 (VT.getVectorElementType() == Operand.getValueType() ||
2444 (VT.getVectorElementType().isInteger() &&
2445 Operand.getValueType().isInteger() &&
2446 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2447 "Illegal SCALAR_TO_VECTOR node!");
2448 if (OpOpcode == ISD::UNDEF)
2449 return getUNDEF(VT);
2450 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2451 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2452 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2453 Operand.getConstantOperandVal(1) == 0 &&
2454 Operand.getOperand(0).getValueType() == VT)
2455 return Operand.getOperand(0);
2458 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2459 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2460 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2461 Operand.getNode()->getOperand(0));
2462 if (OpOpcode == ISD::FNEG) // --X -> X
2463 return Operand.getNode()->getOperand(0);
2466 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2467 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2472 SDVTList VTs = getVTList(VT);
2473 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2474 FoldingSetNodeID ID;
2475 SDValue Ops[1] = { Operand };
2476 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2478 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2479 return SDValue(E, 0);
2480 N = NodeAllocator.Allocate<UnarySDNode>();
2481 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2482 CSEMap.InsertNode(N, IP);
2484 N = NodeAllocator.Allocate<UnarySDNode>();
2485 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2488 AllNodes.push_back(N);
2492 return SDValue(N, 0);
2495 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2497 ConstantSDNode *Cst1,
2498 ConstantSDNode *Cst2) {
2499 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2502 case ISD::ADD: return getConstant(C1 + C2, VT);
2503 case ISD::SUB: return getConstant(C1 - C2, VT);
2504 case ISD::MUL: return getConstant(C1 * C2, VT);
2506 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2509 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2512 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2515 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2517 case ISD::AND: return getConstant(C1 & C2, VT);
2518 case ISD::OR: return getConstant(C1 | C2, VT);
2519 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2520 case ISD::SHL: return getConstant(C1 << C2, VT);
2521 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2522 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2523 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2524 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2531 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2532 SDValue N1, SDValue N2) {
2533 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2534 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2537 case ISD::TokenFactor:
2538 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2539 N2.getValueType() == MVT::Other && "Invalid token factor!");
2540 // Fold trivial token factors.
2541 if (N1.getOpcode() == ISD::EntryToken) return N2;
2542 if (N2.getOpcode() == ISD::EntryToken) return N1;
2543 if (N1 == N2) return N1;
2545 case ISD::CONCAT_VECTORS:
2546 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2547 // one big BUILD_VECTOR.
2548 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2549 N2.getOpcode() == ISD::BUILD_VECTOR) {
2550 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2551 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2552 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2556 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2557 N1.getValueType() == VT && "Binary operator types must match!");
2558 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2559 // worth handling here.
2560 if (N2C && N2C->isNullValue())
2562 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2569 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2570 N1.getValueType() == VT && "Binary operator types must match!");
2571 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2572 // it's worth handling here.
2573 if (N2C && N2C->isNullValue())
2583 assert(VT.isInteger() && "This operator does not apply to FP types!");
2591 if (Opcode == ISD::FADD) {
2593 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2594 if (CFP->getValueAPF().isZero())
2597 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2598 if (CFP->getValueAPF().isZero())
2600 } else if (Opcode == ISD::FSUB) {
2602 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2603 if (CFP->getValueAPF().isZero())
2607 assert(N1.getValueType() == N2.getValueType() &&
2608 N1.getValueType() == VT && "Binary operator types must match!");
2610 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2611 assert(N1.getValueType() == VT &&
2612 N1.getValueType().isFloatingPoint() &&
2613 N2.getValueType().isFloatingPoint() &&
2614 "Invalid FCOPYSIGN!");
2621 assert(VT == N1.getValueType() &&
2622 "Shift operators return type must be the same as their first arg");
2623 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2624 "Shifts only work on integers");
2626 // Always fold shifts of i1 values so the code generator doesn't need to
2627 // handle them. Since we know the size of the shift has to be less than the
2628 // size of the value, the shift/rotate count is guaranteed to be zero.
2632 case ISD::FP_ROUND_INREG: {
2633 EVT EVT = cast<VTSDNode>(N2)->getVT();
2634 assert(VT == N1.getValueType() && "Not an inreg round!");
2635 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2636 "Cannot FP_ROUND_INREG integer types");
2637 assert(EVT.bitsLE(VT) && "Not rounding down!");
2638 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2642 assert(VT.isFloatingPoint() &&
2643 N1.getValueType().isFloatingPoint() &&
2644 VT.bitsLE(N1.getValueType()) &&
2645 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2646 if (N1.getValueType() == VT) return N1; // noop conversion.
2648 case ISD::AssertSext:
2649 case ISD::AssertZext: {
2650 EVT EVT = cast<VTSDNode>(N2)->getVT();
2651 assert(VT == N1.getValueType() && "Not an inreg extend!");
2652 assert(VT.isInteger() && EVT.isInteger() &&
2653 "Cannot *_EXTEND_INREG FP types");
2654 assert(EVT.bitsLE(VT) && "Not extending!");
2655 if (VT == EVT) return N1; // noop assertion.
2658 case ISD::SIGN_EXTEND_INREG: {
2659 EVT EVT = cast<VTSDNode>(N2)->getVT();
2660 assert(VT == N1.getValueType() && "Not an inreg extend!");
2661 assert(VT.isInteger() && EVT.isInteger() &&
2662 "Cannot *_EXTEND_INREG FP types");
2663 assert(EVT.bitsLE(VT) && "Not extending!");
2664 if (EVT == VT) return N1; // Not actually extending
2667 APInt Val = N1C->getAPIntValue();
2668 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2669 Val <<= Val.getBitWidth()-FromBits;
2670 Val = Val.ashr(Val.getBitWidth()-FromBits);
2671 return getConstant(Val, VT);
2675 case ISD::EXTRACT_VECTOR_ELT:
2676 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2677 if (N1.getOpcode() == ISD::UNDEF)
2678 return getUNDEF(VT);
2680 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2681 // expanding copies of large vectors from registers.
2683 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2684 N1.getNumOperands() > 0) {
2686 N1.getOperand(0).getValueType().getVectorNumElements();
2687 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2688 N1.getOperand(N2C->getZExtValue() / Factor),
2689 getConstant(N2C->getZExtValue() % Factor,
2690 N2.getValueType()));
2693 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2694 // expanding large vector constants.
2695 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2696 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2697 EVT VEltTy = N1.getValueType().getVectorElementType();
2698 if (Elt.getValueType() != VEltTy) {
2699 // If the vector element type is not legal, the BUILD_VECTOR operands
2700 // are promoted and implicitly truncated. Make that explicit here.
2701 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2704 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2705 // result is implicitly extended.
2706 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2711 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2712 // operations are lowered to scalars.
2713 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2714 // If the indices are the same, return the inserted element.
2715 if (N1.getOperand(2) == N2)
2716 return N1.getOperand(1);
2717 // If the indices are known different, extract the element from
2718 // the original vector.
2719 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2720 isa<ConstantSDNode>(N2))
2721 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2724 case ISD::EXTRACT_ELEMENT:
2725 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2726 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2727 (N1.getValueType().isInteger() == VT.isInteger()) &&
2728 "Wrong types for EXTRACT_ELEMENT!");
2730 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2731 // 64-bit integers into 32-bit parts. Instead of building the extract of
2732 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2733 if (N1.getOpcode() == ISD::BUILD_PAIR)
2734 return N1.getOperand(N2C->getZExtValue());
2736 // EXTRACT_ELEMENT of a constant int is also very common.
2737 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2738 unsigned ElementSize = VT.getSizeInBits();
2739 unsigned Shift = ElementSize * N2C->getZExtValue();
2740 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2741 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2744 case ISD::EXTRACT_SUBVECTOR:
2745 if (N1.getValueType() == VT) // Trivial extraction.
2752 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2753 if (SV.getNode()) return SV;
2754 } else { // Cannonicalize constant to RHS if commutative
2755 if (isCommutativeBinOp(Opcode)) {
2756 std::swap(N1C, N2C);
2762 // Constant fold FP operations.
2763 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2764 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2766 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2767 // Cannonicalize constant to RHS if commutative
2768 std::swap(N1CFP, N2CFP);
2770 } else if (N2CFP && VT != MVT::ppcf128) {
2771 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2772 APFloat::opStatus s;
2775 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2776 if (s != APFloat::opInvalidOp)
2777 return getConstantFP(V1, VT);
2780 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2781 if (s!=APFloat::opInvalidOp)
2782 return getConstantFP(V1, VT);
2785 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2786 if (s!=APFloat::opInvalidOp)
2787 return getConstantFP(V1, VT);
2790 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2791 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2792 return getConstantFP(V1, VT);
2795 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2796 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2797 return getConstantFP(V1, VT);
2799 case ISD::FCOPYSIGN:
2801 return getConstantFP(V1, VT);
2807 // Canonicalize an UNDEF to the RHS, even over a constant.
2808 if (N1.getOpcode() == ISD::UNDEF) {
2809 if (isCommutativeBinOp(Opcode)) {
2813 case ISD::FP_ROUND_INREG:
2814 case ISD::SIGN_EXTEND_INREG:
2820 return N1; // fold op(undef, arg2) -> undef
2828 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2829 // For vectors, we can't easily build an all zero vector, just return
2836 // Fold a bunch of operators when the RHS is undef.
2837 if (N2.getOpcode() == ISD::UNDEF) {
2840 if (N1.getOpcode() == ISD::UNDEF)
2841 // Handle undef ^ undef -> 0 special case. This is a common
2843 return getConstant(0, VT);
2853 return N2; // fold op(arg1, undef) -> undef
2867 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2868 // For vectors, we can't easily build an all zero vector, just return
2873 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2874 // For vectors, we can't easily build an all one vector, just return
2882 // Memoize this node if possible.
2884 SDVTList VTs = getVTList(VT);
2885 if (VT != MVT::Flag) {
2886 SDValue Ops[] = { N1, N2 };
2887 FoldingSetNodeID ID;
2888 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2890 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2891 return SDValue(E, 0);
2892 N = NodeAllocator.Allocate<BinarySDNode>();
2893 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2894 CSEMap.InsertNode(N, IP);
2896 N = NodeAllocator.Allocate<BinarySDNode>();
2897 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2900 AllNodes.push_back(N);
2904 return SDValue(N, 0);
2907 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2908 SDValue N1, SDValue N2, SDValue N3) {
2909 // Perform various simplifications.
2910 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2911 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2913 case ISD::CONCAT_VECTORS:
2914 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2915 // one big BUILD_VECTOR.
2916 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2917 N2.getOpcode() == ISD::BUILD_VECTOR &&
2918 N3.getOpcode() == ISD::BUILD_VECTOR) {
2919 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2920 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2921 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2922 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2926 // Use FoldSetCC to simplify SETCC's.
2927 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
2928 if (Simp.getNode()) return Simp;
2933 if (N1C->getZExtValue())
2934 return N2; // select true, X, Y -> X
2936 return N3; // select false, X, Y -> Y
2939 if (N2 == N3) return N2; // select C, X, X -> X
2943 if (N2C->getZExtValue()) // Unconditional branch
2944 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
2946 return N1; // Never-taken branch
2949 case ISD::VECTOR_SHUFFLE:
2950 llvm_unreachable("should use getVectorShuffle constructor!");
2952 case ISD::BIT_CONVERT:
2953 // Fold bit_convert nodes from a type to themselves.
2954 if (N1.getValueType() == VT)
2959 // Memoize node if it doesn't produce a flag.
2961 SDVTList VTs = getVTList(VT);
2962 if (VT != MVT::Flag) {
2963 SDValue Ops[] = { N1, N2, N3 };
2964 FoldingSetNodeID ID;
2965 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2967 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2968 return SDValue(E, 0);
2969 N = NodeAllocator.Allocate<TernarySDNode>();
2970 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2971 CSEMap.InsertNode(N, IP);
2973 N = NodeAllocator.Allocate<TernarySDNode>();
2974 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2976 AllNodes.push_back(N);
2980 return SDValue(N, 0);
2983 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2984 SDValue N1, SDValue N2, SDValue N3,
2986 SDValue Ops[] = { N1, N2, N3, N4 };
2987 return getNode(Opcode, DL, VT, Ops, 4);
2990 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2991 SDValue N1, SDValue N2, SDValue N3,
2992 SDValue N4, SDValue N5) {
2993 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2994 return getNode(Opcode, DL, VT, Ops, 5);
2997 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
2998 /// the incoming stack arguments to be loaded from the stack.
2999 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3000 SmallVector<SDValue, 8> ArgChains;
3002 // Include the original chain at the beginning of the list. When this is
3003 // used by target LowerCall hooks, this helps legalize find the
3004 // CALLSEQ_BEGIN node.
3005 ArgChains.push_back(Chain);
3007 // Add a chain value for each stack argument.
3008 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3009 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3010 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3011 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3012 if (FI->getIndex() < 0)
3013 ArgChains.push_back(SDValue(L, 1));
3015 // Build a tokenfactor for all the chains.
3016 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3017 &ArgChains[0], ArgChains.size());
3020 /// getMemsetValue - Vectorized representation of the memset value
3022 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3024 unsigned NumBits = VT.isVector() ?
3025 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
3026 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3027 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
3029 for (unsigned i = NumBits; i > 8; i >>= 1) {
3030 Val = (Val << Shift) | Val;
3034 return DAG.getConstant(Val, VT);
3035 return DAG.getConstantFP(APFloat(Val), VT);
3038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3039 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3041 for (unsigned i = NumBits; i > 8; i >>= 1) {
3042 Value = DAG.getNode(ISD::OR, dl, VT,
3043 DAG.getNode(ISD::SHL, dl, VT, Value,
3044 DAG.getConstant(Shift,
3045 TLI.getShiftAmountTy())),
3053 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3054 /// used when a memcpy is turned into a memset when the source is a constant
3056 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3057 const TargetLowering &TLI,
3058 std::string &Str, unsigned Offset) {
3059 // Handle vector with all elements zero.
3062 return DAG.getConstant(0, VT);
3063 unsigned NumElts = VT.getVectorNumElements();
3064 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3065 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3067 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
3070 assert(!VT.isVector() && "Can't handle vector type here!");
3071 unsigned NumBits = VT.getSizeInBits();
3072 unsigned MSB = NumBits / 8;
3074 if (TLI.isLittleEndian())
3075 Offset = Offset + MSB - 1;
3076 for (unsigned i = 0; i != MSB; ++i) {
3077 Val = (Val << 8) | (unsigned char)Str[Offset];
3078 Offset += TLI.isLittleEndian() ? -1 : 1;
3080 return DAG.getConstant(Val, VT);
3083 /// getMemBasePlusOffset - Returns base and offset node for the
3085 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3086 SelectionDAG &DAG) {
3087 EVT VT = Base.getValueType();
3088 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3089 VT, Base, DAG.getConstant(Offset, VT));
3092 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3094 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3095 unsigned SrcDelta = 0;
3096 GlobalAddressSDNode *G = NULL;
3097 if (Src.getOpcode() == ISD::GlobalAddress)
3098 G = cast<GlobalAddressSDNode>(Src);
3099 else if (Src.getOpcode() == ISD::ADD &&
3100 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3101 Src.getOperand(1).getOpcode() == ISD::Constant) {
3102 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3103 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3108 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3109 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3115 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3116 /// to replace the memset / memcpy is below the threshold. It also returns the
3117 /// types of the sequence of memory ops to perform memset / memcpy.
3119 bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
3120 SDValue Dst, SDValue Src,
3121 unsigned Limit, uint64_t Size, unsigned &Align,
3122 std::string &Str, bool &isSrcStr,
3124 const TargetLowering &TLI) {
3125 isSrcStr = isMemSrcFromString(Src, Str);
3126 bool isSrcConst = isa<ConstantSDNode>(Src);
3127 EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3128 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
3129 if (VT != MVT::iAny) {
3130 const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3131 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3132 // If source is a string constant, this will require an unaligned load.
3133 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3134 if (Dst.getOpcode() != ISD::FrameIndex) {
3135 // Can't change destination alignment. It requires a unaligned store.
3139 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3140 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3141 if (MFI->isFixedObjectIndex(FI)) {
3142 // Can't change destination alignment. It requires a unaligned store.
3146 // Give the stack frame object a larger alignment if needed.
3147 if (MFI->getObjectAlignment(FI) < NewAlign)
3148 MFI->setObjectAlignment(FI, NewAlign);
3155 if (VT == MVT::iAny) {
3156 if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
3159 switch (Align & 7) {
3160 case 0: VT = MVT::i64; break;
3161 case 4: VT = MVT::i32; break;
3162 case 2: VT = MVT::i16; break;
3163 default: VT = MVT::i8; break;
3168 while (!TLI.isTypeLegal(LVT))
3169 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3170 assert(LVT.isInteger());
3176 unsigned NumMemOps = 0;
3178 unsigned VTSize = VT.getSizeInBits() / 8;
3179 while (VTSize > Size) {
3180 // For now, only use non-vector load / store's for the left-over pieces.
3181 if (VT.isVector()) {
3183 while (!TLI.isTypeLegal(VT))
3184 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3185 VTSize = VT.getSizeInBits() / 8;
3187 // This can result in a type that is not legal on the target, e.g.
3188 // 1 or 2 bytes on PPC.
3189 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3194 if (++NumMemOps > Limit)
3196 MemOps.push_back(VT);
3203 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3204 SDValue Chain, SDValue Dst,
3205 SDValue Src, uint64_t Size,
3206 unsigned Align, bool AlwaysInline,
3207 const Value *DstSV, uint64_t DstSVOff,
3208 const Value *SrcSV, uint64_t SrcSVOff){
3209 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3211 // Expand memcpy to a series of load and store ops if the size operand falls
3212 // below a certain threshold.
3213 std::vector<EVT> MemOps;
3214 uint64_t Limit = -1ULL;
3216 Limit = TLI.getMaxStoresPerMemcpy();
3217 unsigned DstAlign = Align; // Destination alignment can change.
3220 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3221 Str, CopyFromStr, DAG, TLI))
3225 bool isZeroStr = CopyFromStr && Str.empty();
3226 SmallVector<SDValue, 8> OutChains;
3227 unsigned NumMemOps = MemOps.size();
3228 uint64_t SrcOff = 0, DstOff = 0;
3229 for (unsigned i = 0; i != NumMemOps; ++i) {
3231 unsigned VTSize = VT.getSizeInBits() / 8;
3232 SDValue Value, Store;
3234 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3235 // It's unlikely a store of a vector immediate can be done in a single
3236 // instruction. It would require a load from a constantpool first.
3237 // We also handle store a vector with all zero's.
3238 // FIXME: Handle other cases where store of vector immediate is done in
3239 // a single instruction.
3240 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3241 Store = DAG.getStore(Chain, dl, Value,
3242 getMemBasePlusOffset(Dst, DstOff, DAG),
3243 DstSV, DstSVOff + DstOff, false, DstAlign);
3245 // The type might not be legal for the target. This should only happen
3246 // if the type is smaller than a legal type, as on PPC, so the right
3247 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3248 // to Load/Store if NVT==VT.
3249 // FIXME does the case above also need this?
3250 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3251 assert(NVT.bitsGE(VT));
3252 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3253 getMemBasePlusOffset(Src, SrcOff, DAG),
3254 SrcSV, SrcSVOff + SrcOff, VT, false, Align);
3255 Store = DAG.getTruncStore(Chain, dl, Value,
3256 getMemBasePlusOffset(Dst, DstOff, DAG),
3257 DstSV, DstSVOff + DstOff, VT, false, DstAlign);
3259 OutChains.push_back(Store);
3264 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3265 &OutChains[0], OutChains.size());
3268 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3269 SDValue Chain, SDValue Dst,
3270 SDValue Src, uint64_t Size,
3271 unsigned Align, bool AlwaysInline,
3272 const Value *DstSV, uint64_t DstSVOff,
3273 const Value *SrcSV, uint64_t SrcSVOff){
3274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3276 // Expand memmove to a series of load and store ops if the size operand falls
3277 // below a certain threshold.
3278 std::vector<EVT> MemOps;
3279 uint64_t Limit = -1ULL;
3281 Limit = TLI.getMaxStoresPerMemmove();
3282 unsigned DstAlign = Align; // Destination alignment can change.
3285 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3286 Str, CopyFromStr, DAG, TLI))
3289 uint64_t SrcOff = 0, DstOff = 0;
3291 SmallVector<SDValue, 8> LoadValues;
3292 SmallVector<SDValue, 8> LoadChains;
3293 SmallVector<SDValue, 8> OutChains;
3294 unsigned NumMemOps = MemOps.size();
3295 for (unsigned i = 0; i < NumMemOps; i++) {
3297 unsigned VTSize = VT.getSizeInBits() / 8;
3298 SDValue Value, Store;
3300 Value = DAG.getLoad(VT, dl, Chain,
3301 getMemBasePlusOffset(Src, SrcOff, DAG),
3302 SrcSV, SrcSVOff + SrcOff, false, Align);
3303 LoadValues.push_back(Value);
3304 LoadChains.push_back(Value.getValue(1));
3307 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3308 &LoadChains[0], LoadChains.size());
3310 for (unsigned i = 0; i < NumMemOps; i++) {
3312 unsigned VTSize = VT.getSizeInBits() / 8;
3313 SDValue Value, Store;
3315 Store = DAG.getStore(Chain, dl, LoadValues[i],
3316 getMemBasePlusOffset(Dst, DstOff, DAG),
3317 DstSV, DstSVOff + DstOff, false, DstAlign);
3318 OutChains.push_back(Store);
3322 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3323 &OutChains[0], OutChains.size());
3326 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3327 SDValue Chain, SDValue Dst,
3328 SDValue Src, uint64_t Size,
3330 const Value *DstSV, uint64_t DstSVOff) {
3331 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3333 // Expand memset to a series of load/store ops if the size operand
3334 // falls below a certain threshold.
3335 std::vector<EVT> MemOps;
3338 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3339 Size, Align, Str, CopyFromStr, DAG, TLI))
3342 SmallVector<SDValue, 8> OutChains;
3343 uint64_t DstOff = 0;
3345 unsigned NumMemOps = MemOps.size();
3346 for (unsigned i = 0; i < NumMemOps; i++) {
3348 unsigned VTSize = VT.getSizeInBits() / 8;
3349 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3350 SDValue Store = DAG.getStore(Chain, dl, Value,
3351 getMemBasePlusOffset(Dst, DstOff, DAG),
3352 DstSV, DstSVOff + DstOff);
3353 OutChains.push_back(Store);
3357 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3358 &OutChains[0], OutChains.size());
3361 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3362 SDValue Src, SDValue Size,
3363 unsigned Align, bool AlwaysInline,
3364 const Value *DstSV, uint64_t DstSVOff,
3365 const Value *SrcSV, uint64_t SrcSVOff) {
3367 // Check to see if we should lower the memcpy to loads and stores first.
3368 // For cases within the target-specified limits, this is the best choice.
3369 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3371 // Memcpy with size zero? Just return the original chain.
3372 if (ConstantSize->isNullValue())
3376 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3377 ConstantSize->getZExtValue(),
3378 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3379 if (Result.getNode())
3383 // Then check to see if we should lower the memcpy with target-specific
3384 // code. If the target chooses to do this, this is the next best.
3386 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3388 DstSV, DstSVOff, SrcSV, SrcSVOff);
3389 if (Result.getNode())
3392 // If we really need inline code and the target declined to provide it,
3393 // use a (potentially long) sequence of loads and stores.
3395 assert(ConstantSize && "AlwaysInline requires a constant size!");
3396 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3397 ConstantSize->getZExtValue(), Align, true,
3398 DstSV, DstSVOff, SrcSV, SrcSVOff);
3401 // Emit a library call.
3402 TargetLowering::ArgListTy Args;
3403 TargetLowering::ArgListEntry Entry;
3404 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3405 Entry.Node = Dst; Args.push_back(Entry);
3406 Entry.Node = Src; Args.push_back(Entry);
3407 Entry.Node = Size; Args.push_back(Entry);
3408 // FIXME: pass in DebugLoc
3409 std::pair<SDValue,SDValue> CallResult =
3410 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3411 false, false, false, false, 0,
3412 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3413 /*isReturnValueUsed=*/false,
3414 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3415 TLI.getPointerTy()),
3417 return CallResult.second;
3420 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3421 SDValue Src, SDValue Size,
3423 const Value *DstSV, uint64_t DstSVOff,
3424 const Value *SrcSV, uint64_t SrcSVOff) {
3426 // Check to see if we should lower the memmove to loads and stores first.
3427 // For cases within the target-specified limits, this is the best choice.
3428 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3430 // Memmove with size zero? Just return the original chain.
3431 if (ConstantSize->isNullValue())
3435 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3436 ConstantSize->getZExtValue(),
3437 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3438 if (Result.getNode())
3442 // Then check to see if we should lower the memmove with target-specific
3443 // code. If the target chooses to do this, this is the next best.
3445 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3446 DstSV, DstSVOff, SrcSV, SrcSVOff);
3447 if (Result.getNode())
3450 // Emit a library call.
3451 TargetLowering::ArgListTy Args;
3452 TargetLowering::ArgListEntry Entry;
3453 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3454 Entry.Node = Dst; Args.push_back(Entry);
3455 Entry.Node = Src; Args.push_back(Entry);
3456 Entry.Node = Size; Args.push_back(Entry);
3457 // FIXME: pass in DebugLoc
3458 std::pair<SDValue,SDValue> CallResult =
3459 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3460 false, false, false, false, 0,
3461 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3462 /*isReturnValueUsed=*/false,
3463 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3464 TLI.getPointerTy()),
3466 return CallResult.second;
3469 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3470 SDValue Src, SDValue Size,
3472 const Value *DstSV, uint64_t DstSVOff) {
3474 // Check to see if we should lower the memset to stores first.
3475 // For cases within the target-specified limits, this is the best choice.
3476 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3478 // Memset with size zero? Just return the original chain.
3479 if (ConstantSize->isNullValue())
3483 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3484 Align, DstSV, DstSVOff);
3485 if (Result.getNode())
3489 // Then check to see if we should lower the memset with target-specific
3490 // code. If the target chooses to do this, this is the next best.
3492 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3494 if (Result.getNode())
3497 // Emit a library call.
3498 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3499 TargetLowering::ArgListTy Args;
3500 TargetLowering::ArgListEntry Entry;
3501 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3502 Args.push_back(Entry);
3503 // Extend or truncate the argument to be an i32 value for the call.
3504 if (Src.getValueType().bitsGT(MVT::i32))
3505 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3507 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3509 Entry.Ty = Type::getInt32Ty(*getContext());
3510 Entry.isSExt = true;
3511 Args.push_back(Entry);
3513 Entry.Ty = IntPtrTy;
3514 Entry.isSExt = false;
3515 Args.push_back(Entry);
3516 // FIXME: pass in DebugLoc
3517 std::pair<SDValue,SDValue> CallResult =
3518 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3519 false, false, false, false, 0,
3520 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3521 /*isReturnValueUsed=*/false,
3522 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3523 TLI.getPointerTy()),
3525 return CallResult.second;
3528 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3530 SDValue Ptr, SDValue Cmp,
3531 SDValue Swp, const Value* PtrVal,
3532 unsigned Alignment) {
3533 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3534 Alignment = getEVTAlignment(MemVT);
3536 // Check if the memory reference references a frame index
3538 if (const FrameIndexSDNode *FI =
3539 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3540 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3542 MachineFunction &MF = getMachineFunction();
3543 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3545 // For now, atomics are considered to be volatile always.
3546 Flags |= MachineMemOperand::MOVolatile;
3548 MachineMemOperand *MMO =
3549 MF.getMachineMemOperand(PtrVal, Flags, 0,
3550 MemVT.getStoreSize(), Alignment);
3552 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3555 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3557 SDValue Ptr, SDValue Cmp,
3558 SDValue Swp, MachineMemOperand *MMO) {
3559 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3560 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3562 EVT VT = Cmp.getValueType();
3564 SDVTList VTs = getVTList(VT, MVT::Other);
3565 FoldingSetNodeID ID;
3566 ID.AddInteger(MemVT.getRawBits());
3567 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3568 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3570 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3571 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3572 return SDValue(E, 0);
3574 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3575 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3576 CSEMap.InsertNode(N, IP);
3577 AllNodes.push_back(N);
3578 return SDValue(N, 0);
3581 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3583 SDValue Ptr, SDValue Val,
3584 const Value* PtrVal,
3585 unsigned Alignment) {
3586 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3587 Alignment = getEVTAlignment(MemVT);
3589 // Check if the memory reference references a frame index
3591 if (const FrameIndexSDNode *FI =
3592 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3593 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3595 MachineFunction &MF = getMachineFunction();
3596 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3598 // For now, atomics are considered to be volatile always.
3599 Flags |= MachineMemOperand::MOVolatile;
3601 MachineMemOperand *MMO =
3602 MF.getMachineMemOperand(PtrVal, Flags, 0,
3603 MemVT.getStoreSize(), Alignment);
3605 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
3608 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3610 SDValue Ptr, SDValue Val,
3611 MachineMemOperand *MMO) {
3612 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3613 Opcode == ISD::ATOMIC_LOAD_SUB ||
3614 Opcode == ISD::ATOMIC_LOAD_AND ||
3615 Opcode == ISD::ATOMIC_LOAD_OR ||
3616 Opcode == ISD::ATOMIC_LOAD_XOR ||
3617 Opcode == ISD::ATOMIC_LOAD_NAND ||
3618 Opcode == ISD::ATOMIC_LOAD_MIN ||
3619 Opcode == ISD::ATOMIC_LOAD_MAX ||
3620 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3621 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3622 Opcode == ISD::ATOMIC_SWAP) &&
3623 "Invalid Atomic Op");
3625 EVT VT = Val.getValueType();
3627 SDVTList VTs = getVTList(VT, MVT::Other);
3628 FoldingSetNodeID ID;
3629 ID.AddInteger(MemVT.getRawBits());
3630 SDValue Ops[] = {Chain, Ptr, Val};
3631 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3633 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3634 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3635 return SDValue(E, 0);
3637 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3638 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Val, MMO);
3639 CSEMap.InsertNode(N, IP);
3640 AllNodes.push_back(N);
3641 return SDValue(N, 0);
3644 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3645 /// Allowed to return something different (and simpler) if Simplify is true.
3646 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3651 SmallVector<EVT, 4> VTs;
3652 VTs.reserve(NumOps);
3653 for (unsigned i = 0; i < NumOps; ++i)
3654 VTs.push_back(Ops[i].getValueType());
3655 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3660 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3661 const EVT *VTs, unsigned NumVTs,
3662 const SDValue *Ops, unsigned NumOps,
3663 EVT MemVT, const Value *srcValue, int SVOff,
3664 unsigned Align, bool Vol,
3665 bool ReadMem, bool WriteMem) {
3666 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3667 MemVT, srcValue, SVOff, Align, Vol,
3672 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3673 const SDValue *Ops, unsigned NumOps,
3674 EVT MemVT, const Value *srcValue, int SVOff,
3675 unsigned Align, bool Vol,
3676 bool ReadMem, bool WriteMem) {
3677 if (Align == 0) // Ensure that codegen never sees alignment 0
3678 Align = getEVTAlignment(MemVT);
3680 MachineFunction &MF = getMachineFunction();
3683 Flags |= MachineMemOperand::MOStore;
3685 Flags |= MachineMemOperand::MOLoad;
3687 Flags |= MachineMemOperand::MOVolatile;
3688 MachineMemOperand *MMO =
3689 MF.getMachineMemOperand(srcValue, Flags, SVOff,
3690 MemVT.getStoreSize(), Align);
3692 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3696 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3697 const SDValue *Ops, unsigned NumOps,
3698 EVT MemVT, MachineMemOperand *MMO) {
3699 assert((Opcode == ISD::INTRINSIC_VOID ||
3700 Opcode == ISD::INTRINSIC_W_CHAIN ||
3701 (Opcode <= INT_MAX &&
3702 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
3703 "Opcode is not a memory-accessing opcode!");
3705 // Memoize the node unless it returns a flag.
3706 MemIntrinsicSDNode *N;
3707 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3708 FoldingSetNodeID ID;
3709 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3711 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3712 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
3713 return SDValue(E, 0);
3716 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3717 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3718 CSEMap.InsertNode(N, IP);
3720 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3721 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3723 AllNodes.push_back(N);
3724 return SDValue(N, 0);
3728 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3729 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3730 SDValue Ptr, SDValue Offset,
3731 const Value *SV, int SVOffset, EVT MemVT,
3732 bool isVolatile, unsigned Alignment) {
3733 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3734 Alignment = getEVTAlignment(VT);
3736 // Check if the memory reference references a frame index
3738 if (const FrameIndexSDNode *FI =
3739 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3740 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3742 MachineFunction &MF = getMachineFunction();
3743 unsigned Flags = MachineMemOperand::MOLoad;
3745 Flags |= MachineMemOperand::MOVolatile;
3746 MachineMemOperand *MMO =
3747 MF.getMachineMemOperand(SV, Flags, SVOffset,
3748 MemVT.getStoreSize(), Alignment);
3749 return getLoad(AM, dl, ExtType, VT, Chain, Ptr, Offset, MemVT, MMO);
3753 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3754 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3755 SDValue Ptr, SDValue Offset, EVT MemVT,
3756 MachineMemOperand *MMO) {
3758 ExtType = ISD::NON_EXTLOAD;
3759 } else if (ExtType == ISD::NON_EXTLOAD) {
3760 assert(VT == MemVT && "Non-extending load from different memory type!");
3764 assert(MemVT.getVectorNumElements() == VT.getVectorNumElements() &&
3765 "Invalid vector extload!");
3767 assert(MemVT.bitsLT(VT) &&
3768 "Should only be an extending load, not truncating!");
3769 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3770 "Cannot sign/zero extend a FP/Vector load!");
3771 assert(VT.isInteger() == MemVT.isInteger() &&
3772 "Cannot convert from FP to Int or Int -> FP!");
3775 bool Indexed = AM != ISD::UNINDEXED;
3776 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3777 "Unindexed load with an offset!");
3779 SDVTList VTs = Indexed ?
3780 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3781 SDValue Ops[] = { Chain, Ptr, Offset };
3782 FoldingSetNodeID ID;
3783 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3784 ID.AddInteger(MemVT.getRawBits());
3785 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile()));
3787 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3788 cast<LoadSDNode>(E)->refineAlignment(MMO);
3789 return SDValue(E, 0);
3791 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3792 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, MemVT, MMO);
3793 CSEMap.InsertNode(N, IP);
3794 AllNodes.push_back(N);
3795 return SDValue(N, 0);
3798 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
3799 SDValue Chain, SDValue Ptr,
3800 const Value *SV, int SVOffset,
3801 bool isVolatile, unsigned Alignment) {
3802 SDValue Undef = getUNDEF(Ptr.getValueType());
3803 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3804 SV, SVOffset, VT, isVolatile, Alignment);
3807 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
3808 SDValue Chain, SDValue Ptr,
3810 int SVOffset, EVT MemVT,
3811 bool isVolatile, unsigned Alignment) {
3812 SDValue Undef = getUNDEF(Ptr.getValueType());
3813 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3814 SV, SVOffset, MemVT, isVolatile, Alignment);
3818 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3819 SDValue Offset, ISD::MemIndexedMode AM) {
3820 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3821 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3822 "Load is already a indexed load!");
3823 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3824 LD->getChain(), Base, Offset, LD->getSrcValue(),
3825 LD->getSrcValueOffset(), LD->getMemoryVT(),
3826 LD->isVolatile(), LD->getAlignment());
3829 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3830 SDValue Ptr, const Value *SV, int SVOffset,
3831 bool isVolatile, unsigned Alignment) {
3832 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3833 Alignment = getEVTAlignment(Val.getValueType());
3835 // Check if the memory reference references a frame index
3837 if (const FrameIndexSDNode *FI =
3838 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3839 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3841 MachineFunction &MF = getMachineFunction();
3842 unsigned Flags = MachineMemOperand::MOStore;
3844 Flags |= MachineMemOperand::MOVolatile;
3845 MachineMemOperand *MMO =
3846 MF.getMachineMemOperand(SV, Flags, SVOffset,
3847 Val.getValueType().getStoreSize(), Alignment);
3849 return getStore(Chain, dl, Val, Ptr, MMO);
3852 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3853 SDValue Ptr, MachineMemOperand *MMO) {
3854 EVT VT = Val.getValueType();
3855 SDVTList VTs = getVTList(MVT::Other);
3856 SDValue Undef = getUNDEF(Ptr.getValueType());
3857 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3858 FoldingSetNodeID ID;
3859 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3860 ID.AddInteger(VT.getRawBits());
3861 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile()));
3863 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3864 cast<StoreSDNode>(E)->refineAlignment(MMO);
3865 return SDValue(E, 0);
3867 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3868 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false, VT, MMO);
3869 CSEMap.InsertNode(N, IP);
3870 AllNodes.push_back(N);
3871 return SDValue(N, 0);
3874 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3875 SDValue Ptr, const Value *SV,
3876 int SVOffset, EVT SVT,
3877 bool isVolatile, unsigned Alignment) {
3878 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3879 Alignment = getEVTAlignment(SVT);
3881 // Check if the memory reference references a frame index
3883 if (const FrameIndexSDNode *FI =
3884 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3885 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3887 MachineFunction &MF = getMachineFunction();
3888 unsigned Flags = MachineMemOperand::MOStore;
3890 Flags |= MachineMemOperand::MOVolatile;
3891 MachineMemOperand *MMO =
3892 MF.getMachineMemOperand(SV, Flags, SVOffset, SVT.getStoreSize(), Alignment);
3894 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
3897 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3898 SDValue Ptr, EVT SVT,
3899 MachineMemOperand *MMO) {
3900 EVT VT = Val.getValueType();
3903 return getStore(Chain, dl, Val, Ptr, MMO);
3905 assert(VT.bitsGT(SVT) && "Not a truncation?");
3906 assert(VT.isInteger() == SVT.isInteger() &&
3907 "Can't do FP-INT conversion!");
3910 SDVTList VTs = getVTList(MVT::Other);
3911 SDValue Undef = getUNDEF(Ptr.getValueType());
3912 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3913 FoldingSetNodeID ID;
3914 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3915 ID.AddInteger(SVT.getRawBits());
3916 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile()));
3918 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3919 cast<StoreSDNode>(E)->refineAlignment(MMO);
3920 return SDValue(E, 0);
3922 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3923 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true, SVT, MMO);
3924 CSEMap.InsertNode(N, IP);
3925 AllNodes.push_back(N);
3926 return SDValue(N, 0);
3930 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
3931 SDValue Offset, ISD::MemIndexedMode AM) {
3932 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3933 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3934 "Store is already a indexed store!");
3935 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3936 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3937 FoldingSetNodeID ID;
3938 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3939 ID.AddInteger(ST->getMemoryVT().getRawBits());
3940 ID.AddInteger(ST->getRawSubclassData());
3942 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3943 return SDValue(E, 0);
3944 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3945 new (N) StoreSDNode(Ops, dl, VTs, AM,
3946 ST->isTruncatingStore(), ST->getMemoryVT(),
3947 ST->getMemOperand());
3948 CSEMap.InsertNode(N, IP);
3949 AllNodes.push_back(N);
3950 return SDValue(N, 0);
3953 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
3954 SDValue Chain, SDValue Ptr,
3956 SDValue Ops[] = { Chain, Ptr, SV };
3957 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
3960 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3961 const SDUse *Ops, unsigned NumOps) {
3963 case 0: return getNode(Opcode, DL, VT);
3964 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3965 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3966 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3970 // Copy from an SDUse array into an SDValue array for use with
3971 // the regular getNode logic.
3972 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3973 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
3976 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3977 const SDValue *Ops, unsigned NumOps) {
3979 case 0: return getNode(Opcode, DL, VT);
3980 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3981 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3982 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3988 case ISD::SELECT_CC: {
3989 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3990 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3991 "LHS and RHS of condition must have same type!");
3992 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3993 "True and False arms of SelectCC must have same type!");
3994 assert(Ops[2].getValueType() == VT &&
3995 "select_cc node must be of same type as true and false value!");
3999 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4000 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4001 "LHS/RHS of comparison should match types!");
4008 SDVTList VTs = getVTList(VT);
4010 if (VT != MVT::Flag) {
4011 FoldingSetNodeID ID;
4012 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4015 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4016 return SDValue(E, 0);
4018 N = NodeAllocator.Allocate<SDNode>();
4019 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4020 CSEMap.InsertNode(N, IP);
4022 N = NodeAllocator.Allocate<SDNode>();
4023 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4026 AllNodes.push_back(N);
4030 return SDValue(N, 0);
4033 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4034 const std::vector<EVT> &ResultTys,
4035 const SDValue *Ops, unsigned NumOps) {
4036 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4040 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4041 const EVT *VTs, unsigned NumVTs,
4042 const SDValue *Ops, unsigned NumOps) {
4044 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4045 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4048 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4049 const SDValue *Ops, unsigned NumOps) {
4050 if (VTList.NumVTs == 1)
4051 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4055 // FIXME: figure out how to safely handle things like
4056 // int foo(int x) { return 1 << (x & 255); }
4057 // int bar() { return foo(256); }
4058 case ISD::SRA_PARTS:
4059 case ISD::SRL_PARTS:
4060 case ISD::SHL_PARTS:
4061 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4062 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4063 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4064 else if (N3.getOpcode() == ISD::AND)
4065 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4066 // If the and is only masking out bits that cannot effect the shift,
4067 // eliminate the and.
4068 unsigned NumBits = VT.getSizeInBits()*2;
4069 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4070 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4076 // Memoize the node unless it returns a flag.
4078 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4079 FoldingSetNodeID ID;
4080 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4082 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4083 return SDValue(E, 0);
4085 N = NodeAllocator.Allocate<UnarySDNode>();
4086 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4087 } else if (NumOps == 2) {
4088 N = NodeAllocator.Allocate<BinarySDNode>();
4089 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4090 } else if (NumOps == 3) {
4091 N = NodeAllocator.Allocate<TernarySDNode>();
4092 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4094 N = NodeAllocator.Allocate<SDNode>();
4095 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4097 CSEMap.InsertNode(N, IP);
4100 N = NodeAllocator.Allocate<UnarySDNode>();
4101 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4102 } else if (NumOps == 2) {
4103 N = NodeAllocator.Allocate<BinarySDNode>();
4104 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4105 } else if (NumOps == 3) {
4106 N = NodeAllocator.Allocate<TernarySDNode>();
4107 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4109 N = NodeAllocator.Allocate<SDNode>();
4110 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4113 AllNodes.push_back(N);
4117 return SDValue(N, 0);
4120 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4121 return getNode(Opcode, DL, VTList, 0, 0);
4124 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4126 SDValue Ops[] = { N1 };
4127 return getNode(Opcode, DL, VTList, Ops, 1);
4130 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4131 SDValue N1, SDValue N2) {
4132 SDValue Ops[] = { N1, N2 };
4133 return getNode(Opcode, DL, VTList, Ops, 2);
4136 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4137 SDValue N1, SDValue N2, SDValue N3) {
4138 SDValue Ops[] = { N1, N2, N3 };
4139 return getNode(Opcode, DL, VTList, Ops, 3);
4142 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4143 SDValue N1, SDValue N2, SDValue N3,
4145 SDValue Ops[] = { N1, N2, N3, N4 };
4146 return getNode(Opcode, DL, VTList, Ops, 4);
4149 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4150 SDValue N1, SDValue N2, SDValue N3,
4151 SDValue N4, SDValue N5) {
4152 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4153 return getNode(Opcode, DL, VTList, Ops, 5);
4156 SDVTList SelectionDAG::getVTList(EVT VT) {
4157 return makeVTList(SDNode::getValueTypeList(VT), 1);
4160 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4161 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4162 E = VTList.rend(); I != E; ++I)
4163 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4166 EVT *Array = Allocator.Allocate<EVT>(2);
4169 SDVTList Result = makeVTList(Array, 2);
4170 VTList.push_back(Result);
4174 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4175 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4176 E = VTList.rend(); I != E; ++I)
4177 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4181 EVT *Array = Allocator.Allocate<EVT>(3);
4185 SDVTList Result = makeVTList(Array, 3);
4186 VTList.push_back(Result);
4190 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4191 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4192 E = VTList.rend(); I != E; ++I)
4193 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4194 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4197 EVT *Array = Allocator.Allocate<EVT>(3);
4202 SDVTList Result = makeVTList(Array, 4);
4203 VTList.push_back(Result);
4207 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4209 case 0: llvm_unreachable("Cannot have nodes without results!");
4210 case 1: return getVTList(VTs[0]);
4211 case 2: return getVTList(VTs[0], VTs[1]);
4212 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4216 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4217 E = VTList.rend(); I != E; ++I) {
4218 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4221 bool NoMatch = false;
4222 for (unsigned i = 2; i != NumVTs; ++i)
4223 if (VTs[i] != I->VTs[i]) {
4231 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4232 std::copy(VTs, VTs+NumVTs, Array);
4233 SDVTList Result = makeVTList(Array, NumVTs);
4234 VTList.push_back(Result);
4239 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4240 /// specified operands. If the resultant node already exists in the DAG,
4241 /// this does not modify the specified node, instead it returns the node that
4242 /// already exists. If the resultant node does not exist in the DAG, the
4243 /// input node is returned. As a degenerate case, if you specify the same
4244 /// input operands as the node already has, the input node is returned.
4245 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4246 SDNode *N = InN.getNode();
4247 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4249 // Check to see if there is no change.
4250 if (Op == N->getOperand(0)) return InN;
4252 // See if the modified node already exists.
4253 void *InsertPos = 0;
4254 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4255 return SDValue(Existing, InN.getResNo());
4257 // Nope it doesn't. Remove the node from its current place in the maps.
4259 if (!RemoveNodeFromCSEMaps(N))
4262 // Now we update the operands.
4263 N->OperandList[0].set(Op);
4265 // If this gets put into a CSE map, add it.
4266 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4270 SDValue SelectionDAG::
4271 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4272 SDNode *N = InN.getNode();
4273 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4275 // Check to see if there is no change.
4276 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4277 return InN; // No operands changed, just return the input node.
4279 // See if the modified node already exists.
4280 void *InsertPos = 0;
4281 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4282 return SDValue(Existing, InN.getResNo());
4284 // Nope it doesn't. Remove the node from its current place in the maps.
4286 if (!RemoveNodeFromCSEMaps(N))
4289 // Now we update the operands.
4290 if (N->OperandList[0] != Op1)
4291 N->OperandList[0].set(Op1);
4292 if (N->OperandList[1] != Op2)
4293 N->OperandList[1].set(Op2);
4295 // If this gets put into a CSE map, add it.
4296 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4300 SDValue SelectionDAG::
4301 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4302 SDValue Ops[] = { Op1, Op2, Op3 };
4303 return UpdateNodeOperands(N, Ops, 3);
4306 SDValue SelectionDAG::
4307 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4308 SDValue Op3, SDValue Op4) {
4309 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4310 return UpdateNodeOperands(N, Ops, 4);
4313 SDValue SelectionDAG::
4314 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4315 SDValue Op3, SDValue Op4, SDValue Op5) {
4316 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4317 return UpdateNodeOperands(N, Ops, 5);
4320 SDValue SelectionDAG::
4321 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4322 SDNode *N = InN.getNode();
4323 assert(N->getNumOperands() == NumOps &&
4324 "Update with wrong number of operands");
4326 // Check to see if there is no change.
4327 bool AnyChange = false;
4328 for (unsigned i = 0; i != NumOps; ++i) {
4329 if (Ops[i] != N->getOperand(i)) {
4335 // No operands changed, just return the input node.
4336 if (!AnyChange) return InN;
4338 // See if the modified node already exists.
4339 void *InsertPos = 0;
4340 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4341 return SDValue(Existing, InN.getResNo());
4343 // Nope it doesn't. Remove the node from its current place in the maps.
4345 if (!RemoveNodeFromCSEMaps(N))
4348 // Now we update the operands.
4349 for (unsigned i = 0; i != NumOps; ++i)
4350 if (N->OperandList[i] != Ops[i])
4351 N->OperandList[i].set(Ops[i]);
4353 // If this gets put into a CSE map, add it.
4354 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4358 /// DropOperands - Release the operands and set this node to have
4360 void SDNode::DropOperands() {
4361 // Unlike the code in MorphNodeTo that does this, we don't need to
4362 // watch for dead nodes here.
4363 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4369 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4372 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4374 SDVTList VTs = getVTList(VT);
4375 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4378 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4379 EVT VT, SDValue Op1) {
4380 SDVTList VTs = getVTList(VT);
4381 SDValue Ops[] = { Op1 };
4382 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4385 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4386 EVT VT, SDValue Op1,
4388 SDVTList VTs = getVTList(VT);
4389 SDValue Ops[] = { Op1, Op2 };
4390 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4393 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4394 EVT VT, SDValue Op1,
4395 SDValue Op2, SDValue Op3) {
4396 SDVTList VTs = getVTList(VT);
4397 SDValue Ops[] = { Op1, Op2, Op3 };
4398 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4401 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4402 EVT VT, const SDValue *Ops,
4404 SDVTList VTs = getVTList(VT);
4405 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4408 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4409 EVT VT1, EVT VT2, const SDValue *Ops,
4411 SDVTList VTs = getVTList(VT1, VT2);
4412 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4415 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4417 SDVTList VTs = getVTList(VT1, VT2);
4418 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4421 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4422 EVT VT1, EVT VT2, EVT VT3,
4423 const SDValue *Ops, unsigned NumOps) {
4424 SDVTList VTs = getVTList(VT1, VT2, VT3);
4425 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4428 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4429 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4430 const SDValue *Ops, unsigned NumOps) {
4431 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4432 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4435 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4438 SDVTList VTs = getVTList(VT1, VT2);
4439 SDValue Ops[] = { Op1 };
4440 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4443 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4445 SDValue Op1, SDValue Op2) {
4446 SDVTList VTs = getVTList(VT1, VT2);
4447 SDValue Ops[] = { Op1, Op2 };
4448 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4451 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4453 SDValue Op1, SDValue Op2,
4455 SDVTList VTs = getVTList(VT1, VT2);
4456 SDValue Ops[] = { Op1, Op2, Op3 };
4457 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4460 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4461 EVT VT1, EVT VT2, EVT VT3,
4462 SDValue Op1, SDValue Op2,
4464 SDVTList VTs = getVTList(VT1, VT2, VT3);
4465 SDValue Ops[] = { Op1, Op2, Op3 };
4466 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4469 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4470 SDVTList VTs, const SDValue *Ops,
4472 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4475 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4477 SDVTList VTs = getVTList(VT);
4478 return MorphNodeTo(N, Opc, VTs, 0, 0);
4481 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4482 EVT VT, SDValue Op1) {
4483 SDVTList VTs = getVTList(VT);
4484 SDValue Ops[] = { Op1 };
4485 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4488 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4489 EVT VT, SDValue Op1,
4491 SDVTList VTs = getVTList(VT);
4492 SDValue Ops[] = { Op1, Op2 };
4493 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4496 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4497 EVT VT, SDValue Op1,
4498 SDValue Op2, SDValue Op3) {
4499 SDVTList VTs = getVTList(VT);
4500 SDValue Ops[] = { Op1, Op2, Op3 };
4501 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4504 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4505 EVT VT, const SDValue *Ops,
4507 SDVTList VTs = getVTList(VT);
4508 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4511 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4512 EVT VT1, EVT VT2, const SDValue *Ops,
4514 SDVTList VTs = getVTList(VT1, VT2);
4515 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4518 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4520 SDVTList VTs = getVTList(VT1, VT2);
4521 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4524 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4525 EVT VT1, EVT VT2, EVT VT3,
4526 const SDValue *Ops, unsigned NumOps) {
4527 SDVTList VTs = getVTList(VT1, VT2, VT3);
4528 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4531 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4534 SDVTList VTs = getVTList(VT1, VT2);
4535 SDValue Ops[] = { Op1 };
4536 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4539 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4541 SDValue Op1, SDValue Op2) {
4542 SDVTList VTs = getVTList(VT1, VT2);
4543 SDValue Ops[] = { Op1, Op2 };
4544 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4547 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4549 SDValue Op1, SDValue Op2,
4551 SDVTList VTs = getVTList(VT1, VT2);
4552 SDValue Ops[] = { Op1, Op2, Op3 };
4553 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4556 /// MorphNodeTo - These *mutate* the specified node to have the specified
4557 /// return type, opcode, and operands.
4559 /// Note that MorphNodeTo returns the resultant node. If there is already a
4560 /// node of the specified opcode and operands, it returns that node instead of
4561 /// the current one. Note that the DebugLoc need not be the same.
4563 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4564 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4565 /// node, and because it doesn't require CSE recalculation for any of
4566 /// the node's users.
4568 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4569 SDVTList VTs, const SDValue *Ops,
4571 // If an identical node already exists, use it.
4573 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4574 FoldingSetNodeID ID;
4575 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4576 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4580 if (!RemoveNodeFromCSEMaps(N))
4583 // Start the morphing.
4585 N->ValueList = VTs.VTs;
4586 N->NumValues = VTs.NumVTs;
4588 // Clear the operands list, updating used nodes to remove this from their
4589 // use list. Keep track of any operands that become dead as a result.
4590 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4591 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4593 SDNode *Used = Use.getNode();
4595 if (Used->use_empty())
4596 DeadNodeSet.insert(Used);
4599 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4600 // Initialize the memory references information.
4601 MN->setMemRefs(0, 0);
4602 // If NumOps is larger than the # of operands we can have in a
4603 // MachineSDNode, reallocate the operand list.
4604 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4605 if (MN->OperandsNeedDelete)
4606 delete[] MN->OperandList;
4607 if (NumOps > array_lengthof(MN->LocalOperands))
4608 // We're creating a final node that will live unmorphed for the
4609 // remainder of the current SelectionDAG iteration, so we can allocate
4610 // the operands directly out of a pool with no recycling metadata.
4611 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4614 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4615 MN->OperandsNeedDelete = false;
4617 MN->InitOperands(MN->OperandList, Ops, NumOps);
4619 // If NumOps is larger than the # of operands we currently have, reallocate
4620 // the operand list.
4621 if (NumOps > N->NumOperands) {
4622 if (N->OperandsNeedDelete)
4623 delete[] N->OperandList;
4624 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4625 N->OperandsNeedDelete = true;
4627 N->InitOperands(N->OperandList, Ops, NumOps);
4630 // Delete any nodes that are still dead after adding the uses for the
4632 SmallVector<SDNode *, 16> DeadNodes;
4633 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4634 E = DeadNodeSet.end(); I != E; ++I)
4635 if ((*I)->use_empty())
4636 DeadNodes.push_back(*I);
4637 RemoveDeadNodes(DeadNodes);
4640 CSEMap.InsertNode(N, IP); // Memoize the new node.
4645 /// getMachineNode - These are used for target selectors to create a new node
4646 /// with specified return type(s), MachineInstr opcode, and operands.
4648 /// Note that getMachineNode returns the resultant node. If there is already a
4649 /// node of the specified opcode and operands, it returns that node instead of
4650 /// the current one.
4652 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4653 SDVTList VTs = getVTList(VT);
4654 return getMachineNode(Opcode, dl, VTs, 0, 0);
4658 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
4659 SDVTList VTs = getVTList(VT);
4660 SDValue Ops[] = { Op1 };
4661 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4665 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4666 SDValue Op1, SDValue Op2) {
4667 SDVTList VTs = getVTList(VT);
4668 SDValue Ops[] = { Op1, Op2 };
4669 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4673 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4674 SDValue Op1, SDValue Op2, SDValue Op3) {
4675 SDVTList VTs = getVTList(VT);
4676 SDValue Ops[] = { Op1, Op2, Op3 };
4677 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4681 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4682 const SDValue *Ops, unsigned NumOps) {
4683 SDVTList VTs = getVTList(VT);
4684 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4688 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
4689 SDVTList VTs = getVTList(VT1, VT2);
4690 return getMachineNode(Opcode, dl, VTs, 0, 0);
4694 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4695 EVT VT1, EVT VT2, SDValue Op1) {
4696 SDVTList VTs = getVTList(VT1, VT2);
4697 SDValue Ops[] = { Op1 };
4698 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4702 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4703 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
4704 SDVTList VTs = getVTList(VT1, VT2);
4705 SDValue Ops[] = { Op1, Op2 };
4706 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4710 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4711 EVT VT1, EVT VT2, SDValue Op1,
4712 SDValue Op2, SDValue Op3) {
4713 SDVTList VTs = getVTList(VT1, VT2);
4714 SDValue Ops[] = { Op1, Op2, Op3 };
4715 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4719 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4721 const SDValue *Ops, unsigned NumOps) {
4722 SDVTList VTs = getVTList(VT1, VT2);
4723 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4727 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4728 EVT VT1, EVT VT2, EVT VT3,
4729 SDValue Op1, SDValue Op2) {
4730 SDVTList VTs = getVTList(VT1, VT2, VT3);
4731 SDValue Ops[] = { Op1, Op2 };
4732 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4736 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4737 EVT VT1, EVT VT2, EVT VT3,
4738 SDValue Op1, SDValue Op2, SDValue Op3) {
4739 SDVTList VTs = getVTList(VT1, VT2, VT3);
4740 SDValue Ops[] = { Op1, Op2, Op3 };
4741 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4745 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4746 EVT VT1, EVT VT2, EVT VT3,
4747 const SDValue *Ops, unsigned NumOps) {
4748 SDVTList VTs = getVTList(VT1, VT2, VT3);
4749 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4753 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4754 EVT VT2, EVT VT3, EVT VT4,
4755 const SDValue *Ops, unsigned NumOps) {
4756 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4757 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4761 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4762 const std::vector<EVT> &ResultTys,
4763 const SDValue *Ops, unsigned NumOps) {
4764 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
4765 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4769 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
4770 const SDValue *Ops, unsigned NumOps) {
4771 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Flag;
4776 FoldingSetNodeID ID;
4777 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
4779 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4780 return cast<MachineSDNode>(E);
4783 // Allocate a new MachineSDNode.
4784 N = NodeAllocator.Allocate<MachineSDNode>();
4785 new (N) MachineSDNode(~Opcode, DL, VTs);
4787 // Initialize the operands list.
4788 if (NumOps > array_lengthof(N->LocalOperands))
4789 // We're creating a final node that will live unmorphed for the
4790 // remainder of the current SelectionDAG iteration, so we can allocate
4791 // the operands directly out of a pool with no recycling metadata.
4792 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4795 N->InitOperands(N->LocalOperands, Ops, NumOps);
4796 N->OperandsNeedDelete = false;
4799 CSEMap.InsertNode(N, IP);
4801 AllNodes.push_back(N);
4808 /// getTargetExtractSubreg - A convenience function for creating
4809 /// TargetInstrInfo::EXTRACT_SUBREG nodes.
4811 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4813 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4814 SDNode *Subreg = getMachineNode(TargetInstrInfo::EXTRACT_SUBREG, DL,
4815 VT, Operand, SRIdxVal);
4816 return SDValue(Subreg, 0);
4819 /// getTargetInsertSubreg - A convenience function for creating
4820 /// TargetInstrInfo::INSERT_SUBREG nodes.
4822 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
4823 SDValue Operand, SDValue Subreg) {
4824 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4825 SDNode *Result = getMachineNode(TargetInstrInfo::INSERT_SUBREG, DL,
4826 VT, Operand, Subreg, SRIdxVal);
4827 return SDValue(Result, 0);
4830 /// getNodeIfExists - Get the specified node if it's already available, or
4831 /// else return NULL.
4832 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4833 const SDValue *Ops, unsigned NumOps) {
4834 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4835 FoldingSetNodeID ID;
4836 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4838 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4844 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4845 /// This can cause recursive merging of nodes in the DAG.
4847 /// This version assumes From has a single result value.
4849 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4850 DAGUpdateListener *UpdateListener) {
4851 SDNode *From = FromN.getNode();
4852 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4853 "Cannot replace with this method!");
4854 assert(From != To.getNode() && "Cannot replace uses of with self");
4856 // Iterate over all the existing uses of From. New uses will be added
4857 // to the beginning of the use list, which we avoid visiting.
4858 // This specifically avoids visiting uses of From that arise while the
4859 // replacement is happening, because any such uses would be the result
4860 // of CSE: If an existing node looks like From after one of its operands
4861 // is replaced by To, we don't want to replace of all its users with To
4862 // too. See PR3018 for more info.
4863 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4867 // This node is about to morph, remove its old self from the CSE maps.
4868 RemoveNodeFromCSEMaps(User);
4870 // A user can appear in a use list multiple times, and when this
4871 // happens the uses are usually next to each other in the list.
4872 // To help reduce the number of CSE recomputations, process all
4873 // the uses of this user that we can find this way.
4875 SDUse &Use = UI.getUse();
4878 } while (UI != UE && *UI == User);
4880 // Now that we have modified User, add it back to the CSE maps. If it
4881 // already exists there, recursively merge the results together.
4882 AddModifiedNodeToCSEMaps(User, UpdateListener);
4886 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4887 /// This can cause recursive merging of nodes in the DAG.
4889 /// This version assumes that for each value of From, there is a
4890 /// corresponding value in To in the same position with the same type.
4892 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4893 DAGUpdateListener *UpdateListener) {
4895 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
4896 assert((!From->hasAnyUseOfValue(i) ||
4897 From->getValueType(i) == To->getValueType(i)) &&
4898 "Cannot use this version of ReplaceAllUsesWith!");
4901 // Handle the trivial case.
4905 // Iterate over just the existing users of From. See the comments in
4906 // the ReplaceAllUsesWith above.
4907 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4911 // This node is about to morph, remove its old self from the CSE maps.
4912 RemoveNodeFromCSEMaps(User);
4914 // A user can appear in a use list multiple times, and when this
4915 // happens the uses are usually next to each other in the list.
4916 // To help reduce the number of CSE recomputations, process all
4917 // the uses of this user that we can find this way.
4919 SDUse &Use = UI.getUse();
4922 } while (UI != UE && *UI == User);
4924 // Now that we have modified User, add it back to the CSE maps. If it
4925 // already exists there, recursively merge the results together.
4926 AddModifiedNodeToCSEMaps(User, UpdateListener);
4930 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4931 /// This can cause recursive merging of nodes in the DAG.
4933 /// This version can replace From with any result values. To must match the
4934 /// number and types of values returned by From.
4935 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4937 DAGUpdateListener *UpdateListener) {
4938 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4939 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4941 // Iterate over just the existing users of From. See the comments in
4942 // the ReplaceAllUsesWith above.
4943 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4947 // This node is about to morph, remove its old self from the CSE maps.
4948 RemoveNodeFromCSEMaps(User);
4950 // A user can appear in a use list multiple times, and when this
4951 // happens the uses are usually next to each other in the list.
4952 // To help reduce the number of CSE recomputations, process all
4953 // the uses of this user that we can find this way.
4955 SDUse &Use = UI.getUse();
4956 const SDValue &ToOp = To[Use.getResNo()];
4959 } while (UI != UE && *UI == User);
4961 // Now that we have modified User, add it back to the CSE maps. If it
4962 // already exists there, recursively merge the results together.
4963 AddModifiedNodeToCSEMaps(User, UpdateListener);
4967 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4968 /// uses of other values produced by From.getNode() alone. The Deleted
4969 /// vector is handled the same way as for ReplaceAllUsesWith.
4970 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4971 DAGUpdateListener *UpdateListener){
4972 // Handle the really simple, really trivial case efficiently.
4973 if (From == To) return;
4975 // Handle the simple, trivial, case efficiently.
4976 if (From.getNode()->getNumValues() == 1) {
4977 ReplaceAllUsesWith(From, To, UpdateListener);
4981 // Iterate over just the existing users of From. See the comments in
4982 // the ReplaceAllUsesWith above.
4983 SDNode::use_iterator UI = From.getNode()->use_begin(),
4984 UE = From.getNode()->use_end();
4987 bool UserRemovedFromCSEMaps = false;
4989 // A user can appear in a use list multiple times, and when this
4990 // happens the uses are usually next to each other in the list.
4991 // To help reduce the number of CSE recomputations, process all
4992 // the uses of this user that we can find this way.
4994 SDUse &Use = UI.getUse();
4996 // Skip uses of different values from the same node.
4997 if (Use.getResNo() != From.getResNo()) {
5002 // If this node hasn't been modified yet, it's still in the CSE maps,
5003 // so remove its old self from the CSE maps.
5004 if (!UserRemovedFromCSEMaps) {
5005 RemoveNodeFromCSEMaps(User);
5006 UserRemovedFromCSEMaps = true;
5011 } while (UI != UE && *UI == User);
5013 // We are iterating over all uses of the From node, so if a use
5014 // doesn't use the specific value, no changes are made.
5015 if (!UserRemovedFromCSEMaps)
5018 // Now that we have modified User, add it back to the CSE maps. If it
5019 // already exists there, recursively merge the results together.
5020 AddModifiedNodeToCSEMaps(User, UpdateListener);
5025 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5026 /// to record information about a use.
5033 /// operator< - Sort Memos by User.
5034 bool operator<(const UseMemo &L, const UseMemo &R) {
5035 return (intptr_t)L.User < (intptr_t)R.User;
5039 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5040 /// uses of other values produced by From.getNode() alone. The same value
5041 /// may appear in both the From and To list. The Deleted vector is
5042 /// handled the same way as for ReplaceAllUsesWith.
5043 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5046 DAGUpdateListener *UpdateListener){
5047 // Handle the simple, trivial case efficiently.
5049 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5051 // Read up all the uses and make records of them. This helps
5052 // processing new uses that are introduced during the
5053 // replacement process.
5054 SmallVector<UseMemo, 4> Uses;
5055 for (unsigned i = 0; i != Num; ++i) {
5056 unsigned FromResNo = From[i].getResNo();
5057 SDNode *FromNode = From[i].getNode();
5058 for (SDNode::use_iterator UI = FromNode->use_begin(),
5059 E = FromNode->use_end(); UI != E; ++UI) {
5060 SDUse &Use = UI.getUse();
5061 if (Use.getResNo() == FromResNo) {
5062 UseMemo Memo = { *UI, i, &Use };
5063 Uses.push_back(Memo);
5068 // Sort the uses, so that all the uses from a given User are together.
5069 std::sort(Uses.begin(), Uses.end());
5071 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5072 UseIndex != UseIndexEnd; ) {
5073 // We know that this user uses some value of From. If it is the right
5074 // value, update it.
5075 SDNode *User = Uses[UseIndex].User;
5077 // This node is about to morph, remove its old self from the CSE maps.
5078 RemoveNodeFromCSEMaps(User);
5080 // The Uses array is sorted, so all the uses for a given User
5081 // are next to each other in the list.
5082 // To help reduce the number of CSE recomputations, process all
5083 // the uses of this user that we can find this way.
5085 unsigned i = Uses[UseIndex].Index;
5086 SDUse &Use = *Uses[UseIndex].Use;
5090 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5092 // Now that we have modified User, add it back to the CSE maps. If it
5093 // already exists there, recursively merge the results together.
5094 AddModifiedNodeToCSEMaps(User, UpdateListener);
5098 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5099 /// based on their topological order. It returns the maximum id and a vector
5100 /// of the SDNodes* in assigned order by reference.
5101 unsigned SelectionDAG::AssignTopologicalOrder() {
5103 unsigned DAGSize = 0;
5105 // SortedPos tracks the progress of the algorithm. Nodes before it are
5106 // sorted, nodes after it are unsorted. When the algorithm completes
5107 // it is at the end of the list.
5108 allnodes_iterator SortedPos = allnodes_begin();
5110 // Visit all the nodes. Move nodes with no operands to the front of
5111 // the list immediately. Annotate nodes that do have operands with their
5112 // operand count. Before we do this, the Node Id fields of the nodes
5113 // may contain arbitrary values. After, the Node Id fields for nodes
5114 // before SortedPos will contain the topological sort index, and the
5115 // Node Id fields for nodes At SortedPos and after will contain the
5116 // count of outstanding operands.
5117 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5119 unsigned Degree = N->getNumOperands();
5121 // A node with no uses, add it to the result array immediately.
5122 N->setNodeId(DAGSize++);
5123 allnodes_iterator Q = N;
5125 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5128 // Temporarily use the Node Id as scratch space for the degree count.
5129 N->setNodeId(Degree);
5133 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5134 // such that by the time the end is reached all nodes will be sorted.
5135 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5137 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5140 unsigned Degree = P->getNodeId();
5143 // All of P's operands are sorted, so P may sorted now.
5144 P->setNodeId(DAGSize++);
5146 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5149 // Update P's outstanding operand count.
5150 P->setNodeId(Degree);
5155 assert(SortedPos == AllNodes.end() &&
5156 "Topological sort incomplete!");
5157 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5158 "First node in topological sort is not the entry token!");
5159 assert(AllNodes.front().getNodeId() == 0 &&
5160 "First node in topological sort has non-zero id!");
5161 assert(AllNodes.front().getNumOperands() == 0 &&
5162 "First node in topological sort has operands!");
5163 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5164 "Last node in topologic sort has unexpected id!");
5165 assert(AllNodes.back().use_empty() &&
5166 "Last node in topologic sort has users!");
5167 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5173 //===----------------------------------------------------------------------===//
5175 //===----------------------------------------------------------------------===//
5177 HandleSDNode::~HandleSDNode() {
5181 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
5182 EVT VT, int64_t o, unsigned char TF)
5183 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
5184 Offset(o), TargetFlags(TF) {
5185 TheGlobal = const_cast<GlobalValue*>(GA);
5188 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5189 MachineMemOperand *mmo)
5190 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5191 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile());
5192 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5193 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5196 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5197 const SDValue *Ops, unsigned NumOps, EVT memvt,
5198 MachineMemOperand *mmo)
5199 : SDNode(Opc, dl, VTs, Ops, NumOps),
5200 MemoryVT(memvt), MMO(mmo) {
5201 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile());
5202 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5203 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5206 /// Profile - Gather unique data for the node.
5208 void SDNode::Profile(FoldingSetNodeID &ID) const {
5209 AddNodeIDNode(ID, this);
5214 std::vector<EVT> VTs;
5217 VTs.reserve(MVT::LAST_VALUETYPE);
5218 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5219 VTs.push_back(MVT((MVT::SimpleValueType)i));
5224 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5225 static ManagedStatic<EVTArray> SimpleVTArray;
5226 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5228 /// getValueTypeList - Return a pointer to the specified value type.
5230 const EVT *SDNode::getValueTypeList(EVT VT) {
5231 if (VT.isExtended()) {
5232 sys::SmartScopedLock<true> Lock(*VTMutex);
5233 return &(*EVTs->insert(VT).first);
5235 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5239 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5240 /// indicated value. This method ignores uses of other values defined by this
5242 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5243 assert(Value < getNumValues() && "Bad value!");
5245 // TODO: Only iterate over uses of a given value of the node
5246 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5247 if (UI.getUse().getResNo() == Value) {
5254 // Found exactly the right number of uses?
5259 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5260 /// value. This method ignores uses of other values defined by this operation.
5261 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5262 assert(Value < getNumValues() && "Bad value!");
5264 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5265 if (UI.getUse().getResNo() == Value)
5272 /// isOnlyUserOf - Return true if this node is the only use of N.
5274 bool SDNode::isOnlyUserOf(SDNode *N) const {
5276 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5287 /// isOperand - Return true if this node is an operand of N.
5289 bool SDValue::isOperandOf(SDNode *N) const {
5290 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5291 if (*this == N->getOperand(i))
5296 bool SDNode::isOperandOf(SDNode *N) const {
5297 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5298 if (this == N->OperandList[i].getNode())
5303 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5304 /// be a chain) reaches the specified operand without crossing any
5305 /// side-effecting instructions. In practice, this looks through token
5306 /// factors and non-volatile loads. In order to remain efficient, this only
5307 /// looks a couple of nodes in, it does not do an exhaustive search.
5308 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5309 unsigned Depth) const {
5310 if (*this == Dest) return true;
5312 // Don't search too deeply, we just want to be able to see through
5313 // TokenFactor's etc.
5314 if (Depth == 0) return false;
5316 // If this is a token factor, all inputs to the TF happen in parallel. If any
5317 // of the operands of the TF reach dest, then we can do the xform.
5318 if (getOpcode() == ISD::TokenFactor) {
5319 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5320 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5325 // Loads don't have side effects, look through them.
5326 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5327 if (!Ld->isVolatile())
5328 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5333 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5334 /// is either an operand of N or it can be reached by traversing up the operands.
5335 /// NOTE: this is an expensive method. Use it carefully.
5336 bool SDNode::isPredecessorOf(SDNode *N) const {
5337 SmallPtrSet<SDNode *, 32> Visited;
5338 SmallVector<SDNode *, 16> Worklist;
5339 Worklist.push_back(N);
5342 N = Worklist.pop_back_val();
5343 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5344 SDNode *Op = N->getOperand(i).getNode();
5347 if (Visited.insert(Op))
5348 Worklist.push_back(Op);
5350 } while (!Worklist.empty());
5355 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5356 assert(Num < NumOperands && "Invalid child # of SDNode!");
5357 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5360 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5361 switch (getOpcode()) {
5363 if (getOpcode() < ISD::BUILTIN_OP_END)
5364 return "<<Unknown DAG Node>>";
5365 if (isMachineOpcode()) {
5367 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5368 if (getMachineOpcode() < TII->getNumOpcodes())
5369 return TII->get(getMachineOpcode()).getName();
5370 return "<<Unknown Machine Node>>";
5373 const TargetLowering &TLI = G->getTargetLoweringInfo();
5374 const char *Name = TLI.getTargetNodeName(getOpcode());
5375 if (Name) return Name;
5376 return "<<Unknown Target Node>>";
5378 return "<<Unknown Node>>";
5381 case ISD::DELETED_NODE:
5382 return "<<Deleted Node!>>";
5384 case ISD::PREFETCH: return "Prefetch";
5385 case ISD::MEMBARRIER: return "MemBarrier";
5386 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5387 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5388 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5389 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5390 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5391 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5392 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5393 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5394 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5395 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5396 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5397 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5398 case ISD::PCMARKER: return "PCMarker";
5399 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5400 case ISD::SRCVALUE: return "SrcValue";
5401 case ISD::EntryToken: return "EntryToken";
5402 case ISD::TokenFactor: return "TokenFactor";
5403 case ISD::AssertSext: return "AssertSext";
5404 case ISD::AssertZext: return "AssertZext";
5406 case ISD::BasicBlock: return "BasicBlock";
5407 case ISD::VALUETYPE: return "ValueType";
5408 case ISD::Register: return "Register";
5410 case ISD::Constant: return "Constant";
5411 case ISD::ConstantFP: return "ConstantFP";
5412 case ISD::GlobalAddress: return "GlobalAddress";
5413 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5414 case ISD::FrameIndex: return "FrameIndex";
5415 case ISD::JumpTable: return "JumpTable";
5416 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5417 case ISD::RETURNADDR: return "RETURNADDR";
5418 case ISD::FRAMEADDR: return "FRAMEADDR";
5419 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5420 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5421 case ISD::LSDAADDR: return "LSDAADDR";
5422 case ISD::EHSELECTION: return "EHSELECTION";
5423 case ISD::EH_RETURN: return "EH_RETURN";
5424 case ISD::ConstantPool: return "ConstantPool";
5425 case ISD::ExternalSymbol: return "ExternalSymbol";
5426 case ISD::BlockAddress: return "BlockAddress";
5427 case ISD::INTRINSIC_WO_CHAIN:
5428 case ISD::INTRINSIC_VOID:
5429 case ISD::INTRINSIC_W_CHAIN: {
5430 unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5431 unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5432 if (IID < Intrinsic::num_intrinsics)
5433 return Intrinsic::getName((Intrinsic::ID)IID);
5434 else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5435 return TII->getName(IID);
5436 llvm_unreachable("Invalid intrinsic ID");
5439 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5440 case ISD::TargetConstant: return "TargetConstant";
5441 case ISD::TargetConstantFP:return "TargetConstantFP";
5442 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5443 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5444 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5445 case ISD::TargetJumpTable: return "TargetJumpTable";
5446 case ISD::TargetConstantPool: return "TargetConstantPool";
5447 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5448 case ISD::TargetBlockAddress: return "TargetBlockAddress";
5450 case ISD::CopyToReg: return "CopyToReg";
5451 case ISD::CopyFromReg: return "CopyFromReg";
5452 case ISD::UNDEF: return "undef";
5453 case ISD::MERGE_VALUES: return "merge_values";
5454 case ISD::INLINEASM: return "inlineasm";
5455 case ISD::DBG_LABEL: return "dbg_label";
5456 case ISD::EH_LABEL: return "eh_label";
5457 case ISD::HANDLENODE: return "handlenode";
5460 case ISD::FABS: return "fabs";
5461 case ISD::FNEG: return "fneg";
5462 case ISD::FSQRT: return "fsqrt";
5463 case ISD::FSIN: return "fsin";
5464 case ISD::FCOS: return "fcos";
5465 case ISD::FPOWI: return "fpowi";
5466 case ISD::FPOW: return "fpow";
5467 case ISD::FTRUNC: return "ftrunc";
5468 case ISD::FFLOOR: return "ffloor";
5469 case ISD::FCEIL: return "fceil";
5470 case ISD::FRINT: return "frint";
5471 case ISD::FNEARBYINT: return "fnearbyint";
5474 case ISD::ADD: return "add";
5475 case ISD::SUB: return "sub";
5476 case ISD::MUL: return "mul";
5477 case ISD::MULHU: return "mulhu";
5478 case ISD::MULHS: return "mulhs";
5479 case ISD::SDIV: return "sdiv";
5480 case ISD::UDIV: return "udiv";
5481 case ISD::SREM: return "srem";
5482 case ISD::UREM: return "urem";
5483 case ISD::SMUL_LOHI: return "smul_lohi";
5484 case ISD::UMUL_LOHI: return "umul_lohi";
5485 case ISD::SDIVREM: return "sdivrem";
5486 case ISD::UDIVREM: return "udivrem";
5487 case ISD::AND: return "and";
5488 case ISD::OR: return "or";
5489 case ISD::XOR: return "xor";
5490 case ISD::SHL: return "shl";
5491 case ISD::SRA: return "sra";
5492 case ISD::SRL: return "srl";
5493 case ISD::ROTL: return "rotl";
5494 case ISD::ROTR: return "rotr";
5495 case ISD::FADD: return "fadd";
5496 case ISD::FSUB: return "fsub";
5497 case ISD::FMUL: return "fmul";
5498 case ISD::FDIV: return "fdiv";
5499 case ISD::FREM: return "frem";
5500 case ISD::FCOPYSIGN: return "fcopysign";
5501 case ISD::FGETSIGN: return "fgetsign";
5503 case ISD::SETCC: return "setcc";
5504 case ISD::VSETCC: return "vsetcc";
5505 case ISD::SELECT: return "select";
5506 case ISD::SELECT_CC: return "select_cc";
5507 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5508 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5509 case ISD::CONCAT_VECTORS: return "concat_vectors";
5510 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5511 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5512 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5513 case ISD::CARRY_FALSE: return "carry_false";
5514 case ISD::ADDC: return "addc";
5515 case ISD::ADDE: return "adde";
5516 case ISD::SADDO: return "saddo";
5517 case ISD::UADDO: return "uaddo";
5518 case ISD::SSUBO: return "ssubo";
5519 case ISD::USUBO: return "usubo";
5520 case ISD::SMULO: return "smulo";
5521 case ISD::UMULO: return "umulo";
5522 case ISD::SUBC: return "subc";
5523 case ISD::SUBE: return "sube";
5524 case ISD::SHL_PARTS: return "shl_parts";
5525 case ISD::SRA_PARTS: return "sra_parts";
5526 case ISD::SRL_PARTS: return "srl_parts";
5528 // Conversion operators.
5529 case ISD::SIGN_EXTEND: return "sign_extend";
5530 case ISD::ZERO_EXTEND: return "zero_extend";
5531 case ISD::ANY_EXTEND: return "any_extend";
5532 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5533 case ISD::TRUNCATE: return "truncate";
5534 case ISD::FP_ROUND: return "fp_round";
5535 case ISD::FLT_ROUNDS_: return "flt_rounds";
5536 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5537 case ISD::FP_EXTEND: return "fp_extend";
5539 case ISD::SINT_TO_FP: return "sint_to_fp";
5540 case ISD::UINT_TO_FP: return "uint_to_fp";
5541 case ISD::FP_TO_SINT: return "fp_to_sint";
5542 case ISD::FP_TO_UINT: return "fp_to_uint";
5543 case ISD::BIT_CONVERT: return "bit_convert";
5545 case ISD::CONVERT_RNDSAT: {
5546 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5547 default: llvm_unreachable("Unknown cvt code!");
5548 case ISD::CVT_FF: return "cvt_ff";
5549 case ISD::CVT_FS: return "cvt_fs";
5550 case ISD::CVT_FU: return "cvt_fu";
5551 case ISD::CVT_SF: return "cvt_sf";
5552 case ISD::CVT_UF: return "cvt_uf";
5553 case ISD::CVT_SS: return "cvt_ss";
5554 case ISD::CVT_SU: return "cvt_su";
5555 case ISD::CVT_US: return "cvt_us";
5556 case ISD::CVT_UU: return "cvt_uu";
5560 // Control flow instructions
5561 case ISD::BR: return "br";
5562 case ISD::BRIND: return "brind";
5563 case ISD::BR_JT: return "br_jt";
5564 case ISD::BRCOND: return "brcond";
5565 case ISD::BR_CC: return "br_cc";
5566 case ISD::CALLSEQ_START: return "callseq_start";
5567 case ISD::CALLSEQ_END: return "callseq_end";
5570 case ISD::LOAD: return "load";
5571 case ISD::STORE: return "store";
5572 case ISD::VAARG: return "vaarg";
5573 case ISD::VACOPY: return "vacopy";
5574 case ISD::VAEND: return "vaend";
5575 case ISD::VASTART: return "vastart";
5576 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5577 case ISD::EXTRACT_ELEMENT: return "extract_element";
5578 case ISD::BUILD_PAIR: return "build_pair";
5579 case ISD::STACKSAVE: return "stacksave";
5580 case ISD::STACKRESTORE: return "stackrestore";
5581 case ISD::TRAP: return "trap";
5584 case ISD::BSWAP: return "bswap";
5585 case ISD::CTPOP: return "ctpop";
5586 case ISD::CTTZ: return "cttz";
5587 case ISD::CTLZ: return "ctlz";
5590 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5591 case ISD::DEBUG_LOC: return "debug_loc";
5594 case ISD::TRAMPOLINE: return "trampoline";
5597 switch (cast<CondCodeSDNode>(this)->get()) {
5598 default: llvm_unreachable("Unknown setcc condition!");
5599 case ISD::SETOEQ: return "setoeq";
5600 case ISD::SETOGT: return "setogt";
5601 case ISD::SETOGE: return "setoge";
5602 case ISD::SETOLT: return "setolt";
5603 case ISD::SETOLE: return "setole";
5604 case ISD::SETONE: return "setone";
5606 case ISD::SETO: return "seto";
5607 case ISD::SETUO: return "setuo";
5608 case ISD::SETUEQ: return "setue";
5609 case ISD::SETUGT: return "setugt";
5610 case ISD::SETUGE: return "setuge";
5611 case ISD::SETULT: return "setult";
5612 case ISD::SETULE: return "setule";
5613 case ISD::SETUNE: return "setune";
5615 case ISD::SETEQ: return "seteq";
5616 case ISD::SETGT: return "setgt";
5617 case ISD::SETGE: return "setge";
5618 case ISD::SETLT: return "setlt";
5619 case ISD::SETLE: return "setle";
5620 case ISD::SETNE: return "setne";
5625 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5634 return "<post-inc>";
5636 return "<post-dec>";
5640 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5641 std::string S = "< ";
5655 if (getByValAlign())
5656 S += "byval-align:" + utostr(getByValAlign()) + " ";
5658 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5660 S += "byval-size:" + utostr(getByValSize()) + " ";
5664 void SDNode::dump() const { dump(0); }
5665 void SDNode::dump(const SelectionDAG *G) const {
5669 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5670 OS << (void*)this << ": ";
5672 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5674 if (getValueType(i) == MVT::Other)
5677 OS << getValueType(i).getEVTString();
5679 OS << " = " << getOperationName(G);
5682 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5683 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
5684 if (!MN->memoperands_empty()) {
5687 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
5688 e = MN->memoperands_end(); i != e; ++i) {
5695 } else if (const ShuffleVectorSDNode *SVN =
5696 dyn_cast<ShuffleVectorSDNode>(this)) {
5698 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5699 int Idx = SVN->getMaskElt(i);
5707 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5708 OS << '<' << CSDN->getAPIntValue() << '>';
5709 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5710 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5711 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5712 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5713 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5716 CSDN->getValueAPF().bitcastToAPInt().dump();
5719 } else if (const GlobalAddressSDNode *GADN =
5720 dyn_cast<GlobalAddressSDNode>(this)) {
5721 int64_t offset = GADN->getOffset();
5723 WriteAsOperand(OS, GADN->getGlobal());
5726 OS << " + " << offset;
5728 OS << " " << offset;
5729 if (unsigned int TF = GADN->getTargetFlags())
5730 OS << " [TF=" << TF << ']';
5731 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5732 OS << "<" << FIDN->getIndex() << ">";
5733 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5734 OS << "<" << JTDN->getIndex() << ">";
5735 if (unsigned int TF = JTDN->getTargetFlags())
5736 OS << " [TF=" << TF << ']';
5737 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5738 int offset = CP->getOffset();
5739 if (CP->isMachineConstantPoolEntry())
5740 OS << "<" << *CP->getMachineCPVal() << ">";
5742 OS << "<" << *CP->getConstVal() << ">";
5744 OS << " + " << offset;
5746 OS << " " << offset;
5747 if (unsigned int TF = CP->getTargetFlags())
5748 OS << " [TF=" << TF << ']';
5749 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5751 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5753 OS << LBB->getName() << " ";
5754 OS << (const void*)BBDN->getBasicBlock() << ">";
5755 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5756 if (G && R->getReg() &&
5757 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5758 OS << " %" << G->getTarget().getRegisterInfo()->getName(R->getReg());
5760 OS << " %reg" << R->getReg();
5762 } else if (const ExternalSymbolSDNode *ES =
5763 dyn_cast<ExternalSymbolSDNode>(this)) {
5764 OS << "'" << ES->getSymbol() << "'";
5765 if (unsigned int TF = ES->getTargetFlags())
5766 OS << " [TF=" << TF << ']';
5767 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5769 OS << "<" << M->getValue() << ">";
5772 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5773 OS << ":" << N->getVT().getEVTString();
5775 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5776 OS << "<" << *LD->getMemOperand();
5779 switch (LD->getExtensionType()) {
5780 default: doExt = false; break;
5781 case ISD::EXTLOAD: OS << ", anyext"; break;
5782 case ISD::SEXTLOAD: OS << ", sext"; break;
5783 case ISD::ZEXTLOAD: OS << ", zext"; break;
5786 OS << " from " << LD->getMemoryVT().getEVTString();
5788 const char *AM = getIndexedModeName(LD->getAddressingMode());
5793 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5794 OS << "<" << *ST->getMemOperand();
5796 if (ST->isTruncatingStore())
5797 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
5799 const char *AM = getIndexedModeName(ST->getAddressingMode());
5804 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
5805 OS << "<" << *M->getMemOperand() << ">";
5806 } else if (const BlockAddressSDNode *BA =
5807 dyn_cast<BlockAddressSDNode>(this)) {
5809 WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
5811 WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
5816 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5818 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5819 if (i) OS << ", "; else OS << " ";
5820 OS << (void*)getOperand(i).getNode();
5821 if (unsigned RN = getOperand(i).getResNo())
5824 print_details(OS, G);
5827 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5828 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5829 if (N->getOperand(i).getNode()->hasOneUse())
5830 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5832 errs() << "\n" << std::string(indent+2, ' ')
5833 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5837 errs().indent(indent);
5841 void SelectionDAG::dump() const {
5842 errs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
5844 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5846 const SDNode *N = I;
5847 if (!N->hasOneUse() && N != getRoot().getNode())
5848 DumpNodes(N, 2, this);
5851 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5856 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
5858 print_details(OS, G);
5861 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
5862 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
5863 const SelectionDAG *G, VisitedSDNodeSet &once) {
5864 if (!once.insert(N)) // If we've been here before, return now.
5866 // Dump the current SDNode, but don't end the line yet.
5867 OS << std::string(indent, ' ');
5869 // Having printed this SDNode, walk the children:
5870 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5871 const SDNode *child = N->getOperand(i).getNode();
5874 if (child->getNumOperands() == 0) {
5875 // This child has no grandchildren; print it inline right here.
5876 child->printr(OS, G);
5878 } else { // Just the address. FIXME: also print the child's opcode
5880 if (unsigned RN = N->getOperand(i).getResNo())
5885 // Dump children that have grandchildren on their own line(s).
5886 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5887 const SDNode *child = N->getOperand(i).getNode();
5888 DumpNodesr(OS, child, indent+2, G, once);
5892 void SDNode::dumpr() const {
5893 VisitedSDNodeSet once;
5894 DumpNodesr(errs(), this, 0, 0, once);
5897 void SDNode::dumpr(const SelectionDAG *G) const {
5898 VisitedSDNodeSet once;
5899 DumpNodesr(errs(), this, 0, G, once);
5903 // getAddressSpace - Return the address space this GlobalAddress belongs to.
5904 unsigned GlobalAddressSDNode::getAddressSpace() const {
5905 return getGlobal()->getType()->getAddressSpace();
5909 const Type *ConstantPoolSDNode::getType() const {
5910 if (isMachineConstantPoolEntry())
5911 return Val.MachineCPVal->getType();
5912 return Val.ConstVal->getType();
5915 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
5917 unsigned &SplatBitSize,
5919 unsigned MinSplatBits) {
5920 EVT VT = getValueType(0);
5921 assert(VT.isVector() && "Expected a vector type");
5922 unsigned sz = VT.getSizeInBits();
5923 if (MinSplatBits > sz)
5926 SplatValue = APInt(sz, 0);
5927 SplatUndef = APInt(sz, 0);
5929 // Get the bits. Bits with undefined values (when the corresponding element
5930 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
5931 // in SplatValue. If any of the values are not constant, give up and return
5933 unsigned int nOps = getNumOperands();
5934 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
5935 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
5936 for (unsigned i = 0; i < nOps; ++i) {
5937 SDValue OpVal = getOperand(i);
5938 unsigned BitPos = i * EltBitSize;
5940 if (OpVal.getOpcode() == ISD::UNDEF)
5941 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos +EltBitSize);
5942 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
5943 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
5944 zextOrTrunc(sz) << BitPos);
5945 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
5946 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
5951 // The build_vector is all constants or undefs. Find the smallest element
5952 // size that splats the vector.
5954 HasAnyUndefs = (SplatUndef != 0);
5957 unsigned HalfSize = sz / 2;
5958 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
5959 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
5960 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
5961 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
5963 // If the two halves do not match (ignoring undef bits), stop here.
5964 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
5965 MinSplatBits > HalfSize)
5968 SplatValue = HighValue | LowValue;
5969 SplatUndef = HighUndef & LowUndef;
5978 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
5979 // Find the first non-undef value in the shuffle mask.
5981 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
5984 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
5986 // Make sure all remaining elements are either undef or the same as the first
5988 for (int Idx = Mask[i]; i != e; ++i)
5989 if (Mask[i] >= 0 && Mask[i] != Idx)