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 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
38 /// makeVTList - Return an instance of the SDVTList struct initialized with the
39 /// specified members.
40 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
41 SDVTList Res = {VTs, NumVTs};
45 //===----------------------------------------------------------------------===//
46 // ConstantFPSDNode Class
47 //===----------------------------------------------------------------------===//
49 /// isExactlyValue - We don't rely on operator== working on double values, as
50 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
51 /// As such, this method can be used to do an exact bit-for-bit comparison of
52 /// two floating point values.
53 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
54 return Value.bitwiseIsEqual(V);
57 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
59 // convert modifies in place, so make a copy.
60 APFloat Val2 = APFloat(Val);
63 return false; // These can't be represented as floating point!
65 // FIXME rounding mode needs to be more flexible
67 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
68 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
71 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
72 &Val2.getSemantics() == &APFloat::IEEEdouble ||
73 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
75 // TODO: Figure out how to test if we can use a shorter type instead!
83 //===----------------------------------------------------------------------===//
85 //===----------------------------------------------------------------------===//
87 /// isBuildVectorAllOnes - Return true if the specified node is a
88 /// BUILD_VECTOR where all of the elements are ~0 or undef.
89 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
90 // Look through a bit convert.
91 if (N->getOpcode() == ISD::BIT_CONVERT)
92 N = N->getOperand(0).Val;
94 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
96 unsigned i = 0, e = N->getNumOperands();
98 // Skip over all of the undef values.
99 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
102 // Do not accept an all-undef vector.
103 if (i == e) return false;
105 // Do not accept build_vectors that aren't all constants or which have non-~0
107 SDOperand NotZero = N->getOperand(i);
108 if (isa<ConstantSDNode>(NotZero)) {
109 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
111 } else if (isa<ConstantFPSDNode>(NotZero)) {
112 MVT::ValueType VT = NotZero.getValueType();
114 if (((cast<ConstantFPSDNode>(NotZero)->getValueAPF().
115 convertToAPInt().getZExtValue())) != (uint64_t)-1)
118 if ((uint32_t)cast<ConstantFPSDNode>(NotZero)->
119 getValueAPF().convertToAPInt().getZExtValue() !=
126 // Okay, we have at least one ~0 value, check to see if the rest match or are
128 for (++i; i != e; ++i)
129 if (N->getOperand(i) != NotZero &&
130 N->getOperand(i).getOpcode() != ISD::UNDEF)
136 /// isBuildVectorAllZeros - Return true if the specified node is a
137 /// BUILD_VECTOR where all of the elements are 0 or undef.
138 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
139 // Look through a bit convert.
140 if (N->getOpcode() == ISD::BIT_CONVERT)
141 N = N->getOperand(0).Val;
143 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
145 unsigned i = 0, e = N->getNumOperands();
147 // Skip over all of the undef values.
148 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
151 // Do not accept an all-undef vector.
152 if (i == e) return false;
154 // Do not accept build_vectors that aren't all constants or which have non-~0
156 SDOperand Zero = N->getOperand(i);
157 if (isa<ConstantSDNode>(Zero)) {
158 if (!cast<ConstantSDNode>(Zero)->isNullValue())
160 } else if (isa<ConstantFPSDNode>(Zero)) {
161 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
166 // Okay, we have at least one ~0 value, check to see if the rest match or are
168 for (++i; i != e; ++i)
169 if (N->getOperand(i) != Zero &&
170 N->getOperand(i).getOpcode() != ISD::UNDEF)
175 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
176 /// when given the operation for (X op Y).
177 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
178 // To perform this operation, we just need to swap the L and G bits of the
180 unsigned OldL = (Operation >> 2) & 1;
181 unsigned OldG = (Operation >> 1) & 1;
182 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
183 (OldL << 1) | // New G bit
184 (OldG << 2)); // New L bit.
187 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
188 /// 'op' is a valid SetCC operation.
189 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
190 unsigned Operation = Op;
192 Operation ^= 7; // Flip L, G, E bits, but not U.
194 Operation ^= 15; // Flip all of the condition bits.
195 if (Operation > ISD::SETTRUE2)
196 Operation &= ~8; // Don't let N and U bits get set.
197 return ISD::CondCode(Operation);
201 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
202 /// signed operation and 2 if the result is an unsigned comparison. Return zero
203 /// if the operation does not depend on the sign of the input (setne and seteq).
204 static int isSignedOp(ISD::CondCode Opcode) {
206 default: assert(0 && "Illegal integer setcc operation!");
208 case ISD::SETNE: return 0;
212 case ISD::SETGE: return 1;
216 case ISD::SETUGE: return 2;
220 /// getSetCCOrOperation - Return the result of a logical OR between different
221 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
222 /// returns SETCC_INVALID if it is not possible to represent the resultant
224 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
226 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
227 // Cannot fold a signed integer setcc with an unsigned integer setcc.
228 return ISD::SETCC_INVALID;
230 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
232 // If the N and U bits get set then the resultant comparison DOES suddenly
233 // care about orderedness, and is true when ordered.
234 if (Op > ISD::SETTRUE2)
235 Op &= ~16; // Clear the U bit if the N bit is set.
237 // Canonicalize illegal integer setcc's.
238 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
241 return ISD::CondCode(Op);
244 /// getSetCCAndOperation - Return the result of a logical AND between different
245 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
246 /// function returns zero if it is not possible to represent the resultant
248 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
250 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
251 // Cannot fold a signed setcc with an unsigned setcc.
252 return ISD::SETCC_INVALID;
254 // Combine all of the condition bits.
255 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
257 // Canonicalize illegal integer setcc's.
261 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
262 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
263 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
264 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
271 const TargetMachine &SelectionDAG::getTarget() const {
272 return TLI.getTargetMachine();
275 //===----------------------------------------------------------------------===//
276 // SDNode Profile Support
277 //===----------------------------------------------------------------------===//
279 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
281 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
285 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
286 /// solely with their pointer.
287 void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
288 ID.AddPointer(VTList.VTs);
291 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
293 static void AddNodeIDOperands(FoldingSetNodeID &ID,
294 const SDOperand *Ops, unsigned NumOps) {
295 for (; NumOps; --NumOps, ++Ops) {
296 ID.AddPointer(Ops->Val);
297 ID.AddInteger(Ops->ResNo);
301 static void AddNodeIDNode(FoldingSetNodeID &ID,
302 unsigned short OpC, SDVTList VTList,
303 const SDOperand *OpList, unsigned N) {
304 AddNodeIDOpcode(ID, OpC);
305 AddNodeIDValueTypes(ID, VTList);
306 AddNodeIDOperands(ID, OpList, N);
309 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
311 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
312 AddNodeIDOpcode(ID, N->getOpcode());
313 // Add the return value info.
314 AddNodeIDValueTypes(ID, N->getVTList());
315 // Add the operand info.
316 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
318 // Handle SDNode leafs with special info.
319 switch (N->getOpcode()) {
320 default: break; // Normal nodes don't need extra info.
321 case ISD::TargetConstant:
323 ID.AddInteger(cast<ConstantSDNode>(N)->getValue());
325 case ISD::TargetConstantFP:
326 case ISD::ConstantFP: {
327 ID.AddAPFloat(cast<ConstantFPSDNode>(N)->getValueAPF());
330 case ISD::TargetGlobalAddress:
331 case ISD::GlobalAddress:
332 case ISD::TargetGlobalTLSAddress:
333 case ISD::GlobalTLSAddress: {
334 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
335 ID.AddPointer(GA->getGlobal());
336 ID.AddInteger(GA->getOffset());
339 case ISD::BasicBlock:
340 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
343 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
345 case ISD::SRCVALUE: {
346 SrcValueSDNode *SV = cast<SrcValueSDNode>(N);
347 ID.AddPointer(SV->getValue());
348 ID.AddInteger(SV->getOffset());
351 case ISD::FrameIndex:
352 case ISD::TargetFrameIndex:
353 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
356 case ISD::TargetJumpTable:
357 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
359 case ISD::ConstantPool:
360 case ISD::TargetConstantPool: {
361 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
362 ID.AddInteger(CP->getAlignment());
363 ID.AddInteger(CP->getOffset());
364 if (CP->isMachineConstantPoolEntry())
365 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
367 ID.AddPointer(CP->getConstVal());
371 LoadSDNode *LD = cast<LoadSDNode>(N);
372 ID.AddInteger(LD->getAddressingMode());
373 ID.AddInteger(LD->getExtensionType());
374 ID.AddInteger((unsigned int)(LD->getLoadedVT()));
375 ID.AddInteger(LD->getAlignment());
376 ID.AddInteger(LD->isVolatile());
380 StoreSDNode *ST = cast<StoreSDNode>(N);
381 ID.AddInteger(ST->getAddressingMode());
382 ID.AddInteger(ST->isTruncatingStore());
383 ID.AddInteger((unsigned int)(ST->getStoredVT()));
384 ID.AddInteger(ST->getAlignment());
385 ID.AddInteger(ST->isVolatile());
391 //===----------------------------------------------------------------------===//
392 // SelectionDAG Class
393 //===----------------------------------------------------------------------===//
395 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
397 void SelectionDAG::RemoveDeadNodes() {
398 // Create a dummy node (which is not added to allnodes), that adds a reference
399 // to the root node, preventing it from being deleted.
400 HandleSDNode Dummy(getRoot());
402 SmallVector<SDNode*, 128> DeadNodes;
404 // Add all obviously-dead nodes to the DeadNodes worklist.
405 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
407 DeadNodes.push_back(I);
409 // Process the worklist, deleting the nodes and adding their uses to the
411 while (!DeadNodes.empty()) {
412 SDNode *N = DeadNodes.back();
413 DeadNodes.pop_back();
415 // Take the node out of the appropriate CSE map.
416 RemoveNodeFromCSEMaps(N);
418 // Next, brutally remove the operand list. This is safe to do, as there are
419 // no cycles in the graph.
420 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
421 SDNode *Operand = I->Val;
422 Operand->removeUser(N);
424 // Now that we removed this operand, see if there are no uses of it left.
425 if (Operand->use_empty())
426 DeadNodes.push_back(Operand);
428 if (N->OperandsNeedDelete)
429 delete[] N->OperandList;
433 // Finally, remove N itself.
437 // If the root changed (e.g. it was a dead load, update the root).
438 setRoot(Dummy.getValue());
441 void SelectionDAG::RemoveDeadNode(SDNode *N, std::vector<SDNode*> &Deleted) {
442 SmallVector<SDNode*, 16> DeadNodes;
443 DeadNodes.push_back(N);
445 // Process the worklist, deleting the nodes and adding their uses to the
447 while (!DeadNodes.empty()) {
448 SDNode *N = DeadNodes.back();
449 DeadNodes.pop_back();
451 // Take the node out of the appropriate CSE map.
452 RemoveNodeFromCSEMaps(N);
454 // Next, brutally remove the operand list. This is safe to do, as there are
455 // no cycles in the graph.
456 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
457 SDNode *Operand = I->Val;
458 Operand->removeUser(N);
460 // Now that we removed this operand, see if there are no uses of it left.
461 if (Operand->use_empty())
462 DeadNodes.push_back(Operand);
464 if (N->OperandsNeedDelete)
465 delete[] N->OperandList;
469 // Finally, remove N itself.
470 Deleted.push_back(N);
475 void SelectionDAG::DeleteNode(SDNode *N) {
476 assert(N->use_empty() && "Cannot delete a node that is not dead!");
478 // First take this out of the appropriate CSE map.
479 RemoveNodeFromCSEMaps(N);
481 // Finally, remove uses due to operands of this node, remove from the
482 // AllNodes list, and delete the node.
483 DeleteNodeNotInCSEMaps(N);
486 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
488 // Remove it from the AllNodes list.
491 // Drop all of the operands and decrement used nodes use counts.
492 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
493 I->Val->removeUser(N);
494 if (N->OperandsNeedDelete)
495 delete[] N->OperandList;
502 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
503 /// correspond to it. This is useful when we're about to delete or repurpose
504 /// the node. We don't want future request for structurally identical nodes
505 /// to return N anymore.
506 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
508 switch (N->getOpcode()) {
509 case ISD::HANDLENODE: return; // noop.
511 Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
514 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
515 "Cond code doesn't exist!");
516 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
517 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
519 case ISD::ExternalSymbol:
520 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
522 case ISD::TargetExternalSymbol:
524 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
526 case ISD::VALUETYPE: {
527 MVT::ValueType VT = cast<VTSDNode>(N)->getVT();
528 if (MVT::isExtendedVT(VT)) {
529 Erased = ExtendedValueTypeNodes.erase(VT);
531 Erased = ValueTypeNodes[VT] != 0;
532 ValueTypeNodes[VT] = 0;
537 // Remove it from the CSE Map.
538 Erased = CSEMap.RemoveNode(N);
542 // Verify that the node was actually in one of the CSE maps, unless it has a
543 // flag result (which cannot be CSE'd) or is one of the special cases that are
544 // not subject to CSE.
545 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
546 !N->isTargetOpcode()) {
549 assert(0 && "Node is not in map!");
554 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
555 /// has been taken out and modified in some way. If the specified node already
556 /// exists in the CSE maps, do not modify the maps, but return the existing node
557 /// instead. If it doesn't exist, add it and return null.
559 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
560 assert(N->getNumOperands() && "This is a leaf node!");
561 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
562 return 0; // Never add these nodes.
564 // Check that remaining values produced are not flags.
565 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
566 if (N->getValueType(i) == MVT::Flag)
567 return 0; // Never CSE anything that produces a flag.
569 SDNode *New = CSEMap.GetOrInsertNode(N);
570 if (New != N) return New; // Node already existed.
574 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
575 /// were replaced with those specified. If this node is never memoized,
576 /// return null, otherwise return a pointer to the slot it would take. If a
577 /// node already exists with these operands, the slot will be non-null.
578 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
580 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
581 return 0; // Never add these nodes.
583 // Check that remaining values produced are not flags.
584 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
585 if (N->getValueType(i) == MVT::Flag)
586 return 0; // Never CSE anything that produces a flag.
588 SDOperand Ops[] = { Op };
590 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
591 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
594 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
595 /// were replaced with those specified. If this node is never memoized,
596 /// return null, otherwise return a pointer to the slot it would take. If a
597 /// node already exists with these operands, the slot will be non-null.
598 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
599 SDOperand Op1, SDOperand Op2,
601 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
602 return 0; // Never add these nodes.
604 // Check that remaining values produced are not flags.
605 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
606 if (N->getValueType(i) == MVT::Flag)
607 return 0; // Never CSE anything that produces a flag.
609 SDOperand Ops[] = { Op1, Op2 };
611 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
612 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
616 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
617 /// were replaced with those specified. If this node is never memoized,
618 /// return null, otherwise return a pointer to the slot it would take. If a
619 /// node already exists with these operands, the slot will be non-null.
620 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
621 const SDOperand *Ops,unsigned NumOps,
623 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
624 return 0; // Never add these nodes.
626 // Check that remaining values produced are not flags.
627 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
628 if (N->getValueType(i) == MVT::Flag)
629 return 0; // Never CSE anything that produces a flag.
632 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
634 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
635 ID.AddInteger(LD->getAddressingMode());
636 ID.AddInteger(LD->getExtensionType());
637 ID.AddInteger((unsigned int)(LD->getLoadedVT()));
638 ID.AddInteger(LD->getAlignment());
639 ID.AddInteger(LD->isVolatile());
640 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
641 ID.AddInteger(ST->getAddressingMode());
642 ID.AddInteger(ST->isTruncatingStore());
643 ID.AddInteger((unsigned int)(ST->getStoredVT()));
644 ID.AddInteger(ST->getAlignment());
645 ID.AddInteger(ST->isVolatile());
648 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
652 SelectionDAG::~SelectionDAG() {
653 while (!AllNodes.empty()) {
654 SDNode *N = AllNodes.begin();
655 N->SetNextInBucket(0);
656 if (N->OperandsNeedDelete)
657 delete [] N->OperandList;
660 AllNodes.pop_front();
664 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
665 if (Op.getValueType() == VT) return Op;
666 int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
667 return getNode(ISD::AND, Op.getValueType(), Op,
668 getConstant(Imm, Op.getValueType()));
671 SDOperand SelectionDAG::getString(const std::string &Val) {
672 StringSDNode *&N = StringNodes[Val];
674 N = new StringSDNode(Val);
675 AllNodes.push_back(N);
677 return SDOperand(N, 0);
680 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
681 assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
683 MVT::ValueType EltVT =
684 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
686 // Mask out any bits that are not valid for this constant.
687 Val &= MVT::getIntVTBitMask(EltVT);
689 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
691 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
695 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
696 if (!MVT::isVector(VT))
697 return SDOperand(N, 0);
699 N = new ConstantSDNode(isT, Val, EltVT);
700 CSEMap.InsertNode(N, IP);
701 AllNodes.push_back(N);
704 SDOperand Result(N, 0);
705 if (MVT::isVector(VT)) {
706 SmallVector<SDOperand, 8> Ops;
707 Ops.assign(MVT::getVectorNumElements(VT), Result);
708 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
713 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
714 return getConstant(Val, TLI.getPointerTy(), isTarget);
718 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
720 assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
722 MVT::ValueType EltVT =
723 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
725 // Do the map lookup using the actual bit pattern for the floating point
726 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
727 // we don't have issues with SNANs.
728 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
730 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
734 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
735 if (!MVT::isVector(VT))
736 return SDOperand(N, 0);
738 N = new ConstantFPSDNode(isTarget, V, EltVT);
739 CSEMap.InsertNode(N, IP);
740 AllNodes.push_back(N);
743 SDOperand Result(N, 0);
744 if (MVT::isVector(VT)) {
745 SmallVector<SDOperand, 8> Ops;
746 Ops.assign(MVT::getVectorNumElements(VT), Result);
747 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
752 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
754 MVT::ValueType EltVT =
755 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
757 return getConstantFP(APFloat((float)Val), VT, isTarget);
759 return getConstantFP(APFloat(Val), VT, isTarget);
762 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
763 MVT::ValueType VT, int Offset,
765 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
767 if (GVar && GVar->isThreadLocal())
768 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
770 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
772 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
774 ID.AddInteger(Offset);
776 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
777 return SDOperand(E, 0);
778 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
779 CSEMap.InsertNode(N, IP);
780 AllNodes.push_back(N);
781 return SDOperand(N, 0);
784 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
786 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
788 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
791 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
792 return SDOperand(E, 0);
793 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
794 CSEMap.InsertNode(N, IP);
795 AllNodes.push_back(N);
796 return SDOperand(N, 0);
799 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
800 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
802 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
805 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
806 return SDOperand(E, 0);
807 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
808 CSEMap.InsertNode(N, IP);
809 AllNodes.push_back(N);
810 return SDOperand(N, 0);
813 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
814 unsigned Alignment, int Offset,
816 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
818 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
819 ID.AddInteger(Alignment);
820 ID.AddInteger(Offset);
823 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
824 return SDOperand(E, 0);
825 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
826 CSEMap.InsertNode(N, IP);
827 AllNodes.push_back(N);
828 return SDOperand(N, 0);
832 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
834 unsigned Alignment, int Offset,
836 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
838 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
839 ID.AddInteger(Alignment);
840 ID.AddInteger(Offset);
841 C->AddSelectionDAGCSEId(ID);
843 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
844 return SDOperand(E, 0);
845 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
846 CSEMap.InsertNode(N, IP);
847 AllNodes.push_back(N);
848 return SDOperand(N, 0);
852 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
854 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
857 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
858 return SDOperand(E, 0);
859 SDNode *N = new BasicBlockSDNode(MBB);
860 CSEMap.InsertNode(N, IP);
861 AllNodes.push_back(N);
862 return SDOperand(N, 0);
865 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
866 if (!MVT::isExtendedVT(VT) && (unsigned)VT >= ValueTypeNodes.size())
867 ValueTypeNodes.resize(VT+1);
869 SDNode *&N = MVT::isExtendedVT(VT) ?
870 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT];
872 if (N) return SDOperand(N, 0);
873 N = new VTSDNode(VT);
874 AllNodes.push_back(N);
875 return SDOperand(N, 0);
878 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
879 SDNode *&N = ExternalSymbols[Sym];
880 if (N) return SDOperand(N, 0);
881 N = new ExternalSymbolSDNode(false, Sym, VT);
882 AllNodes.push_back(N);
883 return SDOperand(N, 0);
886 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
888 SDNode *&N = TargetExternalSymbols[Sym];
889 if (N) return SDOperand(N, 0);
890 N = new ExternalSymbolSDNode(true, Sym, VT);
891 AllNodes.push_back(N);
892 return SDOperand(N, 0);
895 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
896 if ((unsigned)Cond >= CondCodeNodes.size())
897 CondCodeNodes.resize(Cond+1);
899 if (CondCodeNodes[Cond] == 0) {
900 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
901 AllNodes.push_back(CondCodeNodes[Cond]);
903 return SDOperand(CondCodeNodes[Cond], 0);
906 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
908 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
909 ID.AddInteger(RegNo);
911 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
912 return SDOperand(E, 0);
913 SDNode *N = new RegisterSDNode(RegNo, VT);
914 CSEMap.InsertNode(N, IP);
915 AllNodes.push_back(N);
916 return SDOperand(N, 0);
919 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
920 assert((!V || isa<PointerType>(V->getType())) &&
921 "SrcValue is not a pointer?");
924 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
926 ID.AddInteger(Offset);
928 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
929 return SDOperand(E, 0);
930 SDNode *N = new SrcValueSDNode(V, Offset);
931 CSEMap.InsertNode(N, IP);
932 AllNodes.push_back(N);
933 return SDOperand(N, 0);
936 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
937 /// specified value type.
938 SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
939 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
940 unsigned ByteSize = MVT::getSizeInBits(VT)/8;
941 const Type *Ty = MVT::getTypeForValueType(VT);
942 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
943 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
944 return getFrameIndex(FrameIdx, TLI.getPointerTy());
948 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
949 SDOperand N2, ISD::CondCode Cond) {
950 // These setcc operations always fold.
954 case ISD::SETFALSE2: return getConstant(0, VT);
956 case ISD::SETTRUE2: return getConstant(1, VT);
968 assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
972 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
973 uint64_t C2 = N2C->getValue();
974 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
975 uint64_t C1 = N1C->getValue();
977 // Sign extend the operands if required
978 if (ISD::isSignedIntSetCC(Cond)) {
979 C1 = N1C->getSignExtended();
980 C2 = N2C->getSignExtended();
984 default: assert(0 && "Unknown integer setcc!");
985 case ISD::SETEQ: return getConstant(C1 == C2, VT);
986 case ISD::SETNE: return getConstant(C1 != C2, VT);
987 case ISD::SETULT: return getConstant(C1 < C2, VT);
988 case ISD::SETUGT: return getConstant(C1 > C2, VT);
989 case ISD::SETULE: return getConstant(C1 <= C2, VT);
990 case ISD::SETUGE: return getConstant(C1 >= C2, VT);
991 case ISD::SETLT: return getConstant((int64_t)C1 < (int64_t)C2, VT);
992 case ISD::SETGT: return getConstant((int64_t)C1 > (int64_t)C2, VT);
993 case ISD::SETLE: return getConstant((int64_t)C1 <= (int64_t)C2, VT);
994 case ISD::SETGE: return getConstant((int64_t)C1 >= (int64_t)C2, VT);
998 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
999 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1000 // No compile time operations on this type yet.
1001 if (N1C->getValueType(0) == MVT::ppcf128)
1004 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1007 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1008 return getNode(ISD::UNDEF, VT);
1010 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1011 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1012 return getNode(ISD::UNDEF, VT);
1014 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1015 R==APFloat::cmpLessThan, VT);
1016 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1017 return getNode(ISD::UNDEF, VT);
1019 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1020 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1021 return getNode(ISD::UNDEF, VT);
1023 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1024 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1025 return getNode(ISD::UNDEF, VT);
1027 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1028 R==APFloat::cmpEqual, VT);
1029 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1030 return getNode(ISD::UNDEF, VT);
1032 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1033 R==APFloat::cmpEqual, VT);
1034 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1035 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1036 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1037 R==APFloat::cmpEqual, VT);
1038 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1039 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1040 R==APFloat::cmpLessThan, VT);
1041 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1042 R==APFloat::cmpUnordered, VT);
1043 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1044 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1047 // Ensure that the constant occurs on the RHS.
1048 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1051 // Could not fold it.
1055 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1056 /// this predicate to simplify operations downstream. Mask is known to be zero
1057 /// for bits that V cannot have.
1058 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, uint64_t Mask,
1059 unsigned Depth) const {
1060 // The masks are not wide enough to represent this type! Should use APInt.
1061 if (Op.getValueType() == MVT::i128)
1064 uint64_t KnownZero, KnownOne;
1065 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1066 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1067 return (KnownZero & Mask) == Mask;
1070 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1071 /// known to be either zero or one and return them in the KnownZero/KnownOne
1072 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1074 void SelectionDAG::ComputeMaskedBits(SDOperand Op, uint64_t Mask,
1075 uint64_t &KnownZero, uint64_t &KnownOne,
1076 unsigned Depth) const {
1077 KnownZero = KnownOne = 0; // Don't know anything.
1078 if (Depth == 6 || Mask == 0)
1079 return; // Limit search depth.
1081 // The masks are not wide enough to represent this type! Should use APInt.
1082 if (Op.getValueType() == MVT::i128)
1085 uint64_t KnownZero2, KnownOne2;
1087 switch (Op.getOpcode()) {
1089 // We know all of the bits for a constant!
1090 KnownOne = cast<ConstantSDNode>(Op)->getValue() & Mask;
1091 KnownZero = ~KnownOne & Mask;
1094 // If either the LHS or the RHS are Zero, the result is zero.
1095 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1097 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1098 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1099 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1101 // Output known-1 bits are only known if set in both the LHS & RHS.
1102 KnownOne &= KnownOne2;
1103 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1104 KnownZero |= KnownZero2;
1107 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1109 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1110 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1111 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1113 // Output known-0 bits are only known if clear in both the LHS & RHS.
1114 KnownZero &= KnownZero2;
1115 // Output known-1 are known to be set if set in either the LHS | RHS.
1116 KnownOne |= KnownOne2;
1119 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1120 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1121 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1122 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1124 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1125 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1126 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1127 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1128 KnownZero = KnownZeroOut;
1132 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1133 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1134 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1135 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1137 // Only known if known in both the LHS and RHS.
1138 KnownOne &= KnownOne2;
1139 KnownZero &= KnownZero2;
1141 case ISD::SELECT_CC:
1142 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1143 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1144 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1145 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1147 // Only known if known in both the LHS and RHS.
1148 KnownOne &= KnownOne2;
1149 KnownZero &= KnownZero2;
1152 // If we know the result of a setcc has the top bits zero, use this info.
1153 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
1154 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
1157 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1158 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1159 ComputeMaskedBits(Op.getOperand(0), Mask >> SA->getValue(),
1160 KnownZero, KnownOne, Depth+1);
1161 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1162 KnownZero <<= SA->getValue();
1163 KnownOne <<= SA->getValue();
1164 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1168 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1169 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1170 MVT::ValueType VT = Op.getValueType();
1171 unsigned ShAmt = SA->getValue();
1173 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1174 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt) & TypeMask,
1175 KnownZero, KnownOne, Depth+1);
1176 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1177 KnownZero &= TypeMask;
1178 KnownOne &= TypeMask;
1179 KnownZero >>= ShAmt;
1182 uint64_t HighBits = (1ULL << ShAmt)-1;
1183 HighBits <<= MVT::getSizeInBits(VT)-ShAmt;
1184 KnownZero |= HighBits; // High bits known zero.
1188 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1189 MVT::ValueType VT = Op.getValueType();
1190 unsigned ShAmt = SA->getValue();
1192 // Compute the new bits that are at the top now.
1193 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1195 uint64_t InDemandedMask = (Mask << ShAmt) & TypeMask;
1196 // If any of the demanded bits are produced by the sign extension, we also
1197 // demand the input sign bit.
1198 uint64_t HighBits = (1ULL << ShAmt)-1;
1199 HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
1200 if (HighBits & Mask)
1201 InDemandedMask |= MVT::getIntVTSignBit(VT);
1203 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1205 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1206 KnownZero &= TypeMask;
1207 KnownOne &= TypeMask;
1208 KnownZero >>= ShAmt;
1211 // Handle the sign bits.
1212 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1213 SignBit >>= ShAmt; // Adjust to where it is now in the mask.
1215 if (KnownZero & SignBit) {
1216 KnownZero |= HighBits; // New bits are known zero.
1217 } else if (KnownOne & SignBit) {
1218 KnownOne |= HighBits; // New bits are known one.
1222 case ISD::SIGN_EXTEND_INREG: {
1223 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1225 // Sign extension. Compute the demanded bits in the result that are not
1226 // present in the input.
1227 uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & Mask;
1229 uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
1230 int64_t InputDemandedBits = Mask & MVT::getIntVTBitMask(EVT);
1232 // If the sign extended bits are demanded, we know that the sign
1235 InputDemandedBits |= InSignBit;
1237 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1238 KnownZero, KnownOne, Depth+1);
1239 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1241 // If the sign bit of the input is known set or clear, then we know the
1242 // top bits of the result.
1243 if (KnownZero & InSignBit) { // Input sign bit known clear
1244 KnownZero |= NewBits;
1245 KnownOne &= ~NewBits;
1246 } else if (KnownOne & InSignBit) { // Input sign bit known set
1247 KnownOne |= NewBits;
1248 KnownZero &= ~NewBits;
1249 } else { // Input sign bit unknown
1250 KnownZero &= ~NewBits;
1251 KnownOne &= ~NewBits;
1258 MVT::ValueType VT = Op.getValueType();
1259 unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
1260 KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
1265 if (ISD::isZEXTLoad(Op.Val)) {
1266 LoadSDNode *LD = cast<LoadSDNode>(Op);
1267 MVT::ValueType VT = LD->getLoadedVT();
1268 KnownZero |= ~MVT::getIntVTBitMask(VT) & Mask;
1272 case ISD::ZERO_EXTEND: {
1273 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
1274 uint64_t NewBits = (~InMask) & Mask;
1275 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1277 KnownZero |= NewBits & Mask;
1278 KnownOne &= ~NewBits;
1281 case ISD::SIGN_EXTEND: {
1282 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1283 unsigned InBits = MVT::getSizeInBits(InVT);
1284 uint64_t InMask = MVT::getIntVTBitMask(InVT);
1285 uint64_t InSignBit = 1ULL << (InBits-1);
1286 uint64_t NewBits = (~InMask) & Mask;
1287 uint64_t InDemandedBits = Mask & InMask;
1289 // If any of the sign extended bits are demanded, we know that the sign
1292 InDemandedBits |= InSignBit;
1294 ComputeMaskedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1296 // If the sign bit is known zero or one, the top bits match.
1297 if (KnownZero & InSignBit) {
1298 KnownZero |= NewBits;
1299 KnownOne &= ~NewBits;
1300 } else if (KnownOne & InSignBit) {
1301 KnownOne |= NewBits;
1302 KnownZero &= ~NewBits;
1303 } else { // Otherwise, top bits aren't known.
1304 KnownOne &= ~NewBits;
1305 KnownZero &= ~NewBits;
1309 case ISD::ANY_EXTEND: {
1310 MVT::ValueType VT = Op.getOperand(0).getValueType();
1311 ComputeMaskedBits(Op.getOperand(0), Mask & MVT::getIntVTBitMask(VT),
1312 KnownZero, KnownOne, Depth+1);
1315 case ISD::TRUNCATE: {
1316 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1317 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1318 uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
1319 KnownZero &= OutMask;
1320 KnownOne &= OutMask;
1323 case ISD::AssertZext: {
1324 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1325 uint64_t InMask = MVT::getIntVTBitMask(VT);
1326 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1328 KnownZero |= (~InMask) & Mask;
1332 // All bits are zero except the low bit.
1333 KnownZero = MVT::getIntVTBitMask(Op.getValueType()) ^ 1;
1337 // If either the LHS or the RHS are Zero, the result is zero.
1338 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1339 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1340 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1341 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1343 // Output known-0 bits are known if clear or set in both the low clear bits
1344 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1345 // low 3 bits clear.
1346 uint64_t KnownZeroOut = std::min(CountTrailingZeros_64(~KnownZero),
1347 CountTrailingZeros_64(~KnownZero2));
1349 KnownZero = (1ULL << KnownZeroOut) - 1;
1354 ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1357 // We know that the top bits of C-X are clear if X contains less bits
1358 // than C (i.e. no wrap-around can happen). For example, 20-X is
1359 // positive if we can prove that X is >= 0 and < 16.
1360 MVT::ValueType VT = CLHS->getValueType(0);
1361 if ((CLHS->getValue() & MVT::getIntVTSignBit(VT)) == 0) { // sign bit clear
1362 unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
1363 uint64_t MaskV = (1ULL << (63-NLZ))-1; // NLZ can't be 64 with no sign bit
1364 MaskV = ~MaskV & MVT::getIntVTBitMask(VT);
1365 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1367 // If all of the MaskV bits are known to be zero, then we know the output
1368 // top bits are zero, because we now know that the output is from [0-C].
1369 if ((KnownZero & MaskV) == MaskV) {
1370 unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
1371 KnownZero = ~((1ULL << (64-NLZ2))-1) & Mask; // Top bits known zero.
1372 KnownOne = 0; // No one bits known.
1374 KnownZero = KnownOne = 0; // Otherwise, nothing known.
1380 // Allow the target to implement this method for its nodes.
1381 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1382 case ISD::INTRINSIC_WO_CHAIN:
1383 case ISD::INTRINSIC_W_CHAIN:
1384 case ISD::INTRINSIC_VOID:
1385 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1391 /// ComputeNumSignBits - Return the number of times the sign bit of the
1392 /// register is replicated into the other bits. We know that at least 1 bit
1393 /// is always equal to the sign bit (itself), but other cases can give us
1394 /// information. For example, immediately after an "SRA X, 2", we know that
1395 /// the top 3 bits are all equal to each other, so we return 3.
1396 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1397 MVT::ValueType VT = Op.getValueType();
1398 assert(MVT::isInteger(VT) && "Invalid VT!");
1399 unsigned VTBits = MVT::getSizeInBits(VT);
1403 return 1; // Limit search depth.
1405 switch (Op.getOpcode()) {
1407 case ISD::AssertSext:
1408 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1409 return VTBits-Tmp+1;
1410 case ISD::AssertZext:
1411 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1414 case ISD::Constant: {
1415 uint64_t Val = cast<ConstantSDNode>(Op)->getValue();
1416 // If negative, invert the bits, then look at it.
1417 if (Val & MVT::getIntVTSignBit(VT))
1420 // Shift the bits so they are the leading bits in the int64_t.
1423 // Return # leading zeros. We use 'min' here in case Val was zero before
1424 // shifting. We don't want to return '64' as for an i32 "0".
1425 return std::min(VTBits, CountLeadingZeros_64(Val));
1428 case ISD::SIGN_EXTEND:
1429 Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1430 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1432 case ISD::SIGN_EXTEND_INREG:
1433 // Max of the input and what this extends.
1434 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1437 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1438 return std::max(Tmp, Tmp2);
1441 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1442 // SRA X, C -> adds C sign bits.
1443 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1444 Tmp += C->getValue();
1445 if (Tmp > VTBits) Tmp = VTBits;
1449 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1450 // shl destroys sign bits.
1451 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1452 if (C->getValue() >= VTBits || // Bad shift.
1453 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1454 return Tmp - C->getValue();
1459 case ISD::XOR: // NOT is handled here.
1460 // Logical binary ops preserve the number of sign bits.
1461 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1462 if (Tmp == 1) return 1; // Early out.
1463 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1464 return std::min(Tmp, Tmp2);
1467 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1468 if (Tmp == 1) return 1; // Early out.
1469 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1470 return std::min(Tmp, Tmp2);
1473 // If setcc returns 0/-1, all bits are sign bits.
1474 if (TLI.getSetCCResultContents() ==
1475 TargetLowering::ZeroOrNegativeOneSetCCResult)
1480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1481 unsigned RotAmt = C->getValue() & (VTBits-1);
1483 // Handle rotate right by N like a rotate left by 32-N.
1484 if (Op.getOpcode() == ISD::ROTR)
1485 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1487 // If we aren't rotating out all of the known-in sign bits, return the
1488 // number that are left. This handles rotl(sext(x), 1) for example.
1489 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1490 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1494 // Add can have at most one carry bit. Thus we know that the output
1495 // is, at worst, one more bit than the inputs.
1496 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1497 if (Tmp == 1) return 1; // Early out.
1499 // Special case decrementing a value (ADD X, -1):
1500 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1501 if (CRHS->isAllOnesValue()) {
1502 uint64_t KnownZero, KnownOne;
1503 uint64_t Mask = MVT::getIntVTBitMask(VT);
1504 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1506 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1508 if ((KnownZero|1) == Mask)
1511 // If we are subtracting one from a positive number, there is no carry
1512 // out of the result.
1513 if (KnownZero & MVT::getIntVTSignBit(VT))
1517 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1518 if (Tmp2 == 1) return 1;
1519 return std::min(Tmp, Tmp2)-1;
1523 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1524 if (Tmp2 == 1) return 1;
1527 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1528 if (CLHS->getValue() == 0) {
1529 uint64_t KnownZero, KnownOne;
1530 uint64_t Mask = MVT::getIntVTBitMask(VT);
1531 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1532 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1534 if ((KnownZero|1) == Mask)
1537 // If the input is known to be positive (the sign bit is known clear),
1538 // the output of the NEG has the same number of sign bits as the input.
1539 if (KnownZero & MVT::getIntVTSignBit(VT))
1542 // Otherwise, we treat this like a SUB.
1545 // Sub can have at most one carry bit. Thus we know that the output
1546 // is, at worst, one more bit than the inputs.
1547 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1548 if (Tmp == 1) return 1; // Early out.
1549 return std::min(Tmp, Tmp2)-1;
1552 // FIXME: it's tricky to do anything useful for this, but it is an important
1553 // case for targets like X86.
1557 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1558 if (Op.getOpcode() == ISD::LOAD) {
1559 LoadSDNode *LD = cast<LoadSDNode>(Op);
1560 unsigned ExtType = LD->getExtensionType();
1563 case ISD::SEXTLOAD: // '17' bits known
1564 Tmp = MVT::getSizeInBits(LD->getLoadedVT());
1565 return VTBits-Tmp+1;
1566 case ISD::ZEXTLOAD: // '16' bits known
1567 Tmp = MVT::getSizeInBits(LD->getLoadedVT());
1572 // Allow the target to implement this method for its nodes.
1573 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1574 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1575 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1576 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1577 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1578 if (NumBits > 1) return NumBits;
1581 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1582 // use this information.
1583 uint64_t KnownZero, KnownOne;
1584 uint64_t Mask = MVT::getIntVTBitMask(VT);
1585 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1587 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1588 if (KnownZero & SignBit) { // SignBit is 0
1590 } else if (KnownOne & SignBit) { // SignBit is 1;
1597 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1598 // the number of identical bits in the top of the input value.
1601 // Return # leading zeros. We use 'min' here in case Val was zero before
1602 // shifting. We don't want to return '64' as for an i32 "0".
1603 return std::min(VTBits, CountLeadingZeros_64(Mask));
1607 /// getNode - Gets or creates the specified node.
1609 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1610 FoldingSetNodeID ID;
1611 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1613 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1614 return SDOperand(E, 0);
1615 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1616 CSEMap.InsertNode(N, IP);
1618 AllNodes.push_back(N);
1619 return SDOperand(N, 0);
1622 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1623 SDOperand Operand) {
1625 // Constant fold unary operations with an integer constant operand.
1626 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1627 uint64_t Val = C->getValue();
1630 case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1631 case ISD::ANY_EXTEND:
1632 case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1633 case ISD::TRUNCATE: return getConstant(Val, VT);
1634 case ISD::UINT_TO_FP:
1635 case ISD::SINT_TO_FP: {
1636 const uint64_t zero[] = {0, 0};
1637 // No compile time operations on this type.
1638 if (VT==MVT::ppcf128)
1640 APFloat apf = APFloat(APInt(MVT::getSizeInBits(VT), 2, zero));
1641 (void)apf.convertFromZeroExtendedInteger(&Val,
1642 MVT::getSizeInBits(Operand.getValueType()),
1643 Opcode==ISD::SINT_TO_FP,
1644 APFloat::rmNearestTiesToEven);
1645 return getConstantFP(apf, VT);
1647 case ISD::BIT_CONVERT:
1648 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1649 return getConstantFP(BitsToFloat(Val), VT);
1650 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1651 return getConstantFP(BitsToDouble(Val), VT);
1655 default: assert(0 && "Invalid bswap!"); break;
1656 case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1657 case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1658 case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1663 default: assert(0 && "Invalid ctpop!"); break;
1664 case MVT::i1: return getConstant(Val != 0, VT);
1666 Tmp1 = (unsigned)Val & 0xFF;
1667 return getConstant(CountPopulation_32(Tmp1), VT);
1669 Tmp1 = (unsigned)Val & 0xFFFF;
1670 return getConstant(CountPopulation_32(Tmp1), VT);
1672 return getConstant(CountPopulation_32((unsigned)Val), VT);
1674 return getConstant(CountPopulation_64(Val), VT);
1678 default: assert(0 && "Invalid ctlz!"); break;
1679 case MVT::i1: return getConstant(Val == 0, VT);
1681 Tmp1 = (unsigned)Val & 0xFF;
1682 return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1684 Tmp1 = (unsigned)Val & 0xFFFF;
1685 return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1687 return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1689 return getConstant(CountLeadingZeros_64(Val), VT);
1693 default: assert(0 && "Invalid cttz!"); break;
1694 case MVT::i1: return getConstant(Val == 0, VT);
1696 Tmp1 = (unsigned)Val | 0x100;
1697 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1699 Tmp1 = (unsigned)Val | 0x10000;
1700 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1702 return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1704 return getConstant(CountTrailingZeros_64(Val), VT);
1709 // Constant fold unary operations with a floating point constant operand.
1710 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1711 APFloat V = C->getValueAPF(); // make copy
1712 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1716 return getConstantFP(V, VT);
1719 return getConstantFP(V, VT);
1721 case ISD::FP_EXTEND:
1722 // This can return overflow, underflow, or inexact; we don't care.
1723 // FIXME need to be more flexible about rounding mode.
1724 (void) V.convert(VT==MVT::f32 ? APFloat::IEEEsingle :
1725 VT==MVT::f64 ? APFloat::IEEEdouble :
1726 VT==MVT::f80 ? APFloat::x87DoubleExtended :
1727 VT==MVT::f128 ? APFloat::IEEEquad :
1729 APFloat::rmNearestTiesToEven);
1730 return getConstantFP(V, VT);
1731 case ISD::FP_TO_SINT:
1732 case ISD::FP_TO_UINT: {
1734 assert(integerPartWidth >= 64);
1735 // FIXME need to be more flexible about rounding mode.
1736 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1737 Opcode==ISD::FP_TO_SINT,
1738 APFloat::rmTowardZero);
1739 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1741 return getConstant(x, VT);
1743 case ISD::BIT_CONVERT:
1744 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1745 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1746 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1747 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1753 unsigned OpOpcode = Operand.Val->getOpcode();
1755 case ISD::TokenFactor:
1756 return Operand; // Factor of one node? No factor.
1757 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1758 case ISD::FP_EXTEND:
1759 assert(MVT::isFloatingPoint(VT) &&
1760 MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1761 if (Operand.getValueType() == VT) return Operand; // noop conversion.
1763 case ISD::SIGN_EXTEND:
1764 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1765 "Invalid SIGN_EXTEND!");
1766 if (Operand.getValueType() == VT) return Operand; // noop extension
1767 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1768 && "Invalid sext node, dst < src!");
1769 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1770 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1772 case ISD::ZERO_EXTEND:
1773 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1774 "Invalid ZERO_EXTEND!");
1775 if (Operand.getValueType() == VT) return Operand; // noop extension
1776 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1777 && "Invalid zext node, dst < src!");
1778 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
1779 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1781 case ISD::ANY_EXTEND:
1782 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1783 "Invalid ANY_EXTEND!");
1784 if (Operand.getValueType() == VT) return Operand; // noop extension
1785 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1786 && "Invalid anyext node, dst < src!");
1787 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1788 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
1789 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1792 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1793 "Invalid TRUNCATE!");
1794 if (Operand.getValueType() == VT) return Operand; // noop truncate
1795 assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
1796 && "Invalid truncate node, src < dst!");
1797 if (OpOpcode == ISD::TRUNCATE)
1798 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1799 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1800 OpOpcode == ISD::ANY_EXTEND) {
1801 // If the source is smaller than the dest, we still need an extend.
1802 if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1803 < MVT::getSizeInBits(VT))
1804 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1805 else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1806 > MVT::getSizeInBits(VT))
1807 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1809 return Operand.Val->getOperand(0);
1812 case ISD::BIT_CONVERT:
1813 // Basic sanity checking.
1814 assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1815 && "Cannot BIT_CONVERT between types of different sizes!");
1816 if (VT == Operand.getValueType()) return Operand; // noop conversion.
1817 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
1818 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1819 if (OpOpcode == ISD::UNDEF)
1820 return getNode(ISD::UNDEF, VT);
1822 case ISD::SCALAR_TO_VECTOR:
1823 assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1824 MVT::getVectorElementType(VT) == Operand.getValueType() &&
1825 "Illegal SCALAR_TO_VECTOR node!");
1828 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
1829 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1830 Operand.Val->getOperand(0));
1831 if (OpOpcode == ISD::FNEG) // --X -> X
1832 return Operand.Val->getOperand(0);
1835 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
1836 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1841 SDVTList VTs = getVTList(VT);
1842 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1843 FoldingSetNodeID ID;
1844 SDOperand Ops[1] = { Operand };
1845 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1847 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1848 return SDOperand(E, 0);
1849 N = new UnarySDNode(Opcode, VTs, Operand);
1850 CSEMap.InsertNode(N, IP);
1852 N = new UnarySDNode(Opcode, VTs, Operand);
1854 AllNodes.push_back(N);
1855 return SDOperand(N, 0);
1860 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1861 SDOperand N1, SDOperand N2) {
1862 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1863 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1866 case ISD::TokenFactor:
1867 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1868 N2.getValueType() == MVT::Other && "Invalid token factor!");
1869 // Fold trivial token factors.
1870 if (N1.getOpcode() == ISD::EntryToken) return N2;
1871 if (N2.getOpcode() == ISD::EntryToken) return N1;
1874 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1875 N1.getValueType() == VT && "Binary operator types must match!");
1876 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
1877 // worth handling here.
1878 if (N2C && N2C->getValue() == 0)
1880 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
1885 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1886 N1.getValueType() == VT && "Binary operator types must match!");
1887 // (X ^| 0) -> X. This commonly occurs when legalizing i64 values, so it's
1888 // worth handling here.
1889 if (N2C && N2C->getValue() == 0)
1896 assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1908 assert(N1.getValueType() == N2.getValueType() &&
1909 N1.getValueType() == VT && "Binary operator types must match!");
1911 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
1912 assert(N1.getValueType() == VT &&
1913 MVT::isFloatingPoint(N1.getValueType()) &&
1914 MVT::isFloatingPoint(N2.getValueType()) &&
1915 "Invalid FCOPYSIGN!");
1922 assert(VT == N1.getValueType() &&
1923 "Shift operators return type must be the same as their first arg");
1924 assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1925 VT != MVT::i1 && "Shifts only work on integers");
1927 case ISD::FP_ROUND_INREG: {
1928 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1929 assert(VT == N1.getValueType() && "Not an inreg round!");
1930 assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1931 "Cannot FP_ROUND_INREG integer types");
1932 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1933 "Not rounding down!");
1934 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
1938 assert(MVT::isFloatingPoint(VT) &&
1939 MVT::isFloatingPoint(N1.getValueType()) &&
1940 MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
1941 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
1942 if (N1.getValueType() == VT) return N1; // noop conversion.
1944 case ISD::AssertSext:
1945 case ISD::AssertZext: {
1946 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1947 assert(VT == N1.getValueType() && "Not an inreg extend!");
1948 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1949 "Cannot *_EXTEND_INREG FP types");
1950 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1954 case ISD::SIGN_EXTEND_INREG: {
1955 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1956 assert(VT == N1.getValueType() && "Not an inreg extend!");
1957 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1958 "Cannot *_EXTEND_INREG FP types");
1959 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1961 if (EVT == VT) return N1; // Not actually extending
1964 int64_t Val = N1C->getValue();
1965 unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
1966 Val <<= 64-FromBits;
1967 Val >>= 64-FromBits;
1968 return getConstant(Val, VT);
1972 case ISD::EXTRACT_VECTOR_ELT:
1973 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
1975 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
1976 // expanding copies of large vectors from registers.
1977 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
1978 N1.getNumOperands() > 0) {
1980 MVT::getVectorNumElements(N1.getOperand(0).getValueType());
1981 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
1982 N1.getOperand(N2C->getValue() / Factor),
1983 getConstant(N2C->getValue() % Factor, N2.getValueType()));
1986 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
1987 // expanding large vector constants.
1988 if (N1.getOpcode() == ISD::BUILD_VECTOR)
1989 return N1.getOperand(N2C->getValue());
1991 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
1992 // operations are lowered to scalars.
1993 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
1994 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
1996 return N1.getOperand(1);
1998 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2001 case ISD::EXTRACT_ELEMENT:
2002 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2004 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2005 // 64-bit integers into 32-bit parts. Instead of building the extract of
2006 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2007 if (N1.getOpcode() == ISD::BUILD_PAIR)
2008 return N1.getOperand(N2C->getValue());
2010 // EXTRACT_ELEMENT of a constant int is also very common.
2011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2012 unsigned Shift = MVT::getSizeInBits(VT) * N2C->getValue();
2013 return getConstant(C->getValue() >> Shift, VT);
2020 uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
2022 case ISD::ADD: return getConstant(C1 + C2, VT);
2023 case ISD::SUB: return getConstant(C1 - C2, VT);
2024 case ISD::MUL: return getConstant(C1 * C2, VT);
2026 if (C2) return getConstant(C1 / C2, VT);
2029 if (C2) return getConstant(C1 % C2, VT);
2032 if (C2) return getConstant(N1C->getSignExtended() /
2033 N2C->getSignExtended(), VT);
2036 if (C2) return getConstant(N1C->getSignExtended() %
2037 N2C->getSignExtended(), VT);
2039 case ISD::AND : return getConstant(C1 & C2, VT);
2040 case ISD::OR : return getConstant(C1 | C2, VT);
2041 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2042 case ISD::SHL : return getConstant(C1 << C2, VT);
2043 case ISD::SRL : return getConstant(C1 >> C2, VT);
2044 case ISD::SRA : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
2046 return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
2049 return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)),
2053 } else { // Cannonicalize constant to RHS if commutative
2054 if (isCommutativeBinOp(Opcode)) {
2055 std::swap(N1C, N2C);
2061 // Constant fold FP operations.
2062 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2063 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2065 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2066 // Cannonicalize constant to RHS if commutative
2067 std::swap(N1CFP, N2CFP);
2069 } else if (N2CFP && VT != MVT::ppcf128) {
2070 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2071 APFloat::opStatus s;
2074 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2075 if (s != APFloat::opInvalidOp)
2076 return getConstantFP(V1, VT);
2079 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2080 if (s!=APFloat::opInvalidOp)
2081 return getConstantFP(V1, VT);
2084 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2085 if (s!=APFloat::opInvalidOp)
2086 return getConstantFP(V1, VT);
2089 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2090 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2091 return getConstantFP(V1, VT);
2094 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2095 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2096 return getConstantFP(V1, VT);
2098 case ISD::FCOPYSIGN:
2100 return getConstantFP(V1, VT);
2106 // Canonicalize an UNDEF to the RHS, even over a constant.
2107 if (N1.getOpcode() == ISD::UNDEF) {
2108 if (isCommutativeBinOp(Opcode)) {
2112 case ISD::FP_ROUND_INREG:
2113 case ISD::SIGN_EXTEND_INREG:
2119 return N1; // fold op(undef, arg2) -> undef
2126 if (!MVT::isVector(VT))
2127 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2128 // For vectors, we can't easily build an all zero vector, just return
2135 // Fold a bunch of operators when the RHS is undef.
2136 if (N2.getOpcode() == ISD::UNDEF) {
2152 return N2; // fold op(arg1, undef) -> undef
2157 if (!MVT::isVector(VT))
2158 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2159 // For vectors, we can't easily build an all zero vector, just return
2163 if (!MVT::isVector(VT))
2164 return getConstant(MVT::getIntVTBitMask(VT), VT);
2165 // For vectors, we can't easily build an all one vector, just return
2173 // Memoize this node if possible.
2175 SDVTList VTs = getVTList(VT);
2176 if (VT != MVT::Flag) {
2177 SDOperand Ops[] = { N1, N2 };
2178 FoldingSetNodeID ID;
2179 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2181 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2182 return SDOperand(E, 0);
2183 N = new BinarySDNode(Opcode, VTs, N1, N2);
2184 CSEMap.InsertNode(N, IP);
2186 N = new BinarySDNode(Opcode, VTs, N1, N2);
2189 AllNodes.push_back(N);
2190 return SDOperand(N, 0);
2193 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2194 SDOperand N1, SDOperand N2, SDOperand N3) {
2195 // Perform various simplifications.
2196 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2197 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2200 // Use FoldSetCC to simplify SETCC's.
2201 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2202 if (Simp.Val) return Simp;
2207 if (N1C->getValue())
2208 return N2; // select true, X, Y -> X
2210 return N3; // select false, X, Y -> Y
2212 if (N2 == N3) return N2; // select C, X, X -> X
2216 if (N2C->getValue()) // Unconditional branch
2217 return getNode(ISD::BR, MVT::Other, N1, N3);
2219 return N1; // Never-taken branch
2221 case ISD::VECTOR_SHUFFLE:
2222 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2223 MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2224 N3.getOpcode() == ISD::BUILD_VECTOR &&
2225 MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2226 "Illegal VECTOR_SHUFFLE node!");
2228 case ISD::BIT_CONVERT:
2229 // Fold bit_convert nodes from a type to themselves.
2230 if (N1.getValueType() == VT)
2235 // Memoize node if it doesn't produce a flag.
2237 SDVTList VTs = getVTList(VT);
2238 if (VT != MVT::Flag) {
2239 SDOperand Ops[] = { N1, N2, N3 };
2240 FoldingSetNodeID ID;
2241 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2243 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2244 return SDOperand(E, 0);
2245 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2246 CSEMap.InsertNode(N, IP);
2248 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2250 AllNodes.push_back(N);
2251 return SDOperand(N, 0);
2254 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2255 SDOperand N1, SDOperand N2, SDOperand N3,
2257 SDOperand Ops[] = { N1, N2, N3, N4 };
2258 return getNode(Opcode, VT, Ops, 4);
2261 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2262 SDOperand N1, SDOperand N2, SDOperand N3,
2263 SDOperand N4, SDOperand N5) {
2264 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2265 return getNode(Opcode, VT, Ops, 5);
2268 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dest,
2269 SDOperand Src, SDOperand Size,
2271 SDOperand AlwaysInline) {
2272 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2273 return getNode(ISD::MEMCPY, MVT::Other, Ops, 6);
2276 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dest,
2277 SDOperand Src, SDOperand Size,
2279 SDOperand AlwaysInline) {
2280 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2281 return getNode(ISD::MEMMOVE, MVT::Other, Ops, 6);
2284 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dest,
2285 SDOperand Src, SDOperand Size,
2287 SDOperand AlwaysInline) {
2288 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2289 return getNode(ISD::MEMSET, MVT::Other, Ops, 6);
2292 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2293 SDOperand Chain, SDOperand Ptr,
2294 const Value *SV, int SVOffset,
2295 bool isVolatile, unsigned Alignment) {
2296 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2298 if (VT != MVT::iPTR) {
2299 Ty = MVT::getTypeForValueType(VT);
2301 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2302 assert(PT && "Value for load must be a pointer");
2303 Ty = PT->getElementType();
2305 assert(Ty && "Could not get type information for load");
2306 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2308 SDVTList VTs = getVTList(VT, MVT::Other);
2309 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2310 SDOperand Ops[] = { Chain, Ptr, Undef };
2311 FoldingSetNodeID ID;
2312 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2313 ID.AddInteger(ISD::UNINDEXED);
2314 ID.AddInteger(ISD::NON_EXTLOAD);
2315 ID.AddInteger((unsigned int)VT);
2316 ID.AddInteger(Alignment);
2317 ID.AddInteger(isVolatile);
2319 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2320 return SDOperand(E, 0);
2321 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2322 ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2324 CSEMap.InsertNode(N, IP);
2325 AllNodes.push_back(N);
2326 return SDOperand(N, 0);
2329 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2330 SDOperand Chain, SDOperand Ptr,
2332 int SVOffset, MVT::ValueType EVT,
2333 bool isVolatile, unsigned Alignment) {
2334 // If they are asking for an extending load from/to the same thing, return a
2337 return getLoad(VT, Chain, Ptr, SV, SVOffset, isVolatile, Alignment);
2339 if (MVT::isVector(VT))
2340 assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2342 assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2343 "Should only be an extending load, not truncating!");
2344 assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2345 "Cannot sign/zero extend a FP/Vector load!");
2346 assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2347 "Cannot convert from FP to Int or Int -> FP!");
2349 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2351 if (VT != MVT::iPTR) {
2352 Ty = MVT::getTypeForValueType(VT);
2354 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2355 assert(PT && "Value for load must be a pointer");
2356 Ty = PT->getElementType();
2358 assert(Ty && "Could not get type information for load");
2359 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2361 SDVTList VTs = getVTList(VT, MVT::Other);
2362 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2363 SDOperand Ops[] = { Chain, Ptr, Undef };
2364 FoldingSetNodeID ID;
2365 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2366 ID.AddInteger(ISD::UNINDEXED);
2367 ID.AddInteger(ExtType);
2368 ID.AddInteger((unsigned int)EVT);
2369 ID.AddInteger(Alignment);
2370 ID.AddInteger(isVolatile);
2372 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2373 return SDOperand(E, 0);
2374 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2375 SV, SVOffset, Alignment, isVolatile);
2376 CSEMap.InsertNode(N, IP);
2377 AllNodes.push_back(N);
2378 return SDOperand(N, 0);
2382 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2383 SDOperand Offset, ISD::MemIndexedMode AM) {
2384 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2385 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2386 "Load is already a indexed load!");
2387 MVT::ValueType VT = OrigLoad.getValueType();
2388 SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2389 SDOperand Ops[] = { LD->getChain(), Base, Offset };
2390 FoldingSetNodeID ID;
2391 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2393 ID.AddInteger(LD->getExtensionType());
2394 ID.AddInteger((unsigned int)(LD->getLoadedVT()));
2395 ID.AddInteger(LD->getAlignment());
2396 ID.AddInteger(LD->isVolatile());
2398 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2399 return SDOperand(E, 0);
2400 SDNode *N = new LoadSDNode(Ops, VTs, AM,
2401 LD->getExtensionType(), LD->getLoadedVT(),
2402 LD->getSrcValue(), LD->getSrcValueOffset(),
2403 LD->getAlignment(), LD->isVolatile());
2404 CSEMap.InsertNode(N, IP);
2405 AllNodes.push_back(N);
2406 return SDOperand(N, 0);
2409 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2410 SDOperand Ptr, const Value *SV, int SVOffset,
2411 bool isVolatile, unsigned Alignment) {
2412 MVT::ValueType VT = Val.getValueType();
2414 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2416 if (VT != MVT::iPTR) {
2417 Ty = MVT::getTypeForValueType(VT);
2419 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2420 assert(PT && "Value for store must be a pointer");
2421 Ty = PT->getElementType();
2423 assert(Ty && "Could not get type information for store");
2424 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2426 SDVTList VTs = getVTList(MVT::Other);
2427 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2428 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2429 FoldingSetNodeID ID;
2430 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2431 ID.AddInteger(ISD::UNINDEXED);
2432 ID.AddInteger(false);
2433 ID.AddInteger((unsigned int)VT);
2434 ID.AddInteger(Alignment);
2435 ID.AddInteger(isVolatile);
2437 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2438 return SDOperand(E, 0);
2439 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2440 VT, SV, SVOffset, Alignment, isVolatile);
2441 CSEMap.InsertNode(N, IP);
2442 AllNodes.push_back(N);
2443 return SDOperand(N, 0);
2446 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2447 SDOperand Ptr, const Value *SV,
2448 int SVOffset, MVT::ValueType SVT,
2449 bool isVolatile, unsigned Alignment) {
2450 MVT::ValueType VT = Val.getValueType();
2453 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
2455 assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
2456 "Not a truncation?");
2457 assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2458 "Can't do FP-INT conversion!");
2460 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2462 if (VT != MVT::iPTR) {
2463 Ty = MVT::getTypeForValueType(VT);
2465 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2466 assert(PT && "Value for store must be a pointer");
2467 Ty = PT->getElementType();
2469 assert(Ty && "Could not get type information for store");
2470 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2472 SDVTList VTs = getVTList(MVT::Other);
2473 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2474 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2475 FoldingSetNodeID ID;
2476 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2477 ID.AddInteger(ISD::UNINDEXED);
2479 ID.AddInteger((unsigned int)SVT);
2480 ID.AddInteger(Alignment);
2481 ID.AddInteger(isVolatile);
2483 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2484 return SDOperand(E, 0);
2485 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
2486 SVT, SV, SVOffset, Alignment, isVolatile);
2487 CSEMap.InsertNode(N, IP);
2488 AllNodes.push_back(N);
2489 return SDOperand(N, 0);
2493 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2494 SDOperand Offset, ISD::MemIndexedMode AM) {
2495 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2496 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2497 "Store is already a indexed store!");
2498 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2499 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2500 FoldingSetNodeID ID;
2501 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2503 ID.AddInteger(ST->isTruncatingStore());
2504 ID.AddInteger((unsigned int)(ST->getStoredVT()));
2505 ID.AddInteger(ST->getAlignment());
2506 ID.AddInteger(ST->isVolatile());
2508 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2509 return SDOperand(E, 0);
2510 SDNode *N = new StoreSDNode(Ops, VTs, AM,
2511 ST->isTruncatingStore(), ST->getStoredVT(),
2512 ST->getSrcValue(), ST->getSrcValueOffset(),
2513 ST->getAlignment(), ST->isVolatile());
2514 CSEMap.InsertNode(N, IP);
2515 AllNodes.push_back(N);
2516 return SDOperand(N, 0);
2519 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2520 SDOperand Chain, SDOperand Ptr,
2522 SDOperand Ops[] = { Chain, Ptr, SV };
2523 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2526 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2527 const SDOperand *Ops, unsigned NumOps) {
2529 case 0: return getNode(Opcode, VT);
2530 case 1: return getNode(Opcode, VT, Ops[0]);
2531 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2532 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2538 case ISD::SELECT_CC: {
2539 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2540 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2541 "LHS and RHS of condition must have same type!");
2542 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2543 "True and False arms of SelectCC must have same type!");
2544 assert(Ops[2].getValueType() == VT &&
2545 "select_cc node must be of same type as true and false value!");
2549 assert(NumOps == 5 && "BR_CC takes 5 operands!");
2550 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2551 "LHS/RHS of comparison should match types!");
2558 SDVTList VTs = getVTList(VT);
2559 if (VT != MVT::Flag) {
2560 FoldingSetNodeID ID;
2561 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2563 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2564 return SDOperand(E, 0);
2565 N = new SDNode(Opcode, VTs, Ops, NumOps);
2566 CSEMap.InsertNode(N, IP);
2568 N = new SDNode(Opcode, VTs, Ops, NumOps);
2570 AllNodes.push_back(N);
2571 return SDOperand(N, 0);
2574 SDOperand SelectionDAG::getNode(unsigned Opcode,
2575 std::vector<MVT::ValueType> &ResultTys,
2576 const SDOperand *Ops, unsigned NumOps) {
2577 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2581 SDOperand SelectionDAG::getNode(unsigned Opcode,
2582 const MVT::ValueType *VTs, unsigned NumVTs,
2583 const SDOperand *Ops, unsigned NumOps) {
2585 return getNode(Opcode, VTs[0], Ops, NumOps);
2586 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2589 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2590 const SDOperand *Ops, unsigned NumOps) {
2591 if (VTList.NumVTs == 1)
2592 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2595 // FIXME: figure out how to safely handle things like
2596 // int foo(int x) { return 1 << (x & 255); }
2597 // int bar() { return foo(256); }
2599 case ISD::SRA_PARTS:
2600 case ISD::SRL_PARTS:
2601 case ISD::SHL_PARTS:
2602 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2603 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2604 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2605 else if (N3.getOpcode() == ISD::AND)
2606 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2607 // If the and is only masking out bits that cannot effect the shift,
2608 // eliminate the and.
2609 unsigned NumBits = MVT::getSizeInBits(VT)*2;
2610 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2611 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2617 // Memoize the node unless it returns a flag.
2619 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2620 FoldingSetNodeID ID;
2621 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2623 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2624 return SDOperand(E, 0);
2626 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2627 else if (NumOps == 2)
2628 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2629 else if (NumOps == 3)
2630 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2632 N = new SDNode(Opcode, VTList, Ops, NumOps);
2633 CSEMap.InsertNode(N, IP);
2636 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2637 else if (NumOps == 2)
2638 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2639 else if (NumOps == 3)
2640 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2642 N = new SDNode(Opcode, VTList, Ops, NumOps);
2644 AllNodes.push_back(N);
2645 return SDOperand(N, 0);
2648 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
2649 return getNode(Opcode, VTList, 0, 0);
2652 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2654 SDOperand Ops[] = { N1 };
2655 return getNode(Opcode, VTList, Ops, 1);
2658 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2659 SDOperand N1, SDOperand N2) {
2660 SDOperand Ops[] = { N1, N2 };
2661 return getNode(Opcode, VTList, Ops, 2);
2664 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2665 SDOperand N1, SDOperand N2, SDOperand N3) {
2666 SDOperand Ops[] = { N1, N2, N3 };
2667 return getNode(Opcode, VTList, Ops, 3);
2670 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2671 SDOperand N1, SDOperand N2, SDOperand N3,
2673 SDOperand Ops[] = { N1, N2, N3, N4 };
2674 return getNode(Opcode, VTList, Ops, 4);
2677 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2678 SDOperand N1, SDOperand N2, SDOperand N3,
2679 SDOperand N4, SDOperand N5) {
2680 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2681 return getNode(Opcode, VTList, Ops, 5);
2684 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2685 return makeVTList(SDNode::getValueTypeList(VT), 1);
2688 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2689 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2690 E = VTList.end(); I != E; ++I) {
2691 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2692 return makeVTList(&(*I)[0], 2);
2694 std::vector<MVT::ValueType> V;
2697 VTList.push_front(V);
2698 return makeVTList(&(*VTList.begin())[0], 2);
2700 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2701 MVT::ValueType VT3) {
2702 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2703 E = VTList.end(); I != E; ++I) {
2704 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2706 return makeVTList(&(*I)[0], 3);
2708 std::vector<MVT::ValueType> V;
2712 VTList.push_front(V);
2713 return makeVTList(&(*VTList.begin())[0], 3);
2716 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2718 case 0: assert(0 && "Cannot have nodes without results!");
2719 case 1: return getVTList(VTs[0]);
2720 case 2: return getVTList(VTs[0], VTs[1]);
2721 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2725 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2726 E = VTList.end(); I != E; ++I) {
2727 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2729 bool NoMatch = false;
2730 for (unsigned i = 2; i != NumVTs; ++i)
2731 if (VTs[i] != (*I)[i]) {
2736 return makeVTList(&*I->begin(), NumVTs);
2739 VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2740 return makeVTList(&*VTList.begin()->begin(), NumVTs);
2744 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2745 /// specified operands. If the resultant node already exists in the DAG,
2746 /// this does not modify the specified node, instead it returns the node that
2747 /// already exists. If the resultant node does not exist in the DAG, the
2748 /// input node is returned. As a degenerate case, if you specify the same
2749 /// input operands as the node already has, the input node is returned.
2750 SDOperand SelectionDAG::
2751 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2752 SDNode *N = InN.Val;
2753 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2755 // Check to see if there is no change.
2756 if (Op == N->getOperand(0)) return InN;
2758 // See if the modified node already exists.
2759 void *InsertPos = 0;
2760 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2761 return SDOperand(Existing, InN.ResNo);
2763 // Nope it doesn't. Remove the node from it's current place in the maps.
2765 RemoveNodeFromCSEMaps(N);
2767 // Now we update the operands.
2768 N->OperandList[0].Val->removeUser(N);
2770 N->OperandList[0] = Op;
2772 // If this gets put into a CSE map, add it.
2773 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2777 SDOperand SelectionDAG::
2778 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2779 SDNode *N = InN.Val;
2780 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2782 // Check to see if there is no change.
2783 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2784 return InN; // No operands changed, just return the input node.
2786 // See if the modified node already exists.
2787 void *InsertPos = 0;
2788 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2789 return SDOperand(Existing, InN.ResNo);
2791 // Nope it doesn't. Remove the node from it's current place in the maps.
2793 RemoveNodeFromCSEMaps(N);
2795 // Now we update the operands.
2796 if (N->OperandList[0] != Op1) {
2797 N->OperandList[0].Val->removeUser(N);
2798 Op1.Val->addUser(N);
2799 N->OperandList[0] = Op1;
2801 if (N->OperandList[1] != Op2) {
2802 N->OperandList[1].Val->removeUser(N);
2803 Op2.Val->addUser(N);
2804 N->OperandList[1] = Op2;
2807 // If this gets put into a CSE map, add it.
2808 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2812 SDOperand SelectionDAG::
2813 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2814 SDOperand Ops[] = { Op1, Op2, Op3 };
2815 return UpdateNodeOperands(N, Ops, 3);
2818 SDOperand SelectionDAG::
2819 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2820 SDOperand Op3, SDOperand Op4) {
2821 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2822 return UpdateNodeOperands(N, Ops, 4);
2825 SDOperand SelectionDAG::
2826 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2827 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2828 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2829 return UpdateNodeOperands(N, Ops, 5);
2833 SDOperand SelectionDAG::
2834 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2835 SDNode *N = InN.Val;
2836 assert(N->getNumOperands() == NumOps &&
2837 "Update with wrong number of operands");
2839 // Check to see if there is no change.
2840 bool AnyChange = false;
2841 for (unsigned i = 0; i != NumOps; ++i) {
2842 if (Ops[i] != N->getOperand(i)) {
2848 // No operands changed, just return the input node.
2849 if (!AnyChange) return InN;
2851 // See if the modified node already exists.
2852 void *InsertPos = 0;
2853 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
2854 return SDOperand(Existing, InN.ResNo);
2856 // Nope it doesn't. Remove the node from it's current place in the maps.
2858 RemoveNodeFromCSEMaps(N);
2860 // Now we update the operands.
2861 for (unsigned i = 0; i != NumOps; ++i) {
2862 if (N->OperandList[i] != Ops[i]) {
2863 N->OperandList[i].Val->removeUser(N);
2864 Ops[i].Val->addUser(N);
2865 N->OperandList[i] = Ops[i];
2869 // If this gets put into a CSE map, add it.
2870 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2875 /// MorphNodeTo - This frees the operands of the current node, resets the
2876 /// opcode, types, and operands to the specified value. This should only be
2877 /// used by the SelectionDAG class.
2878 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
2879 const SDOperand *Ops, unsigned NumOps) {
2882 NumValues = L.NumVTs;
2884 // Clear the operands list, updating used nodes to remove this from their
2886 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2887 I->Val->removeUser(this);
2889 // If NumOps is larger than the # of operands we currently have, reallocate
2890 // the operand list.
2891 if (NumOps > NumOperands) {
2892 if (OperandsNeedDelete)
2893 delete [] OperandList;
2894 OperandList = new SDOperand[NumOps];
2895 OperandsNeedDelete = true;
2898 // Assign the new operands.
2899 NumOperands = NumOps;
2901 for (unsigned i = 0, e = NumOps; i != e; ++i) {
2902 OperandList[i] = Ops[i];
2903 SDNode *N = OperandList[i].Val;
2904 N->Uses.push_back(this);
2908 /// SelectNodeTo - These are used for target selectors to *mutate* the
2909 /// specified node to have the specified return type, Target opcode, and
2910 /// operands. Note that target opcodes are stored as
2911 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2913 /// Note that SelectNodeTo returns the resultant node. If there is already a
2914 /// node of the specified opcode and operands, it returns that node instead of
2915 /// the current one.
2916 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2917 MVT::ValueType VT) {
2918 SDVTList VTs = getVTList(VT);
2919 FoldingSetNodeID ID;
2920 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2922 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2925 RemoveNodeFromCSEMaps(N);
2927 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2929 CSEMap.InsertNode(N, IP);
2933 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2934 MVT::ValueType VT, SDOperand Op1) {
2935 // If an identical node already exists, use it.
2936 SDVTList VTs = getVTList(VT);
2937 SDOperand Ops[] = { Op1 };
2939 FoldingSetNodeID ID;
2940 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2942 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2945 RemoveNodeFromCSEMaps(N);
2946 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2947 CSEMap.InsertNode(N, IP);
2951 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2952 MVT::ValueType VT, SDOperand Op1,
2954 // If an identical node already exists, use it.
2955 SDVTList VTs = getVTList(VT);
2956 SDOperand Ops[] = { Op1, Op2 };
2958 FoldingSetNodeID ID;
2959 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2961 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2964 RemoveNodeFromCSEMaps(N);
2966 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2968 CSEMap.InsertNode(N, IP); // Memoize the new node.
2972 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2973 MVT::ValueType VT, SDOperand Op1,
2974 SDOperand Op2, SDOperand Op3) {
2975 // If an identical node already exists, use it.
2976 SDVTList VTs = getVTList(VT);
2977 SDOperand Ops[] = { Op1, Op2, Op3 };
2978 FoldingSetNodeID ID;
2979 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2981 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2984 RemoveNodeFromCSEMaps(N);
2986 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2988 CSEMap.InsertNode(N, IP); // Memoize the new node.
2992 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2993 MVT::ValueType VT, const SDOperand *Ops,
2995 // If an identical node already exists, use it.
2996 SDVTList VTs = getVTList(VT);
2997 FoldingSetNodeID ID;
2998 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3000 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3003 RemoveNodeFromCSEMaps(N);
3004 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3006 CSEMap.InsertNode(N, IP); // Memoize the new node.
3010 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3011 MVT::ValueType VT1, MVT::ValueType VT2,
3012 SDOperand Op1, SDOperand Op2) {
3013 SDVTList VTs = getVTList(VT1, VT2);
3014 FoldingSetNodeID ID;
3015 SDOperand Ops[] = { Op1, Op2 };
3016 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3018 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3021 RemoveNodeFromCSEMaps(N);
3022 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3023 CSEMap.InsertNode(N, IP); // Memoize the new node.
3027 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3028 MVT::ValueType VT1, MVT::ValueType VT2,
3029 SDOperand Op1, SDOperand Op2,
3031 // If an identical node already exists, use it.
3032 SDVTList VTs = getVTList(VT1, VT2);
3033 SDOperand Ops[] = { Op1, Op2, Op3 };
3034 FoldingSetNodeID ID;
3035 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3037 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3040 RemoveNodeFromCSEMaps(N);
3042 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3043 CSEMap.InsertNode(N, IP); // Memoize the new node.
3048 /// getTargetNode - These are used for target selectors to create a new node
3049 /// with specified return type(s), target opcode, and operands.
3051 /// Note that getTargetNode returns the resultant node. If there is already a
3052 /// node of the specified opcode and operands, it returns that node instead of
3053 /// the current one.
3054 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3055 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3057 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3059 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3061 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3062 SDOperand Op1, SDOperand Op2) {
3063 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3065 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3066 SDOperand Op1, SDOperand Op2,
3068 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3070 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3071 const SDOperand *Ops, unsigned NumOps) {
3072 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3074 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3075 MVT::ValueType VT2) {
3076 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3078 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3080 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3081 MVT::ValueType VT2, SDOperand Op1) {
3082 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3083 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3085 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3086 MVT::ValueType VT2, SDOperand Op1,
3088 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3089 SDOperand Ops[] = { Op1, Op2 };
3090 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3092 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3093 MVT::ValueType VT2, SDOperand Op1,
3094 SDOperand Op2, SDOperand Op3) {
3095 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3096 SDOperand Ops[] = { Op1, Op2, Op3 };
3097 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3099 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3101 const SDOperand *Ops, unsigned NumOps) {
3102 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3103 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3105 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3106 MVT::ValueType VT2, MVT::ValueType VT3,
3107 SDOperand Op1, SDOperand Op2) {
3108 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3109 SDOperand Ops[] = { Op1, Op2 };
3110 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3112 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3113 MVT::ValueType VT2, MVT::ValueType VT3,
3114 SDOperand Op1, SDOperand Op2,
3116 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3117 SDOperand Ops[] = { Op1, Op2, Op3 };
3118 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3120 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3121 MVT::ValueType VT2, MVT::ValueType VT3,
3122 const SDOperand *Ops, unsigned NumOps) {
3123 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3124 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3126 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3127 MVT::ValueType VT2, MVT::ValueType VT3,
3129 const SDOperand *Ops, unsigned NumOps) {
3130 std::vector<MVT::ValueType> VTList;
3131 VTList.push_back(VT1);
3132 VTList.push_back(VT2);
3133 VTList.push_back(VT3);
3134 VTList.push_back(VT4);
3135 const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3136 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3138 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3139 std::vector<MVT::ValueType> &ResultTys,
3140 const SDOperand *Ops, unsigned NumOps) {
3141 const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3142 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3146 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3147 /// This can cause recursive merging of nodes in the DAG.
3149 /// This version assumes From/To have a single result value.
3151 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
3152 std::vector<SDNode*> *Deleted) {
3153 SDNode *From = FromN.Val, *To = ToN.Val;
3154 assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
3155 "Cannot replace with this method!");
3156 assert(From != To && "Cannot replace uses of with self");
3158 while (!From->use_empty()) {
3159 // Process users until they are all gone.
3160 SDNode *U = *From->use_begin();
3162 // This node is about to morph, remove its old self from the CSE maps.
3163 RemoveNodeFromCSEMaps(U);
3165 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3167 if (I->Val == From) {
3168 From->removeUser(U);
3173 // Now that we have modified U, add it back to the CSE maps. If it already
3174 // exists there, recursively merge the results together.
3175 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3176 ReplaceAllUsesWith(U, Existing, Deleted);
3178 if (Deleted) Deleted->push_back(U);
3179 DeleteNodeNotInCSEMaps(U);
3184 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3185 /// This can cause recursive merging of nodes in the DAG.
3187 /// This version assumes From/To have matching types and numbers of result
3190 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3191 std::vector<SDNode*> *Deleted) {
3192 assert(From != To && "Cannot replace uses of with self");
3193 assert(From->getNumValues() == To->getNumValues() &&
3194 "Cannot use this version of ReplaceAllUsesWith!");
3195 if (From->getNumValues() == 1) { // If possible, use the faster version.
3196 ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
3200 while (!From->use_empty()) {
3201 // Process users until they are all gone.
3202 SDNode *U = *From->use_begin();
3204 // This node is about to morph, remove its old self from the CSE maps.
3205 RemoveNodeFromCSEMaps(U);
3207 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3209 if (I->Val == From) {
3210 From->removeUser(U);
3215 // Now that we have modified U, add it back to the CSE maps. If it already
3216 // exists there, recursively merge the results together.
3217 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3218 ReplaceAllUsesWith(U, Existing, Deleted);
3220 if (Deleted) Deleted->push_back(U);
3221 DeleteNodeNotInCSEMaps(U);
3226 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3227 /// This can cause recursive merging of nodes in the DAG.
3229 /// This version can replace From with any result values. To must match the
3230 /// number and types of values returned by From.
3231 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3232 const SDOperand *To,
3233 std::vector<SDNode*> *Deleted) {
3234 if (From->getNumValues() == 1 && To[0].Val->getNumValues() == 1) {
3235 // Degenerate case handled above.
3236 ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
3240 while (!From->use_empty()) {
3241 // Process users until they are all gone.
3242 SDNode *U = *From->use_begin();
3244 // This node is about to morph, remove its old self from the CSE maps.
3245 RemoveNodeFromCSEMaps(U);
3247 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3249 if (I->Val == From) {
3250 const SDOperand &ToOp = To[I->ResNo];
3251 From->removeUser(U);
3253 ToOp.Val->addUser(U);
3256 // Now that we have modified U, add it back to the CSE maps. If it already
3257 // exists there, recursively merge the results together.
3258 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3259 ReplaceAllUsesWith(U, Existing, Deleted);
3261 if (Deleted) Deleted->push_back(U);
3262 DeleteNodeNotInCSEMaps(U);
3267 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3268 /// uses of other values produced by From.Val alone. The Deleted vector is
3269 /// handled the same was as for ReplaceAllUsesWith.
3270 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3271 std::vector<SDNode*> *Deleted) {
3272 assert(From != To && "Cannot replace a value with itself");
3273 // Handle the simple, trivial, case efficiently.
3274 if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
3275 ReplaceAllUsesWith(From, To, Deleted);
3279 // Get all of the users of From.Val. We want these in a nice,
3280 // deterministically ordered and uniqued set, so we use a SmallSetVector.
3281 SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3283 std::vector<SDNode*> LocalDeletionVector;
3285 // Pick a deletion vector to use. If the user specified one, use theirs,
3286 // otherwise use a local one.
3287 std::vector<SDNode*> *DeleteVector = Deleted ? Deleted : &LocalDeletionVector;
3288 while (!Users.empty()) {
3289 // We know that this user uses some value of From. If it is the right
3290 // value, update it.
3291 SDNode *User = Users.back();
3294 // Scan for an operand that matches From.
3295 SDOperand *Op = User->OperandList, *E = User->OperandList+User->NumOperands;
3296 for (; Op != E; ++Op)
3297 if (*Op == From) break;
3299 // If there are no matches, the user must use some other result of From.
3300 if (Op == E) continue;
3302 // Okay, we know this user needs to be updated. Remove its old self
3303 // from the CSE maps.
3304 RemoveNodeFromCSEMaps(User);
3306 // Update all operands that match "From".
3307 for (; Op != E; ++Op) {
3309 From.Val->removeUser(User);
3311 To.Val->addUser(User);
3315 // Now that we have modified User, add it back to the CSE maps. If it
3316 // already exists there, recursively merge the results together.
3317 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3318 if (!Existing) continue; // Continue on to next user.
3320 // If there was already an existing matching node, use ReplaceAllUsesWith
3321 // to replace the dead one with the existing one. However, this can cause
3322 // recursive merging of other unrelated nodes down the line. The merging
3323 // can cause deletion of nodes that used the old value. In this case,
3324 // we have to be certain to remove them from the Users set.
3325 unsigned NumDeleted = DeleteVector->size();
3326 ReplaceAllUsesWith(User, Existing, DeleteVector);
3328 // User is now dead.
3329 DeleteVector->push_back(User);
3330 DeleteNodeNotInCSEMaps(User);
3332 // We have to be careful here, because ReplaceAllUsesWith could have
3333 // deleted a user of From, which means there may be dangling pointers
3334 // in the "Users" setvector. Scan over the deleted node pointers and
3335 // remove them from the setvector.
3336 for (unsigned i = NumDeleted, e = DeleteVector->size(); i != e; ++i)
3337 Users.remove((*DeleteVector)[i]);
3339 // If the user doesn't need the set of deleted elements, don't retain them
3340 // to the next loop iteration.
3342 LocalDeletionVector.clear();
3347 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3348 /// their allnodes order. It returns the maximum id.
3349 unsigned SelectionDAG::AssignNodeIds() {
3351 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3358 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3359 /// based on their topological order. It returns the maximum id and a vector
3360 /// of the SDNodes* in assigned order by reference.
3361 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3362 unsigned DAGSize = AllNodes.size();
3363 std::vector<unsigned> InDegree(DAGSize);
3364 std::vector<SDNode*> Sources;
3366 // Use a two pass approach to avoid using a std::map which is slow.
3368 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3371 unsigned Degree = N->use_size();
3372 InDegree[N->getNodeId()] = Degree;
3374 Sources.push_back(N);
3378 while (!Sources.empty()) {
3379 SDNode *N = Sources.back();
3381 TopOrder.push_back(N);
3382 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3384 unsigned Degree = --InDegree[P->getNodeId()];
3386 Sources.push_back(P);
3390 // Second pass, assign the actual topological order as node ids.
3392 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3394 (*TI)->setNodeId(Id++);
3401 //===----------------------------------------------------------------------===//
3403 //===----------------------------------------------------------------------===//
3405 // Out-of-line virtual method to give class a home.
3406 void SDNode::ANCHOR() {}
3407 void UnarySDNode::ANCHOR() {}
3408 void BinarySDNode::ANCHOR() {}
3409 void TernarySDNode::ANCHOR() {}
3410 void HandleSDNode::ANCHOR() {}
3411 void StringSDNode::ANCHOR() {}
3412 void ConstantSDNode::ANCHOR() {}
3413 void ConstantFPSDNode::ANCHOR() {}
3414 void GlobalAddressSDNode::ANCHOR() {}
3415 void FrameIndexSDNode::ANCHOR() {}
3416 void JumpTableSDNode::ANCHOR() {}
3417 void ConstantPoolSDNode::ANCHOR() {}
3418 void BasicBlockSDNode::ANCHOR() {}
3419 void SrcValueSDNode::ANCHOR() {}
3420 void RegisterSDNode::ANCHOR() {}
3421 void ExternalSymbolSDNode::ANCHOR() {}
3422 void CondCodeSDNode::ANCHOR() {}
3423 void VTSDNode::ANCHOR() {}
3424 void LoadSDNode::ANCHOR() {}
3425 void StoreSDNode::ANCHOR() {}
3427 HandleSDNode::~HandleSDNode() {
3428 SDVTList VTs = { 0, 0 };
3429 MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0); // Drops operand uses.
3432 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3433 MVT::ValueType VT, int o)
3434 : SDNode(isa<GlobalVariable>(GA) &&
3435 cast<GlobalVariable>(GA)->isThreadLocal() ?
3437 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3439 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3440 getSDVTList(VT)), Offset(o) {
3441 TheGlobal = const_cast<GlobalValue*>(GA);
3444 /// Profile - Gather unique data for the node.
3446 void SDNode::Profile(FoldingSetNodeID &ID) {
3447 AddNodeIDNode(ID, this);
3450 /// getValueTypeList - Return a pointer to the specified value type.
3452 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3453 if (MVT::isExtendedVT(VT)) {
3454 static std::set<MVT::ValueType> EVTs;
3455 return (MVT::ValueType *)&(*EVTs.insert(VT).first);
3457 static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3463 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3464 /// indicated value. This method ignores uses of other values defined by this
3466 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3467 assert(Value < getNumValues() && "Bad value!");
3469 // If there is only one value, this is easy.
3470 if (getNumValues() == 1)
3471 return use_size() == NUses;
3472 if (use_size() < NUses) return false;
3474 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3476 SmallPtrSet<SDNode*, 32> UsersHandled;
3478 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3480 if (User->getNumOperands() == 1 ||
3481 UsersHandled.insert(User)) // First time we've seen this?
3482 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3483 if (User->getOperand(i) == TheValue) {
3485 return false; // too many uses
3490 // Found exactly the right number of uses?
3495 /// hasAnyUseOfValue - Return true if there are any use of the indicated
3496 /// value. This method ignores uses of other values defined by this operation.
3497 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3498 assert(Value < getNumValues() && "Bad value!");
3500 if (use_size() == 0) return false;
3502 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3504 SmallPtrSet<SDNode*, 32> UsersHandled;
3506 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3508 if (User->getNumOperands() == 1 ||
3509 UsersHandled.insert(User)) // First time we've seen this?
3510 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3511 if (User->getOperand(i) == TheValue) {
3520 /// isOnlyUse - Return true if this node is the only use of N.
3522 bool SDNode::isOnlyUse(SDNode *N) const {
3524 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3535 /// isOperand - Return true if this node is an operand of N.
3537 bool SDOperand::isOperand(SDNode *N) const {
3538 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3539 if (*this == N->getOperand(i))
3544 bool SDNode::isOperand(SDNode *N) const {
3545 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3546 if (this == N->OperandList[i].Val)
3551 /// reachesChainWithoutSideEffects - Return true if this operand (which must
3552 /// be a chain) reaches the specified operand without crossing any
3553 /// side-effecting instructions. In practice, this looks through token
3554 /// factors and non-volatile loads. In order to remain efficient, this only
3555 /// looks a couple of nodes in, it does not do an exhaustive search.
3556 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
3557 unsigned Depth) const {
3558 if (*this == Dest) return true;
3560 // Don't search too deeply, we just want to be able to see through
3561 // TokenFactor's etc.
3562 if (Depth == 0) return false;
3564 // If this is a token factor, all inputs to the TF happen in parallel. If any
3565 // of the operands of the TF reach dest, then we can do the xform.
3566 if (getOpcode() == ISD::TokenFactor) {
3567 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3568 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
3573 // Loads don't have side effects, look through them.
3574 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
3575 if (!Ld->isVolatile())
3576 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
3582 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3583 SmallPtrSet<SDNode *, 32> &Visited) {
3584 if (found || !Visited.insert(N))
3587 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3588 SDNode *Op = N->getOperand(i).Val;
3593 findPredecessor(Op, P, found, Visited);
3597 /// isPredecessor - Return true if this node is a predecessor of N. This node
3598 /// is either an operand of N or it can be reached by recursively traversing
3599 /// up the operands.
3600 /// NOTE: this is an expensive method. Use it carefully.
3601 bool SDNode::isPredecessor(SDNode *N) const {
3602 SmallPtrSet<SDNode *, 32> Visited;
3604 findPredecessor(N, this, found, Visited);
3608 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3609 assert(Num < NumOperands && "Invalid child # of SDNode!");
3610 return cast<ConstantSDNode>(OperandList[Num])->getValue();
3613 std::string SDNode::getOperationName(const SelectionDAG *G) const {
3614 switch (getOpcode()) {
3616 if (getOpcode() < ISD::BUILTIN_OP_END)
3617 return "<<Unknown DAG Node>>";
3620 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3621 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3622 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
3624 TargetLowering &TLI = G->getTargetLoweringInfo();
3626 TLI.getTargetNodeName(getOpcode());
3627 if (Name) return Name;
3630 return "<<Unknown Target Node>>";
3633 case ISD::PCMARKER: return "PCMarker";
3634 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3635 case ISD::SRCVALUE: return "SrcValue";
3636 case ISD::EntryToken: return "EntryToken";
3637 case ISD::TokenFactor: return "TokenFactor";
3638 case ISD::AssertSext: return "AssertSext";
3639 case ISD::AssertZext: return "AssertZext";
3641 case ISD::STRING: return "String";
3642 case ISD::BasicBlock: return "BasicBlock";
3643 case ISD::VALUETYPE: return "ValueType";
3644 case ISD::Register: return "Register";
3646 case ISD::Constant: return "Constant";
3647 case ISD::ConstantFP: return "ConstantFP";
3648 case ISD::GlobalAddress: return "GlobalAddress";
3649 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3650 case ISD::FrameIndex: return "FrameIndex";
3651 case ISD::JumpTable: return "JumpTable";
3652 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3653 case ISD::RETURNADDR: return "RETURNADDR";
3654 case ISD::FRAMEADDR: return "FRAMEADDR";
3655 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3656 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3657 case ISD::EHSELECTION: return "EHSELECTION";
3658 case ISD::EH_RETURN: return "EH_RETURN";
3659 case ISD::ConstantPool: return "ConstantPool";
3660 case ISD::ExternalSymbol: return "ExternalSymbol";
3661 case ISD::INTRINSIC_WO_CHAIN: {
3662 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3663 return Intrinsic::getName((Intrinsic::ID)IID);
3665 case ISD::INTRINSIC_VOID:
3666 case ISD::INTRINSIC_W_CHAIN: {
3667 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3668 return Intrinsic::getName((Intrinsic::ID)IID);
3671 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
3672 case ISD::TargetConstant: return "TargetConstant";
3673 case ISD::TargetConstantFP:return "TargetConstantFP";
3674 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3675 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3676 case ISD::TargetFrameIndex: return "TargetFrameIndex";
3677 case ISD::TargetJumpTable: return "TargetJumpTable";
3678 case ISD::TargetConstantPool: return "TargetConstantPool";
3679 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3681 case ISD::CopyToReg: return "CopyToReg";
3682 case ISD::CopyFromReg: return "CopyFromReg";
3683 case ISD::UNDEF: return "undef";
3684 case ISD::MERGE_VALUES: return "merge_values";
3685 case ISD::INLINEASM: return "inlineasm";
3686 case ISD::LABEL: return "label";
3687 case ISD::HANDLENODE: return "handlenode";
3688 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3689 case ISD::CALL: return "call";
3692 case ISD::FABS: return "fabs";
3693 case ISD::FNEG: return "fneg";
3694 case ISD::FSQRT: return "fsqrt";
3695 case ISD::FSIN: return "fsin";
3696 case ISD::FCOS: return "fcos";
3697 case ISD::FPOWI: return "fpowi";
3698 case ISD::FPOW: return "fpow";
3701 case ISD::ADD: return "add";
3702 case ISD::SUB: return "sub";
3703 case ISD::MUL: return "mul";
3704 case ISD::MULHU: return "mulhu";
3705 case ISD::MULHS: return "mulhs";
3706 case ISD::SDIV: return "sdiv";
3707 case ISD::UDIV: return "udiv";
3708 case ISD::SREM: return "srem";
3709 case ISD::UREM: return "urem";
3710 case ISD::SMUL_LOHI: return "smul_lohi";
3711 case ISD::UMUL_LOHI: return "umul_lohi";
3712 case ISD::SDIVREM: return "sdivrem";
3713 case ISD::UDIVREM: return "divrem";
3714 case ISD::AND: return "and";
3715 case ISD::OR: return "or";
3716 case ISD::XOR: return "xor";
3717 case ISD::SHL: return "shl";
3718 case ISD::SRA: return "sra";
3719 case ISD::SRL: return "srl";
3720 case ISD::ROTL: return "rotl";
3721 case ISD::ROTR: return "rotr";
3722 case ISD::FADD: return "fadd";
3723 case ISD::FSUB: return "fsub";
3724 case ISD::FMUL: return "fmul";
3725 case ISD::FDIV: return "fdiv";
3726 case ISD::FREM: return "frem";
3727 case ISD::FCOPYSIGN: return "fcopysign";
3728 case ISD::FGETSIGN: return "fgetsign";
3730 case ISD::SETCC: return "setcc";
3731 case ISD::SELECT: return "select";
3732 case ISD::SELECT_CC: return "select_cc";
3733 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
3734 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
3735 case ISD::CONCAT_VECTORS: return "concat_vectors";
3736 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
3737 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
3738 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
3739 case ISD::CARRY_FALSE: return "carry_false";
3740 case ISD::ADDC: return "addc";
3741 case ISD::ADDE: return "adde";
3742 case ISD::SUBC: return "subc";
3743 case ISD::SUBE: return "sube";
3744 case ISD::SHL_PARTS: return "shl_parts";
3745 case ISD::SRA_PARTS: return "sra_parts";
3746 case ISD::SRL_PARTS: return "srl_parts";
3748 case ISD::EXTRACT_SUBREG: return "extract_subreg";
3749 case ISD::INSERT_SUBREG: return "insert_subreg";
3751 // Conversion operators.
3752 case ISD::SIGN_EXTEND: return "sign_extend";
3753 case ISD::ZERO_EXTEND: return "zero_extend";
3754 case ISD::ANY_EXTEND: return "any_extend";
3755 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3756 case ISD::TRUNCATE: return "truncate";
3757 case ISD::FP_ROUND: return "fp_round";
3758 case ISD::FLT_ROUNDS: return "flt_rounds";
3759 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3760 case ISD::FP_EXTEND: return "fp_extend";
3762 case ISD::SINT_TO_FP: return "sint_to_fp";
3763 case ISD::UINT_TO_FP: return "uint_to_fp";
3764 case ISD::FP_TO_SINT: return "fp_to_sint";
3765 case ISD::FP_TO_UINT: return "fp_to_uint";
3766 case ISD::BIT_CONVERT: return "bit_convert";
3768 // Control flow instructions
3769 case ISD::BR: return "br";
3770 case ISD::BRIND: return "brind";
3771 case ISD::BR_JT: return "br_jt";
3772 case ISD::BRCOND: return "brcond";
3773 case ISD::BR_CC: return "br_cc";
3774 case ISD::RET: return "ret";
3775 case ISD::CALLSEQ_START: return "callseq_start";
3776 case ISD::CALLSEQ_END: return "callseq_end";
3779 case ISD::LOAD: return "load";
3780 case ISD::STORE: return "store";
3781 case ISD::VAARG: return "vaarg";
3782 case ISD::VACOPY: return "vacopy";
3783 case ISD::VAEND: return "vaend";
3784 case ISD::VASTART: return "vastart";
3785 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
3786 case ISD::EXTRACT_ELEMENT: return "extract_element";
3787 case ISD::BUILD_PAIR: return "build_pair";
3788 case ISD::STACKSAVE: return "stacksave";
3789 case ISD::STACKRESTORE: return "stackrestore";
3790 case ISD::TRAP: return "trap";
3792 // Block memory operations.
3793 case ISD::MEMSET: return "memset";
3794 case ISD::MEMCPY: return "memcpy";
3795 case ISD::MEMMOVE: return "memmove";
3798 case ISD::BSWAP: return "bswap";
3799 case ISD::CTPOP: return "ctpop";
3800 case ISD::CTTZ: return "cttz";
3801 case ISD::CTLZ: return "ctlz";
3804 case ISD::LOCATION: return "location";
3805 case ISD::DEBUG_LOC: return "debug_loc";
3808 case ISD::TRAMPOLINE: return "trampoline";
3811 switch (cast<CondCodeSDNode>(this)->get()) {
3812 default: assert(0 && "Unknown setcc condition!");
3813 case ISD::SETOEQ: return "setoeq";
3814 case ISD::SETOGT: return "setogt";
3815 case ISD::SETOGE: return "setoge";
3816 case ISD::SETOLT: return "setolt";
3817 case ISD::SETOLE: return "setole";
3818 case ISD::SETONE: return "setone";
3820 case ISD::SETO: return "seto";
3821 case ISD::SETUO: return "setuo";
3822 case ISD::SETUEQ: return "setue";
3823 case ISD::SETUGT: return "setugt";
3824 case ISD::SETUGE: return "setuge";
3825 case ISD::SETULT: return "setult";
3826 case ISD::SETULE: return "setule";
3827 case ISD::SETUNE: return "setune";
3829 case ISD::SETEQ: return "seteq";
3830 case ISD::SETGT: return "setgt";
3831 case ISD::SETGE: return "setge";
3832 case ISD::SETLT: return "setlt";
3833 case ISD::SETLE: return "setle";
3834 case ISD::SETNE: return "setne";
3839 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
3848 return "<post-inc>";
3850 return "<post-dec>";
3854 void SDNode::dump() const { dump(0); }
3855 void SDNode::dump(const SelectionDAG *G) const {
3856 cerr << (void*)this << ": ";
3858 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
3860 if (getValueType(i) == MVT::Other)
3863 cerr << MVT::getValueTypeString(getValueType(i));
3865 cerr << " = " << getOperationName(G);
3868 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3869 if (i) cerr << ", ";
3870 cerr << (void*)getOperand(i).Val;
3871 if (unsigned RN = getOperand(i).ResNo)
3875 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
3876 SDNode *Mask = getOperand(2).Val;
3878 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
3880 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
3883 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
3888 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
3889 cerr << "<" << CSDN->getValue() << ">";
3890 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
3891 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
3892 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
3893 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
3894 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
3896 cerr << "<APFloat(";
3897 CSDN->getValueAPF().convertToAPInt().dump();
3900 } else if (const GlobalAddressSDNode *GADN =
3901 dyn_cast<GlobalAddressSDNode>(this)) {
3902 int offset = GADN->getOffset();
3904 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
3906 cerr << " + " << offset;
3908 cerr << " " << offset;
3909 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
3910 cerr << "<" << FIDN->getIndex() << ">";
3911 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
3912 cerr << "<" << JTDN->getIndex() << ">";
3913 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
3914 int offset = CP->getOffset();
3915 if (CP->isMachineConstantPoolEntry())
3916 cerr << "<" << *CP->getMachineCPVal() << ">";
3918 cerr << "<" << *CP->getConstVal() << ">";
3920 cerr << " + " << offset;
3922 cerr << " " << offset;
3923 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
3925 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
3927 cerr << LBB->getName() << " ";
3928 cerr << (const void*)BBDN->getBasicBlock() << ">";
3929 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
3930 if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
3931 cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
3933 cerr << " #" << R->getReg();
3935 } else if (const ExternalSymbolSDNode *ES =
3936 dyn_cast<ExternalSymbolSDNode>(this)) {
3937 cerr << "'" << ES->getSymbol() << "'";
3938 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
3940 cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
3942 cerr << "<null:" << M->getOffset() << ">";
3943 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
3944 cerr << ":" << MVT::getValueTypeString(N->getVT());
3945 } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
3946 const Value *SrcValue = LD->getSrcValue();
3947 int SrcOffset = LD->getSrcValueOffset();
3953 cerr << ":" << SrcOffset << ">";
3956 switch (LD->getExtensionType()) {
3957 default: doExt = false; break;
3959 cerr << " <anyext ";
3969 cerr << MVT::getValueTypeString(LD->getLoadedVT()) << ">";
3971 const char *AM = getIndexedModeName(LD->getAddressingMode());
3974 if (LD->isVolatile())
3975 cerr << " <volatile>";
3976 cerr << " alignment=" << LD->getAlignment();
3977 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
3978 const Value *SrcValue = ST->getSrcValue();
3979 int SrcOffset = ST->getSrcValueOffset();
3985 cerr << ":" << SrcOffset << ">";
3987 if (ST->isTruncatingStore())
3989 << MVT::getValueTypeString(ST->getStoredVT()) << ">";
3991 const char *AM = getIndexedModeName(ST->getAddressingMode());
3994 if (ST->isVolatile())
3995 cerr << " <volatile>";
3996 cerr << " alignment=" << ST->getAlignment();
4000 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4001 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4002 if (N->getOperand(i).Val->hasOneUse())
4003 DumpNodes(N->getOperand(i).Val, indent+2, G);
4005 cerr << "\n" << std::string(indent+2, ' ')
4006 << (void*)N->getOperand(i).Val << ": <multiple use>";
4009 cerr << "\n" << std::string(indent, ' ');
4013 void SelectionDAG::dump() const {
4014 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4015 std::vector<const SDNode*> Nodes;
4016 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4020 std::sort(Nodes.begin(), Nodes.end());
4022 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4023 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4024 DumpNodes(Nodes[i], 2, this);
4027 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4032 const Type *ConstantPoolSDNode::getType() const {
4033 if (isMachineConstantPoolEntry())
4034 return Val.MachineCPVal->getType();
4035 return Val.ConstVal->getType();