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/CodeGen/MachineModuleInfo.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
39 /// makeVTList - Return an instance of the SDVTList struct initialized with the
40 /// specified members.
41 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
42 SDVTList Res = {VTs, NumVTs};
46 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
48 //===----------------------------------------------------------------------===//
49 // ConstantFPSDNode Class
50 //===----------------------------------------------------------------------===//
52 /// isExactlyValue - We don't rely on operator== working on double values, as
53 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
54 /// As such, this method can be used to do an exact bit-for-bit comparison of
55 /// two floating point values.
56 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
57 return Value.bitwiseIsEqual(V);
60 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
62 // convert modifies in place, so make a copy.
63 APFloat Val2 = APFloat(Val);
66 return false; // These can't be represented as floating point!
68 // FIXME rounding mode needs to be more flexible
70 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
71 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
74 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
75 &Val2.getSemantics() == &APFloat::IEEEdouble ||
76 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
78 // TODO: Figure out how to test if we can use a shorter type instead!
86 //===----------------------------------------------------------------------===//
88 //===----------------------------------------------------------------------===//
90 /// isBuildVectorAllOnes - Return true if the specified node is a
91 /// BUILD_VECTOR where all of the elements are ~0 or undef.
92 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
93 // Look through a bit convert.
94 if (N->getOpcode() == ISD::BIT_CONVERT)
95 N = N->getOperand(0).Val;
97 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
99 unsigned i = 0, e = N->getNumOperands();
101 // Skip over all of the undef values.
102 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
105 // Do not accept an all-undef vector.
106 if (i == e) return false;
108 // Do not accept build_vectors that aren't all constants or which have non-~0
110 SDOperand NotZero = N->getOperand(i);
111 if (isa<ConstantSDNode>(NotZero)) {
112 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
114 } else if (isa<ConstantFPSDNode>(NotZero)) {
115 MVT::ValueType VT = NotZero.getValueType();
117 if (((cast<ConstantFPSDNode>(NotZero)->getValueAPF().
118 convertToAPInt().getZExtValue())) != (uint64_t)-1)
121 if ((uint32_t)cast<ConstantFPSDNode>(NotZero)->
122 getValueAPF().convertToAPInt().getZExtValue() !=
129 // Okay, we have at least one ~0 value, check to see if the rest match or are
131 for (++i; i != e; ++i)
132 if (N->getOperand(i) != NotZero &&
133 N->getOperand(i).getOpcode() != ISD::UNDEF)
139 /// isBuildVectorAllZeros - Return true if the specified node is a
140 /// BUILD_VECTOR where all of the elements are 0 or undef.
141 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
142 // Look through a bit convert.
143 if (N->getOpcode() == ISD::BIT_CONVERT)
144 N = N->getOperand(0).Val;
146 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
148 unsigned i = 0, e = N->getNumOperands();
150 // Skip over all of the undef values.
151 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
154 // Do not accept an all-undef vector.
155 if (i == e) return false;
157 // Do not accept build_vectors that aren't all constants or which have non-~0
159 SDOperand Zero = N->getOperand(i);
160 if (isa<ConstantSDNode>(Zero)) {
161 if (!cast<ConstantSDNode>(Zero)->isNullValue())
163 } else if (isa<ConstantFPSDNode>(Zero)) {
164 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
169 // Okay, we have at least one ~0 value, check to see if the rest match or are
171 for (++i; i != e; ++i)
172 if (N->getOperand(i) != Zero &&
173 N->getOperand(i).getOpcode() != ISD::UNDEF)
178 /// isDebugLabel - Return true if the specified node represents a debug
179 /// label (i.e. ISD::LABEL or TargetInstrInfo::LABEL node and third operand
181 bool ISD::isDebugLabel(const SDNode *N) {
183 if (N->getOpcode() == ISD::LABEL)
184 Zero = N->getOperand(2);
185 else if (N->isTargetOpcode() &&
186 N->getTargetOpcode() == TargetInstrInfo::LABEL)
187 // Chain moved to last operand.
188 Zero = N->getOperand(1);
191 return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
194 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
195 /// when given the operation for (X op Y).
196 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
197 // To perform this operation, we just need to swap the L and G bits of the
199 unsigned OldL = (Operation >> 2) & 1;
200 unsigned OldG = (Operation >> 1) & 1;
201 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
202 (OldL << 1) | // New G bit
203 (OldG << 2)); // New L bit.
206 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
207 /// 'op' is a valid SetCC operation.
208 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
209 unsigned Operation = Op;
211 Operation ^= 7; // Flip L, G, E bits, but not U.
213 Operation ^= 15; // Flip all of the condition bits.
214 if (Operation > ISD::SETTRUE2)
215 Operation &= ~8; // Don't let N and U bits get set.
216 return ISD::CondCode(Operation);
220 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
221 /// signed operation and 2 if the result is an unsigned comparison. Return zero
222 /// if the operation does not depend on the sign of the input (setne and seteq).
223 static int isSignedOp(ISD::CondCode Opcode) {
225 default: assert(0 && "Illegal integer setcc operation!");
227 case ISD::SETNE: return 0;
231 case ISD::SETGE: return 1;
235 case ISD::SETUGE: return 2;
239 /// getSetCCOrOperation - Return the result of a logical OR between different
240 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
241 /// returns SETCC_INVALID if it is not possible to represent the resultant
243 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
245 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
246 // Cannot fold a signed integer setcc with an unsigned integer setcc.
247 return ISD::SETCC_INVALID;
249 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
251 // If the N and U bits get set then the resultant comparison DOES suddenly
252 // care about orderedness, and is true when ordered.
253 if (Op > ISD::SETTRUE2)
254 Op &= ~16; // Clear the U bit if the N bit is set.
256 // Canonicalize illegal integer setcc's.
257 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
260 return ISD::CondCode(Op);
263 /// getSetCCAndOperation - Return the result of a logical AND between different
264 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
265 /// function returns zero if it is not possible to represent the resultant
267 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
269 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
270 // Cannot fold a signed setcc with an unsigned setcc.
271 return ISD::SETCC_INVALID;
273 // Combine all of the condition bits.
274 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
276 // Canonicalize illegal integer setcc's.
280 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
281 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
282 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
283 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
290 const TargetMachine &SelectionDAG::getTarget() const {
291 return TLI.getTargetMachine();
294 //===----------------------------------------------------------------------===//
295 // SDNode Profile Support
296 //===----------------------------------------------------------------------===//
298 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
300 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
304 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
305 /// solely with their pointer.
306 void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
307 ID.AddPointer(VTList.VTs);
310 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
312 static void AddNodeIDOperands(FoldingSetNodeID &ID,
313 const SDOperand *Ops, unsigned NumOps) {
314 for (; NumOps; --NumOps, ++Ops) {
315 ID.AddPointer(Ops->Val);
316 ID.AddInteger(Ops->ResNo);
320 static void AddNodeIDNode(FoldingSetNodeID &ID,
321 unsigned short OpC, SDVTList VTList,
322 const SDOperand *OpList, unsigned N) {
323 AddNodeIDOpcode(ID, OpC);
324 AddNodeIDValueTypes(ID, VTList);
325 AddNodeIDOperands(ID, OpList, N);
328 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
330 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
331 AddNodeIDOpcode(ID, N->getOpcode());
332 // Add the return value info.
333 AddNodeIDValueTypes(ID, N->getVTList());
334 // Add the operand info.
335 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
337 // Handle SDNode leafs with special info.
338 switch (N->getOpcode()) {
339 default: break; // Normal nodes don't need extra info.
340 case ISD::TargetConstant:
342 ID.AddInteger(cast<ConstantSDNode>(N)->getValue());
344 case ISD::TargetConstantFP:
345 case ISD::ConstantFP: {
346 ID.AddAPFloat(cast<ConstantFPSDNode>(N)->getValueAPF());
349 case ISD::TargetGlobalAddress:
350 case ISD::GlobalAddress:
351 case ISD::TargetGlobalTLSAddress:
352 case ISD::GlobalTLSAddress: {
353 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
354 ID.AddPointer(GA->getGlobal());
355 ID.AddInteger(GA->getOffset());
358 case ISD::BasicBlock:
359 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
362 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
364 case ISD::SRCVALUE: {
365 SrcValueSDNode *SV = cast<SrcValueSDNode>(N);
366 ID.AddPointer(SV->getValue());
367 ID.AddInteger(SV->getOffset());
370 case ISD::FrameIndex:
371 case ISD::TargetFrameIndex:
372 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
375 case ISD::TargetJumpTable:
376 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
378 case ISD::ConstantPool:
379 case ISD::TargetConstantPool: {
380 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
381 ID.AddInteger(CP->getAlignment());
382 ID.AddInteger(CP->getOffset());
383 if (CP->isMachineConstantPoolEntry())
384 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
386 ID.AddPointer(CP->getConstVal());
390 LoadSDNode *LD = cast<LoadSDNode>(N);
391 ID.AddInteger(LD->getAddressingMode());
392 ID.AddInteger(LD->getExtensionType());
393 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
394 ID.AddInteger(LD->getAlignment());
395 ID.AddInteger(LD->isVolatile());
399 StoreSDNode *ST = cast<StoreSDNode>(N);
400 ID.AddInteger(ST->getAddressingMode());
401 ID.AddInteger(ST->isTruncatingStore());
402 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
403 ID.AddInteger(ST->getAlignment());
404 ID.AddInteger(ST->isVolatile());
410 //===----------------------------------------------------------------------===//
411 // SelectionDAG Class
412 //===----------------------------------------------------------------------===//
414 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
416 void SelectionDAG::RemoveDeadNodes() {
417 // Create a dummy node (which is not added to allnodes), that adds a reference
418 // to the root node, preventing it from being deleted.
419 HandleSDNode Dummy(getRoot());
421 SmallVector<SDNode*, 128> DeadNodes;
423 // Add all obviously-dead nodes to the DeadNodes worklist.
424 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
426 DeadNodes.push_back(I);
428 // Process the worklist, deleting the nodes and adding their uses to the
430 while (!DeadNodes.empty()) {
431 SDNode *N = DeadNodes.back();
432 DeadNodes.pop_back();
434 // Take the node out of the appropriate CSE map.
435 RemoveNodeFromCSEMaps(N);
437 // Next, brutally remove the operand list. This is safe to do, as there are
438 // no cycles in the graph.
439 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
440 SDNode *Operand = I->Val;
441 Operand->removeUser(N);
443 // Now that we removed this operand, see if there are no uses of it left.
444 if (Operand->use_empty())
445 DeadNodes.push_back(Operand);
447 if (N->OperandsNeedDelete)
448 delete[] N->OperandList;
452 // Finally, remove N itself.
456 // If the root changed (e.g. it was a dead load, update the root).
457 setRoot(Dummy.getValue());
460 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
461 SmallVector<SDNode*, 16> DeadNodes;
462 DeadNodes.push_back(N);
464 // Process the worklist, deleting the nodes and adding their uses to the
466 while (!DeadNodes.empty()) {
467 SDNode *N = DeadNodes.back();
468 DeadNodes.pop_back();
471 UpdateListener->NodeDeleted(N);
473 // Take the node out of the appropriate CSE map.
474 RemoveNodeFromCSEMaps(N);
476 // Next, brutally remove the operand list. This is safe to do, as there are
477 // no cycles in the graph.
478 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
479 SDNode *Operand = I->Val;
480 Operand->removeUser(N);
482 // Now that we removed this operand, see if there are no uses of it left.
483 if (Operand->use_empty())
484 DeadNodes.push_back(Operand);
486 if (N->OperandsNeedDelete)
487 delete[] N->OperandList;
491 // Finally, remove N itself.
496 void SelectionDAG::DeleteNode(SDNode *N) {
497 assert(N->use_empty() && "Cannot delete a node that is not dead!");
499 // First take this out of the appropriate CSE map.
500 RemoveNodeFromCSEMaps(N);
502 // Finally, remove uses due to operands of this node, remove from the
503 // AllNodes list, and delete the node.
504 DeleteNodeNotInCSEMaps(N);
507 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
509 // Remove it from the AllNodes list.
512 // Drop all of the operands and decrement used nodes use counts.
513 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
514 I->Val->removeUser(N);
515 if (N->OperandsNeedDelete)
516 delete[] N->OperandList;
523 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
524 /// correspond to it. This is useful when we're about to delete or repurpose
525 /// the node. We don't want future request for structurally identical nodes
526 /// to return N anymore.
527 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
529 switch (N->getOpcode()) {
530 case ISD::HANDLENODE: return; // noop.
532 Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
535 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
536 "Cond code doesn't exist!");
537 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
538 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
540 case ISD::ExternalSymbol:
541 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
543 case ISD::TargetExternalSymbol:
545 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
547 case ISD::VALUETYPE: {
548 MVT::ValueType VT = cast<VTSDNode>(N)->getVT();
549 if (MVT::isExtendedVT(VT)) {
550 Erased = ExtendedValueTypeNodes.erase(VT);
552 Erased = ValueTypeNodes[VT] != 0;
553 ValueTypeNodes[VT] = 0;
558 // Remove it from the CSE Map.
559 Erased = CSEMap.RemoveNode(N);
563 // Verify that the node was actually in one of the CSE maps, unless it has a
564 // flag result (which cannot be CSE'd) or is one of the special cases that are
565 // not subject to CSE.
566 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
567 !N->isTargetOpcode()) {
570 assert(0 && "Node is not in map!");
575 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
576 /// has been taken out and modified in some way. If the specified node already
577 /// exists in the CSE maps, do not modify the maps, but return the existing node
578 /// instead. If it doesn't exist, add it and return null.
580 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
581 assert(N->getNumOperands() && "This is a leaf node!");
582 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
583 return 0; // Never add these nodes.
585 // Check that remaining values produced are not flags.
586 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
587 if (N->getValueType(i) == MVT::Flag)
588 return 0; // Never CSE anything that produces a flag.
590 SDNode *New = CSEMap.GetOrInsertNode(N);
591 if (New != N) return New; // Node already existed.
595 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
596 /// were replaced with those specified. If this node is never memoized,
597 /// return null, otherwise return a pointer to the slot it would take. If a
598 /// node already exists with these operands, the slot will be non-null.
599 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
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[] = { Op };
611 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
612 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
615 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
616 /// were replaced with those specified. If this node is never memoized,
617 /// return null, otherwise return a pointer to the slot it would take. If a
618 /// node already exists with these operands, the slot will be non-null.
619 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
620 SDOperand Op1, SDOperand Op2,
622 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
623 return 0; // Never add these nodes.
625 // Check that remaining values produced are not flags.
626 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
627 if (N->getValueType(i) == MVT::Flag)
628 return 0; // Never CSE anything that produces a flag.
630 SDOperand Ops[] = { Op1, Op2 };
632 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
633 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
637 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
638 /// were replaced with those specified. If this node is never memoized,
639 /// return null, otherwise return a pointer to the slot it would take. If a
640 /// node already exists with these operands, the slot will be non-null.
641 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
642 const SDOperand *Ops,unsigned NumOps,
644 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
645 return 0; // Never add these nodes.
647 // Check that remaining values produced are not flags.
648 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
649 if (N->getValueType(i) == MVT::Flag)
650 return 0; // Never CSE anything that produces a flag.
653 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
655 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
656 ID.AddInteger(LD->getAddressingMode());
657 ID.AddInteger(LD->getExtensionType());
658 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
659 ID.AddInteger(LD->getAlignment());
660 ID.AddInteger(LD->isVolatile());
661 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
662 ID.AddInteger(ST->getAddressingMode());
663 ID.AddInteger(ST->isTruncatingStore());
664 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
665 ID.AddInteger(ST->getAlignment());
666 ID.AddInteger(ST->isVolatile());
669 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
673 SelectionDAG::~SelectionDAG() {
674 while (!AllNodes.empty()) {
675 SDNode *N = AllNodes.begin();
676 N->SetNextInBucket(0);
677 if (N->OperandsNeedDelete)
678 delete [] N->OperandList;
681 AllNodes.pop_front();
685 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
686 if (Op.getValueType() == VT) return Op;
687 int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
688 return getNode(ISD::AND, Op.getValueType(), Op,
689 getConstant(Imm, Op.getValueType()));
692 SDOperand SelectionDAG::getString(const std::string &Val) {
693 StringSDNode *&N = StringNodes[Val];
695 N = new StringSDNode(Val);
696 AllNodes.push_back(N);
698 return SDOperand(N, 0);
701 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
702 assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
704 MVT::ValueType EltVT =
705 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
707 // Mask out any bits that are not valid for this constant.
708 Val &= MVT::getIntVTBitMask(EltVT);
710 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
712 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
716 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
717 if (!MVT::isVector(VT))
718 return SDOperand(N, 0);
720 N = new ConstantSDNode(isT, Val, EltVT);
721 CSEMap.InsertNode(N, IP);
722 AllNodes.push_back(N);
725 SDOperand Result(N, 0);
726 if (MVT::isVector(VT)) {
727 SmallVector<SDOperand, 8> Ops;
728 Ops.assign(MVT::getVectorNumElements(VT), Result);
729 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
734 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
735 return getConstant(Val, TLI.getPointerTy(), isTarget);
739 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
741 assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
743 MVT::ValueType EltVT =
744 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
746 // Do the map lookup using the actual bit pattern for the floating point
747 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
748 // we don't have issues with SNANs.
749 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
751 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
755 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
756 if (!MVT::isVector(VT))
757 return SDOperand(N, 0);
759 N = new ConstantFPSDNode(isTarget, V, EltVT);
760 CSEMap.InsertNode(N, IP);
761 AllNodes.push_back(N);
764 SDOperand Result(N, 0);
765 if (MVT::isVector(VT)) {
766 SmallVector<SDOperand, 8> Ops;
767 Ops.assign(MVT::getVectorNumElements(VT), Result);
768 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
773 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
775 MVT::ValueType EltVT =
776 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
778 return getConstantFP(APFloat((float)Val), VT, isTarget);
780 return getConstantFP(APFloat(Val), VT, isTarget);
783 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
784 MVT::ValueType VT, int Offset,
786 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
788 if (GVar && GVar->isThreadLocal())
789 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
791 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
793 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
795 ID.AddInteger(Offset);
797 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
798 return SDOperand(E, 0);
799 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
800 CSEMap.InsertNode(N, IP);
801 AllNodes.push_back(N);
802 return SDOperand(N, 0);
805 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
807 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
809 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
812 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
813 return SDOperand(E, 0);
814 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
815 CSEMap.InsertNode(N, IP);
816 AllNodes.push_back(N);
817 return SDOperand(N, 0);
820 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
821 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
823 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
826 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
827 return SDOperand(E, 0);
828 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
829 CSEMap.InsertNode(N, IP);
830 AllNodes.push_back(N);
831 return SDOperand(N, 0);
834 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
835 unsigned Alignment, int Offset,
837 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
839 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
840 ID.AddInteger(Alignment);
841 ID.AddInteger(Offset);
844 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
845 return SDOperand(E, 0);
846 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
847 CSEMap.InsertNode(N, IP);
848 AllNodes.push_back(N);
849 return SDOperand(N, 0);
853 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
855 unsigned Alignment, int Offset,
857 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
859 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
860 ID.AddInteger(Alignment);
861 ID.AddInteger(Offset);
862 C->AddSelectionDAGCSEId(ID);
864 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
865 return SDOperand(E, 0);
866 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
867 CSEMap.InsertNode(N, IP);
868 AllNodes.push_back(N);
869 return SDOperand(N, 0);
873 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
875 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
878 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
879 return SDOperand(E, 0);
880 SDNode *N = new BasicBlockSDNode(MBB);
881 CSEMap.InsertNode(N, IP);
882 AllNodes.push_back(N);
883 return SDOperand(N, 0);
886 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
887 if (!MVT::isExtendedVT(VT) && (unsigned)VT >= ValueTypeNodes.size())
888 ValueTypeNodes.resize(VT+1);
890 SDNode *&N = MVT::isExtendedVT(VT) ?
891 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT];
893 if (N) return SDOperand(N, 0);
894 N = new VTSDNode(VT);
895 AllNodes.push_back(N);
896 return SDOperand(N, 0);
899 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
900 SDNode *&N = ExternalSymbols[Sym];
901 if (N) return SDOperand(N, 0);
902 N = new ExternalSymbolSDNode(false, Sym, VT);
903 AllNodes.push_back(N);
904 return SDOperand(N, 0);
907 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
909 SDNode *&N = TargetExternalSymbols[Sym];
910 if (N) return SDOperand(N, 0);
911 N = new ExternalSymbolSDNode(true, Sym, VT);
912 AllNodes.push_back(N);
913 return SDOperand(N, 0);
916 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
917 if ((unsigned)Cond >= CondCodeNodes.size())
918 CondCodeNodes.resize(Cond+1);
920 if (CondCodeNodes[Cond] == 0) {
921 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
922 AllNodes.push_back(CondCodeNodes[Cond]);
924 return SDOperand(CondCodeNodes[Cond], 0);
927 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
929 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
930 ID.AddInteger(RegNo);
932 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
933 return SDOperand(E, 0);
934 SDNode *N = new RegisterSDNode(RegNo, VT);
935 CSEMap.InsertNode(N, IP);
936 AllNodes.push_back(N);
937 return SDOperand(N, 0);
940 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
941 assert((!V || isa<PointerType>(V->getType())) &&
942 "SrcValue is not a pointer?");
945 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
947 ID.AddInteger(Offset);
949 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
950 return SDOperand(E, 0);
951 SDNode *N = new SrcValueSDNode(V, Offset);
952 CSEMap.InsertNode(N, IP);
953 AllNodes.push_back(N);
954 return SDOperand(N, 0);
957 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
958 /// specified value type.
959 SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
960 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
961 unsigned ByteSize = MVT::getSizeInBits(VT)/8;
962 const Type *Ty = MVT::getTypeForValueType(VT);
963 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
964 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
965 return getFrameIndex(FrameIdx, TLI.getPointerTy());
969 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
970 SDOperand N2, ISD::CondCode Cond) {
971 // These setcc operations always fold.
975 case ISD::SETFALSE2: return getConstant(0, VT);
977 case ISD::SETTRUE2: return getConstant(1, VT);
989 assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
993 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
994 uint64_t C2 = N2C->getValue();
995 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
996 uint64_t C1 = N1C->getValue();
998 // Sign extend the operands if required
999 if (ISD::isSignedIntSetCC(Cond)) {
1000 C1 = N1C->getSignExtended();
1001 C2 = N2C->getSignExtended();
1005 default: assert(0 && "Unknown integer setcc!");
1006 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1007 case ISD::SETNE: return getConstant(C1 != C2, VT);
1008 case ISD::SETULT: return getConstant(C1 < C2, VT);
1009 case ISD::SETUGT: return getConstant(C1 > C2, VT);
1010 case ISD::SETULE: return getConstant(C1 <= C2, VT);
1011 case ISD::SETUGE: return getConstant(C1 >= C2, VT);
1012 case ISD::SETLT: return getConstant((int64_t)C1 < (int64_t)C2, VT);
1013 case ISD::SETGT: return getConstant((int64_t)C1 > (int64_t)C2, VT);
1014 case ISD::SETLE: return getConstant((int64_t)C1 <= (int64_t)C2, VT);
1015 case ISD::SETGE: return getConstant((int64_t)C1 >= (int64_t)C2, VT);
1019 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
1020 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1021 // No compile time operations on this type yet.
1022 if (N1C->getValueType(0) == MVT::ppcf128)
1025 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1028 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1029 return getNode(ISD::UNDEF, VT);
1031 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1032 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1033 return getNode(ISD::UNDEF, VT);
1035 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1036 R==APFloat::cmpLessThan, VT);
1037 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1038 return getNode(ISD::UNDEF, VT);
1040 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1041 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1042 return getNode(ISD::UNDEF, VT);
1044 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1045 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1046 return getNode(ISD::UNDEF, VT);
1048 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1049 R==APFloat::cmpEqual, VT);
1050 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1051 return getNode(ISD::UNDEF, VT);
1053 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1054 R==APFloat::cmpEqual, VT);
1055 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1056 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1057 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1058 R==APFloat::cmpEqual, VT);
1059 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1060 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1061 R==APFloat::cmpLessThan, VT);
1062 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1063 R==APFloat::cmpUnordered, VT);
1064 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1065 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1068 // Ensure that the constant occurs on the RHS.
1069 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1072 // Could not fold it.
1076 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1077 /// this predicate to simplify operations downstream. Mask is known to be zero
1078 /// for bits that V cannot have.
1079 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, uint64_t Mask,
1080 unsigned Depth) const {
1081 // The masks are not wide enough to represent this type! Should use APInt.
1082 if (Op.getValueType() == MVT::i128)
1085 uint64_t KnownZero, KnownOne;
1086 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1087 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1088 return (KnownZero & Mask) == Mask;
1091 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1092 /// known to be either zero or one and return them in the KnownZero/KnownOne
1093 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1095 void SelectionDAG::ComputeMaskedBits(SDOperand Op, uint64_t Mask,
1096 uint64_t &KnownZero, uint64_t &KnownOne,
1097 unsigned Depth) const {
1098 KnownZero = KnownOne = 0; // Don't know anything.
1099 if (Depth == 6 || Mask == 0)
1100 return; // Limit search depth.
1102 // The masks are not wide enough to represent this type! Should use APInt.
1103 if (Op.getValueType() == MVT::i128)
1106 uint64_t KnownZero2, KnownOne2;
1108 switch (Op.getOpcode()) {
1110 // We know all of the bits for a constant!
1111 KnownOne = cast<ConstantSDNode>(Op)->getValue() & Mask;
1112 KnownZero = ~KnownOne & Mask;
1115 // If either the LHS or the RHS are Zero, the result is zero.
1116 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1118 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1119 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1120 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1122 // Output known-1 bits are only known if set in both the LHS & RHS.
1123 KnownOne &= KnownOne2;
1124 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1125 KnownZero |= KnownZero2;
1128 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1130 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1131 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1132 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1134 // Output known-0 bits are only known if clear in both the LHS & RHS.
1135 KnownZero &= KnownZero2;
1136 // Output known-1 are known to be set if set in either the LHS | RHS.
1137 KnownOne |= KnownOne2;
1140 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1141 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1142 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1143 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1145 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1146 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1147 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1148 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1149 KnownZero = KnownZeroOut;
1153 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1154 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1155 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1156 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1158 // Only known if known in both the LHS and RHS.
1159 KnownOne &= KnownOne2;
1160 KnownZero &= KnownZero2;
1162 case ISD::SELECT_CC:
1163 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1164 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1165 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1166 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1168 // Only known if known in both the LHS and RHS.
1169 KnownOne &= KnownOne2;
1170 KnownZero &= KnownZero2;
1173 // If we know the result of a setcc has the top bits zero, use this info.
1174 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
1175 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
1178 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1179 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1180 ComputeMaskedBits(Op.getOperand(0), Mask >> SA->getValue(),
1181 KnownZero, KnownOne, Depth+1);
1182 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1183 KnownZero <<= SA->getValue();
1184 KnownOne <<= SA->getValue();
1185 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1189 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1190 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1191 MVT::ValueType VT = Op.getValueType();
1192 unsigned ShAmt = SA->getValue();
1194 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1195 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt) & TypeMask,
1196 KnownZero, KnownOne, Depth+1);
1197 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1198 KnownZero &= TypeMask;
1199 KnownOne &= TypeMask;
1200 KnownZero >>= ShAmt;
1203 uint64_t HighBits = (1ULL << ShAmt)-1;
1204 HighBits <<= MVT::getSizeInBits(VT)-ShAmt;
1205 KnownZero |= HighBits; // High bits known zero.
1209 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1210 MVT::ValueType VT = Op.getValueType();
1211 unsigned ShAmt = SA->getValue();
1213 // Compute the new bits that are at the top now.
1214 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1216 uint64_t InDemandedMask = (Mask << ShAmt) & TypeMask;
1217 // If any of the demanded bits are produced by the sign extension, we also
1218 // demand the input sign bit.
1219 uint64_t HighBits = (1ULL << ShAmt)-1;
1220 HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
1221 if (HighBits & Mask)
1222 InDemandedMask |= MVT::getIntVTSignBit(VT);
1224 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1226 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1227 KnownZero &= TypeMask;
1228 KnownOne &= TypeMask;
1229 KnownZero >>= ShAmt;
1232 // Handle the sign bits.
1233 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1234 SignBit >>= ShAmt; // Adjust to where it is now in the mask.
1236 if (KnownZero & SignBit) {
1237 KnownZero |= HighBits; // New bits are known zero.
1238 } else if (KnownOne & SignBit) {
1239 KnownOne |= HighBits; // New bits are known one.
1243 case ISD::SIGN_EXTEND_INREG: {
1244 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1246 // Sign extension. Compute the demanded bits in the result that are not
1247 // present in the input.
1248 uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & Mask;
1250 uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
1251 int64_t InputDemandedBits = Mask & MVT::getIntVTBitMask(EVT);
1253 // If the sign extended bits are demanded, we know that the sign
1256 InputDemandedBits |= InSignBit;
1258 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1259 KnownZero, KnownOne, Depth+1);
1260 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1262 // If the sign bit of the input is known set or clear, then we know the
1263 // top bits of the result.
1264 if (KnownZero & InSignBit) { // Input sign bit known clear
1265 KnownZero |= NewBits;
1266 KnownOne &= ~NewBits;
1267 } else if (KnownOne & InSignBit) { // Input sign bit known set
1268 KnownOne |= NewBits;
1269 KnownZero &= ~NewBits;
1270 } else { // Input sign bit unknown
1271 KnownZero &= ~NewBits;
1272 KnownOne &= ~NewBits;
1279 MVT::ValueType VT = Op.getValueType();
1280 unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
1281 KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
1286 if (ISD::isZEXTLoad(Op.Val)) {
1287 LoadSDNode *LD = cast<LoadSDNode>(Op);
1288 MVT::ValueType VT = LD->getMemoryVT();
1289 KnownZero |= ~MVT::getIntVTBitMask(VT) & Mask;
1293 case ISD::ZERO_EXTEND: {
1294 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
1295 uint64_t NewBits = (~InMask) & Mask;
1296 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1298 KnownZero |= NewBits & Mask;
1299 KnownOne &= ~NewBits;
1302 case ISD::SIGN_EXTEND: {
1303 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1304 unsigned InBits = MVT::getSizeInBits(InVT);
1305 uint64_t InMask = MVT::getIntVTBitMask(InVT);
1306 uint64_t InSignBit = 1ULL << (InBits-1);
1307 uint64_t NewBits = (~InMask) & Mask;
1308 uint64_t InDemandedBits = Mask & InMask;
1310 // If any of the sign extended bits are demanded, we know that the sign
1313 InDemandedBits |= InSignBit;
1315 ComputeMaskedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1317 // If the sign bit is known zero or one, the top bits match.
1318 if (KnownZero & InSignBit) {
1319 KnownZero |= NewBits;
1320 KnownOne &= ~NewBits;
1321 } else if (KnownOne & InSignBit) {
1322 KnownOne |= NewBits;
1323 KnownZero &= ~NewBits;
1324 } else { // Otherwise, top bits aren't known.
1325 KnownOne &= ~NewBits;
1326 KnownZero &= ~NewBits;
1330 case ISD::ANY_EXTEND: {
1331 MVT::ValueType VT = Op.getOperand(0).getValueType();
1332 ComputeMaskedBits(Op.getOperand(0), Mask & MVT::getIntVTBitMask(VT),
1333 KnownZero, KnownOne, Depth+1);
1336 case ISD::TRUNCATE: {
1337 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1338 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1339 uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
1340 KnownZero &= OutMask;
1341 KnownOne &= OutMask;
1344 case ISD::AssertZext: {
1345 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1346 uint64_t InMask = MVT::getIntVTBitMask(VT);
1347 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1349 KnownZero |= (~InMask) & Mask;
1353 // All bits are zero except the low bit.
1354 KnownZero = MVT::getIntVTBitMask(Op.getValueType()) ^ 1;
1358 // If either the LHS or the RHS are Zero, the result is zero.
1359 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1360 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1361 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1362 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1364 // Output known-0 bits are known if clear or set in both the low clear bits
1365 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1366 // low 3 bits clear.
1367 uint64_t KnownZeroOut = std::min(CountTrailingZeros_64(~KnownZero),
1368 CountTrailingZeros_64(~KnownZero2));
1370 KnownZero = (1ULL << KnownZeroOut) - 1;
1375 ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1378 // We know that the top bits of C-X are clear if X contains less bits
1379 // than C (i.e. no wrap-around can happen). For example, 20-X is
1380 // positive if we can prove that X is >= 0 and < 16.
1381 MVT::ValueType VT = CLHS->getValueType(0);
1382 if ((CLHS->getValue() & MVT::getIntVTSignBit(VT)) == 0) { // sign bit clear
1383 unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
1384 uint64_t MaskV = (1ULL << (63-NLZ))-1; // NLZ can't be 64 with no sign bit
1385 MaskV = ~MaskV & MVT::getIntVTBitMask(VT);
1386 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1388 // If all of the MaskV bits are known to be zero, then we know the output
1389 // top bits are zero, because we now know that the output is from [0-C].
1390 if ((KnownZero & MaskV) == MaskV) {
1391 unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
1392 KnownZero = ~((1ULL << (64-NLZ2))-1) & Mask; // Top bits known zero.
1393 KnownOne = 0; // No one bits known.
1395 KnownZero = KnownOne = 0; // Otherwise, nothing known.
1401 // Allow the target to implement this method for its nodes.
1402 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1403 case ISD::INTRINSIC_WO_CHAIN:
1404 case ISD::INTRINSIC_W_CHAIN:
1405 case ISD::INTRINSIC_VOID:
1406 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1412 /// ComputeNumSignBits - Return the number of times the sign bit of the
1413 /// register is replicated into the other bits. We know that at least 1 bit
1414 /// is always equal to the sign bit (itself), but other cases can give us
1415 /// information. For example, immediately after an "SRA X, 2", we know that
1416 /// the top 3 bits are all equal to each other, so we return 3.
1417 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1418 MVT::ValueType VT = Op.getValueType();
1419 assert(MVT::isInteger(VT) && "Invalid VT!");
1420 unsigned VTBits = MVT::getSizeInBits(VT);
1424 return 1; // Limit search depth.
1426 switch (Op.getOpcode()) {
1428 case ISD::AssertSext:
1429 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1430 return VTBits-Tmp+1;
1431 case ISD::AssertZext:
1432 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1435 case ISD::Constant: {
1436 uint64_t Val = cast<ConstantSDNode>(Op)->getValue();
1437 // If negative, invert the bits, then look at it.
1438 if (Val & MVT::getIntVTSignBit(VT))
1441 // Shift the bits so they are the leading bits in the int64_t.
1444 // Return # leading zeros. We use 'min' here in case Val was zero before
1445 // shifting. We don't want to return '64' as for an i32 "0".
1446 return std::min(VTBits, CountLeadingZeros_64(Val));
1449 case ISD::SIGN_EXTEND:
1450 Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1451 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1453 case ISD::SIGN_EXTEND_INREG:
1454 // Max of the input and what this extends.
1455 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1458 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1459 return std::max(Tmp, Tmp2);
1462 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1463 // SRA X, C -> adds C sign bits.
1464 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1465 Tmp += C->getValue();
1466 if (Tmp > VTBits) Tmp = VTBits;
1470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1471 // shl destroys sign bits.
1472 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1473 if (C->getValue() >= VTBits || // Bad shift.
1474 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1475 return Tmp - C->getValue();
1480 case ISD::XOR: // NOT is handled here.
1481 // Logical binary ops preserve the number of sign bits.
1482 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1483 if (Tmp == 1) return 1; // Early out.
1484 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1485 return std::min(Tmp, Tmp2);
1488 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1489 if (Tmp == 1) return 1; // Early out.
1490 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1491 return std::min(Tmp, Tmp2);
1494 // If setcc returns 0/-1, all bits are sign bits.
1495 if (TLI.getSetCCResultContents() ==
1496 TargetLowering::ZeroOrNegativeOneSetCCResult)
1501 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1502 unsigned RotAmt = C->getValue() & (VTBits-1);
1504 // Handle rotate right by N like a rotate left by 32-N.
1505 if (Op.getOpcode() == ISD::ROTR)
1506 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1508 // If we aren't rotating out all of the known-in sign bits, return the
1509 // number that are left. This handles rotl(sext(x), 1) for example.
1510 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1511 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1515 // Add can have at most one carry bit. Thus we know that the output
1516 // is, at worst, one more bit than the inputs.
1517 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1518 if (Tmp == 1) return 1; // Early out.
1520 // Special case decrementing a value (ADD X, -1):
1521 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1522 if (CRHS->isAllOnesValue()) {
1523 uint64_t KnownZero, KnownOne;
1524 uint64_t Mask = MVT::getIntVTBitMask(VT);
1525 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1527 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1529 if ((KnownZero|1) == Mask)
1532 // If we are subtracting one from a positive number, there is no carry
1533 // out of the result.
1534 if (KnownZero & MVT::getIntVTSignBit(VT))
1538 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1539 if (Tmp2 == 1) return 1;
1540 return std::min(Tmp, Tmp2)-1;
1544 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1545 if (Tmp2 == 1) return 1;
1548 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1549 if (CLHS->getValue() == 0) {
1550 uint64_t KnownZero, KnownOne;
1551 uint64_t Mask = MVT::getIntVTBitMask(VT);
1552 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1553 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1555 if ((KnownZero|1) == Mask)
1558 // If the input is known to be positive (the sign bit is known clear),
1559 // the output of the NEG has the same number of sign bits as the input.
1560 if (KnownZero & MVT::getIntVTSignBit(VT))
1563 // Otherwise, we treat this like a SUB.
1566 // Sub can have at most one carry bit. Thus we know that the output
1567 // is, at worst, one more bit than the inputs.
1568 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1569 if (Tmp == 1) return 1; // Early out.
1570 return std::min(Tmp, Tmp2)-1;
1573 // FIXME: it's tricky to do anything useful for this, but it is an important
1574 // case for targets like X86.
1578 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1579 if (Op.getOpcode() == ISD::LOAD) {
1580 LoadSDNode *LD = cast<LoadSDNode>(Op);
1581 unsigned ExtType = LD->getExtensionType();
1584 case ISD::SEXTLOAD: // '17' bits known
1585 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1586 return VTBits-Tmp+1;
1587 case ISD::ZEXTLOAD: // '16' bits known
1588 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1593 // Allow the target to implement this method for its nodes.
1594 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1595 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1596 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1597 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1598 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1599 if (NumBits > 1) return NumBits;
1602 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1603 // use this information.
1604 uint64_t KnownZero, KnownOne;
1605 uint64_t Mask = MVT::getIntVTBitMask(VT);
1606 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1608 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1609 if (KnownZero & SignBit) { // SignBit is 0
1611 } else if (KnownOne & SignBit) { // SignBit is 1;
1618 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1619 // the number of identical bits in the top of the input value.
1622 // Return # leading zeros. We use 'min' here in case Val was zero before
1623 // shifting. We don't want to return '64' as for an i32 "0".
1624 return std::min(VTBits, CountLeadingZeros_64(Mask));
1628 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1629 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1630 if (!GA) return false;
1631 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1632 if (!GV) return false;
1633 MachineModuleInfo *MMI = getMachineModuleInfo();
1634 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1638 /// getNode - Gets or creates the specified node.
1640 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1641 FoldingSetNodeID ID;
1642 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1644 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1645 return SDOperand(E, 0);
1646 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1647 CSEMap.InsertNode(N, IP);
1649 AllNodes.push_back(N);
1650 return SDOperand(N, 0);
1653 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1654 SDOperand Operand) {
1656 // Constant fold unary operations with an integer constant operand.
1657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1658 uint64_t Val = C->getValue();
1661 case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1662 case ISD::ANY_EXTEND:
1663 case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1664 case ISD::TRUNCATE: return getConstant(Val, VT);
1665 case ISD::UINT_TO_FP:
1666 case ISD::SINT_TO_FP: {
1667 const uint64_t zero[] = {0, 0};
1668 // No compile time operations on this type.
1669 if (VT==MVT::ppcf128)
1671 APFloat apf = APFloat(APInt(MVT::getSizeInBits(VT), 2, zero));
1672 (void)apf.convertFromZeroExtendedInteger(&Val,
1673 MVT::getSizeInBits(Operand.getValueType()),
1674 Opcode==ISD::SINT_TO_FP,
1675 APFloat::rmNearestTiesToEven);
1676 return getConstantFP(apf, VT);
1678 case ISD::BIT_CONVERT:
1679 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1680 return getConstantFP(BitsToFloat(Val), VT);
1681 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1682 return getConstantFP(BitsToDouble(Val), VT);
1686 default: assert(0 && "Invalid bswap!"); break;
1687 case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1688 case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1689 case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1694 default: assert(0 && "Invalid ctpop!"); break;
1695 case MVT::i1: return getConstant(Val != 0, VT);
1697 Tmp1 = (unsigned)Val & 0xFF;
1698 return getConstant(CountPopulation_32(Tmp1), VT);
1700 Tmp1 = (unsigned)Val & 0xFFFF;
1701 return getConstant(CountPopulation_32(Tmp1), VT);
1703 return getConstant(CountPopulation_32((unsigned)Val), VT);
1705 return getConstant(CountPopulation_64(Val), VT);
1709 default: assert(0 && "Invalid ctlz!"); break;
1710 case MVT::i1: return getConstant(Val == 0, VT);
1712 Tmp1 = (unsigned)Val & 0xFF;
1713 return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1715 Tmp1 = (unsigned)Val & 0xFFFF;
1716 return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1718 return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1720 return getConstant(CountLeadingZeros_64(Val), VT);
1724 default: assert(0 && "Invalid cttz!"); break;
1725 case MVT::i1: return getConstant(Val == 0, VT);
1727 Tmp1 = (unsigned)Val | 0x100;
1728 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1730 Tmp1 = (unsigned)Val | 0x10000;
1731 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1733 return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1735 return getConstant(CountTrailingZeros_64(Val), VT);
1740 // Constant fold unary operations with a floating point constant operand.
1741 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1742 APFloat V = C->getValueAPF(); // make copy
1743 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1747 return getConstantFP(V, VT);
1750 return getConstantFP(V, VT);
1752 case ISD::FP_EXTEND:
1753 // This can return overflow, underflow, or inexact; we don't care.
1754 // FIXME need to be more flexible about rounding mode.
1755 (void) V.convert(VT==MVT::f32 ? APFloat::IEEEsingle :
1756 VT==MVT::f64 ? APFloat::IEEEdouble :
1757 VT==MVT::f80 ? APFloat::x87DoubleExtended :
1758 VT==MVT::f128 ? APFloat::IEEEquad :
1760 APFloat::rmNearestTiesToEven);
1761 return getConstantFP(V, VT);
1762 case ISD::FP_TO_SINT:
1763 case ISD::FP_TO_UINT: {
1765 assert(integerPartWidth >= 64);
1766 // FIXME need to be more flexible about rounding mode.
1767 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1768 Opcode==ISD::FP_TO_SINT,
1769 APFloat::rmTowardZero);
1770 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1772 return getConstant(x, VT);
1774 case ISD::BIT_CONVERT:
1775 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1776 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1777 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1778 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1784 unsigned OpOpcode = Operand.Val->getOpcode();
1786 case ISD::TokenFactor:
1787 return Operand; // Factor of one node? No factor.
1788 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1789 case ISD::FP_EXTEND:
1790 assert(MVT::isFloatingPoint(VT) &&
1791 MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1792 if (Operand.getValueType() == VT) return Operand; // noop conversion.
1794 case ISD::SIGN_EXTEND:
1795 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1796 "Invalid SIGN_EXTEND!");
1797 if (Operand.getValueType() == VT) return Operand; // noop extension
1798 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1799 && "Invalid sext node, dst < src!");
1800 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1801 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1803 case ISD::ZERO_EXTEND:
1804 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1805 "Invalid ZERO_EXTEND!");
1806 if (Operand.getValueType() == VT) return Operand; // noop extension
1807 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1808 && "Invalid zext node, dst < src!");
1809 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
1810 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1812 case ISD::ANY_EXTEND:
1813 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1814 "Invalid ANY_EXTEND!");
1815 if (Operand.getValueType() == VT) return Operand; // noop extension
1816 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1817 && "Invalid anyext node, dst < src!");
1818 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1819 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
1820 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1823 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1824 "Invalid TRUNCATE!");
1825 if (Operand.getValueType() == VT) return Operand; // noop truncate
1826 assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
1827 && "Invalid truncate node, src < dst!");
1828 if (OpOpcode == ISD::TRUNCATE)
1829 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1830 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1831 OpOpcode == ISD::ANY_EXTEND) {
1832 // If the source is smaller than the dest, we still need an extend.
1833 if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1834 < MVT::getSizeInBits(VT))
1835 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1836 else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1837 > MVT::getSizeInBits(VT))
1838 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1840 return Operand.Val->getOperand(0);
1843 case ISD::BIT_CONVERT:
1844 // Basic sanity checking.
1845 assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1846 && "Cannot BIT_CONVERT between types of different sizes!");
1847 if (VT == Operand.getValueType()) return Operand; // noop conversion.
1848 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
1849 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1850 if (OpOpcode == ISD::UNDEF)
1851 return getNode(ISD::UNDEF, VT);
1853 case ISD::SCALAR_TO_VECTOR:
1854 assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1855 MVT::getVectorElementType(VT) == Operand.getValueType() &&
1856 "Illegal SCALAR_TO_VECTOR node!");
1859 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
1860 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1861 Operand.Val->getOperand(0));
1862 if (OpOpcode == ISD::FNEG) // --X -> X
1863 return Operand.Val->getOperand(0);
1866 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
1867 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1872 SDVTList VTs = getVTList(VT);
1873 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1874 FoldingSetNodeID ID;
1875 SDOperand Ops[1] = { Operand };
1876 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1878 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1879 return SDOperand(E, 0);
1880 N = new UnarySDNode(Opcode, VTs, Operand);
1881 CSEMap.InsertNode(N, IP);
1883 N = new UnarySDNode(Opcode, VTs, Operand);
1885 AllNodes.push_back(N);
1886 return SDOperand(N, 0);
1891 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1892 SDOperand N1, SDOperand N2) {
1893 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1894 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1897 case ISD::TokenFactor:
1898 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1899 N2.getValueType() == MVT::Other && "Invalid token factor!");
1900 // Fold trivial token factors.
1901 if (N1.getOpcode() == ISD::EntryToken) return N2;
1902 if (N2.getOpcode() == ISD::EntryToken) return N1;
1905 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1906 N1.getValueType() == VT && "Binary operator types must match!");
1907 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
1908 // worth handling here.
1909 if (N2C && N2C->getValue() == 0)
1911 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
1916 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1917 N1.getValueType() == VT && "Binary operator types must match!");
1918 // (X ^| 0) -> X. This commonly occurs when legalizing i64 values, so it's
1919 // worth handling here.
1920 if (N2C && N2C->getValue() == 0)
1927 assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1939 assert(N1.getValueType() == N2.getValueType() &&
1940 N1.getValueType() == VT && "Binary operator types must match!");
1942 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
1943 assert(N1.getValueType() == VT &&
1944 MVT::isFloatingPoint(N1.getValueType()) &&
1945 MVT::isFloatingPoint(N2.getValueType()) &&
1946 "Invalid FCOPYSIGN!");
1953 assert(VT == N1.getValueType() &&
1954 "Shift operators return type must be the same as their first arg");
1955 assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1956 VT != MVT::i1 && "Shifts only work on integers");
1958 case ISD::FP_ROUND_INREG: {
1959 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1960 assert(VT == N1.getValueType() && "Not an inreg round!");
1961 assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1962 "Cannot FP_ROUND_INREG integer types");
1963 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1964 "Not rounding down!");
1965 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
1969 assert(MVT::isFloatingPoint(VT) &&
1970 MVT::isFloatingPoint(N1.getValueType()) &&
1971 MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
1972 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
1973 if (N1.getValueType() == VT) return N1; // noop conversion.
1975 case ISD::AssertSext:
1976 case ISD::AssertZext: {
1977 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1978 assert(VT == N1.getValueType() && "Not an inreg extend!");
1979 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1980 "Cannot *_EXTEND_INREG FP types");
1981 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1985 case ISD::SIGN_EXTEND_INREG: {
1986 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1987 assert(VT == N1.getValueType() && "Not an inreg extend!");
1988 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1989 "Cannot *_EXTEND_INREG FP types");
1990 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1992 if (EVT == VT) return N1; // Not actually extending
1995 int64_t Val = N1C->getValue();
1996 unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
1997 Val <<= 64-FromBits;
1998 Val >>= 64-FromBits;
1999 return getConstant(Val, VT);
2003 case ISD::EXTRACT_VECTOR_ELT:
2004 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2006 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2007 // expanding copies of large vectors from registers.
2008 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2009 N1.getNumOperands() > 0) {
2011 MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2012 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2013 N1.getOperand(N2C->getValue() / Factor),
2014 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2017 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2018 // expanding large vector constants.
2019 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2020 return N1.getOperand(N2C->getValue());
2022 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2023 // operations are lowered to scalars.
2024 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2025 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2027 return N1.getOperand(1);
2029 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2032 case ISD::EXTRACT_ELEMENT:
2033 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2035 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2036 // 64-bit integers into 32-bit parts. Instead of building the extract of
2037 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2038 if (N1.getOpcode() == ISD::BUILD_PAIR)
2039 return N1.getOperand(N2C->getValue());
2041 // EXTRACT_ELEMENT of a constant int is also very common.
2042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2043 unsigned Shift = MVT::getSizeInBits(VT) * N2C->getValue();
2044 return getConstant(C->getValue() >> Shift, VT);
2051 uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
2053 case ISD::ADD: return getConstant(C1 + C2, VT);
2054 case ISD::SUB: return getConstant(C1 - C2, VT);
2055 case ISD::MUL: return getConstant(C1 * C2, VT);
2057 if (C2) return getConstant(C1 / C2, VT);
2060 if (C2) return getConstant(C1 % C2, VT);
2063 if (C2) return getConstant(N1C->getSignExtended() /
2064 N2C->getSignExtended(), VT);
2067 if (C2) return getConstant(N1C->getSignExtended() %
2068 N2C->getSignExtended(), VT);
2070 case ISD::AND : return getConstant(C1 & C2, VT);
2071 case ISD::OR : return getConstant(C1 | C2, VT);
2072 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2073 case ISD::SHL : return getConstant(C1 << C2, VT);
2074 case ISD::SRL : return getConstant(C1 >> C2, VT);
2075 case ISD::SRA : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
2077 return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
2080 return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)),
2084 } else { // Cannonicalize constant to RHS if commutative
2085 if (isCommutativeBinOp(Opcode)) {
2086 std::swap(N1C, N2C);
2092 // Constant fold FP operations.
2093 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2094 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2096 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2097 // Cannonicalize constant to RHS if commutative
2098 std::swap(N1CFP, N2CFP);
2100 } else if (N2CFP && VT != MVT::ppcf128) {
2101 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2102 APFloat::opStatus s;
2105 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2106 if (s != APFloat::opInvalidOp)
2107 return getConstantFP(V1, VT);
2110 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2111 if (s!=APFloat::opInvalidOp)
2112 return getConstantFP(V1, VT);
2115 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2116 if (s!=APFloat::opInvalidOp)
2117 return getConstantFP(V1, VT);
2120 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2121 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2122 return getConstantFP(V1, VT);
2125 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2126 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2127 return getConstantFP(V1, VT);
2129 case ISD::FCOPYSIGN:
2131 return getConstantFP(V1, VT);
2137 // Canonicalize an UNDEF to the RHS, even over a constant.
2138 if (N1.getOpcode() == ISD::UNDEF) {
2139 if (isCommutativeBinOp(Opcode)) {
2143 case ISD::FP_ROUND_INREG:
2144 case ISD::SIGN_EXTEND_INREG:
2150 return N1; // fold op(undef, arg2) -> undef
2157 if (!MVT::isVector(VT))
2158 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2159 // For vectors, we can't easily build an all zero vector, just return
2166 // Fold a bunch of operators when the RHS is undef.
2167 if (N2.getOpcode() == ISD::UNDEF) {
2183 return N2; // fold op(arg1, undef) -> undef
2188 if (!MVT::isVector(VT))
2189 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2190 // For vectors, we can't easily build an all zero vector, just return
2194 if (!MVT::isVector(VT))
2195 return getConstant(MVT::getIntVTBitMask(VT), VT);
2196 // For vectors, we can't easily build an all one vector, just return
2204 // Memoize this node if possible.
2206 SDVTList VTs = getVTList(VT);
2207 if (VT != MVT::Flag) {
2208 SDOperand Ops[] = { N1, N2 };
2209 FoldingSetNodeID ID;
2210 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2212 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2213 return SDOperand(E, 0);
2214 N = new BinarySDNode(Opcode, VTs, N1, N2);
2215 CSEMap.InsertNode(N, IP);
2217 N = new BinarySDNode(Opcode, VTs, N1, N2);
2220 AllNodes.push_back(N);
2221 return SDOperand(N, 0);
2224 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2225 SDOperand N1, SDOperand N2, SDOperand N3) {
2226 // Perform various simplifications.
2227 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2228 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2231 // Use FoldSetCC to simplify SETCC's.
2232 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2233 if (Simp.Val) return Simp;
2238 if (N1C->getValue())
2239 return N2; // select true, X, Y -> X
2241 return N3; // select false, X, Y -> Y
2243 if (N2 == N3) return N2; // select C, X, X -> X
2247 if (N2C->getValue()) // Unconditional branch
2248 return getNode(ISD::BR, MVT::Other, N1, N3);
2250 return N1; // Never-taken branch
2252 case ISD::VECTOR_SHUFFLE:
2253 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2254 MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2255 N3.getOpcode() == ISD::BUILD_VECTOR &&
2256 MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2257 "Illegal VECTOR_SHUFFLE node!");
2259 case ISD::BIT_CONVERT:
2260 // Fold bit_convert nodes from a type to themselves.
2261 if (N1.getValueType() == VT)
2266 // Memoize node if it doesn't produce a flag.
2268 SDVTList VTs = getVTList(VT);
2269 if (VT != MVT::Flag) {
2270 SDOperand Ops[] = { N1, N2, N3 };
2271 FoldingSetNodeID ID;
2272 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2274 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2275 return SDOperand(E, 0);
2276 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2277 CSEMap.InsertNode(N, IP);
2279 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2281 AllNodes.push_back(N);
2282 return SDOperand(N, 0);
2285 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2286 SDOperand N1, SDOperand N2, SDOperand N3,
2288 SDOperand Ops[] = { N1, N2, N3, N4 };
2289 return getNode(Opcode, VT, Ops, 4);
2292 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2293 SDOperand N1, SDOperand N2, SDOperand N3,
2294 SDOperand N4, SDOperand N5) {
2295 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2296 return getNode(Opcode, VT, Ops, 5);
2299 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dest,
2300 SDOperand Src, SDOperand Size,
2302 SDOperand AlwaysInline) {
2303 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2304 return getNode(ISD::MEMCPY, MVT::Other, Ops, 6);
2307 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dest,
2308 SDOperand Src, SDOperand Size,
2310 SDOperand AlwaysInline) {
2311 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2312 return getNode(ISD::MEMMOVE, MVT::Other, Ops, 6);
2315 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dest,
2316 SDOperand Src, SDOperand Size,
2318 SDOperand AlwaysInline) {
2319 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2320 return getNode(ISD::MEMSET, MVT::Other, Ops, 6);
2323 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2324 SDOperand Chain, SDOperand Ptr,
2325 const Value *SV, int SVOffset,
2326 bool isVolatile, unsigned Alignment) {
2327 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2329 if (VT != MVT::iPTR) {
2330 Ty = MVT::getTypeForValueType(VT);
2332 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2333 assert(PT && "Value for load must be a pointer");
2334 Ty = PT->getElementType();
2336 assert(Ty && "Could not get type information for load");
2337 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2339 SDVTList VTs = getVTList(VT, MVT::Other);
2340 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2341 SDOperand Ops[] = { Chain, Ptr, Undef };
2342 FoldingSetNodeID ID;
2343 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2344 ID.AddInteger(ISD::UNINDEXED);
2345 ID.AddInteger(ISD::NON_EXTLOAD);
2346 ID.AddInteger((unsigned int)VT);
2347 ID.AddInteger(Alignment);
2348 ID.AddInteger(isVolatile);
2350 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2351 return SDOperand(E, 0);
2352 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2353 ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2355 CSEMap.InsertNode(N, IP);
2356 AllNodes.push_back(N);
2357 return SDOperand(N, 0);
2360 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2361 SDOperand Chain, SDOperand Ptr,
2363 int SVOffset, MVT::ValueType EVT,
2364 bool isVolatile, unsigned Alignment) {
2365 // If they are asking for an extending load from/to the same thing, return a
2368 return getLoad(VT, Chain, Ptr, SV, SVOffset, isVolatile, Alignment);
2370 if (MVT::isVector(VT))
2371 assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2373 assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2374 "Should only be an extending load, not truncating!");
2375 assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2376 "Cannot sign/zero extend a FP/Vector load!");
2377 assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2378 "Cannot convert from FP to Int or Int -> FP!");
2380 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2382 if (VT != MVT::iPTR) {
2383 Ty = MVT::getTypeForValueType(VT);
2385 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2386 assert(PT && "Value for load must be a pointer");
2387 Ty = PT->getElementType();
2389 assert(Ty && "Could not get type information for load");
2390 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2392 SDVTList VTs = getVTList(VT, MVT::Other);
2393 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2394 SDOperand Ops[] = { Chain, Ptr, Undef };
2395 FoldingSetNodeID ID;
2396 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2397 ID.AddInteger(ISD::UNINDEXED);
2398 ID.AddInteger(ExtType);
2399 ID.AddInteger((unsigned int)EVT);
2400 ID.AddInteger(Alignment);
2401 ID.AddInteger(isVolatile);
2403 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2404 return SDOperand(E, 0);
2405 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2406 SV, SVOffset, Alignment, isVolatile);
2407 CSEMap.InsertNode(N, IP);
2408 AllNodes.push_back(N);
2409 return SDOperand(N, 0);
2413 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2414 SDOperand Offset, ISD::MemIndexedMode AM) {
2415 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2416 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2417 "Load is already a indexed load!");
2418 MVT::ValueType VT = OrigLoad.getValueType();
2419 SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2420 SDOperand Ops[] = { LD->getChain(), Base, Offset };
2421 FoldingSetNodeID ID;
2422 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2424 ID.AddInteger(LD->getExtensionType());
2425 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
2426 ID.AddInteger(LD->getAlignment());
2427 ID.AddInteger(LD->isVolatile());
2429 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2430 return SDOperand(E, 0);
2431 SDNode *N = new LoadSDNode(Ops, VTs, AM,
2432 LD->getExtensionType(), LD->getMemoryVT(),
2433 LD->getSrcValue(), LD->getSrcValueOffset(),
2434 LD->getAlignment(), LD->isVolatile());
2435 CSEMap.InsertNode(N, IP);
2436 AllNodes.push_back(N);
2437 return SDOperand(N, 0);
2440 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2441 SDOperand Ptr, const Value *SV, int SVOffset,
2442 bool isVolatile, unsigned Alignment) {
2443 MVT::ValueType VT = Val.getValueType();
2445 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2447 if (VT != MVT::iPTR) {
2448 Ty = MVT::getTypeForValueType(VT);
2450 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2451 assert(PT && "Value for store must be a pointer");
2452 Ty = PT->getElementType();
2454 assert(Ty && "Could not get type information for store");
2455 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2457 SDVTList VTs = getVTList(MVT::Other);
2458 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2459 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2460 FoldingSetNodeID ID;
2461 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2462 ID.AddInteger(ISD::UNINDEXED);
2463 ID.AddInteger(false);
2464 ID.AddInteger((unsigned int)VT);
2465 ID.AddInteger(Alignment);
2466 ID.AddInteger(isVolatile);
2468 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2469 return SDOperand(E, 0);
2470 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2471 VT, SV, SVOffset, Alignment, isVolatile);
2472 CSEMap.InsertNode(N, IP);
2473 AllNodes.push_back(N);
2474 return SDOperand(N, 0);
2477 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2478 SDOperand Ptr, const Value *SV,
2479 int SVOffset, MVT::ValueType SVT,
2480 bool isVolatile, unsigned Alignment) {
2481 MVT::ValueType VT = Val.getValueType();
2484 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
2486 assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
2487 "Not a truncation?");
2488 assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2489 "Can't do FP-INT conversion!");
2491 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2493 if (VT != MVT::iPTR) {
2494 Ty = MVT::getTypeForValueType(VT);
2496 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2497 assert(PT && "Value for store must be a pointer");
2498 Ty = PT->getElementType();
2500 assert(Ty && "Could not get type information for store");
2501 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2503 SDVTList VTs = getVTList(MVT::Other);
2504 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2505 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2506 FoldingSetNodeID ID;
2507 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2508 ID.AddInteger(ISD::UNINDEXED);
2510 ID.AddInteger((unsigned int)SVT);
2511 ID.AddInteger(Alignment);
2512 ID.AddInteger(isVolatile);
2514 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2515 return SDOperand(E, 0);
2516 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
2517 SVT, SV, SVOffset, Alignment, isVolatile);
2518 CSEMap.InsertNode(N, IP);
2519 AllNodes.push_back(N);
2520 return SDOperand(N, 0);
2524 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2525 SDOperand Offset, ISD::MemIndexedMode AM) {
2526 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2527 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2528 "Store is already a indexed store!");
2529 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2530 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2531 FoldingSetNodeID ID;
2532 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2534 ID.AddInteger(ST->isTruncatingStore());
2535 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
2536 ID.AddInteger(ST->getAlignment());
2537 ID.AddInteger(ST->isVolatile());
2539 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2540 return SDOperand(E, 0);
2541 SDNode *N = new StoreSDNode(Ops, VTs, AM,
2542 ST->isTruncatingStore(), ST->getMemoryVT(),
2543 ST->getSrcValue(), ST->getSrcValueOffset(),
2544 ST->getAlignment(), ST->isVolatile());
2545 CSEMap.InsertNode(N, IP);
2546 AllNodes.push_back(N);
2547 return SDOperand(N, 0);
2550 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2551 SDOperand Chain, SDOperand Ptr,
2553 SDOperand Ops[] = { Chain, Ptr, SV };
2554 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2557 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2558 const SDOperand *Ops, unsigned NumOps) {
2560 case 0: return getNode(Opcode, VT);
2561 case 1: return getNode(Opcode, VT, Ops[0]);
2562 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2563 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2569 case ISD::SELECT_CC: {
2570 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2571 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2572 "LHS and RHS of condition must have same type!");
2573 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2574 "True and False arms of SelectCC must have same type!");
2575 assert(Ops[2].getValueType() == VT &&
2576 "select_cc node must be of same type as true and false value!");
2580 assert(NumOps == 5 && "BR_CC takes 5 operands!");
2581 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2582 "LHS/RHS of comparison should match types!");
2589 SDVTList VTs = getVTList(VT);
2590 if (VT != MVT::Flag) {
2591 FoldingSetNodeID ID;
2592 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2594 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2595 return SDOperand(E, 0);
2596 N = new SDNode(Opcode, VTs, Ops, NumOps);
2597 CSEMap.InsertNode(N, IP);
2599 N = new SDNode(Opcode, VTs, Ops, NumOps);
2601 AllNodes.push_back(N);
2602 return SDOperand(N, 0);
2605 SDOperand SelectionDAG::getNode(unsigned Opcode,
2606 std::vector<MVT::ValueType> &ResultTys,
2607 const SDOperand *Ops, unsigned NumOps) {
2608 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2612 SDOperand SelectionDAG::getNode(unsigned Opcode,
2613 const MVT::ValueType *VTs, unsigned NumVTs,
2614 const SDOperand *Ops, unsigned NumOps) {
2616 return getNode(Opcode, VTs[0], Ops, NumOps);
2617 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2620 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2621 const SDOperand *Ops, unsigned NumOps) {
2622 if (VTList.NumVTs == 1)
2623 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2626 // FIXME: figure out how to safely handle things like
2627 // int foo(int x) { return 1 << (x & 255); }
2628 // int bar() { return foo(256); }
2630 case ISD::SRA_PARTS:
2631 case ISD::SRL_PARTS:
2632 case ISD::SHL_PARTS:
2633 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2634 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2635 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2636 else if (N3.getOpcode() == ISD::AND)
2637 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2638 // If the and is only masking out bits that cannot effect the shift,
2639 // eliminate the and.
2640 unsigned NumBits = MVT::getSizeInBits(VT)*2;
2641 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2642 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2648 // Memoize the node unless it returns a flag.
2650 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2651 FoldingSetNodeID ID;
2652 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2654 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2655 return SDOperand(E, 0);
2657 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2658 else if (NumOps == 2)
2659 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2660 else if (NumOps == 3)
2661 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2663 N = new SDNode(Opcode, VTList, Ops, NumOps);
2664 CSEMap.InsertNode(N, IP);
2667 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2668 else if (NumOps == 2)
2669 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2670 else if (NumOps == 3)
2671 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2673 N = new SDNode(Opcode, VTList, Ops, NumOps);
2675 AllNodes.push_back(N);
2676 return SDOperand(N, 0);
2679 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
2680 return getNode(Opcode, VTList, 0, 0);
2683 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2685 SDOperand Ops[] = { N1 };
2686 return getNode(Opcode, VTList, Ops, 1);
2689 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2690 SDOperand N1, SDOperand N2) {
2691 SDOperand Ops[] = { N1, N2 };
2692 return getNode(Opcode, VTList, Ops, 2);
2695 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2696 SDOperand N1, SDOperand N2, SDOperand N3) {
2697 SDOperand Ops[] = { N1, N2, N3 };
2698 return getNode(Opcode, VTList, Ops, 3);
2701 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2702 SDOperand N1, SDOperand N2, SDOperand N3,
2704 SDOperand Ops[] = { N1, N2, N3, N4 };
2705 return getNode(Opcode, VTList, Ops, 4);
2708 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2709 SDOperand N1, SDOperand N2, SDOperand N3,
2710 SDOperand N4, SDOperand N5) {
2711 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2712 return getNode(Opcode, VTList, Ops, 5);
2715 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2716 return makeVTList(SDNode::getValueTypeList(VT), 1);
2719 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2720 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2721 E = VTList.end(); I != E; ++I) {
2722 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2723 return makeVTList(&(*I)[0], 2);
2725 std::vector<MVT::ValueType> V;
2728 VTList.push_front(V);
2729 return makeVTList(&(*VTList.begin())[0], 2);
2731 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2732 MVT::ValueType VT3) {
2733 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2734 E = VTList.end(); I != E; ++I) {
2735 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2737 return makeVTList(&(*I)[0], 3);
2739 std::vector<MVT::ValueType> V;
2743 VTList.push_front(V);
2744 return makeVTList(&(*VTList.begin())[0], 3);
2747 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2749 case 0: assert(0 && "Cannot have nodes without results!");
2750 case 1: return getVTList(VTs[0]);
2751 case 2: return getVTList(VTs[0], VTs[1]);
2752 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2756 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2757 E = VTList.end(); I != E; ++I) {
2758 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2760 bool NoMatch = false;
2761 for (unsigned i = 2; i != NumVTs; ++i)
2762 if (VTs[i] != (*I)[i]) {
2767 return makeVTList(&*I->begin(), NumVTs);
2770 VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2771 return makeVTList(&*VTList.begin()->begin(), NumVTs);
2775 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2776 /// specified operands. If the resultant node already exists in the DAG,
2777 /// this does not modify the specified node, instead it returns the node that
2778 /// already exists. If the resultant node does not exist in the DAG, the
2779 /// input node is returned. As a degenerate case, if you specify the same
2780 /// input operands as the node already has, the input node is returned.
2781 SDOperand SelectionDAG::
2782 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2783 SDNode *N = InN.Val;
2784 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2786 // Check to see if there is no change.
2787 if (Op == N->getOperand(0)) return InN;
2789 // See if the modified node already exists.
2790 void *InsertPos = 0;
2791 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2792 return SDOperand(Existing, InN.ResNo);
2794 // Nope it doesn't. Remove the node from it's current place in the maps.
2796 RemoveNodeFromCSEMaps(N);
2798 // Now we update the operands.
2799 N->OperandList[0].Val->removeUser(N);
2801 N->OperandList[0] = Op;
2803 // If this gets put into a CSE map, add it.
2804 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2808 SDOperand SelectionDAG::
2809 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2810 SDNode *N = InN.Val;
2811 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2813 // Check to see if there is no change.
2814 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2815 return InN; // No operands changed, just return the input node.
2817 // See if the modified node already exists.
2818 void *InsertPos = 0;
2819 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2820 return SDOperand(Existing, InN.ResNo);
2822 // Nope it doesn't. Remove the node from it's current place in the maps.
2824 RemoveNodeFromCSEMaps(N);
2826 // Now we update the operands.
2827 if (N->OperandList[0] != Op1) {
2828 N->OperandList[0].Val->removeUser(N);
2829 Op1.Val->addUser(N);
2830 N->OperandList[0] = Op1;
2832 if (N->OperandList[1] != Op2) {
2833 N->OperandList[1].Val->removeUser(N);
2834 Op2.Val->addUser(N);
2835 N->OperandList[1] = Op2;
2838 // If this gets put into a CSE map, add it.
2839 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2843 SDOperand SelectionDAG::
2844 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2845 SDOperand Ops[] = { Op1, Op2, Op3 };
2846 return UpdateNodeOperands(N, Ops, 3);
2849 SDOperand SelectionDAG::
2850 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2851 SDOperand Op3, SDOperand Op4) {
2852 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2853 return UpdateNodeOperands(N, Ops, 4);
2856 SDOperand SelectionDAG::
2857 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2858 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2859 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2860 return UpdateNodeOperands(N, Ops, 5);
2864 SDOperand SelectionDAG::
2865 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2866 SDNode *N = InN.Val;
2867 assert(N->getNumOperands() == NumOps &&
2868 "Update with wrong number of operands");
2870 // Check to see if there is no change.
2871 bool AnyChange = false;
2872 for (unsigned i = 0; i != NumOps; ++i) {
2873 if (Ops[i] != N->getOperand(i)) {
2879 // No operands changed, just return the input node.
2880 if (!AnyChange) return InN;
2882 // See if the modified node already exists.
2883 void *InsertPos = 0;
2884 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
2885 return SDOperand(Existing, InN.ResNo);
2887 // Nope it doesn't. Remove the node from it's current place in the maps.
2889 RemoveNodeFromCSEMaps(N);
2891 // Now we update the operands.
2892 for (unsigned i = 0; i != NumOps; ++i) {
2893 if (N->OperandList[i] != Ops[i]) {
2894 N->OperandList[i].Val->removeUser(N);
2895 Ops[i].Val->addUser(N);
2896 N->OperandList[i] = Ops[i];
2900 // If this gets put into a CSE map, add it.
2901 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2906 /// MorphNodeTo - This frees the operands of the current node, resets the
2907 /// opcode, types, and operands to the specified value. This should only be
2908 /// used by the SelectionDAG class.
2909 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
2910 const SDOperand *Ops, unsigned NumOps) {
2913 NumValues = L.NumVTs;
2915 // Clear the operands list, updating used nodes to remove this from their
2917 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2918 I->Val->removeUser(this);
2920 // If NumOps is larger than the # of operands we currently have, reallocate
2921 // the operand list.
2922 if (NumOps > NumOperands) {
2923 if (OperandsNeedDelete)
2924 delete [] OperandList;
2925 OperandList = new SDOperand[NumOps];
2926 OperandsNeedDelete = true;
2929 // Assign the new operands.
2930 NumOperands = NumOps;
2932 for (unsigned i = 0, e = NumOps; i != e; ++i) {
2933 OperandList[i] = Ops[i];
2934 SDNode *N = OperandList[i].Val;
2935 N->Uses.push_back(this);
2939 /// SelectNodeTo - These are used for target selectors to *mutate* the
2940 /// specified node to have the specified return type, Target opcode, and
2941 /// operands. Note that target opcodes are stored as
2942 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2944 /// Note that SelectNodeTo returns the resultant node. If there is already a
2945 /// node of the specified opcode and operands, it returns that node instead of
2946 /// the current one.
2947 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2948 MVT::ValueType VT) {
2949 SDVTList VTs = getVTList(VT);
2950 FoldingSetNodeID ID;
2951 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2953 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2956 RemoveNodeFromCSEMaps(N);
2958 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2960 CSEMap.InsertNode(N, IP);
2964 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2965 MVT::ValueType VT, SDOperand Op1) {
2966 // If an identical node already exists, use it.
2967 SDVTList VTs = getVTList(VT);
2968 SDOperand Ops[] = { Op1 };
2970 FoldingSetNodeID ID;
2971 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2973 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2976 RemoveNodeFromCSEMaps(N);
2977 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2978 CSEMap.InsertNode(N, IP);
2982 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2983 MVT::ValueType VT, SDOperand Op1,
2985 // If an identical node already exists, use it.
2986 SDVTList VTs = getVTList(VT);
2987 SDOperand Ops[] = { Op1, Op2 };
2989 FoldingSetNodeID ID;
2990 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2992 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2995 RemoveNodeFromCSEMaps(N);
2997 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2999 CSEMap.InsertNode(N, IP); // Memoize the new node.
3003 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3004 MVT::ValueType VT, SDOperand Op1,
3005 SDOperand Op2, SDOperand Op3) {
3006 // If an identical node already exists, use it.
3007 SDVTList VTs = getVTList(VT);
3008 SDOperand Ops[] = { Op1, Op2, Op3 };
3009 FoldingSetNodeID ID;
3010 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3012 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3015 RemoveNodeFromCSEMaps(N);
3017 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3019 CSEMap.InsertNode(N, IP); // Memoize the new node.
3023 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3024 MVT::ValueType VT, const SDOperand *Ops,
3026 // If an identical node already exists, use it.
3027 SDVTList VTs = getVTList(VT);
3028 FoldingSetNodeID ID;
3029 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3031 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3034 RemoveNodeFromCSEMaps(N);
3035 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3037 CSEMap.InsertNode(N, IP); // Memoize the new node.
3041 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3042 MVT::ValueType VT1, MVT::ValueType VT2,
3043 SDOperand Op1, SDOperand Op2) {
3044 SDVTList VTs = getVTList(VT1, VT2);
3045 FoldingSetNodeID ID;
3046 SDOperand Ops[] = { Op1, Op2 };
3047 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3049 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3052 RemoveNodeFromCSEMaps(N);
3053 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3054 CSEMap.InsertNode(N, IP); // Memoize the new node.
3058 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3059 MVT::ValueType VT1, MVT::ValueType VT2,
3060 SDOperand Op1, SDOperand Op2,
3062 // If an identical node already exists, use it.
3063 SDVTList VTs = getVTList(VT1, VT2);
3064 SDOperand Ops[] = { Op1, Op2, Op3 };
3065 FoldingSetNodeID ID;
3066 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3068 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3071 RemoveNodeFromCSEMaps(N);
3073 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3074 CSEMap.InsertNode(N, IP); // Memoize the new node.
3079 /// getTargetNode - These are used for target selectors to create a new node
3080 /// with specified return type(s), target opcode, and operands.
3082 /// Note that getTargetNode returns the resultant node. If there is already a
3083 /// node of the specified opcode and operands, it returns that node instead of
3084 /// the current one.
3085 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3086 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3088 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3090 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3092 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3093 SDOperand Op1, SDOperand Op2) {
3094 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3096 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3097 SDOperand Op1, SDOperand Op2,
3099 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3101 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3102 const SDOperand *Ops, unsigned NumOps) {
3103 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3105 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3106 MVT::ValueType VT2) {
3107 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3109 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3111 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3112 MVT::ValueType VT2, SDOperand Op1) {
3113 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3114 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3116 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3117 MVT::ValueType VT2, SDOperand Op1,
3119 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3120 SDOperand Ops[] = { Op1, Op2 };
3121 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3123 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3124 MVT::ValueType VT2, SDOperand Op1,
3125 SDOperand Op2, SDOperand Op3) {
3126 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3127 SDOperand Ops[] = { Op1, Op2, Op3 };
3128 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3130 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3132 const SDOperand *Ops, unsigned NumOps) {
3133 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3134 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3136 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3137 MVT::ValueType VT2, MVT::ValueType VT3,
3138 SDOperand Op1, SDOperand Op2) {
3139 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3140 SDOperand Ops[] = { Op1, Op2 };
3141 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3143 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3144 MVT::ValueType VT2, MVT::ValueType VT3,
3145 SDOperand Op1, SDOperand Op2,
3147 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3148 SDOperand Ops[] = { Op1, Op2, Op3 };
3149 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3151 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3152 MVT::ValueType VT2, MVT::ValueType VT3,
3153 const SDOperand *Ops, unsigned NumOps) {
3154 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3155 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3157 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3158 MVT::ValueType VT2, MVT::ValueType VT3,
3160 const SDOperand *Ops, unsigned NumOps) {
3161 std::vector<MVT::ValueType> VTList;
3162 VTList.push_back(VT1);
3163 VTList.push_back(VT2);
3164 VTList.push_back(VT3);
3165 VTList.push_back(VT4);
3166 const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3167 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3169 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3170 std::vector<MVT::ValueType> &ResultTys,
3171 const SDOperand *Ops, unsigned NumOps) {
3172 const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3173 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3178 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3179 /// This can cause recursive merging of nodes in the DAG.
3181 /// This version assumes From has a single result value.
3183 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3184 DAGUpdateListener *UpdateListener) {
3185 SDNode *From = FromN.Val;
3186 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3187 "Cannot replace with this method!");
3188 assert(From != To.Val && "Cannot replace uses of with self");
3190 while (!From->use_empty()) {
3191 // Process users until they are all gone.
3192 SDNode *U = *From->use_begin();
3194 // This node is about to morph, remove its old self from the CSE maps.
3195 RemoveNodeFromCSEMaps(U);
3197 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3199 if (I->Val == From) {
3200 From->removeUser(U);
3205 // Now that we have modified U, add it back to the CSE maps. If it already
3206 // exists there, recursively merge the results together.
3207 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3208 ReplaceAllUsesWith(U, Existing, UpdateListener);
3209 // U is now dead. Inform the listener if it exists and delete it.
3211 UpdateListener->NodeDeleted(U);
3212 DeleteNodeNotInCSEMaps(U);
3214 // If the node doesn't already exist, we updated it. Inform a listener if
3217 UpdateListener->NodeUpdated(U);
3222 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3223 /// This can cause recursive merging of nodes in the DAG.
3225 /// This version assumes From/To have matching types and numbers of result
3228 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3229 DAGUpdateListener *UpdateListener) {
3230 assert(From != To && "Cannot replace uses of with self");
3231 assert(From->getNumValues() == To->getNumValues() &&
3232 "Cannot use this version of ReplaceAllUsesWith!");
3233 if (From->getNumValues() == 1) // If possible, use the faster version.
3234 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3237 while (!From->use_empty()) {
3238 // Process users until they are all gone.
3239 SDNode *U = *From->use_begin();
3241 // This node is about to morph, remove its old self from the CSE maps.
3242 RemoveNodeFromCSEMaps(U);
3244 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3246 if (I->Val == From) {
3247 From->removeUser(U);
3252 // Now that we have modified U, add it back to the CSE maps. If it already
3253 // exists there, recursively merge the results together.
3254 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3255 ReplaceAllUsesWith(U, Existing, UpdateListener);
3256 // U is now dead. Inform the listener if it exists and delete it.
3258 UpdateListener->NodeDeleted(U);
3259 DeleteNodeNotInCSEMaps(U);
3261 // If the node doesn't already exist, we updated it. Inform a listener if
3264 UpdateListener->NodeUpdated(U);
3269 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3270 /// This can cause recursive merging of nodes in the DAG.
3272 /// This version can replace From with any result values. To must match the
3273 /// number and types of values returned by From.
3274 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3275 const SDOperand *To,
3276 DAGUpdateListener *UpdateListener) {
3277 if (From->getNumValues() == 1) // Handle the simple case efficiently.
3278 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3280 while (!From->use_empty()) {
3281 // Process users until they are all gone.
3282 SDNode *U = *From->use_begin();
3284 // This node is about to morph, remove its old self from the CSE maps.
3285 RemoveNodeFromCSEMaps(U);
3287 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3289 if (I->Val == From) {
3290 const SDOperand &ToOp = To[I->ResNo];
3291 From->removeUser(U);
3293 ToOp.Val->addUser(U);
3296 // Now that we have modified U, add it back to the CSE maps. If it already
3297 // exists there, recursively merge the results together.
3298 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3299 ReplaceAllUsesWith(U, Existing, UpdateListener);
3300 // U is now dead. Inform the listener if it exists and delete it.
3302 UpdateListener->NodeDeleted(U);
3303 DeleteNodeNotInCSEMaps(U);
3305 // If the node doesn't already exist, we updated it. Inform a listener if
3308 UpdateListener->NodeUpdated(U);
3314 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
3315 /// any deleted nodes from the set passed into its constructor and recursively
3316 /// notifies another update listener if specified.
3317 class ChainedSetUpdaterListener :
3318 public SelectionDAG::DAGUpdateListener {
3319 SmallSetVector<SDNode*, 16> &Set;
3320 SelectionDAG::DAGUpdateListener *Chain;
3322 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
3323 SelectionDAG::DAGUpdateListener *chain)
3324 : Set(set), Chain(chain) {}
3326 virtual void NodeDeleted(SDNode *N) {
3328 if (Chain) Chain->NodeDeleted(N);
3330 virtual void NodeUpdated(SDNode *N) {
3331 if (Chain) Chain->NodeUpdated(N);
3336 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3337 /// uses of other values produced by From.Val alone. The Deleted vector is
3338 /// handled the same way as for ReplaceAllUsesWith.
3339 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3340 DAGUpdateListener *UpdateListener){
3341 assert(From != To && "Cannot replace a value with itself");
3343 // Handle the simple, trivial, case efficiently.
3344 if (From.Val->getNumValues() == 1) {
3345 ReplaceAllUsesWith(From, To, UpdateListener);
3349 if (From.use_empty()) return;
3351 // Get all of the users of From.Val. We want these in a nice,
3352 // deterministically ordered and uniqued set, so we use a SmallSetVector.
3353 SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3355 // When one of the recursive merges deletes nodes from the graph, we need to
3356 // make sure that UpdateListener is notified *and* that the node is removed
3357 // from Users if present. CSUL does this.
3358 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
3360 while (!Users.empty()) {
3361 // We know that this user uses some value of From. If it is the right
3362 // value, update it.
3363 SDNode *User = Users.back();
3366 // Scan for an operand that matches From.
3367 SDOperand *Op = User->OperandList, *E = User->OperandList+User->NumOperands;
3368 for (; Op != E; ++Op)
3369 if (*Op == From) break;
3371 // If there are no matches, the user must use some other result of From.
3372 if (Op == E) continue;
3374 // Okay, we know this user needs to be updated. Remove its old self
3375 // from the CSE maps.
3376 RemoveNodeFromCSEMaps(User);
3378 // Update all operands that match "From" in case there are multiple uses.
3379 for (; Op != E; ++Op) {
3381 From.Val->removeUser(User);
3383 To.Val->addUser(User);
3387 // Now that we have modified User, add it back to the CSE maps. If it
3388 // already exists there, recursively merge the results together.
3389 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3391 if (UpdateListener) UpdateListener->NodeUpdated(User);
3392 continue; // Continue on to next user.
3395 // If there was already an existing matching node, use ReplaceAllUsesWith
3396 // to replace the dead one with the existing one. This can cause
3397 // recursive merging of other unrelated nodes down the line. The merging
3398 // can cause deletion of nodes that used the old value. To handle this, we
3399 // use CSUL to remove them from the Users set.
3400 ReplaceAllUsesWith(User, Existing, &CSUL);
3402 // User is now dead. Notify a listener if present.
3403 if (UpdateListener) UpdateListener->NodeDeleted(User);
3404 DeleteNodeNotInCSEMaps(User);
3409 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3410 /// their allnodes order. It returns the maximum id.
3411 unsigned SelectionDAG::AssignNodeIds() {
3413 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3420 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3421 /// based on their topological order. It returns the maximum id and a vector
3422 /// of the SDNodes* in assigned order by reference.
3423 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3424 unsigned DAGSize = AllNodes.size();
3425 std::vector<unsigned> InDegree(DAGSize);
3426 std::vector<SDNode*> Sources;
3428 // Use a two pass approach to avoid using a std::map which is slow.
3430 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3433 unsigned Degree = N->use_size();
3434 InDegree[N->getNodeId()] = Degree;
3436 Sources.push_back(N);
3440 while (!Sources.empty()) {
3441 SDNode *N = Sources.back();
3443 TopOrder.push_back(N);
3444 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3446 unsigned Degree = --InDegree[P->getNodeId()];
3448 Sources.push_back(P);
3452 // Second pass, assign the actual topological order as node ids.
3454 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3456 (*TI)->setNodeId(Id++);
3463 //===----------------------------------------------------------------------===//
3465 //===----------------------------------------------------------------------===//
3467 // Out-of-line virtual method to give class a home.
3468 void SDNode::ANCHOR() {}
3469 void UnarySDNode::ANCHOR() {}
3470 void BinarySDNode::ANCHOR() {}
3471 void TernarySDNode::ANCHOR() {}
3472 void HandleSDNode::ANCHOR() {}
3473 void StringSDNode::ANCHOR() {}
3474 void ConstantSDNode::ANCHOR() {}
3475 void ConstantFPSDNode::ANCHOR() {}
3476 void GlobalAddressSDNode::ANCHOR() {}
3477 void FrameIndexSDNode::ANCHOR() {}
3478 void JumpTableSDNode::ANCHOR() {}
3479 void ConstantPoolSDNode::ANCHOR() {}
3480 void BasicBlockSDNode::ANCHOR() {}
3481 void SrcValueSDNode::ANCHOR() {}
3482 void RegisterSDNode::ANCHOR() {}
3483 void ExternalSymbolSDNode::ANCHOR() {}
3484 void CondCodeSDNode::ANCHOR() {}
3485 void VTSDNode::ANCHOR() {}
3486 void LoadSDNode::ANCHOR() {}
3487 void StoreSDNode::ANCHOR() {}
3489 HandleSDNode::~HandleSDNode() {
3490 SDVTList VTs = { 0, 0 };
3491 MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0); // Drops operand uses.
3494 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3495 MVT::ValueType VT, int o)
3496 : SDNode(isa<GlobalVariable>(GA) &&
3497 cast<GlobalVariable>(GA)->isThreadLocal() ?
3499 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3501 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3502 getSDVTList(VT)), Offset(o) {
3503 TheGlobal = const_cast<GlobalValue*>(GA);
3506 /// Profile - Gather unique data for the node.
3508 void SDNode::Profile(FoldingSetNodeID &ID) {
3509 AddNodeIDNode(ID, this);
3512 /// getValueTypeList - Return a pointer to the specified value type.
3514 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3515 if (MVT::isExtendedVT(VT)) {
3516 static std::set<MVT::ValueType> EVTs;
3517 return (MVT::ValueType *)&(*EVTs.insert(VT).first);
3519 static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3525 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3526 /// indicated value. This method ignores uses of other values defined by this
3528 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3529 assert(Value < getNumValues() && "Bad value!");
3531 // If there is only one value, this is easy.
3532 if (getNumValues() == 1)
3533 return use_size() == NUses;
3534 if (use_size() < NUses) return false;
3536 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3538 SmallPtrSet<SDNode*, 32> UsersHandled;
3540 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3542 if (User->getNumOperands() == 1 ||
3543 UsersHandled.insert(User)) // First time we've seen this?
3544 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3545 if (User->getOperand(i) == TheValue) {
3547 return false; // too many uses
3552 // Found exactly the right number of uses?
3557 /// hasAnyUseOfValue - Return true if there are any use of the indicated
3558 /// value. This method ignores uses of other values defined by this operation.
3559 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3560 assert(Value < getNumValues() && "Bad value!");
3562 if (use_empty()) return false;
3564 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3566 SmallPtrSet<SDNode*, 32> UsersHandled;
3568 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3570 if (User->getNumOperands() == 1 ||
3571 UsersHandled.insert(User)) // First time we've seen this?
3572 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3573 if (User->getOperand(i) == TheValue) {
3582 /// isOnlyUse - Return true if this node is the only use of N.
3584 bool SDNode::isOnlyUse(SDNode *N) const {
3586 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3597 /// isOperand - Return true if this node is an operand of N.
3599 bool SDOperand::isOperand(SDNode *N) const {
3600 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3601 if (*this == N->getOperand(i))
3606 bool SDNode::isOperand(SDNode *N) const {
3607 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3608 if (this == N->OperandList[i].Val)
3613 /// reachesChainWithoutSideEffects - Return true if this operand (which must
3614 /// be a chain) reaches the specified operand without crossing any
3615 /// side-effecting instructions. In practice, this looks through token
3616 /// factors and non-volatile loads. In order to remain efficient, this only
3617 /// looks a couple of nodes in, it does not do an exhaustive search.
3618 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
3619 unsigned Depth) const {
3620 if (*this == Dest) return true;
3622 // Don't search too deeply, we just want to be able to see through
3623 // TokenFactor's etc.
3624 if (Depth == 0) return false;
3626 // If this is a token factor, all inputs to the TF happen in parallel. If any
3627 // of the operands of the TF reach dest, then we can do the xform.
3628 if (getOpcode() == ISD::TokenFactor) {
3629 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3630 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
3635 // Loads don't have side effects, look through them.
3636 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
3637 if (!Ld->isVolatile())
3638 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
3644 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3645 SmallPtrSet<SDNode *, 32> &Visited) {
3646 if (found || !Visited.insert(N))
3649 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3650 SDNode *Op = N->getOperand(i).Val;
3655 findPredecessor(Op, P, found, Visited);
3659 /// isPredecessor - Return true if this node is a predecessor of N. This node
3660 /// is either an operand of N or it can be reached by recursively traversing
3661 /// up the operands.
3662 /// NOTE: this is an expensive method. Use it carefully.
3663 bool SDNode::isPredecessor(SDNode *N) const {
3664 SmallPtrSet<SDNode *, 32> Visited;
3666 findPredecessor(N, this, found, Visited);
3670 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3671 assert(Num < NumOperands && "Invalid child # of SDNode!");
3672 return cast<ConstantSDNode>(OperandList[Num])->getValue();
3675 std::string SDNode::getOperationName(const SelectionDAG *G) const {
3676 switch (getOpcode()) {
3678 if (getOpcode() < ISD::BUILTIN_OP_END)
3679 return "<<Unknown DAG Node>>";
3682 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3683 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3684 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
3686 TargetLowering &TLI = G->getTargetLoweringInfo();
3688 TLI.getTargetNodeName(getOpcode());
3689 if (Name) return Name;
3692 return "<<Unknown Target Node>>";
3695 case ISD::PCMARKER: return "PCMarker";
3696 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3697 case ISD::SRCVALUE: return "SrcValue";
3698 case ISD::EntryToken: return "EntryToken";
3699 case ISD::TokenFactor: return "TokenFactor";
3700 case ISD::AssertSext: return "AssertSext";
3701 case ISD::AssertZext: return "AssertZext";
3703 case ISD::STRING: return "String";
3704 case ISD::BasicBlock: return "BasicBlock";
3705 case ISD::VALUETYPE: return "ValueType";
3706 case ISD::Register: return "Register";
3708 case ISD::Constant: return "Constant";
3709 case ISD::ConstantFP: return "ConstantFP";
3710 case ISD::GlobalAddress: return "GlobalAddress";
3711 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3712 case ISD::FrameIndex: return "FrameIndex";
3713 case ISD::JumpTable: return "JumpTable";
3714 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3715 case ISD::RETURNADDR: return "RETURNADDR";
3716 case ISD::FRAMEADDR: return "FRAMEADDR";
3717 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3718 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3719 case ISD::EHSELECTION: return "EHSELECTION";
3720 case ISD::EH_RETURN: return "EH_RETURN";
3721 case ISD::ConstantPool: return "ConstantPool";
3722 case ISD::ExternalSymbol: return "ExternalSymbol";
3723 case ISD::INTRINSIC_WO_CHAIN: {
3724 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3725 return Intrinsic::getName((Intrinsic::ID)IID);
3727 case ISD::INTRINSIC_VOID:
3728 case ISD::INTRINSIC_W_CHAIN: {
3729 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3730 return Intrinsic::getName((Intrinsic::ID)IID);
3733 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
3734 case ISD::TargetConstant: return "TargetConstant";
3735 case ISD::TargetConstantFP:return "TargetConstantFP";
3736 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3737 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3738 case ISD::TargetFrameIndex: return "TargetFrameIndex";
3739 case ISD::TargetJumpTable: return "TargetJumpTable";
3740 case ISD::TargetConstantPool: return "TargetConstantPool";
3741 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3743 case ISD::CopyToReg: return "CopyToReg";
3744 case ISD::CopyFromReg: return "CopyFromReg";
3745 case ISD::UNDEF: return "undef";
3746 case ISD::MERGE_VALUES: return "merge_values";
3747 case ISD::INLINEASM: return "inlineasm";
3748 case ISD::LABEL: return "label";
3749 case ISD::DECLARE: return "declare";
3750 case ISD::HANDLENODE: return "handlenode";
3751 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3752 case ISD::CALL: return "call";
3755 case ISD::FABS: return "fabs";
3756 case ISD::FNEG: return "fneg";
3757 case ISD::FSQRT: return "fsqrt";
3758 case ISD::FSIN: return "fsin";
3759 case ISD::FCOS: return "fcos";
3760 case ISD::FPOWI: return "fpowi";
3761 case ISD::FPOW: return "fpow";
3764 case ISD::ADD: return "add";
3765 case ISD::SUB: return "sub";
3766 case ISD::MUL: return "mul";
3767 case ISD::MULHU: return "mulhu";
3768 case ISD::MULHS: return "mulhs";
3769 case ISD::SDIV: return "sdiv";
3770 case ISD::UDIV: return "udiv";
3771 case ISD::SREM: return "srem";
3772 case ISD::UREM: return "urem";
3773 case ISD::SMUL_LOHI: return "smul_lohi";
3774 case ISD::UMUL_LOHI: return "umul_lohi";
3775 case ISD::SDIVREM: return "sdivrem";
3776 case ISD::UDIVREM: return "divrem";
3777 case ISD::AND: return "and";
3778 case ISD::OR: return "or";
3779 case ISD::XOR: return "xor";
3780 case ISD::SHL: return "shl";
3781 case ISD::SRA: return "sra";
3782 case ISD::SRL: return "srl";
3783 case ISD::ROTL: return "rotl";
3784 case ISD::ROTR: return "rotr";
3785 case ISD::FADD: return "fadd";
3786 case ISD::FSUB: return "fsub";
3787 case ISD::FMUL: return "fmul";
3788 case ISD::FDIV: return "fdiv";
3789 case ISD::FREM: return "frem";
3790 case ISD::FCOPYSIGN: return "fcopysign";
3791 case ISD::FGETSIGN: return "fgetsign";
3793 case ISD::SETCC: return "setcc";
3794 case ISD::SELECT: return "select";
3795 case ISD::SELECT_CC: return "select_cc";
3796 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
3797 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
3798 case ISD::CONCAT_VECTORS: return "concat_vectors";
3799 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
3800 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
3801 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
3802 case ISD::CARRY_FALSE: return "carry_false";
3803 case ISD::ADDC: return "addc";
3804 case ISD::ADDE: return "adde";
3805 case ISD::SUBC: return "subc";
3806 case ISD::SUBE: return "sube";
3807 case ISD::SHL_PARTS: return "shl_parts";
3808 case ISD::SRA_PARTS: return "sra_parts";
3809 case ISD::SRL_PARTS: return "srl_parts";
3811 case ISD::EXTRACT_SUBREG: return "extract_subreg";
3812 case ISD::INSERT_SUBREG: return "insert_subreg";
3814 // Conversion operators.
3815 case ISD::SIGN_EXTEND: return "sign_extend";
3816 case ISD::ZERO_EXTEND: return "zero_extend";
3817 case ISD::ANY_EXTEND: return "any_extend";
3818 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3819 case ISD::TRUNCATE: return "truncate";
3820 case ISD::FP_ROUND: return "fp_round";
3821 case ISD::FLT_ROUNDS_: return "flt_rounds";
3822 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3823 case ISD::FP_EXTEND: return "fp_extend";
3825 case ISD::SINT_TO_FP: return "sint_to_fp";
3826 case ISD::UINT_TO_FP: return "uint_to_fp";
3827 case ISD::FP_TO_SINT: return "fp_to_sint";
3828 case ISD::FP_TO_UINT: return "fp_to_uint";
3829 case ISD::BIT_CONVERT: return "bit_convert";
3831 // Control flow instructions
3832 case ISD::BR: return "br";
3833 case ISD::BRIND: return "brind";
3834 case ISD::BR_JT: return "br_jt";
3835 case ISD::BRCOND: return "brcond";
3836 case ISD::BR_CC: return "br_cc";
3837 case ISD::RET: return "ret";
3838 case ISD::CALLSEQ_START: return "callseq_start";
3839 case ISD::CALLSEQ_END: return "callseq_end";
3842 case ISD::LOAD: return "load";
3843 case ISD::STORE: return "store";
3844 case ISD::VAARG: return "vaarg";
3845 case ISD::VACOPY: return "vacopy";
3846 case ISD::VAEND: return "vaend";
3847 case ISD::VASTART: return "vastart";
3848 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
3849 case ISD::EXTRACT_ELEMENT: return "extract_element";
3850 case ISD::BUILD_PAIR: return "build_pair";
3851 case ISD::STACKSAVE: return "stacksave";
3852 case ISD::STACKRESTORE: return "stackrestore";
3853 case ISD::TRAP: return "trap";
3855 // Block memory operations.
3856 case ISD::MEMSET: return "memset";
3857 case ISD::MEMCPY: return "memcpy";
3858 case ISD::MEMMOVE: return "memmove";
3861 case ISD::BSWAP: return "bswap";
3862 case ISD::CTPOP: return "ctpop";
3863 case ISD::CTTZ: return "cttz";
3864 case ISD::CTLZ: return "ctlz";
3867 case ISD::LOCATION: return "location";
3868 case ISD::DEBUG_LOC: return "debug_loc";
3871 case ISD::TRAMPOLINE: return "trampoline";
3874 switch (cast<CondCodeSDNode>(this)->get()) {
3875 default: assert(0 && "Unknown setcc condition!");
3876 case ISD::SETOEQ: return "setoeq";
3877 case ISD::SETOGT: return "setogt";
3878 case ISD::SETOGE: return "setoge";
3879 case ISD::SETOLT: return "setolt";
3880 case ISD::SETOLE: return "setole";
3881 case ISD::SETONE: return "setone";
3883 case ISD::SETO: return "seto";
3884 case ISD::SETUO: return "setuo";
3885 case ISD::SETUEQ: return "setue";
3886 case ISD::SETUGT: return "setugt";
3887 case ISD::SETUGE: return "setuge";
3888 case ISD::SETULT: return "setult";
3889 case ISD::SETULE: return "setule";
3890 case ISD::SETUNE: return "setune";
3892 case ISD::SETEQ: return "seteq";
3893 case ISD::SETGT: return "setgt";
3894 case ISD::SETGE: return "setge";
3895 case ISD::SETLT: return "setlt";
3896 case ISD::SETLE: return "setle";
3897 case ISD::SETNE: return "setne";
3902 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
3911 return "<post-inc>";
3913 return "<post-dec>";
3917 void SDNode::dump() const { dump(0); }
3918 void SDNode::dump(const SelectionDAG *G) const {
3919 cerr << (void*)this << ": ";
3921 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
3923 if (getValueType(i) == MVT::Other)
3926 cerr << MVT::getValueTypeString(getValueType(i));
3928 cerr << " = " << getOperationName(G);
3931 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3932 if (i) cerr << ", ";
3933 cerr << (void*)getOperand(i).Val;
3934 if (unsigned RN = getOperand(i).ResNo)
3938 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
3939 SDNode *Mask = getOperand(2).Val;
3941 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
3943 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
3946 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
3951 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
3952 cerr << "<" << CSDN->getValue() << ">";
3953 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
3954 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
3955 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
3956 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
3957 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
3959 cerr << "<APFloat(";
3960 CSDN->getValueAPF().convertToAPInt().dump();
3963 } else if (const GlobalAddressSDNode *GADN =
3964 dyn_cast<GlobalAddressSDNode>(this)) {
3965 int offset = GADN->getOffset();
3967 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
3969 cerr << " + " << offset;
3971 cerr << " " << offset;
3972 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
3973 cerr << "<" << FIDN->getIndex() << ">";
3974 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
3975 cerr << "<" << JTDN->getIndex() << ">";
3976 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
3977 int offset = CP->getOffset();
3978 if (CP->isMachineConstantPoolEntry())
3979 cerr << "<" << *CP->getMachineCPVal() << ">";
3981 cerr << "<" << *CP->getConstVal() << ">";
3983 cerr << " + " << offset;
3985 cerr << " " << offset;
3986 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
3988 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
3990 cerr << LBB->getName() << " ";
3991 cerr << (const void*)BBDN->getBasicBlock() << ">";
3992 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
3993 if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
3994 cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
3996 cerr << " #" << R->getReg();
3998 } else if (const ExternalSymbolSDNode *ES =
3999 dyn_cast<ExternalSymbolSDNode>(this)) {
4000 cerr << "'" << ES->getSymbol() << "'";
4001 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4003 cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
4005 cerr << "<null:" << M->getOffset() << ">";
4006 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4007 cerr << ":" << MVT::getValueTypeString(N->getVT());
4008 } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4009 const Value *SrcValue = LD->getSrcValue();
4010 int SrcOffset = LD->getSrcValueOffset();
4016 cerr << ":" << SrcOffset << ">";
4019 switch (LD->getExtensionType()) {
4020 default: doExt = false; break;
4022 cerr << " <anyext ";
4032 cerr << MVT::getValueTypeString(LD->getMemoryVT()) << ">";
4034 const char *AM = getIndexedModeName(LD->getAddressingMode());
4037 if (LD->isVolatile())
4038 cerr << " <volatile>";
4039 cerr << " alignment=" << LD->getAlignment();
4040 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4041 const Value *SrcValue = ST->getSrcValue();
4042 int SrcOffset = ST->getSrcValueOffset();
4048 cerr << ":" << SrcOffset << ">";
4050 if (ST->isTruncatingStore())
4052 << MVT::getValueTypeString(ST->getMemoryVT()) << ">";
4054 const char *AM = getIndexedModeName(ST->getAddressingMode());
4057 if (ST->isVolatile())
4058 cerr << " <volatile>";
4059 cerr << " alignment=" << ST->getAlignment();
4063 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4064 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4065 if (N->getOperand(i).Val->hasOneUse())
4066 DumpNodes(N->getOperand(i).Val, indent+2, G);
4068 cerr << "\n" << std::string(indent+2, ' ')
4069 << (void*)N->getOperand(i).Val << ": <multiple use>";
4072 cerr << "\n" << std::string(indent, ' ');
4076 void SelectionDAG::dump() const {
4077 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4078 std::vector<const SDNode*> Nodes;
4079 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4083 std::sort(Nodes.begin(), Nodes.end());
4085 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4086 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4087 DumpNodes(Nodes[i], 2, this);
4090 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4095 const Type *ConstantPoolSDNode::getType() const {
4096 if (isMachineConstantPoolEntry())
4097 return Val.MachineCPVal->getType();
4098 return Val.ConstVal->getType();