1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
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 pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "dagcombine"
16 #include "llvm/CodeGen/SelectionDAG.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetFrameInfo.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
34 STATISTIC(NodesCombined , "Number of dag nodes combined");
35 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
36 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
41 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
42 cl::desc("Pop up a window to show dags before the first "
45 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
46 cl::desc("Pop up a window to show dags before the second "
49 static const bool ViewDAGCombine1 = false;
50 static const bool ViewDAGCombine2 = false;
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Turn on alias analysis during testing"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Include global information in alias analysis"));
61 //------------------------------ DAGCombiner ---------------------------------//
63 class VISIBILITY_HIDDEN DAGCombiner {
68 // Worklist of all of the nodes that need to be simplified.
69 std::vector<SDNode*> WorkList;
71 // AA - Used for DAG load/store alias analysis.
74 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
78 void AddUsersToWorkList(SDNode *N) {
79 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
84 /// visit - call the node-specific routine that knows how to fold each
85 /// particular type of node.
86 SDOperand visit(SDNode *N);
89 /// AddToWorkList - Add to the work list making sure it's instance is at the
90 /// the back (next to be processed.)
91 void AddToWorkList(SDNode *N) {
92 removeFromWorkList(N);
93 WorkList.push_back(N);
96 /// removeFromWorkList - remove all instances of N from the worklist.
98 void removeFromWorkList(SDNode *N) {
99 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
103 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
106 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
107 return CombineTo(N, &Res, 1, AddTo);
110 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
112 SDOperand To[] = { Res0, Res1 };
113 return CombineTo(N, To, 2, AddTo);
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
121 bool SimplifyDemandedBits(SDOperand Op, uint64_t Demanded = ~0ULL);
123 bool CombineToPreIndexedLoadStore(SDNode *N);
124 bool CombineToPostIndexedLoadStore(SDNode *N);
127 /// combine - call the node-specific routine that knows how to fold each
128 /// particular type of node. If that doesn't do anything, try the
129 /// target-specific DAG combines.
130 SDOperand combine(SDNode *N);
132 // Visitation implementation - Implement dag node combining for different
133 // node types. The semantics are as follows:
135 // SDOperand.Val == 0 - No change was made
136 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
137 // otherwise - N should be replaced by the returned Operand.
139 SDOperand visitTokenFactor(SDNode *N);
140 SDOperand visitADD(SDNode *N);
141 SDOperand visitSUB(SDNode *N);
142 SDOperand visitADDC(SDNode *N);
143 SDOperand visitADDE(SDNode *N);
144 SDOperand visitMUL(SDNode *N);
145 SDOperand visitSDIV(SDNode *N);
146 SDOperand visitUDIV(SDNode *N);
147 SDOperand visitSREM(SDNode *N);
148 SDOperand visitUREM(SDNode *N);
149 SDOperand visitMULHU(SDNode *N);
150 SDOperand visitMULHS(SDNode *N);
151 SDOperand visitSMUL_LOHI(SDNode *N);
152 SDOperand visitUMUL_LOHI(SDNode *N);
153 SDOperand visitSDIVREM(SDNode *N);
154 SDOperand visitUDIVREM(SDNode *N);
155 SDOperand visitAND(SDNode *N);
156 SDOperand visitOR(SDNode *N);
157 SDOperand visitXOR(SDNode *N);
158 SDOperand SimplifyVBinOp(SDNode *N);
159 SDOperand visitSHL(SDNode *N);
160 SDOperand visitSRA(SDNode *N);
161 SDOperand visitSRL(SDNode *N);
162 SDOperand visitCTLZ(SDNode *N);
163 SDOperand visitCTTZ(SDNode *N);
164 SDOperand visitCTPOP(SDNode *N);
165 SDOperand visitSELECT(SDNode *N);
166 SDOperand visitSELECT_CC(SDNode *N);
167 SDOperand visitSETCC(SDNode *N);
168 SDOperand visitSIGN_EXTEND(SDNode *N);
169 SDOperand visitZERO_EXTEND(SDNode *N);
170 SDOperand visitANY_EXTEND(SDNode *N);
171 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
172 SDOperand visitTRUNCATE(SDNode *N);
173 SDOperand visitBIT_CONVERT(SDNode *N);
174 SDOperand visitFADD(SDNode *N);
175 SDOperand visitFSUB(SDNode *N);
176 SDOperand visitFMUL(SDNode *N);
177 SDOperand visitFDIV(SDNode *N);
178 SDOperand visitFREM(SDNode *N);
179 SDOperand visitFCOPYSIGN(SDNode *N);
180 SDOperand visitSINT_TO_FP(SDNode *N);
181 SDOperand visitUINT_TO_FP(SDNode *N);
182 SDOperand visitFP_TO_SINT(SDNode *N);
183 SDOperand visitFP_TO_UINT(SDNode *N);
184 SDOperand visitFP_ROUND(SDNode *N);
185 SDOperand visitFP_ROUND_INREG(SDNode *N);
186 SDOperand visitFP_EXTEND(SDNode *N);
187 SDOperand visitFNEG(SDNode *N);
188 SDOperand visitFABS(SDNode *N);
189 SDOperand visitBRCOND(SDNode *N);
190 SDOperand visitBR_CC(SDNode *N);
191 SDOperand visitLOAD(SDNode *N);
192 SDOperand visitSTORE(SDNode *N);
193 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
194 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
195 SDOperand visitBUILD_VECTOR(SDNode *N);
196 SDOperand visitCONCAT_VECTORS(SDNode *N);
197 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
199 SDOperand XformToShuffleWithZero(SDNode *N);
200 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
202 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
204 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
205 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
206 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
207 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
208 SDOperand N3, ISD::CondCode CC,
209 bool NotExtCompare = false);
210 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
211 ISD::CondCode Cond, bool foldBooleans = true);
212 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
214 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
215 SDOperand BuildSDIV(SDNode *N);
216 SDOperand BuildUDIV(SDNode *N);
217 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
218 SDOperand ReduceLoadWidth(SDNode *N);
220 SDOperand GetDemandedBits(SDOperand V, uint64_t Mask);
222 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
223 /// looking for aliasing nodes and adding them to the Aliases vector.
224 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
225 SmallVector<SDOperand, 8> &Aliases);
227 /// isAlias - Return true if there is any possibility that the two addresses
229 bool isAlias(SDOperand Ptr1, int64_t Size1,
230 const Value *SrcValue1, int SrcValueOffset1,
231 SDOperand Ptr2, int64_t Size2,
232 const Value *SrcValue2, int SrcValueOffset2);
234 /// FindAliasInfo - Extracts the relevant alias information from the memory
235 /// node. Returns true if the operand was a load.
236 bool FindAliasInfo(SDNode *N,
237 SDOperand &Ptr, int64_t &Size,
238 const Value *&SrcValue, int &SrcValueOffset);
240 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
241 /// looking for a better chain (aliasing node.)
242 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
245 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
247 TLI(D.getTargetLoweringInfo()),
248 AfterLegalize(false),
251 /// Run - runs the dag combiner on all nodes in the work list
252 void Run(bool RunningAfterLegalize);
258 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
259 /// nodes from the worklist.
260 class VISIBILITY_HIDDEN WorkListRemover :
261 public SelectionDAG::DAGUpdateListener {
264 WorkListRemover(DAGCombiner &dc) : DC(dc) {}
266 virtual void NodeDeleted(SDNode *N) {
267 printf("remove from WL: %p\n", (void*)N);
268 DC.removeFromWorkList(N);
271 virtual void NodeUpdated(SDNode *N) {
277 //===----------------------------------------------------------------------===//
278 // TargetLowering::DAGCombinerInfo implementation
279 //===----------------------------------------------------------------------===//
281 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
282 ((DAGCombiner*)DC)->AddToWorkList(N);
285 SDOperand TargetLowering::DAGCombinerInfo::
286 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
287 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
290 SDOperand TargetLowering::DAGCombinerInfo::
291 CombineTo(SDNode *N, SDOperand Res) {
292 return ((DAGCombiner*)DC)->CombineTo(N, Res);
296 SDOperand TargetLowering::DAGCombinerInfo::
297 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
298 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
302 //===----------------------------------------------------------------------===//
304 //===----------------------------------------------------------------------===//
306 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
307 /// specified expression for the same cost as the expression itself, or 2 if we
308 /// can compute the negated form more cheaply than the expression itself.
309 static char isNegatibleForFree(SDOperand Op, unsigned Depth = 0) {
310 // No compile time optimizations on this type.
311 if (Op.getValueType() == MVT::ppcf128)
314 // fneg is removable even if it has multiple uses.
315 if (Op.getOpcode() == ISD::FNEG) return 2;
317 // Don't allow anything with multiple uses.
318 if (!Op.hasOneUse()) return 0;
320 // Don't recurse exponentially.
321 if (Depth > 6) return 0;
323 switch (Op.getOpcode()) {
324 default: return false;
325 case ISD::ConstantFP:
328 // FIXME: determine better conditions for this xform.
329 if (!UnsafeFPMath) return 0;
332 if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
335 return isNegatibleForFree(Op.getOperand(1), Depth+1);
337 // We can't turn -(A-B) into B-A when we honor signed zeros.
338 if (!UnsafeFPMath) return 0;
345 if (HonorSignDependentRoundingFPMath()) return 0;
347 // -(X*Y) -> (-X * Y) or (X*-Y)
348 if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
351 return isNegatibleForFree(Op.getOperand(1), Depth+1);
356 return isNegatibleForFree(Op.getOperand(0), Depth+1);
360 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
361 /// returns the newly negated expression.
362 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
363 unsigned Depth = 0) {
364 // fneg is removable even if it has multiple uses.
365 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
367 // Don't allow anything with multiple uses.
368 assert(Op.hasOneUse() && "Unknown reuse!");
370 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
371 switch (Op.getOpcode()) {
372 default: assert(0 && "Unknown code");
373 case ISD::ConstantFP: {
374 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
376 return DAG.getConstantFP(V, Op.getValueType());
379 // FIXME: determine better conditions for this xform.
380 assert(UnsafeFPMath);
383 if (isNegatibleForFree(Op.getOperand(0), Depth+1))
384 return DAG.getNode(ISD::FSUB, Op.getValueType(),
385 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
388 return DAG.getNode(ISD::FSUB, Op.getValueType(),
389 GetNegatedExpression(Op.getOperand(1), DAG, Depth+1),
392 // We can't turn -(A-B) into B-A when we honor signed zeros.
393 assert(UnsafeFPMath);
396 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
397 if (N0CFP->getValueAPF().isZero())
398 return Op.getOperand(1);
401 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
406 assert(!HonorSignDependentRoundingFPMath());
409 if (isNegatibleForFree(Op.getOperand(0), Depth+1))
410 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
411 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
415 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
417 GetNegatedExpression(Op.getOperand(1), DAG, Depth+1));
421 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
422 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1));
424 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
425 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
431 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
432 // that selects between the values 1 and 0, making it equivalent to a setcc.
433 // Also, set the incoming LHS, RHS, and CC references to the appropriate
434 // nodes based on the type of node we are checking. This simplifies life a
435 // bit for the callers.
436 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
438 if (N.getOpcode() == ISD::SETCC) {
439 LHS = N.getOperand(0);
440 RHS = N.getOperand(1);
441 CC = N.getOperand(2);
444 if (N.getOpcode() == ISD::SELECT_CC &&
445 N.getOperand(2).getOpcode() == ISD::Constant &&
446 N.getOperand(3).getOpcode() == ISD::Constant &&
447 cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
448 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
449 LHS = N.getOperand(0);
450 RHS = N.getOperand(1);
451 CC = N.getOperand(4);
457 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
458 // one use. If this is true, it allows the users to invert the operation for
459 // free when it is profitable to do so.
460 static bool isOneUseSetCC(SDOperand N) {
461 SDOperand N0, N1, N2;
462 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
467 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
468 MVT::ValueType VT = N0.getValueType();
469 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
470 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
471 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
472 if (isa<ConstantSDNode>(N1)) {
473 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
474 AddToWorkList(OpNode.Val);
475 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
476 } else if (N0.hasOneUse()) {
477 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
478 AddToWorkList(OpNode.Val);
479 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
482 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
483 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
484 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
485 if (isa<ConstantSDNode>(N0)) {
486 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
487 AddToWorkList(OpNode.Val);
488 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
489 } else if (N1.hasOneUse()) {
490 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
491 AddToWorkList(OpNode.Val);
492 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
498 SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
500 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
502 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
503 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
504 DOUT << " and " << NumTo-1 << " other values\n";
505 WorkListRemover DeadNodes(*this);
506 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
509 // Push the new nodes and any users onto the worklist
510 for (unsigned i = 0, e = NumTo; i != e; ++i) {
511 AddToWorkList(To[i].Val);
512 AddUsersToWorkList(To[i].Val);
516 // Nodes can be reintroduced into the worklist. Make sure we do not
517 // process a node that has been replaced.
518 removeFromWorkList(N);
520 // Finally, since the node is now dead, remove it from the graph.
522 return SDOperand(N, 0);
525 /// SimplifyDemandedBits - Check the specified integer node value to see if
526 /// it can be simplified or if things it uses can be simplified by bit
527 /// propagation. If so, return true.
528 bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, uint64_t Demanded) {
529 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
530 uint64_t KnownZero, KnownOne;
531 Demanded &= MVT::getIntVTBitMask(Op.getValueType());
532 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
536 AddToWorkList(Op.Val);
538 // Replace the old value with the new one.
540 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
541 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
544 // Replace all uses. If any nodes become isomorphic to other nodes and
545 // are deleted, make sure to remove them from our worklist.
546 WorkListRemover DeadNodes(*this);
547 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
549 // Push the new node and any (possibly new) users onto the worklist.
550 AddToWorkList(TLO.New.Val);
551 AddUsersToWorkList(TLO.New.Val);
553 // Finally, if the node is now dead, remove it from the graph. The node
554 // may not be dead if the replacement process recursively simplified to
555 // something else needing this node.
556 if (TLO.Old.Val->use_empty()) {
557 removeFromWorkList(TLO.Old.Val);
559 // If the operands of this node are only used by the node, they will now
560 // be dead. Make sure to visit them first to delete dead nodes early.
561 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
562 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
563 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
565 DAG.DeleteNode(TLO.Old.Val);
570 //===----------------------------------------------------------------------===//
571 // Main DAG Combiner implementation
572 //===----------------------------------------------------------------------===//
574 void DAGCombiner::Run(bool RunningAfterLegalize) {
575 // set the instance variable, so that the various visit routines may use it.
576 AfterLegalize = RunningAfterLegalize;
578 // Add all the dag nodes to the worklist.
579 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
580 E = DAG.allnodes_end(); I != E; ++I)
581 WorkList.push_back(I);
583 // Create a dummy node (which is not added to allnodes), that adds a reference
584 // to the root node, preventing it from being deleted, and tracking any
585 // changes of the root.
586 HandleSDNode Dummy(DAG.getRoot());
588 // The root of the dag may dangle to deleted nodes until the dag combiner is
589 // done. Set it to null to avoid confusion.
590 DAG.setRoot(SDOperand());
592 // while the worklist isn't empty, inspect the node on the end of it and
593 // try and combine it.
594 while (!WorkList.empty()) {
595 SDNode *N = WorkList.back();
598 // If N has no uses, it is dead. Make sure to revisit all N's operands once
599 // N is deleted from the DAG, since they too may now be dead or may have a
600 // reduced number of uses, allowing other xforms.
601 if (N->use_empty() && N != &Dummy) {
602 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
603 AddToWorkList(N->getOperand(i).Val);
609 SDOperand RV = combine(N);
616 // If we get back the same node we passed in, rather than a new node or
617 // zero, we know that the node must have defined multiple values and
618 // CombineTo was used. Since CombineTo takes care of the worklist
619 // mechanics for us, we have no work to do in this case.
623 assert(N->getOpcode() != ISD::DELETED_NODE &&
624 RV.Val->getOpcode() != ISD::DELETED_NODE &&
625 "Node was deleted but visit returned new node!");
627 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
628 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
630 WorkListRemover DeadNodes(*this);
631 if (N->getNumValues() == RV.Val->getNumValues())
632 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
634 assert(N->getValueType(0) == RV.getValueType() &&
635 N->getNumValues() == 1 && "Type mismatch");
637 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
640 // Push the new node and any users onto the worklist
641 AddToWorkList(RV.Val);
642 AddUsersToWorkList(RV.Val);
644 // Add any uses of the old node to the worklist in case this node is the
645 // last one that uses them. They may become dead after this node is
647 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
648 AddToWorkList(N->getOperand(i).Val);
650 // Nodes can be reintroduced into the worklist. Make sure we do not
651 // process a node that has been replaced.
652 removeFromWorkList(N);
654 // Finally, since the node is now dead, remove it from the graph.
658 // If the root changed (e.g. it was a dead load, update the root).
659 DAG.setRoot(Dummy.getValue());
662 SDOperand DAGCombiner::visit(SDNode *N) {
663 switch(N->getOpcode()) {
665 case ISD::TokenFactor: return visitTokenFactor(N);
666 case ISD::ADD: return visitADD(N);
667 case ISD::SUB: return visitSUB(N);
668 case ISD::ADDC: return visitADDC(N);
669 case ISD::ADDE: return visitADDE(N);
670 case ISD::MUL: return visitMUL(N);
671 case ISD::SDIV: return visitSDIV(N);
672 case ISD::UDIV: return visitUDIV(N);
673 case ISD::SREM: return visitSREM(N);
674 case ISD::UREM: return visitUREM(N);
675 case ISD::MULHU: return visitMULHU(N);
676 case ISD::MULHS: return visitMULHS(N);
677 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
678 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
679 case ISD::SDIVREM: return visitSDIVREM(N);
680 case ISD::UDIVREM: return visitUDIVREM(N);
681 case ISD::AND: return visitAND(N);
682 case ISD::OR: return visitOR(N);
683 case ISD::XOR: return visitXOR(N);
684 case ISD::SHL: return visitSHL(N);
685 case ISD::SRA: return visitSRA(N);
686 case ISD::SRL: return visitSRL(N);
687 case ISD::CTLZ: return visitCTLZ(N);
688 case ISD::CTTZ: return visitCTTZ(N);
689 case ISD::CTPOP: return visitCTPOP(N);
690 case ISD::SELECT: return visitSELECT(N);
691 case ISD::SELECT_CC: return visitSELECT_CC(N);
692 case ISD::SETCC: return visitSETCC(N);
693 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
694 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
695 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
696 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
697 case ISD::TRUNCATE: return visitTRUNCATE(N);
698 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
699 case ISD::FADD: return visitFADD(N);
700 case ISD::FSUB: return visitFSUB(N);
701 case ISD::FMUL: return visitFMUL(N);
702 case ISD::FDIV: return visitFDIV(N);
703 case ISD::FREM: return visitFREM(N);
704 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
705 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
706 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
707 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
708 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
709 case ISD::FP_ROUND: return visitFP_ROUND(N);
710 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
711 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
712 case ISD::FNEG: return visitFNEG(N);
713 case ISD::FABS: return visitFABS(N);
714 case ISD::BRCOND: return visitBRCOND(N);
715 case ISD::BR_CC: return visitBR_CC(N);
716 case ISD::LOAD: return visitLOAD(N);
717 case ISD::STORE: return visitSTORE(N);
718 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
719 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
720 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
721 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
722 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
727 SDOperand DAGCombiner::combine(SDNode *N) {
729 SDOperand RV = visit(N);
731 // If nothing happened, try a target-specific DAG combine.
733 assert(N->getOpcode() != ISD::DELETED_NODE &&
734 "Node was deleted but visit returned NULL!");
736 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
737 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
739 // Expose the DAG combiner to the target combiner impls.
740 TargetLowering::DAGCombinerInfo
741 DagCombineInfo(DAG, !AfterLegalize, false, this);
743 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
750 /// getInputChainForNode - Given a node, return its input chain if it has one,
751 /// otherwise return a null sd operand.
752 static SDOperand getInputChainForNode(SDNode *N) {
753 if (unsigned NumOps = N->getNumOperands()) {
754 if (N->getOperand(0).getValueType() == MVT::Other)
755 return N->getOperand(0);
756 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
757 return N->getOperand(NumOps-1);
758 for (unsigned i = 1; i < NumOps-1; ++i)
759 if (N->getOperand(i).getValueType() == MVT::Other)
760 return N->getOperand(i);
762 return SDOperand(0, 0);
765 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
766 // If N has two operands, where one has an input chain equal to the other,
767 // the 'other' chain is redundant.
768 if (N->getNumOperands() == 2) {
769 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
770 return N->getOperand(0);
771 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
772 return N->getOperand(1);
775 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
776 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
777 SmallPtrSet<SDNode*, 16> SeenOps;
778 bool Changed = false; // If we should replace this token factor.
780 // Start out with this token factor.
783 // Iterate through token factors. The TFs grows when new token factors are
785 for (unsigned i = 0; i < TFs.size(); ++i) {
788 // Check each of the operands.
789 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
790 SDOperand Op = TF->getOperand(i);
792 switch (Op.getOpcode()) {
793 case ISD::EntryToken:
794 // Entry tokens don't need to be added to the list. They are
799 case ISD::TokenFactor:
800 if ((CombinerAA || Op.hasOneUse()) &&
801 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
802 // Queue up for processing.
803 TFs.push_back(Op.Val);
804 // Clean up in case the token factor is removed.
805 AddToWorkList(Op.Val);
812 // Only add if it isn't already in the list.
813 if (SeenOps.insert(Op.Val))
824 // If we've change things around then replace token factor.
827 // The entry token is the only possible outcome.
828 Result = DAG.getEntryNode();
830 // New and improved token factor.
831 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
834 // Don't add users to work list.
835 return CombineTo(N, Result, false);
842 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
843 MVT::ValueType VT = N0.getValueType();
844 SDOperand N00 = N0.getOperand(0);
845 SDOperand N01 = N0.getOperand(1);
846 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
847 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
848 isa<ConstantSDNode>(N00.getOperand(1))) {
849 N0 = DAG.getNode(ISD::ADD, VT,
850 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
851 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
852 return DAG.getNode(ISD::ADD, VT, N0, N1);
858 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
860 MVT::ValueType VT = N->getValueType(0);
861 unsigned Opc = N->getOpcode();
862 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
863 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
864 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
865 ISD::CondCode CC = ISD::SETCC_INVALID;
867 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
869 SDOperand CCOp = Slct.getOperand(0);
870 if (CCOp.getOpcode() == ISD::SETCC)
871 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
874 bool DoXform = false;
876 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
878 if (LHS.getOpcode() == ISD::Constant &&
879 cast<ConstantSDNode>(LHS)->isNullValue())
881 else if (CC != ISD::SETCC_INVALID &&
882 RHS.getOpcode() == ISD::Constant &&
883 cast<ConstantSDNode>(RHS)->isNullValue()) {
885 SDOperand Op0 = Slct.getOperand(0);
886 bool isInt = MVT::isInteger(isSlctCC ? Op0.getValueType()
887 : Op0.getOperand(0).getValueType());
888 CC = ISD::getSetCCInverse(CC, isInt);
894 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
896 return DAG.getSelectCC(OtherOp, Result,
897 Slct.getOperand(0), Slct.getOperand(1), CC);
898 SDOperand CCOp = Slct.getOperand(0);
900 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
901 CCOp.getOperand(1), CC);
902 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
907 SDOperand DAGCombiner::visitADD(SDNode *N) {
908 SDOperand N0 = N->getOperand(0);
909 SDOperand N1 = N->getOperand(1);
910 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
911 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
912 MVT::ValueType VT = N0.getValueType();
915 if (MVT::isVector(VT)) {
916 SDOperand FoldedVOp = SimplifyVBinOp(N);
917 if (FoldedVOp.Val) return FoldedVOp;
920 // fold (add x, undef) -> undef
921 if (N0.getOpcode() == ISD::UNDEF)
923 if (N1.getOpcode() == ISD::UNDEF)
925 // fold (add c1, c2) -> c1+c2
927 return DAG.getNode(ISD::ADD, VT, N0, N1);
928 // canonicalize constant to RHS
930 return DAG.getNode(ISD::ADD, VT, N1, N0);
931 // fold (add x, 0) -> x
932 if (N1C && N1C->isNullValue())
934 // fold ((c1-A)+c2) -> (c1+c2)-A
935 if (N1C && N0.getOpcode() == ISD::SUB)
936 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
937 return DAG.getNode(ISD::SUB, VT,
938 DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
941 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
944 // fold ((0-A) + B) -> B-A
945 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
946 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
947 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
948 // fold (A + (0-B)) -> A-B
949 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
950 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
951 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
952 // fold (A+(B-A)) -> B
953 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
954 return N1.getOperand(0);
956 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
957 return SDOperand(N, 0);
959 // fold (a+b) -> (a|b) iff a and b share no bits.
960 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
961 uint64_t LHSZero, LHSOne;
962 uint64_t RHSZero, RHSOne;
963 uint64_t Mask = MVT::getIntVTBitMask(VT);
964 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
966 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
968 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
969 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
970 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
971 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
972 return DAG.getNode(ISD::OR, VT, N0, N1);
976 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
977 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
978 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
979 if (Result.Val) return Result;
981 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
982 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
983 if (Result.Val) return Result;
986 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
987 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
988 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
989 if (Result.Val) return Result;
991 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
992 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
993 if (Result.Val) return Result;
999 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1000 SDOperand N0 = N->getOperand(0);
1001 SDOperand N1 = N->getOperand(1);
1002 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1003 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1004 MVT::ValueType VT = N0.getValueType();
1006 // If the flag result is dead, turn this into an ADD.
1007 if (N->hasNUsesOfValue(0, 1))
1008 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1009 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1011 // canonicalize constant to RHS.
1013 SDOperand Ops[] = { N1, N0 };
1014 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1017 // fold (addc x, 0) -> x + no carry out
1018 if (N1C && N1C->isNullValue())
1019 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1021 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1022 uint64_t LHSZero, LHSOne;
1023 uint64_t RHSZero, RHSOne;
1024 uint64_t Mask = MVT::getIntVTBitMask(VT);
1025 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1027 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1029 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1030 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1031 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1032 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1033 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1034 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1040 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1041 SDOperand N0 = N->getOperand(0);
1042 SDOperand N1 = N->getOperand(1);
1043 SDOperand CarryIn = N->getOperand(2);
1044 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1045 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1046 //MVT::ValueType VT = N0.getValueType();
1048 // canonicalize constant to RHS
1050 SDOperand Ops[] = { N1, N0, CarryIn };
1051 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1054 // fold (adde x, y, false) -> (addc x, y)
1055 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1056 SDOperand Ops[] = { N1, N0 };
1057 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1065 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1066 SDOperand N0 = N->getOperand(0);
1067 SDOperand N1 = N->getOperand(1);
1068 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1070 MVT::ValueType VT = N0.getValueType();
1073 if (MVT::isVector(VT)) {
1074 SDOperand FoldedVOp = SimplifyVBinOp(N);
1075 if (FoldedVOp.Val) return FoldedVOp;
1078 // fold (sub x, x) -> 0
1080 return DAG.getConstant(0, N->getValueType(0));
1081 // fold (sub c1, c2) -> c1-c2
1083 return DAG.getNode(ISD::SUB, VT, N0, N1);
1084 // fold (sub x, c) -> (add x, -c)
1086 return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
1087 // fold (A+B)-A -> B
1088 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1089 return N0.getOperand(1);
1090 // fold (A+B)-B -> A
1091 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1092 return N0.getOperand(0);
1093 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1094 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1095 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1096 if (Result.Val) return Result;
1098 // If either operand of a sub is undef, the result is undef
1099 if (N0.getOpcode() == ISD::UNDEF)
1101 if (N1.getOpcode() == ISD::UNDEF)
1107 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1108 SDOperand N0 = N->getOperand(0);
1109 SDOperand N1 = N->getOperand(1);
1110 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1111 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1112 MVT::ValueType VT = N0.getValueType();
1115 if (MVT::isVector(VT)) {
1116 SDOperand FoldedVOp = SimplifyVBinOp(N);
1117 if (FoldedVOp.Val) return FoldedVOp;
1120 // fold (mul x, undef) -> 0
1121 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1122 return DAG.getConstant(0, VT);
1123 // fold (mul c1, c2) -> c1*c2
1125 return DAG.getNode(ISD::MUL, VT, N0, N1);
1126 // canonicalize constant to RHS
1128 return DAG.getNode(ISD::MUL, VT, N1, N0);
1129 // fold (mul x, 0) -> 0
1130 if (N1C && N1C->isNullValue())
1132 // fold (mul x, -1) -> 0-x
1133 if (N1C && N1C->isAllOnesValue())
1134 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1135 // fold (mul x, (1 << c)) -> x << c
1136 if (N1C && isPowerOf2_64(N1C->getValue()))
1137 return DAG.getNode(ISD::SHL, VT, N0,
1138 DAG.getConstant(Log2_64(N1C->getValue()),
1139 TLI.getShiftAmountTy()));
1140 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1141 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1142 // FIXME: If the input is something that is easily negated (e.g. a
1143 // single-use add), we should put the negate there.
1144 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1145 DAG.getNode(ISD::SHL, VT, N0,
1146 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1147 TLI.getShiftAmountTy())));
1150 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1151 if (N1C && N0.getOpcode() == ISD::SHL &&
1152 isa<ConstantSDNode>(N0.getOperand(1))) {
1153 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1154 AddToWorkList(C3.Val);
1155 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1158 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1161 SDOperand Sh(0,0), Y(0,0);
1162 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1163 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1164 N0.Val->hasOneUse()) {
1166 } else if (N1.getOpcode() == ISD::SHL &&
1167 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1171 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1172 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1175 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1176 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1177 isa<ConstantSDNode>(N0.getOperand(1))) {
1178 return DAG.getNode(ISD::ADD, VT,
1179 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1180 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1184 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1191 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1192 SDOperand N0 = N->getOperand(0);
1193 SDOperand N1 = N->getOperand(1);
1194 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1195 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1196 MVT::ValueType VT = N->getValueType(0);
1199 if (MVT::isVector(VT)) {
1200 SDOperand FoldedVOp = SimplifyVBinOp(N);
1201 if (FoldedVOp.Val) return FoldedVOp;
1204 // fold (sdiv c1, c2) -> c1/c2
1205 if (N0C && N1C && !N1C->isNullValue())
1206 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1207 // fold (sdiv X, 1) -> X
1208 if (N1C && N1C->getSignExtended() == 1LL)
1210 // fold (sdiv X, -1) -> 0-X
1211 if (N1C && N1C->isAllOnesValue())
1212 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1213 // If we know the sign bits of both operands are zero, strength reduce to a
1214 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1215 if (!MVT::isVector(VT)) {
1216 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1217 if (DAG.MaskedValueIsZero(N1, SignBit) &&
1218 DAG.MaskedValueIsZero(N0, SignBit))
1219 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1221 // fold (sdiv X, pow2) -> simple ops after legalize
1222 if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1223 (isPowerOf2_64(N1C->getSignExtended()) ||
1224 isPowerOf2_64(-N1C->getSignExtended()))) {
1225 // If dividing by powers of two is cheap, then don't perform the following
1227 if (TLI.isPow2DivCheap())
1229 int64_t pow2 = N1C->getSignExtended();
1230 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1231 unsigned lg2 = Log2_64(abs2);
1232 // Splat the sign bit into the register
1233 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1234 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1235 TLI.getShiftAmountTy()));
1236 AddToWorkList(SGN.Val);
1237 // Add (N0 < 0) ? abs2 - 1 : 0;
1238 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1239 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1240 TLI.getShiftAmountTy()));
1241 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1242 AddToWorkList(SRL.Val);
1243 AddToWorkList(ADD.Val); // Divide by pow2
1244 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1245 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1246 // If we're dividing by a positive value, we're done. Otherwise, we must
1247 // negate the result.
1250 AddToWorkList(SRA.Val);
1251 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1253 // if integer divide is expensive and we satisfy the requirements, emit an
1254 // alternate sequence.
1255 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1256 !TLI.isIntDivCheap()) {
1257 SDOperand Op = BuildSDIV(N);
1258 if (Op.Val) return Op;
1262 if (N0.getOpcode() == ISD::UNDEF)
1263 return DAG.getConstant(0, VT);
1264 // X / undef -> undef
1265 if (N1.getOpcode() == ISD::UNDEF)
1271 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1272 SDOperand N0 = N->getOperand(0);
1273 SDOperand N1 = N->getOperand(1);
1274 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1275 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1276 MVT::ValueType VT = N->getValueType(0);
1279 if (MVT::isVector(VT)) {
1280 SDOperand FoldedVOp = SimplifyVBinOp(N);
1281 if (FoldedVOp.Val) return FoldedVOp;
1284 // fold (udiv c1, c2) -> c1/c2
1285 if (N0C && N1C && !N1C->isNullValue())
1286 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1287 // fold (udiv x, (1 << c)) -> x >>u c
1288 if (N1C && isPowerOf2_64(N1C->getValue()))
1289 return DAG.getNode(ISD::SRL, VT, N0,
1290 DAG.getConstant(Log2_64(N1C->getValue()),
1291 TLI.getShiftAmountTy()));
1292 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1293 if (N1.getOpcode() == ISD::SHL) {
1294 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1295 if (isPowerOf2_64(SHC->getValue())) {
1296 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1297 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1298 DAG.getConstant(Log2_64(SHC->getValue()),
1300 AddToWorkList(Add.Val);
1301 return DAG.getNode(ISD::SRL, VT, N0, Add);
1305 // fold (udiv x, c) -> alternate
1306 if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1307 SDOperand Op = BuildUDIV(N);
1308 if (Op.Val) return Op;
1312 if (N0.getOpcode() == ISD::UNDEF)
1313 return DAG.getConstant(0, VT);
1314 // X / undef -> undef
1315 if (N1.getOpcode() == ISD::UNDEF)
1321 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1322 SDOperand N0 = N->getOperand(0);
1323 SDOperand N1 = N->getOperand(1);
1324 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1326 MVT::ValueType VT = N->getValueType(0);
1328 // fold (srem c1, c2) -> c1%c2
1329 if (N0C && N1C && !N1C->isNullValue())
1330 return DAG.getNode(ISD::SREM, VT, N0, N1);
1331 // If we know the sign bits of both operands are zero, strength reduce to a
1332 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1333 if (!MVT::isVector(VT)) {
1334 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1335 if (DAG.MaskedValueIsZero(N1, SignBit) &&
1336 DAG.MaskedValueIsZero(N0, SignBit))
1337 return DAG.getNode(ISD::UREM, VT, N0, N1);
1340 // If X/C can be simplified by the division-by-constant logic, lower
1341 // X%C to the equivalent of X-X/C*C.
1342 if (N1C && !N1C->isNullValue()) {
1343 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1344 AddToWorkList(Div.Val);
1345 SDOperand OptimizedDiv = combine(Div.Val);
1346 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1347 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1348 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1349 AddToWorkList(Mul.Val);
1355 if (N0.getOpcode() == ISD::UNDEF)
1356 return DAG.getConstant(0, VT);
1357 // X % undef -> undef
1358 if (N1.getOpcode() == ISD::UNDEF)
1364 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1365 SDOperand N0 = N->getOperand(0);
1366 SDOperand N1 = N->getOperand(1);
1367 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1368 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1369 MVT::ValueType VT = N->getValueType(0);
1371 // fold (urem c1, c2) -> c1%c2
1372 if (N0C && N1C && !N1C->isNullValue())
1373 return DAG.getNode(ISD::UREM, VT, N0, N1);
1374 // fold (urem x, pow2) -> (and x, pow2-1)
1375 if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1376 return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1377 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1378 if (N1.getOpcode() == ISD::SHL) {
1379 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1380 if (isPowerOf2_64(SHC->getValue())) {
1381 SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1382 AddToWorkList(Add.Val);
1383 return DAG.getNode(ISD::AND, VT, N0, Add);
1388 // If X/C can be simplified by the division-by-constant logic, lower
1389 // X%C to the equivalent of X-X/C*C.
1390 if (N1C && !N1C->isNullValue()) {
1391 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1392 SDOperand OptimizedDiv = combine(Div.Val);
1393 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1394 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1395 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1396 AddToWorkList(Mul.Val);
1402 if (N0.getOpcode() == ISD::UNDEF)
1403 return DAG.getConstant(0, VT);
1404 // X % undef -> undef
1405 if (N1.getOpcode() == ISD::UNDEF)
1411 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1412 SDOperand N0 = N->getOperand(0);
1413 SDOperand N1 = N->getOperand(1);
1414 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1415 MVT::ValueType VT = N->getValueType(0);
1417 // fold (mulhs x, 0) -> 0
1418 if (N1C && N1C->isNullValue())
1420 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1421 if (N1C && N1C->getValue() == 1)
1422 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1423 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1424 TLI.getShiftAmountTy()));
1425 // fold (mulhs x, undef) -> 0
1426 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1427 return DAG.getConstant(0, VT);
1432 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1433 SDOperand N0 = N->getOperand(0);
1434 SDOperand N1 = N->getOperand(1);
1435 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1436 MVT::ValueType VT = N->getValueType(0);
1438 // fold (mulhu x, 0) -> 0
1439 if (N1C && N1C->isNullValue())
1441 // fold (mulhu x, 1) -> 0
1442 if (N1C && N1C->getValue() == 1)
1443 return DAG.getConstant(0, N0.getValueType());
1444 // fold (mulhu x, undef) -> 0
1445 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1446 return DAG.getConstant(0, VT);
1451 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1452 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1453 /// that are being performed. Return true if a simplification was made.
1455 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1457 // If the high half is not needed, just compute the low half.
1458 bool HiExists = N->hasAnyUseOfValue(1);
1461 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1462 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1463 N->getNumOperands());
1464 return CombineTo(N, Res, Res);
1467 // If the low half is not needed, just compute the high half.
1468 bool LoExists = N->hasAnyUseOfValue(0);
1471 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1472 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1473 N->getNumOperands());
1474 return CombineTo(N, Res, Res);
1477 // If both halves are used, return as it is.
1478 if (LoExists && HiExists)
1481 // If the two computed results can be simplified separately, separate them.
1483 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1484 N->op_begin(), N->getNumOperands());
1485 AddToWorkList(Lo.Val);
1486 SDOperand LoOpt = combine(Lo.Val);
1487 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1488 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))
1489 return CombineTo(N, LoOpt, LoOpt);
1493 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1494 N->op_begin(), N->getNumOperands());
1495 AddToWorkList(Hi.Val);
1496 SDOperand HiOpt = combine(Hi.Val);
1497 if (HiOpt.Val && HiOpt != Hi &&
1498 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))
1499 return CombineTo(N, HiOpt, HiOpt);
1504 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1505 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1506 if (Res.Val) return Res;
1511 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1512 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1513 if (Res.Val) return Res;
1518 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1519 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1520 if (Res.Val) return Res;
1525 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1526 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1527 if (Res.Val) return Res;
1532 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1533 /// two operands of the same opcode, try to simplify it.
1534 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1535 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1536 MVT::ValueType VT = N0.getValueType();
1537 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1539 // For each of OP in AND/OR/XOR:
1540 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1541 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1542 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1543 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1544 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1545 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1546 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1547 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1548 N0.getOperand(0).getValueType(),
1549 N0.getOperand(0), N1.getOperand(0));
1550 AddToWorkList(ORNode.Val);
1551 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1554 // For each of OP in SHL/SRL/SRA/AND...
1555 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1556 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1557 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1558 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1559 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1560 N0.getOperand(1) == N1.getOperand(1)) {
1561 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1562 N0.getOperand(0).getValueType(),
1563 N0.getOperand(0), N1.getOperand(0));
1564 AddToWorkList(ORNode.Val);
1565 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1571 SDOperand DAGCombiner::visitAND(SDNode *N) {
1572 SDOperand N0 = N->getOperand(0);
1573 SDOperand N1 = N->getOperand(1);
1574 SDOperand LL, LR, RL, RR, CC0, CC1;
1575 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1576 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1577 MVT::ValueType VT = N1.getValueType();
1580 if (MVT::isVector(VT)) {
1581 SDOperand FoldedVOp = SimplifyVBinOp(N);
1582 if (FoldedVOp.Val) return FoldedVOp;
1585 // fold (and x, undef) -> 0
1586 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1587 return DAG.getConstant(0, VT);
1588 // fold (and c1, c2) -> c1&c2
1590 return DAG.getNode(ISD::AND, VT, N0, N1);
1591 // canonicalize constant to RHS
1593 return DAG.getNode(ISD::AND, VT, N1, N0);
1594 // fold (and x, -1) -> x
1595 if (N1C && N1C->isAllOnesValue())
1597 // if (and x, c) is known to be zero, return 0
1598 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1599 return DAG.getConstant(0, VT);
1601 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1604 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1605 if (N1C && N0.getOpcode() == ISD::OR)
1606 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1607 if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1609 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1610 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1611 unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1612 if (DAG.MaskedValueIsZero(N0.getOperand(0),
1613 ~N1C->getValue() & InMask)) {
1614 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1617 // Replace uses of the AND with uses of the Zero extend node.
1620 // We actually want to replace all uses of the any_extend with the
1621 // zero_extend, to avoid duplicating things. This will later cause this
1622 // AND to be folded.
1623 CombineTo(N0.Val, Zext);
1624 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1627 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1628 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1629 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1630 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1632 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1633 MVT::isInteger(LL.getValueType())) {
1634 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1635 if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1636 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1637 AddToWorkList(ORNode.Val);
1638 return DAG.getSetCC(VT, ORNode, LR, Op1);
1640 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1641 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1642 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1643 AddToWorkList(ANDNode.Val);
1644 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1646 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1647 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1648 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1649 AddToWorkList(ORNode.Val);
1650 return DAG.getSetCC(VT, ORNode, LR, Op1);
1653 // canonicalize equivalent to ll == rl
1654 if (LL == RR && LR == RL) {
1655 Op1 = ISD::getSetCCSwappedOperands(Op1);
1658 if (LL == RL && LR == RR) {
1659 bool isInteger = MVT::isInteger(LL.getValueType());
1660 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1661 if (Result != ISD::SETCC_INVALID)
1662 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1666 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1667 if (N0.getOpcode() == N1.getOpcode()) {
1668 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1669 if (Tmp.Val) return Tmp;
1672 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1673 // fold (and (sra)) -> (and (srl)) when possible.
1674 if (!MVT::isVector(VT) &&
1675 SimplifyDemandedBits(SDOperand(N, 0)))
1676 return SDOperand(N, 0);
1677 // fold (zext_inreg (extload x)) -> (zextload x)
1678 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1679 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1680 MVT::ValueType EVT = LN0->getMemoryVT();
1681 // If we zero all the possible extended bits, then we can turn this into
1682 // a zextload if we are running before legalize or the operation is legal.
1683 if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1684 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1685 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1686 LN0->getBasePtr(), LN0->getSrcValue(),
1687 LN0->getSrcValueOffset(), EVT,
1689 LN0->getAlignment());
1691 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1692 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1695 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1696 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1698 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1699 MVT::ValueType EVT = LN0->getMemoryVT();
1700 // If we zero all the possible extended bits, then we can turn this into
1701 // a zextload if we are running before legalize or the operation is legal.
1702 if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1703 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1704 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1705 LN0->getBasePtr(), LN0->getSrcValue(),
1706 LN0->getSrcValueOffset(), EVT,
1708 LN0->getAlignment());
1710 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1711 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1715 // fold (and (load x), 255) -> (zextload x, i8)
1716 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1717 if (N1C && N0.getOpcode() == ISD::LOAD) {
1718 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1719 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1720 LN0->isUnindexed() && N0.hasOneUse()) {
1721 MVT::ValueType EVT, LoadedVT;
1722 if (N1C->getValue() == 255)
1724 else if (N1C->getValue() == 65535)
1726 else if (N1C->getValue() == ~0U)
1731 LoadedVT = LN0->getMemoryVT();
1732 if (EVT != MVT::Other && LoadedVT > EVT &&
1733 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1734 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1735 // For big endian targets, we need to add an offset to the pointer to
1736 // load the correct bytes. For little endian systems, we merely need to
1737 // read fewer bytes from the same pointer.
1738 unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
1739 unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
1740 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1741 unsigned Alignment = LN0->getAlignment();
1742 SDOperand NewPtr = LN0->getBasePtr();
1743 if (!TLI.isLittleEndian()) {
1744 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1745 DAG.getConstant(PtrOff, PtrType));
1746 Alignment = MinAlign(Alignment, PtrOff);
1748 AddToWorkList(NewPtr.Val);
1750 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1751 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1752 LN0->isVolatile(), Alignment);
1754 CombineTo(N0.Val, Load, Load.getValue(1));
1755 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1763 SDOperand DAGCombiner::visitOR(SDNode *N) {
1764 SDOperand N0 = N->getOperand(0);
1765 SDOperand N1 = N->getOperand(1);
1766 SDOperand LL, LR, RL, RR, CC0, CC1;
1767 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1768 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1769 MVT::ValueType VT = N1.getValueType();
1770 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1773 if (MVT::isVector(VT)) {
1774 SDOperand FoldedVOp = SimplifyVBinOp(N);
1775 if (FoldedVOp.Val) return FoldedVOp;
1778 // fold (or x, undef) -> -1
1779 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1780 return DAG.getConstant(~0ULL, VT);
1781 // fold (or c1, c2) -> c1|c2
1783 return DAG.getNode(ISD::OR, VT, N0, N1);
1784 // canonicalize constant to RHS
1786 return DAG.getNode(ISD::OR, VT, N1, N0);
1787 // fold (or x, 0) -> x
1788 if (N1C && N1C->isNullValue())
1790 // fold (or x, -1) -> -1
1791 if (N1C && N1C->isAllOnesValue())
1793 // fold (or x, c) -> c iff (x & ~c) == 0
1795 DAG.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1798 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1801 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1802 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1803 isa<ConstantSDNode>(N0.getOperand(1))) {
1804 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1805 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1807 DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1809 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1810 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1811 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1812 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1814 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1815 MVT::isInteger(LL.getValueType())) {
1816 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1817 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1818 if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1819 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1820 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1821 AddToWorkList(ORNode.Val);
1822 return DAG.getSetCC(VT, ORNode, LR, Op1);
1824 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1825 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1826 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1827 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1828 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1829 AddToWorkList(ANDNode.Val);
1830 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1833 // canonicalize equivalent to ll == rl
1834 if (LL == RR && LR == RL) {
1835 Op1 = ISD::getSetCCSwappedOperands(Op1);
1838 if (LL == RL && LR == RR) {
1839 bool isInteger = MVT::isInteger(LL.getValueType());
1840 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1841 if (Result != ISD::SETCC_INVALID)
1842 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1846 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1847 if (N0.getOpcode() == N1.getOpcode()) {
1848 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1849 if (Tmp.Val) return Tmp;
1852 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1853 if (N0.getOpcode() == ISD::AND &&
1854 N1.getOpcode() == ISD::AND &&
1855 N0.getOperand(1).getOpcode() == ISD::Constant &&
1856 N1.getOperand(1).getOpcode() == ISD::Constant &&
1857 // Don't increase # computations.
1858 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1859 // We can only do this xform if we know that bits from X that are set in C2
1860 // but not in C1 are already zero. Likewise for Y.
1861 uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1862 uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1864 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1865 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1866 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1867 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1872 // See if this is some rotate idiom.
1873 if (SDNode *Rot = MatchRotate(N0, N1))
1874 return SDOperand(Rot, 0);
1880 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1881 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1882 if (Op.getOpcode() == ISD::AND) {
1883 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1884 Mask = Op.getOperand(1);
1885 Op = Op.getOperand(0);
1891 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1899 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1900 // idioms for rotate, and if the target supports rotation instructions, generate
1902 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1903 // Must be a legal type. Expanded an promoted things won't work with rotates.
1904 MVT::ValueType VT = LHS.getValueType();
1905 if (!TLI.isTypeLegal(VT)) return 0;
1907 // The target must have at least one rotate flavor.
1908 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1909 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1910 if (!HasROTL && !HasROTR) return 0;
1912 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1913 SDOperand LHSShift; // The shift.
1914 SDOperand LHSMask; // AND value if any.
1915 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1916 return 0; // Not part of a rotate.
1918 SDOperand RHSShift; // The shift.
1919 SDOperand RHSMask; // AND value if any.
1920 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1921 return 0; // Not part of a rotate.
1923 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1924 return 0; // Not shifting the same value.
1926 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1927 return 0; // Shifts must disagree.
1929 // Canonicalize shl to left side in a shl/srl pair.
1930 if (RHSShift.getOpcode() == ISD::SHL) {
1931 std::swap(LHS, RHS);
1932 std::swap(LHSShift, RHSShift);
1933 std::swap(LHSMask , RHSMask );
1936 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1937 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1938 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1939 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1941 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1942 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1943 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1944 RHSShiftAmt.getOpcode() == ISD::Constant) {
1945 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1946 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1947 if ((LShVal + RShVal) != OpSizeInBits)
1952 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1954 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1956 // If there is an AND of either shifted operand, apply it to the result.
1957 if (LHSMask.Val || RHSMask.Val) {
1958 uint64_t Mask = MVT::getIntVTBitMask(VT);
1961 uint64_t RHSBits = (1ULL << LShVal)-1;
1962 Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1965 uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1966 Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1969 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1975 // If there is a mask here, and we have a variable shift, we can't be sure
1976 // that we're masking out the right stuff.
1977 if (LHSMask.Val || RHSMask.Val)
1980 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1981 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1982 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
1983 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
1984 if (ConstantSDNode *SUBC =
1985 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
1986 if (SUBC->getValue() == OpSizeInBits)
1988 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1990 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1994 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1995 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1996 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
1997 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
1998 if (ConstantSDNode *SUBC =
1999 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2000 if (SUBC->getValue() == OpSizeInBits)
2002 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2004 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2008 // Look for sign/zext/any-extended cases:
2009 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2010 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2011 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2012 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2013 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2014 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2015 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2016 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2017 if (RExtOp0.getOpcode() == ISD::SUB &&
2018 RExtOp0.getOperand(1) == LExtOp0) {
2019 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2021 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2022 // (rotl x, (sub 32, y))
2023 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2024 if (SUBC->getValue() == OpSizeInBits) {
2026 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2028 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2031 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2032 RExtOp0 == LExtOp0.getOperand(1)) {
2033 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2035 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2036 // (rotr x, (sub 32, y))
2037 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2038 if (SUBC->getValue() == OpSizeInBits) {
2040 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2042 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2052 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2053 SDOperand N0 = N->getOperand(0);
2054 SDOperand N1 = N->getOperand(1);
2055 SDOperand LHS, RHS, CC;
2056 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2057 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2058 MVT::ValueType VT = N0.getValueType();
2061 if (MVT::isVector(VT)) {
2062 SDOperand FoldedVOp = SimplifyVBinOp(N);
2063 if (FoldedVOp.Val) return FoldedVOp;
2066 // fold (xor x, undef) -> undef
2067 if (N0.getOpcode() == ISD::UNDEF)
2069 if (N1.getOpcode() == ISD::UNDEF)
2071 // fold (xor c1, c2) -> c1^c2
2073 return DAG.getNode(ISD::XOR, VT, N0, N1);
2074 // canonicalize constant to RHS
2076 return DAG.getNode(ISD::XOR, VT, N1, N0);
2077 // fold (xor x, 0) -> x
2078 if (N1C && N1C->isNullValue())
2081 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2084 // fold !(x cc y) -> (x !cc y)
2085 if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2086 bool isInt = MVT::isInteger(LHS.getValueType());
2087 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2089 if (N0.getOpcode() == ISD::SETCC)
2090 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2091 if (N0.getOpcode() == ISD::SELECT_CC)
2092 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2093 assert(0 && "Unhandled SetCC Equivalent!");
2096 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2097 if (N1C && N1C->getValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2098 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2099 SDOperand V = N0.getOperand(0);
2100 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2101 DAG.getConstant(1, V.getValueType()));
2102 AddToWorkList(V.Val);
2103 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2106 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2107 if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
2108 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2109 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2110 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2111 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2112 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2113 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2114 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2115 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2118 // fold !(x or y) -> (!x and !y) iff x or y are constants
2119 if (N1C && N1C->isAllOnesValue() &&
2120 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2121 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2122 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2123 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2124 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2125 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2126 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2127 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2130 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2131 if (N1C && N0.getOpcode() == ISD::XOR) {
2132 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2133 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2135 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2136 DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
2138 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2139 DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
2141 // fold (xor x, x) -> 0
2143 if (!MVT::isVector(VT)) {
2144 return DAG.getConstant(0, VT);
2145 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2146 // Produce a vector of zeros.
2147 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
2148 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
2149 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2153 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2154 if (N0.getOpcode() == N1.getOpcode()) {
2155 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2156 if (Tmp.Val) return Tmp;
2159 // Simplify the expression using non-local knowledge.
2160 if (!MVT::isVector(VT) &&
2161 SimplifyDemandedBits(SDOperand(N, 0)))
2162 return SDOperand(N, 0);
2167 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2168 /// the shift amount is a constant.
2169 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2170 SDNode *LHS = N->getOperand(0).Val;
2171 if (!LHS->hasOneUse()) return SDOperand();
2173 // We want to pull some binops through shifts, so that we have (and (shift))
2174 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2175 // thing happens with address calculations, so it's important to canonicalize
2177 bool HighBitSet = false; // Can we transform this if the high bit is set?
2179 switch (LHS->getOpcode()) {
2180 default: return SDOperand();
2183 HighBitSet = false; // We can only transform sra if the high bit is clear.
2186 HighBitSet = true; // We can only transform sra if the high bit is set.
2189 if (N->getOpcode() != ISD::SHL)
2190 return SDOperand(); // only shl(add) not sr[al](add).
2191 HighBitSet = false; // We can only transform sra if the high bit is clear.
2195 // We require the RHS of the binop to be a constant as well.
2196 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2197 if (!BinOpCst) return SDOperand();
2200 // FIXME: disable this for unless the input to the binop is a shift by a
2201 // constant. If it is not a shift, it pessimizes some common cases like:
2203 //void foo(int *X, int i) { X[i & 1235] = 1; }
2204 //int bar(int *X, int i) { return X[i & 255]; }
2205 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2206 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2207 BinOpLHSVal->getOpcode() != ISD::SRA &&
2208 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2209 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2212 MVT::ValueType VT = N->getValueType(0);
2214 // If this is a signed shift right, and the high bit is modified
2215 // by the logical operation, do not perform the transformation.
2216 // The highBitSet boolean indicates the value of the high bit of
2217 // the constant which would cause it to be modified for this
2219 if (N->getOpcode() == ISD::SRA) {
2220 uint64_t BinOpRHSSign = BinOpCst->getValue() >> MVT::getSizeInBits(VT)-1;
2221 if ((bool)BinOpRHSSign != HighBitSet)
2225 // Fold the constants, shifting the binop RHS by the shift amount.
2226 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2227 LHS->getOperand(1), N->getOperand(1));
2229 // Create the new shift.
2230 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2233 // Create the new binop.
2234 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2238 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2239 SDOperand N0 = N->getOperand(0);
2240 SDOperand N1 = N->getOperand(1);
2241 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2242 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2243 MVT::ValueType VT = N0.getValueType();
2244 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2246 // fold (shl c1, c2) -> c1<<c2
2248 return DAG.getNode(ISD::SHL, VT, N0, N1);
2249 // fold (shl 0, x) -> 0
2250 if (N0C && N0C->isNullValue())
2252 // fold (shl x, c >= size(x)) -> undef
2253 if (N1C && N1C->getValue() >= OpSizeInBits)
2254 return DAG.getNode(ISD::UNDEF, VT);
2255 // fold (shl x, 0) -> x
2256 if (N1C && N1C->isNullValue())
2258 // if (shl x, c) is known to be zero, return 0
2259 if (DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
2260 return DAG.getConstant(0, VT);
2261 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2262 return SDOperand(N, 0);
2263 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2264 if (N1C && N0.getOpcode() == ISD::SHL &&
2265 N0.getOperand(1).getOpcode() == ISD::Constant) {
2266 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2267 uint64_t c2 = N1C->getValue();
2268 if (c1 + c2 > OpSizeInBits)
2269 return DAG.getConstant(0, VT);
2270 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2271 DAG.getConstant(c1 + c2, N1.getValueType()));
2273 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2274 // (srl (and x, -1 << c1), c1-c2)
2275 if (N1C && N0.getOpcode() == ISD::SRL &&
2276 N0.getOperand(1).getOpcode() == ISD::Constant) {
2277 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2278 uint64_t c2 = N1C->getValue();
2279 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2280 DAG.getConstant(~0ULL << c1, VT));
2282 return DAG.getNode(ISD::SHL, VT, Mask,
2283 DAG.getConstant(c2-c1, N1.getValueType()));
2285 return DAG.getNode(ISD::SRL, VT, Mask,
2286 DAG.getConstant(c1-c2, N1.getValueType()));
2288 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2289 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2290 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2291 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2293 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2296 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2297 SDOperand N0 = N->getOperand(0);
2298 SDOperand N1 = N->getOperand(1);
2299 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2300 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2301 MVT::ValueType VT = N0.getValueType();
2303 // fold (sra c1, c2) -> c1>>c2
2305 return DAG.getNode(ISD::SRA, VT, N0, N1);
2306 // fold (sra 0, x) -> 0
2307 if (N0C && N0C->isNullValue())
2309 // fold (sra -1, x) -> -1
2310 if (N0C && N0C->isAllOnesValue())
2312 // fold (sra x, c >= size(x)) -> undef
2313 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2314 return DAG.getNode(ISD::UNDEF, VT);
2315 // fold (sra x, 0) -> x
2316 if (N1C && N1C->isNullValue())
2318 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2320 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2321 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2324 default: EVT = MVT::Other; break;
2325 case 1: EVT = MVT::i1; break;
2326 case 8: EVT = MVT::i8; break;
2327 case 16: EVT = MVT::i16; break;
2328 case 32: EVT = MVT::i32; break;
2330 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2331 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2332 DAG.getValueType(EVT));
2335 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2336 if (N1C && N0.getOpcode() == ISD::SRA) {
2337 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2338 unsigned Sum = N1C->getValue() + C1->getValue();
2339 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2340 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2341 DAG.getConstant(Sum, N1C->getValueType(0)));
2345 // Simplify, based on bits shifted out of the LHS.
2346 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2347 return SDOperand(N, 0);
2350 // If the sign bit is known to be zero, switch this to a SRL.
2351 if (DAG.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
2352 return DAG.getNode(ISD::SRL, VT, N0, N1);
2354 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2357 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2358 SDOperand N0 = N->getOperand(0);
2359 SDOperand N1 = N->getOperand(1);
2360 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2361 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2362 MVT::ValueType VT = N0.getValueType();
2363 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2365 // fold (srl c1, c2) -> c1 >>u c2
2367 return DAG.getNode(ISD::SRL, VT, N0, N1);
2368 // fold (srl 0, x) -> 0
2369 if (N0C && N0C->isNullValue())
2371 // fold (srl x, c >= size(x)) -> undef
2372 if (N1C && N1C->getValue() >= OpSizeInBits)
2373 return DAG.getNode(ISD::UNDEF, VT);
2374 // fold (srl x, 0) -> x
2375 if (N1C && N1C->isNullValue())
2377 // if (srl x, c) is known to be zero, return 0
2378 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
2379 return DAG.getConstant(0, VT);
2381 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2382 if (N1C && N0.getOpcode() == ISD::SRL &&
2383 N0.getOperand(1).getOpcode() == ISD::Constant) {
2384 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2385 uint64_t c2 = N1C->getValue();
2386 if (c1 + c2 > OpSizeInBits)
2387 return DAG.getConstant(0, VT);
2388 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2389 DAG.getConstant(c1 + c2, N1.getValueType()));
2392 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2393 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2394 // Shifting in all undef bits?
2395 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2396 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2397 return DAG.getNode(ISD::UNDEF, VT);
2399 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2400 AddToWorkList(SmallShift.Val);
2401 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2404 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2405 // bit, which is unmodified by sra.
2406 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2407 if (N0.getOpcode() == ISD::SRA)
2408 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2411 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2412 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2413 N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
2414 uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
2415 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2417 // If any of the input bits are KnownOne, then the input couldn't be all
2418 // zeros, thus the result of the srl will always be zero.
2419 if (KnownOne) return DAG.getConstant(0, VT);
2421 // If all of the bits input the to ctlz node are known to be zero, then
2422 // the result of the ctlz is "32" and the result of the shift is one.
2423 uint64_t UnknownBits = ~KnownZero & Mask;
2424 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2426 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2427 if ((UnknownBits & (UnknownBits-1)) == 0) {
2428 // Okay, we know that only that the single bit specified by UnknownBits
2429 // could be set on input to the CTLZ node. If this bit is set, the SRL
2430 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2431 // to an SRL,XOR pair, which is likely to simplify more.
2432 unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
2433 SDOperand Op = N0.getOperand(0);
2435 Op = DAG.getNode(ISD::SRL, VT, Op,
2436 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2437 AddToWorkList(Op.Val);
2439 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2443 // fold operands of srl based on knowledge that the low bits are not
2445 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2446 return SDOperand(N, 0);
2448 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2451 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2452 SDOperand N0 = N->getOperand(0);
2453 MVT::ValueType VT = N->getValueType(0);
2455 // fold (ctlz c1) -> c2
2456 if (isa<ConstantSDNode>(N0))
2457 return DAG.getNode(ISD::CTLZ, VT, N0);
2461 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2462 SDOperand N0 = N->getOperand(0);
2463 MVT::ValueType VT = N->getValueType(0);
2465 // fold (cttz c1) -> c2
2466 if (isa<ConstantSDNode>(N0))
2467 return DAG.getNode(ISD::CTTZ, VT, N0);
2471 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2472 SDOperand N0 = N->getOperand(0);
2473 MVT::ValueType VT = N->getValueType(0);
2475 // fold (ctpop c1) -> c2
2476 if (isa<ConstantSDNode>(N0))
2477 return DAG.getNode(ISD::CTPOP, VT, N0);
2481 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2482 SDOperand N0 = N->getOperand(0);
2483 SDOperand N1 = N->getOperand(1);
2484 SDOperand N2 = N->getOperand(2);
2485 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2486 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2487 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2488 MVT::ValueType VT = N->getValueType(0);
2489 MVT::ValueType VT0 = N0.getValueType();
2491 // fold select C, X, X -> X
2494 // fold select true, X, Y -> X
2495 if (N0C && !N0C->isNullValue())
2497 // fold select false, X, Y -> Y
2498 if (N0C && N0C->isNullValue())
2500 // fold select C, 1, X -> C | X
2501 if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2502 return DAG.getNode(ISD::OR, VT, N0, N2);
2503 // fold select C, 0, 1 -> ~C
2504 if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
2505 N1C && N2C && N1C->isNullValue() && N2C->getValue() == 1) {
2506 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2509 AddToWorkList(XORNode.Val);
2510 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2511 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2512 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2514 // fold select C, 0, X -> ~C & X
2515 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2516 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2517 AddToWorkList(XORNode.Val);
2518 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2520 // fold select C, X, 1 -> ~C | X
2521 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getValue() == 1) {
2522 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2523 AddToWorkList(XORNode.Val);
2524 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2526 // fold select C, X, 0 -> C & X
2527 // FIXME: this should check for C type == X type, not i1?
2528 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2529 return DAG.getNode(ISD::AND, VT, N0, N1);
2530 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2531 if (MVT::i1 == VT && N0 == N1)
2532 return DAG.getNode(ISD::OR, VT, N0, N2);
2533 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2534 if (MVT::i1 == VT && N0 == N2)
2535 return DAG.getNode(ISD::AND, VT, N0, N1);
2537 // If we can fold this based on the true/false value, do so.
2538 if (SimplifySelectOps(N, N1, N2))
2539 return SDOperand(N, 0); // Don't revisit N.
2541 // fold selects based on a setcc into other things, such as min/max/abs
2542 if (N0.getOpcode() == ISD::SETCC)
2544 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2545 // having to say they don't support SELECT_CC on every type the DAG knows
2546 // about, since there is no way to mark an opcode illegal at all value types
2547 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2548 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2549 N1, N2, N0.getOperand(2));
2551 return SimplifySelect(N0, N1, N2);
2555 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2556 SDOperand N0 = N->getOperand(0);
2557 SDOperand N1 = N->getOperand(1);
2558 SDOperand N2 = N->getOperand(2);
2559 SDOperand N3 = N->getOperand(3);
2560 SDOperand N4 = N->getOperand(4);
2561 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2563 // fold select_cc lhs, rhs, x, x, cc -> x
2567 // Determine if the condition we're dealing with is constant
2568 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2569 if (SCC.Val) AddToWorkList(SCC.Val);
2571 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2572 if (SCCC->getValue())
2573 return N2; // cond always true -> true val
2575 return N3; // cond always false -> false val
2578 // Fold to a simpler select_cc
2579 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2580 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2581 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2584 // If we can fold this based on the true/false value, do so.
2585 if (SimplifySelectOps(N, N2, N3))
2586 return SDOperand(N, 0); // Don't revisit N.
2588 // fold select_cc into other things, such as min/max/abs
2589 return SimplifySelectCC(N0, N1, N2, N3, CC);
2592 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2593 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2594 cast<CondCodeSDNode>(N->getOperand(2))->get());
2597 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2598 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2599 // transformation. Returns true if extension are possible and the above
2600 // mentioned transformation is profitable.
2601 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2603 SmallVector<SDNode*, 4> &ExtendNodes,
2604 TargetLowering &TLI) {
2605 bool HasCopyToRegUses = false;
2606 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2607 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2612 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2613 if (User->getOpcode() == ISD::SETCC) {
2614 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2615 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2616 // Sign bits will be lost after a zext.
2619 for (unsigned i = 0; i != 2; ++i) {
2620 SDOperand UseOp = User->getOperand(i);
2623 if (!isa<ConstantSDNode>(UseOp))
2628 ExtendNodes.push_back(User);
2630 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2631 SDOperand UseOp = User->getOperand(i);
2633 // If truncate from extended type to original load type is free
2634 // on this target, then it's ok to extend a CopyToReg.
2635 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2636 HasCopyToRegUses = true;
2644 if (HasCopyToRegUses) {
2645 bool BothLiveOut = false;
2646 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2649 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2650 SDOperand UseOp = User->getOperand(i);
2651 if (UseOp.Val == N && UseOp.ResNo == 0) {
2658 // Both unextended and extended values are live out. There had better be
2659 // good a reason for the transformation.
2660 return ExtendNodes.size();
2665 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2666 SDOperand N0 = N->getOperand(0);
2667 MVT::ValueType VT = N->getValueType(0);
2669 // fold (sext c1) -> c1
2670 if (isa<ConstantSDNode>(N0))
2671 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2673 // fold (sext (sext x)) -> (sext x)
2674 // fold (sext (aext x)) -> (sext x)
2675 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2676 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2678 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2679 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2680 if (N0.getOpcode() == ISD::TRUNCATE) {
2681 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2682 if (NarrowLoad.Val) {
2683 if (NarrowLoad.Val != N0.Val)
2684 CombineTo(N0.Val, NarrowLoad);
2685 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2689 // See if the value being truncated is already sign extended. If so, just
2690 // eliminate the trunc/sext pair.
2691 if (N0.getOpcode() == ISD::TRUNCATE) {
2692 SDOperand Op = N0.getOperand(0);
2693 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2694 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2695 unsigned DestBits = MVT::getSizeInBits(VT);
2696 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2698 if (OpBits == DestBits) {
2699 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2700 // bits, it is already ready.
2701 if (NumSignBits > DestBits-MidBits)
2703 } else if (OpBits < DestBits) {
2704 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2705 // bits, just sext from i32.
2706 if (NumSignBits > OpBits-MidBits)
2707 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2709 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2710 // bits, just truncate to i32.
2711 if (NumSignBits > OpBits-MidBits)
2712 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2715 // fold (sext (truncate x)) -> (sextinreg x).
2716 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2717 N0.getValueType())) {
2718 if (Op.getValueType() < VT)
2719 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2720 else if (Op.getValueType() > VT)
2721 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2722 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2723 DAG.getValueType(N0.getValueType()));
2727 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2728 if (ISD::isNON_EXTLoad(N0.Val) &&
2729 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2730 bool DoXform = true;
2731 SmallVector<SDNode*, 4> SetCCs;
2732 if (!N0.hasOneUse())
2733 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2735 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2736 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2737 LN0->getBasePtr(), LN0->getSrcValue(),
2738 LN0->getSrcValueOffset(),
2741 LN0->getAlignment());
2742 CombineTo(N, ExtLoad);
2743 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2744 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2745 // Extend SetCC uses if necessary.
2746 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2747 SDNode *SetCC = SetCCs[i];
2748 SmallVector<SDOperand, 4> Ops;
2749 for (unsigned j = 0; j != 2; ++j) {
2750 SDOperand SOp = SetCC->getOperand(j);
2752 Ops.push_back(ExtLoad);
2754 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2756 Ops.push_back(SetCC->getOperand(2));
2757 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2758 &Ops[0], Ops.size()));
2760 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2764 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2765 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2766 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2767 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2768 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2769 MVT::ValueType EVT = LN0->getMemoryVT();
2770 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2771 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2772 LN0->getBasePtr(), LN0->getSrcValue(),
2773 LN0->getSrcValueOffset(), EVT,
2775 LN0->getAlignment());
2776 CombineTo(N, ExtLoad);
2777 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2778 ExtLoad.getValue(1));
2779 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2783 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2784 if (N0.getOpcode() == ISD::SETCC) {
2786 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2787 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2788 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2789 if (SCC.Val) return SCC;
2795 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2796 SDOperand N0 = N->getOperand(0);
2797 MVT::ValueType VT = N->getValueType(0);
2799 // fold (zext c1) -> c1
2800 if (isa<ConstantSDNode>(N0))
2801 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2802 // fold (zext (zext x)) -> (zext x)
2803 // fold (zext (aext x)) -> (zext x)
2804 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2805 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2807 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2808 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2809 if (N0.getOpcode() == ISD::TRUNCATE) {
2810 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2811 if (NarrowLoad.Val) {
2812 if (NarrowLoad.Val != N0.Val)
2813 CombineTo(N0.Val, NarrowLoad);
2814 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2818 // fold (zext (truncate x)) -> (and x, mask)
2819 if (N0.getOpcode() == ISD::TRUNCATE &&
2820 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2821 SDOperand Op = N0.getOperand(0);
2822 if (Op.getValueType() < VT) {
2823 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2824 } else if (Op.getValueType() > VT) {
2825 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2827 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2830 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2831 if (N0.getOpcode() == ISD::AND &&
2832 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2833 N0.getOperand(1).getOpcode() == ISD::Constant) {
2834 SDOperand X = N0.getOperand(0).getOperand(0);
2835 if (X.getValueType() < VT) {
2836 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2837 } else if (X.getValueType() > VT) {
2838 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2840 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2841 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2844 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2845 if (ISD::isNON_EXTLoad(N0.Val) &&
2846 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2847 bool DoXform = true;
2848 SmallVector<SDNode*, 4> SetCCs;
2849 if (!N0.hasOneUse())
2850 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2852 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2853 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2854 LN0->getBasePtr(), LN0->getSrcValue(),
2855 LN0->getSrcValueOffset(),
2858 LN0->getAlignment());
2859 CombineTo(N, ExtLoad);
2860 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2861 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2862 // Extend SetCC uses if necessary.
2863 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2864 SDNode *SetCC = SetCCs[i];
2865 SmallVector<SDOperand, 4> Ops;
2866 for (unsigned j = 0; j != 2; ++j) {
2867 SDOperand SOp = SetCC->getOperand(j);
2869 Ops.push_back(ExtLoad);
2871 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2873 Ops.push_back(SetCC->getOperand(2));
2874 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2875 &Ops[0], Ops.size()));
2877 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2881 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2882 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2883 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2884 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2885 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2886 MVT::ValueType EVT = LN0->getMemoryVT();
2887 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2888 LN0->getBasePtr(), LN0->getSrcValue(),
2889 LN0->getSrcValueOffset(), EVT,
2891 LN0->getAlignment());
2892 CombineTo(N, ExtLoad);
2893 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2894 ExtLoad.getValue(1));
2895 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2898 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2899 if (N0.getOpcode() == ISD::SETCC) {
2901 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2902 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2903 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2904 if (SCC.Val) return SCC;
2910 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2911 SDOperand N0 = N->getOperand(0);
2912 MVT::ValueType VT = N->getValueType(0);
2914 // fold (aext c1) -> c1
2915 if (isa<ConstantSDNode>(N0))
2916 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2917 // fold (aext (aext x)) -> (aext x)
2918 // fold (aext (zext x)) -> (zext x)
2919 // fold (aext (sext x)) -> (sext x)
2920 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2921 N0.getOpcode() == ISD::ZERO_EXTEND ||
2922 N0.getOpcode() == ISD::SIGN_EXTEND)
2923 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2925 // fold (aext (truncate (load x))) -> (aext (smaller load x))
2926 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
2927 if (N0.getOpcode() == ISD::TRUNCATE) {
2928 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2929 if (NarrowLoad.Val) {
2930 if (NarrowLoad.Val != N0.Val)
2931 CombineTo(N0.Val, NarrowLoad);
2932 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
2936 // fold (aext (truncate x))
2937 if (N0.getOpcode() == ISD::TRUNCATE) {
2938 SDOperand TruncOp = N0.getOperand(0);
2939 if (TruncOp.getValueType() == VT)
2940 return TruncOp; // x iff x size == zext size.
2941 if (TruncOp.getValueType() > VT)
2942 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2943 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2946 // fold (aext (and (trunc x), cst)) -> (and x, cst).
2947 if (N0.getOpcode() == ISD::AND &&
2948 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2949 N0.getOperand(1).getOpcode() == ISD::Constant) {
2950 SDOperand X = N0.getOperand(0).getOperand(0);
2951 if (X.getValueType() < VT) {
2952 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2953 } else if (X.getValueType() > VT) {
2954 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2956 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2957 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2960 // fold (aext (load x)) -> (aext (truncate (extload x)))
2961 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2962 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2963 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2964 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2965 LN0->getBasePtr(), LN0->getSrcValue(),
2966 LN0->getSrcValueOffset(),
2969 LN0->getAlignment());
2970 CombineTo(N, ExtLoad);
2971 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2972 ExtLoad.getValue(1));
2973 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2976 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2977 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2978 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
2979 if (N0.getOpcode() == ISD::LOAD &&
2980 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
2982 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2983 MVT::ValueType EVT = LN0->getMemoryVT();
2984 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2985 LN0->getChain(), LN0->getBasePtr(),
2987 LN0->getSrcValueOffset(), EVT,
2989 LN0->getAlignment());
2990 CombineTo(N, ExtLoad);
2991 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2992 ExtLoad.getValue(1));
2993 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2996 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2997 if (N0.getOpcode() == ISD::SETCC) {
2999 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3000 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3001 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3009 /// GetDemandedBits - See if the specified operand can be simplified with the
3010 /// knowledge that only the bits specified by Mask are used. If so, return the
3011 /// simpler operand, otherwise return a null SDOperand.
3012 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, uint64_t Mask) {
3013 switch (V.getOpcode()) {
3017 // If the LHS or RHS don't contribute bits to the or, drop them.
3018 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3019 return V.getOperand(1);
3020 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3021 return V.getOperand(0);
3024 // Only look at single-use SRLs.
3025 if (!V.Val->hasOneUse())
3027 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3028 // See if we can recursively simplify the LHS.
3029 unsigned Amt = RHSC->getValue();
3030 Mask = (Mask << Amt) & MVT::getIntVTBitMask(V.getValueType());
3031 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), Mask);
3032 if (SimplifyLHS.Val) {
3033 return DAG.getNode(ISD::SRL, V.getValueType(),
3034 SimplifyLHS, V.getOperand(1));
3041 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3042 /// bits and then truncated to a narrower type and where N is a multiple
3043 /// of number of bits of the narrower type, transform it to a narrower load
3044 /// from address + N / num of bits of new type. If the result is to be
3045 /// extended, also fold the extension to form a extending load.
3046 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3047 unsigned Opc = N->getOpcode();
3048 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3049 SDOperand N0 = N->getOperand(0);
3050 MVT::ValueType VT = N->getValueType(0);
3051 MVT::ValueType EVT = N->getValueType(0);
3053 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3055 if (Opc == ISD::SIGN_EXTEND_INREG) {
3056 ExtType = ISD::SEXTLOAD;
3057 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3058 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3062 unsigned EVTBits = MVT::getSizeInBits(EVT);
3064 bool CombineSRL = false;
3065 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3066 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3067 ShAmt = N01->getValue();
3068 // Is the shift amount a multiple of size of VT?
3069 if ((ShAmt & (EVTBits-1)) == 0) {
3070 N0 = N0.getOperand(0);
3071 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
3078 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3079 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
3080 // zero extended form: by shrinking the load, we lose track of the fact
3081 // that it is already zero extended.
3082 // FIXME: This should be reevaluated.
3084 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
3085 "Cannot truncate to larger type!");
3086 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3087 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
3088 // For big endian targets, we need to adjust the offset to the pointer to
3089 // load the correct bytes.
3090 if (!TLI.isLittleEndian()) {
3091 unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
3092 unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
3093 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3095 uint64_t PtrOff = ShAmt / 8;
3096 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3097 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3098 DAG.getConstant(PtrOff, PtrType));
3099 AddToWorkList(NewPtr.Val);
3100 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3101 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3102 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3103 LN0->isVolatile(), NewAlign)
3104 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3105 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3106 LN0->isVolatile(), NewAlign);
3109 WorkListRemover DeadNodes(*this);
3110 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3112 CombineTo(N->getOperand(0).Val, Load);
3114 CombineTo(N0.Val, Load, Load.getValue(1));
3116 if (Opc == ISD::SIGN_EXTEND_INREG)
3117 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3119 return DAG.getNode(Opc, VT, Load);
3121 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3128 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3129 SDOperand N0 = N->getOperand(0);
3130 SDOperand N1 = N->getOperand(1);
3131 MVT::ValueType VT = N->getValueType(0);
3132 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
3133 unsigned EVTBits = MVT::getSizeInBits(EVT);
3135 // fold (sext_in_reg c1) -> c1
3136 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3137 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3139 // If the input is already sign extended, just drop the extension.
3140 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
3143 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3144 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3145 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
3146 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3149 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3150 if (DAG.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
3151 return DAG.getZeroExtendInReg(N0, EVT);
3153 // fold operands of sext_in_reg based on knowledge that the top bits are not
3155 if (SimplifyDemandedBits(SDOperand(N, 0)))
3156 return SDOperand(N, 0);
3158 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3159 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3160 SDOperand NarrowLoad = ReduceLoadWidth(N);
3164 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3165 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3166 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3167 if (N0.getOpcode() == ISD::SRL) {
3168 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3169 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
3170 // We can turn this into an SRA iff the input to the SRL is already sign
3172 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3173 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
3174 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3178 // fold (sext_inreg (extload x)) -> (sextload x)
3179 if (ISD::isEXTLoad(N0.Val) &&
3180 ISD::isUNINDEXEDLoad(N0.Val) &&
3181 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3182 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3183 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3184 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3185 LN0->getBasePtr(), LN0->getSrcValue(),
3186 LN0->getSrcValueOffset(), EVT,
3188 LN0->getAlignment());
3189 CombineTo(N, ExtLoad);
3190 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3191 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3193 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3194 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3196 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3197 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3198 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3199 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3200 LN0->getBasePtr(), LN0->getSrcValue(),
3201 LN0->getSrcValueOffset(), EVT,
3203 LN0->getAlignment());
3204 CombineTo(N, ExtLoad);
3205 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3206 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3211 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3212 SDOperand N0 = N->getOperand(0);
3213 MVT::ValueType VT = N->getValueType(0);
3216 if (N0.getValueType() == N->getValueType(0))
3218 // fold (truncate c1) -> c1
3219 if (isa<ConstantSDNode>(N0))
3220 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3221 // fold (truncate (truncate x)) -> (truncate x)
3222 if (N0.getOpcode() == ISD::TRUNCATE)
3223 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3224 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3225 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3226 N0.getOpcode() == ISD::ANY_EXTEND) {
3227 if (N0.getOperand(0).getValueType() < VT)
3228 // if the source is smaller than the dest, we still need an extend
3229 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3230 else if (N0.getOperand(0).getValueType() > VT)
3231 // if the source is larger than the dest, than we just need the truncate
3232 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3234 // if the source and dest are the same type, we can drop both the extend
3236 return N0.getOperand(0);
3239 // See if we can simplify the input to this truncate through knowledge that
3240 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3242 SDOperand Shorter = GetDemandedBits(N0, MVT::getIntVTBitMask(VT));
3244 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3246 // fold (truncate (load x)) -> (smaller load x)
3247 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3248 return ReduceLoadWidth(N);
3251 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3252 SDOperand N0 = N->getOperand(0);
3253 MVT::ValueType VT = N->getValueType(0);
3255 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3256 // Only do this before legalize, since afterward the target may be depending
3257 // on the bitconvert.
3258 // First check to see if this is all constant.
3259 if (!AfterLegalize &&
3260 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3261 MVT::isVector(VT)) {
3262 bool isSimple = true;
3263 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3264 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3265 N0.getOperand(i).getOpcode() != ISD::Constant &&
3266 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3271 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
3272 assert(!MVT::isVector(DestEltVT) &&
3273 "Element type of vector ValueType must not be vector!");
3275 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3279 // If the input is a constant, let getNode() fold it.
3280 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3281 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3282 if (Res.Val != N) return Res;
3285 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3286 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3288 // fold (conv (load x)) -> (load (conv*)x)
3289 // If the resultant load doesn't need a higher alignment than the original!
3290 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3291 TLI.isOperationLegal(ISD::LOAD, VT)) {
3292 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3293 unsigned Align = TLI.getTargetMachine().getTargetData()->
3294 getABITypeAlignment(MVT::getTypeForValueType(VT));
3295 unsigned OrigAlign = LN0->getAlignment();
3296 if (Align <= OrigAlign) {
3297 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3298 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3299 LN0->isVolatile(), Align);
3301 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3307 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3308 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3309 // This often reduces constant pool loads.
3310 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3311 N0.Val->hasOneUse() && MVT::isInteger(VT) && !MVT::isVector(VT)) {
3312 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3313 AddToWorkList(NewConv.Val);
3315 uint64_t SignBit = MVT::getIntVTSignBit(VT);
3316 if (N0.getOpcode() == ISD::FNEG)
3317 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3318 assert(N0.getOpcode() == ISD::FABS);
3319 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3322 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3323 // Note that we don't handle copysign(x,cst) because this can always be folded
3324 // to an fneg or fabs.
3325 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3326 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3327 MVT::isInteger(VT) && !MVT::isVector(VT)) {
3328 unsigned OrigXWidth = MVT::getSizeInBits(N0.getOperand(1).getValueType());
3329 SDOperand X = DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerType(OrigXWidth),
3331 AddToWorkList(X.Val);
3333 // If X has a different width than the result/lhs, sext it or truncate it.
3334 unsigned VTWidth = MVT::getSizeInBits(VT);
3335 if (OrigXWidth < VTWidth) {
3336 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3337 AddToWorkList(X.Val);
3338 } else if (OrigXWidth > VTWidth) {
3339 // To get the sign bit in the right place, we have to shift it right
3340 // before truncating.
3341 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3342 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3343 AddToWorkList(X.Val);
3344 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3345 AddToWorkList(X.Val);
3348 uint64_t SignBit = MVT::getIntVTSignBit(VT);
3349 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3350 AddToWorkList(X.Val);
3352 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3353 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3354 AddToWorkList(Cst.Val);
3356 return DAG.getNode(ISD::OR, VT, X, Cst);
3362 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3363 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3364 /// destination element value type.
3365 SDOperand DAGCombiner::
3366 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
3367 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
3369 // If this is already the right type, we're done.
3370 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3372 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
3373 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
3375 // If this is a conversion of N elements of one type to N elements of another
3376 // type, convert each element. This handles FP<->INT cases.
3377 if (SrcBitSize == DstBitSize) {
3378 SmallVector<SDOperand, 8> Ops;
3379 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3380 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3381 AddToWorkList(Ops.back().Val);
3384 MVT::getVectorType(DstEltVT,
3385 MVT::getVectorNumElements(BV->getValueType(0)));
3386 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3389 // Otherwise, we're growing or shrinking the elements. To avoid having to
3390 // handle annoying details of growing/shrinking FP values, we convert them to
3392 if (MVT::isFloatingPoint(SrcEltVT)) {
3393 // Convert the input float vector to a int vector where the elements are the
3395 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3396 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3397 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3401 // Now we know the input is an integer vector. If the output is a FP type,
3402 // convert to integer first, then to FP of the right size.
3403 if (MVT::isFloatingPoint(DstEltVT)) {
3404 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3405 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3406 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3408 // Next, convert to FP elements of the same size.
3409 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3412 // Okay, we know the src/dst types are both integers of differing types.
3413 // Handling growing first.
3414 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
3415 if (SrcBitSize < DstBitSize) {
3416 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3418 SmallVector<SDOperand, 8> Ops;
3419 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3420 i += NumInputsPerOutput) {
3421 bool isLE = TLI.isLittleEndian();
3422 uint64_t NewBits = 0;
3423 bool EltIsUndef = true;
3424 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3425 // Shift the previously computed bits over.
3426 NewBits <<= SrcBitSize;
3427 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3428 if (Op.getOpcode() == ISD::UNDEF) continue;
3431 NewBits |= cast<ConstantSDNode>(Op)->getValue();
3435 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3437 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3440 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3442 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3445 // Finally, this must be the case where we are shrinking elements: each input
3446 // turns into multiple outputs.
3447 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3448 SmallVector<SDOperand, 8> Ops;
3449 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3450 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3451 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3452 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3455 uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
3457 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3458 unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
3459 OpVal >>= DstBitSize;
3460 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3463 // For big endian targets, swap the order of the pieces of each element.
3464 if (!TLI.isLittleEndian())
3465 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3467 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
3468 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3473 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3474 SDOperand N0 = N->getOperand(0);
3475 SDOperand N1 = N->getOperand(1);
3476 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3477 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3478 MVT::ValueType VT = N->getValueType(0);
3481 if (MVT::isVector(VT)) {
3482 SDOperand FoldedVOp = SimplifyVBinOp(N);
3483 if (FoldedVOp.Val) return FoldedVOp;
3486 // fold (fadd c1, c2) -> c1+c2
3487 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3488 return DAG.getNode(ISD::FADD, VT, N0, N1);
3489 // canonicalize constant to RHS
3490 if (N0CFP && !N1CFP)
3491 return DAG.getNode(ISD::FADD, VT, N1, N0);
3492 // fold (A + (-B)) -> A-B
3493 if (isNegatibleForFree(N1) == 2)
3494 return DAG.getNode(ISD::FSUB, VT, N0, GetNegatedExpression(N1, DAG));
3495 // fold ((-A) + B) -> B-A
3496 if (isNegatibleForFree(N0) == 2)
3497 return DAG.getNode(ISD::FSUB, VT, N1, GetNegatedExpression(N0, DAG));
3499 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3500 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3501 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3502 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3503 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3508 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3509 SDOperand N0 = N->getOperand(0);
3510 SDOperand N1 = N->getOperand(1);
3511 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3512 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3513 MVT::ValueType VT = N->getValueType(0);
3516 if (MVT::isVector(VT)) {
3517 SDOperand FoldedVOp = SimplifyVBinOp(N);
3518 if (FoldedVOp.Val) return FoldedVOp;
3521 // fold (fsub c1, c2) -> c1-c2
3522 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3523 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3525 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3526 if (isNegatibleForFree(N1))
3527 return GetNegatedExpression(N1, DAG);
3528 return DAG.getNode(ISD::FNEG, VT, N1);
3530 // fold (A-(-B)) -> A+B
3531 if (isNegatibleForFree(N1))
3532 return DAG.getNode(ISD::FADD, VT, N0, GetNegatedExpression(N1, DAG));
3537 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3538 SDOperand N0 = N->getOperand(0);
3539 SDOperand N1 = N->getOperand(1);
3540 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3541 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3542 MVT::ValueType VT = N->getValueType(0);
3545 if (MVT::isVector(VT)) {
3546 SDOperand FoldedVOp = SimplifyVBinOp(N);
3547 if (FoldedVOp.Val) return FoldedVOp;
3550 // fold (fmul c1, c2) -> c1*c2
3551 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3552 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3553 // canonicalize constant to RHS
3554 if (N0CFP && !N1CFP)
3555 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3556 // fold (fmul X, 2.0) -> (fadd X, X)
3557 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3558 return DAG.getNode(ISD::FADD, VT, N0, N0);
3559 // fold (fmul X, -1.0) -> (fneg X)
3560 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3561 return DAG.getNode(ISD::FNEG, VT, N0);
3564 if (char LHSNeg = isNegatibleForFree(N0)) {
3565 if (char RHSNeg = isNegatibleForFree(N1)) {
3566 // Both can be negated for free, check to see if at least one is cheaper
3568 if (LHSNeg == 2 || RHSNeg == 2)
3569 return DAG.getNode(ISD::FMUL, VT, GetNegatedExpression(N0, DAG),
3570 GetNegatedExpression(N1, DAG));
3574 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3575 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3576 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3577 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3578 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3583 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3584 SDOperand N0 = N->getOperand(0);
3585 SDOperand N1 = N->getOperand(1);
3586 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3587 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3588 MVT::ValueType VT = N->getValueType(0);
3591 if (MVT::isVector(VT)) {
3592 SDOperand FoldedVOp = SimplifyVBinOp(N);
3593 if (FoldedVOp.Val) return FoldedVOp;
3596 // fold (fdiv c1, c2) -> c1/c2
3597 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3598 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3602 if (char LHSNeg = isNegatibleForFree(N0)) {
3603 if (char RHSNeg = isNegatibleForFree(N1)) {
3604 // Both can be negated for free, check to see if at least one is cheaper
3606 if (LHSNeg == 2 || RHSNeg == 2)
3607 return DAG.getNode(ISD::FDIV, VT, GetNegatedExpression(N0, DAG),
3608 GetNegatedExpression(N1, DAG));
3615 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3616 SDOperand N0 = N->getOperand(0);
3617 SDOperand N1 = N->getOperand(1);
3618 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3619 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3620 MVT::ValueType VT = N->getValueType(0);
3622 // fold (frem c1, c2) -> fmod(c1,c2)
3623 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3624 return DAG.getNode(ISD::FREM, VT, N0, N1);
3629 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3630 SDOperand N0 = N->getOperand(0);
3631 SDOperand N1 = N->getOperand(1);
3632 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3633 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3634 MVT::ValueType VT = N->getValueType(0);
3636 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3637 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3640 const APFloat& V = N1CFP->getValueAPF();
3641 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3642 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3643 if (!V.isNegative())
3644 return DAG.getNode(ISD::FABS, VT, N0);
3646 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3649 // copysign(fabs(x), y) -> copysign(x, y)
3650 // copysign(fneg(x), y) -> copysign(x, y)
3651 // copysign(copysign(x,z), y) -> copysign(x, y)
3652 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3653 N0.getOpcode() == ISD::FCOPYSIGN)
3654 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3656 // copysign(x, abs(y)) -> abs(x)
3657 if (N1.getOpcode() == ISD::FABS)
3658 return DAG.getNode(ISD::FABS, VT, N0);
3660 // copysign(x, copysign(y,z)) -> copysign(x, z)
3661 if (N1.getOpcode() == ISD::FCOPYSIGN)
3662 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3664 // copysign(x, fp_extend(y)) -> copysign(x, y)
3665 // copysign(x, fp_round(y)) -> copysign(x, y)
3666 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3667 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3674 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3675 SDOperand N0 = N->getOperand(0);
3676 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3677 MVT::ValueType VT = N->getValueType(0);
3679 // fold (sint_to_fp c1) -> c1fp
3680 if (N0C && N0.getValueType() != MVT::ppcf128)
3681 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3685 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3686 SDOperand N0 = N->getOperand(0);
3687 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3688 MVT::ValueType VT = N->getValueType(0);
3690 // fold (uint_to_fp c1) -> c1fp
3691 if (N0C && N0.getValueType() != MVT::ppcf128)
3692 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3696 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3697 SDOperand N0 = N->getOperand(0);
3698 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3699 MVT::ValueType VT = N->getValueType(0);
3701 // fold (fp_to_sint c1fp) -> c1
3703 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3707 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3708 SDOperand N0 = N->getOperand(0);
3709 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3710 MVT::ValueType VT = N->getValueType(0);
3712 // fold (fp_to_uint c1fp) -> c1
3713 if (N0CFP && VT != MVT::ppcf128)
3714 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3718 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3719 SDOperand N0 = N->getOperand(0);
3720 SDOperand N1 = N->getOperand(1);
3721 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3722 MVT::ValueType VT = N->getValueType(0);
3724 // fold (fp_round c1fp) -> c1fp
3725 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3726 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3728 // fold (fp_round (fp_extend x)) -> x
3729 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3730 return N0.getOperand(0);
3732 // fold (fp_round (fp_round x)) -> (fp_round x)
3733 if (N0.getOpcode() == ISD::FP_ROUND) {
3734 // This is a value preserving truncation if both round's are.
3735 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3736 N0.Val->getConstantOperandVal(1) == 1;
3737 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3738 DAG.getIntPtrConstant(IsTrunc));
3741 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3742 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3743 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3744 AddToWorkList(Tmp.Val);
3745 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3751 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3752 SDOperand N0 = N->getOperand(0);
3753 MVT::ValueType VT = N->getValueType(0);
3754 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3755 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3757 // fold (fp_round_inreg c1fp) -> c1fp
3759 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3760 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3765 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3766 SDOperand N0 = N->getOperand(0);
3767 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3768 MVT::ValueType VT = N->getValueType(0);
3770 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3771 if (N->hasOneUse() && (*N->use_begin())->getOpcode() == ISD::FP_ROUND)
3774 // fold (fp_extend c1fp) -> c1fp
3775 if (N0CFP && VT != MVT::ppcf128)
3776 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3778 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3780 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3781 SDOperand In = N0.getOperand(0);
3782 if (In.getValueType() == VT) return In;
3783 if (VT < In.getValueType())
3784 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3785 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3788 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3789 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3790 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3791 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3792 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3793 LN0->getBasePtr(), LN0->getSrcValue(),
3794 LN0->getSrcValueOffset(),
3797 LN0->getAlignment());
3798 CombineTo(N, ExtLoad);
3799 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3800 DAG.getIntPtrConstant(1)),
3801 ExtLoad.getValue(1));
3802 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3809 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3810 SDOperand N0 = N->getOperand(0);
3812 if (isNegatibleForFree(N0))
3813 return GetNegatedExpression(N0, DAG);
3815 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3816 // constant pool values.
3817 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3818 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3819 !MVT::isVector(N0.getOperand(0).getValueType())) {
3820 SDOperand Int = N0.getOperand(0);
3821 MVT::ValueType IntVT = Int.getValueType();
3822 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3823 Int = DAG.getNode(ISD::XOR, IntVT, Int,
3824 DAG.getConstant(MVT::getIntVTSignBit(IntVT), IntVT));
3825 AddToWorkList(Int.Val);
3826 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3833 SDOperand DAGCombiner::visitFABS(SDNode *N) {
3834 SDOperand N0 = N->getOperand(0);
3835 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3836 MVT::ValueType VT = N->getValueType(0);
3838 // fold (fabs c1) -> fabs(c1)
3839 if (N0CFP && VT != MVT::ppcf128)
3840 return DAG.getNode(ISD::FABS, VT, N0);
3841 // fold (fabs (fabs x)) -> (fabs x)
3842 if (N0.getOpcode() == ISD::FABS)
3843 return N->getOperand(0);
3844 // fold (fabs (fneg x)) -> (fabs x)
3845 // fold (fabs (fcopysign x, y)) -> (fabs x)
3846 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3847 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3849 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
3850 // constant pool values.
3851 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3852 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3853 !MVT::isVector(N0.getOperand(0).getValueType())) {
3854 SDOperand Int = N0.getOperand(0);
3855 MVT::ValueType IntVT = Int.getValueType();
3856 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3857 Int = DAG.getNode(ISD::AND, IntVT, Int,
3858 DAG.getConstant(~MVT::getIntVTSignBit(IntVT), IntVT));
3859 AddToWorkList(Int.Val);
3860 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3867 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3868 SDOperand Chain = N->getOperand(0);
3869 SDOperand N1 = N->getOperand(1);
3870 SDOperand N2 = N->getOperand(2);
3871 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3873 // never taken branch, fold to chain
3874 if (N1C && N1C->isNullValue())
3876 // unconditional branch
3877 if (N1C && N1C->getValue() == 1)
3878 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3879 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3881 if (N1.getOpcode() == ISD::SETCC &&
3882 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3883 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3884 N1.getOperand(0), N1.getOperand(1), N2);
3889 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
3891 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
3892 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
3893 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
3895 // Use SimplifySetCC to simplify SETCC's.
3896 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
3897 if (Simp.Val) AddToWorkList(Simp.Val);
3899 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
3901 // fold br_cc true, dest -> br dest (unconditional branch)
3902 if (SCCC && SCCC->getValue())
3903 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
3905 // fold br_cc false, dest -> unconditional fall through
3906 if (SCCC && SCCC->isNullValue())
3907 return N->getOperand(0);
3909 // fold to a simpler setcc
3910 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
3911 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
3912 Simp.getOperand(2), Simp.getOperand(0),
3913 Simp.getOperand(1), N->getOperand(4));
3918 /// CombineToPreIndexedLoadStore - Try turning a load / store and a
3919 /// pre-indexed load / store when the base pointer is a add or subtract
3920 /// and it has other uses besides the load / store. After the
3921 /// transformation, the new indexed load / store has effectively folded
3922 /// the add / subtract in and all of its other uses are redirected to the
3923 /// new load / store.
3924 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
3931 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3932 if (LD->isIndexed())
3934 VT = LD->getMemoryVT();
3935 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
3936 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
3938 Ptr = LD->getBasePtr();
3939 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3940 if (ST->isIndexed())
3942 VT = ST->getMemoryVT();
3943 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
3944 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
3946 Ptr = ST->getBasePtr();
3951 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
3952 // out. There is no reason to make this a preinc/predec.
3953 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
3954 Ptr.Val->hasOneUse())
3957 // Ask the target to do addressing mode selection.
3960 ISD::MemIndexedMode AM = ISD::UNINDEXED;
3961 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
3963 // Don't create a indexed load / store with zero offset.
3964 if (isa<ConstantSDNode>(Offset) &&
3965 cast<ConstantSDNode>(Offset)->getValue() == 0)
3968 // Try turning it into a pre-indexed load / store except when:
3969 // 1) The new base ptr is a frame index.
3970 // 2) If N is a store and the new base ptr is either the same as or is a
3971 // predecessor of the value being stored.
3972 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
3973 // that would create a cycle.
3974 // 4) All uses are load / store ops that use it as old base ptr.
3976 // Check #1. Preinc'ing a frame index would require copying the stack pointer
3977 // (plus the implicit offset) to a register to preinc anyway.
3978 if (isa<FrameIndexSDNode>(BasePtr))
3983 SDOperand Val = cast<StoreSDNode>(N)->getValue();
3984 if (Val == BasePtr || BasePtr.Val->isPredecessor(Val.Val))
3988 // Now check for #3 and #4.
3989 bool RealUse = false;
3990 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3991 E = Ptr.Val->use_end(); I != E; ++I) {
3995 if (Use->isPredecessor(N))
3998 if (!((Use->getOpcode() == ISD::LOAD &&
3999 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4000 (Use->getOpcode() == ISD::STORE) &&
4001 cast<StoreSDNode>(Use)->getBasePtr() == Ptr))
4009 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4011 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4014 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4015 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4017 WorkListRemover DeadNodes(*this);
4019 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4021 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4024 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4028 // Finally, since the node is now dead, remove it from the graph.
4031 // Replace the uses of Ptr with uses of the updated base value.
4032 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4034 removeFromWorkList(Ptr.Val);
4035 DAG.DeleteNode(Ptr.Val);
4040 /// CombineToPostIndexedLoadStore - Try combine a load / store with a
4041 /// add / sub of the base pointer node into a post-indexed load / store.
4042 /// The transformation folded the add / subtract into the new indexed
4043 /// load / store effectively and all of its uses are redirected to the
4044 /// new load / store.
4045 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4052 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4053 if (LD->isIndexed())
4055 VT = LD->getMemoryVT();
4056 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4057 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4059 Ptr = LD->getBasePtr();
4060 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4061 if (ST->isIndexed())
4063 VT = ST->getMemoryVT();
4064 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4065 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4067 Ptr = ST->getBasePtr();
4072 if (Ptr.Val->hasOneUse())
4075 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4076 E = Ptr.Val->use_end(); I != E; ++I) {
4079 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4084 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4085 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4087 std::swap(BasePtr, Offset);
4090 // Don't create a indexed load / store with zero offset.
4091 if (isa<ConstantSDNode>(Offset) &&
4092 cast<ConstantSDNode>(Offset)->getValue() == 0)
4095 // Try turning it into a post-indexed load / store except when
4096 // 1) All uses are load / store ops that use it as base ptr.
4097 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4098 // nor a successor of N. Otherwise, if Op is folded that would
4102 bool TryNext = false;
4103 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4104 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4109 // If all the uses are load / store addresses, then don't do the
4111 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4112 bool RealUse = false;
4113 for (SDNode::use_iterator III = Use->use_begin(),
4114 EEE = Use->use_end(); III != EEE; ++III) {
4115 SDNode *UseUse = *III;
4116 if (!((UseUse->getOpcode() == ISD::LOAD &&
4117 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4118 (UseUse->getOpcode() == ISD::STORE) &&
4119 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use))
4133 if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
4134 SDOperand Result = isLoad
4135 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4136 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4139 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4140 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4142 WorkListRemover DeadNodes(*this);
4144 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4146 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4149 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4153 // Finally, since the node is now dead, remove it from the graph.
4156 // Replace the uses of Use with uses of the updated base value.
4157 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4158 Result.getValue(isLoad ? 1 : 0),
4160 removeFromWorkList(Op);
4169 /// InferAlignment - If we can infer some alignment information from this
4170 /// pointer, return it.
4171 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4172 // If this is a direct reference to a stack slot, use information about the
4173 // stack slot's alignment.
4174 int FrameIdx = 1 << 31;
4175 int64_t FrameOffset = 0;
4176 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4177 FrameIdx = FI->getIndex();
4178 } else if (Ptr.getOpcode() == ISD::ADD &&
4179 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4180 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4181 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4182 FrameOffset = Ptr.getConstantOperandVal(1);
4185 if (FrameIdx != (1 << 31)) {
4186 // FIXME: Handle FI+CST.
4187 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4188 if (MFI.isFixedObjectIndex(FrameIdx)) {
4189 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4191 // The alignment of the frame index can be determined from its offset from
4192 // the incoming frame position. If the frame object is at offset 32 and
4193 // the stack is guaranteed to be 16-byte aligned, then we know that the
4194 // object is 16-byte aligned.
4195 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4196 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4198 // Finally, the frame object itself may have a known alignment. Factor
4199 // the alignment + offset into a new alignment. For example, if we know
4200 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4201 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4202 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4203 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4205 return std::max(Align, FIInfoAlign);
4212 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4213 LoadSDNode *LD = cast<LoadSDNode>(N);
4214 SDOperand Chain = LD->getChain();
4215 SDOperand Ptr = LD->getBasePtr();
4217 // Try to infer better alignment information than the load already has.
4218 if (LD->isUnindexed()) {
4219 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4220 if (Align > LD->getAlignment())
4221 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4222 Chain, Ptr, LD->getSrcValue(),
4223 LD->getSrcValueOffset(), LD->getMemoryVT(),
4224 LD->isVolatile(), Align);
4229 // If load is not volatile and there are no uses of the loaded value (and
4230 // the updated indexed value in case of indexed loads), change uses of the
4231 // chain value into uses of the chain input (i.e. delete the dead load).
4232 if (!LD->isVolatile()) {
4233 if (N->getValueType(1) == MVT::Other) {
4235 if (N->hasNUsesOfValue(0, 0)) {
4236 // It's not safe to use the two value CombineTo variant here. e.g.
4237 // v1, chain2 = load chain1, loc
4238 // v2, chain3 = load chain2, loc
4240 // Now we replace use of chain2 with chain1. This makes the second load
4241 // isomorphic to the one we are deleting, and thus makes this load live.
4242 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4243 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4245 WorkListRemover DeadNodes(*this);
4246 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4247 if (N->use_empty()) {
4248 removeFromWorkList(N);
4251 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4255 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4256 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4257 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4258 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4259 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4260 DOUT << " and 2 other values\n";
4261 WorkListRemover DeadNodes(*this);
4262 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4263 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4264 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4266 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4267 removeFromWorkList(N);
4269 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4274 // If this load is directly stored, replace the load value with the stored
4276 // TODO: Handle store large -> read small portion.
4277 // TODO: Handle TRUNCSTORE/LOADEXT
4278 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4279 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4280 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4281 if (PrevST->getBasePtr() == Ptr &&
4282 PrevST->getValue().getValueType() == N->getValueType(0))
4283 return CombineTo(N, Chain.getOperand(1), Chain);
4288 // Walk up chain skipping non-aliasing memory nodes.
4289 SDOperand BetterChain = FindBetterChain(N, Chain);
4291 // If there is a better chain.
4292 if (Chain != BetterChain) {
4295 // Replace the chain to void dependency.
4296 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4297 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4298 LD->getSrcValue(), LD->getSrcValueOffset(),
4299 LD->isVolatile(), LD->getAlignment());
4301 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4302 LD->getValueType(0),
4303 BetterChain, Ptr, LD->getSrcValue(),
4304 LD->getSrcValueOffset(),
4307 LD->getAlignment());
4310 // Create token factor to keep old chain connected.
4311 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4312 Chain, ReplLoad.getValue(1));
4314 // Replace uses with load result and token factor. Don't add users
4316 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4320 // Try transforming N to an indexed load.
4321 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4322 return SDOperand(N, 0);
4328 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4329 StoreSDNode *ST = cast<StoreSDNode>(N);
4330 SDOperand Chain = ST->getChain();
4331 SDOperand Value = ST->getValue();
4332 SDOperand Ptr = ST->getBasePtr();
4334 // Try to infer better alignment information than the store already has.
4335 if (ST->isUnindexed()) {
4336 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4337 if (Align > ST->getAlignment())
4338 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4339 ST->getSrcValueOffset(), ST->getMemoryVT(),
4340 ST->isVolatile(), Align);
4344 // If this is a store of a bit convert, store the input value if the
4345 // resultant store does not need a higher alignment than the original.
4346 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4347 ST->isUnindexed()) {
4348 unsigned Align = ST->getAlignment();
4349 MVT::ValueType SVT = Value.getOperand(0).getValueType();
4350 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4351 getABITypeAlignment(MVT::getTypeForValueType(SVT));
4352 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
4353 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4354 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4357 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4358 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4359 if (Value.getOpcode() != ISD::TargetConstantFP) {
4361 switch (CFP->getValueType(0)) {
4362 default: assert(0 && "Unknown FP type");
4363 case MVT::f80: // We don't do this for these yet.
4368 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
4369 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4370 convertToAPInt().getZExtValue(), MVT::i32);
4371 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4372 ST->getSrcValueOffset(), ST->isVolatile(),
4373 ST->getAlignment());
4377 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
4378 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4379 getZExtValue(), MVT::i64);
4380 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4381 ST->getSrcValueOffset(), ST->isVolatile(),
4382 ST->getAlignment());
4383 } else if (TLI.isTypeLegal(MVT::i32)) {
4384 // Many FP stores are not made apparent until after legalize, e.g. for
4385 // argument passing. Since this is so common, custom legalize the
4386 // 64-bit integer store into two 32-bit stores.
4387 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4388 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4389 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4390 if (!TLI.isLittleEndian()) std::swap(Lo, Hi);
4392 int SVOffset = ST->getSrcValueOffset();
4393 unsigned Alignment = ST->getAlignment();
4394 bool isVolatile = ST->isVolatile();
4396 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4397 ST->getSrcValueOffset(),
4398 isVolatile, ST->getAlignment());
4399 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4400 DAG.getConstant(4, Ptr.getValueType()));
4402 Alignment = MinAlign(Alignment, 4U);
4403 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4404 SVOffset, isVolatile, Alignment);
4405 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4413 // Walk up chain skipping non-aliasing memory nodes.
4414 SDOperand BetterChain = FindBetterChain(N, Chain);
4416 // If there is a better chain.
4417 if (Chain != BetterChain) {
4418 // Replace the chain to avoid dependency.
4419 SDOperand ReplStore;
4420 if (ST->isTruncatingStore()) {
4421 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4422 ST->getSrcValue(),ST->getSrcValueOffset(),
4424 ST->isVolatile(), ST->getAlignment());
4426 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4427 ST->getSrcValue(), ST->getSrcValueOffset(),
4428 ST->isVolatile(), ST->getAlignment());
4431 // Create token to keep both nodes around.
4433 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4435 // Don't add users to work list.
4436 return CombineTo(N, Token, false);
4440 // Try transforming N to an indexed store.
4441 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4442 return SDOperand(N, 0);
4444 // FIXME: is there such a thing as a truncating indexed store?
4445 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4446 MVT::isInteger(Value.getValueType())) {
4447 // See if we can simplify the input to this truncstore with knowledge that
4448 // only the low bits are being used. For example:
4449 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4451 GetDemandedBits(Value, MVT::getIntVTBitMask(ST->getMemoryVT()));
4452 AddToWorkList(Value.Val);
4454 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4455 ST->getSrcValueOffset(), ST->getMemoryVT(),
4456 ST->isVolatile(), ST->getAlignment());
4458 // Otherwise, see if we can simplify the operation with
4459 // SimplifyDemandedBits, which only works if the value has a single use.
4460 if (SimplifyDemandedBits(Value, MVT::getIntVTBitMask(ST->getMemoryVT())))
4461 return SDOperand(N, 0);
4464 // If this is a load followed by a store to the same location, then the store
4466 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4467 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4468 ST->isUnindexed() && !ST->isVolatile() &&
4469 // There can't be any side effects between the load and store, such as
4471 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4472 // The store is dead, remove it.
4477 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4478 // truncating store. We can do this even if this is already a truncstore.
4479 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4480 && TLI.isTypeLegal(Value.getOperand(0).getValueType()) &&
4481 Value.Val->hasOneUse() && ST->isUnindexed() &&
4482 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4483 ST->getMemoryVT())) {
4484 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4485 ST->getSrcValueOffset(), ST->getMemoryVT(),
4486 ST->isVolatile(), ST->getAlignment());
4492 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4493 SDOperand InVec = N->getOperand(0);
4494 SDOperand InVal = N->getOperand(1);
4495 SDOperand EltNo = N->getOperand(2);
4497 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4498 // vector with the inserted element.
4499 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4500 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4501 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4502 if (Elt < Ops.size())
4504 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4505 &Ops[0], Ops.size());
4511 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4512 SDOperand InVec = N->getOperand(0);
4513 SDOperand EltNo = N->getOperand(1);
4515 // (vextract (v4f32 s2v (f32 load $addr)), 0) -> (f32 load $addr)
4516 // (vextract (v4i32 bc (v4f32 s2v (f32 load $addr))), 0) -> (i32 load $addr)
4517 if (isa<ConstantSDNode>(EltNo)) {
4518 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4519 bool NewLoad = false;
4521 MVT::ValueType VT = InVec.getValueType();
4522 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4523 MVT::ValueType LVT = EVT;
4524 unsigned NumElts = MVT::getVectorNumElements(VT);
4525 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4526 MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
4527 if (!MVT::isVector(BCVT) ||
4528 NumElts != MVT::getVectorNumElements(BCVT))
4530 InVec = InVec.getOperand(0);
4531 EVT = MVT::getVectorElementType(BCVT);
4534 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4535 InVec.getOperand(0).getValueType() == EVT &&
4536 ISD::isNormalLoad(InVec.getOperand(0).Val) &&
4537 InVec.getOperand(0).hasOneUse()) {
4538 LoadSDNode *LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4539 unsigned Align = LN0->getAlignment();
4541 // Check the resultant load doesn't need a higher alignment than the
4543 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4544 getABITypeAlignment(MVT::getTypeForValueType(LVT));
4545 if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
4550 return DAG.getLoad(LVT, LN0->getChain(), LN0->getBasePtr(),
4551 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4552 LN0->isVolatile(), Align);
4560 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4561 unsigned NumInScalars = N->getNumOperands();
4562 MVT::ValueType VT = N->getValueType(0);
4563 unsigned NumElts = MVT::getVectorNumElements(VT);
4564 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4566 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4567 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4568 // at most two distinct vectors, turn this into a shuffle node.
4569 SDOperand VecIn1, VecIn2;
4570 for (unsigned i = 0; i != NumInScalars; ++i) {
4571 // Ignore undef inputs.
4572 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4574 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4575 // constant index, bail out.
4576 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4577 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4578 VecIn1 = VecIn2 = SDOperand(0, 0);
4582 // If the input vector type disagrees with the result of the build_vector,
4583 // we can't make a shuffle.
4584 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4585 if (ExtractedFromVec.getValueType() != VT) {
4586 VecIn1 = VecIn2 = SDOperand(0, 0);
4590 // Otherwise, remember this. We allow up to two distinct input vectors.
4591 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4594 if (VecIn1.Val == 0) {
4595 VecIn1 = ExtractedFromVec;
4596 } else if (VecIn2.Val == 0) {
4597 VecIn2 = ExtractedFromVec;
4600 VecIn1 = VecIn2 = SDOperand(0, 0);
4605 // If everything is good, we can make a shuffle operation.
4607 SmallVector<SDOperand, 8> BuildVecIndices;
4608 for (unsigned i = 0; i != NumInScalars; ++i) {
4609 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4610 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4614 SDOperand Extract = N->getOperand(i);
4616 // If extracting from the first vector, just use the index directly.
4617 if (Extract.getOperand(0) == VecIn1) {
4618 BuildVecIndices.push_back(Extract.getOperand(1));
4622 // Otherwise, use InIdx + VecSize
4623 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4624 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4627 // Add count and size info.
4628 MVT::ValueType BuildVecVT = MVT::getVectorType(TLI.getPointerTy(), NumElts);
4630 // Return the new VECTOR_SHUFFLE node.
4636 // Use an undef build_vector as input for the second operand.
4637 std::vector<SDOperand> UnOps(NumInScalars,
4638 DAG.getNode(ISD::UNDEF,
4640 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4641 &UnOps[0], UnOps.size());
4642 AddToWorkList(Ops[1].Val);
4644 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4645 &BuildVecIndices[0], BuildVecIndices.size());
4646 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4652 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4653 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4654 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4655 // inputs come from at most two distinct vectors, turn this into a shuffle
4658 // If we only have one input vector, we don't need to do any concatenation.
4659 if (N->getNumOperands() == 1) {
4660 return N->getOperand(0);
4666 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4667 SDOperand ShufMask = N->getOperand(2);
4668 unsigned NumElts = ShufMask.getNumOperands();
4670 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4671 bool isIdentity = true;
4672 for (unsigned i = 0; i != NumElts; ++i) {
4673 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4674 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4679 if (isIdentity) return N->getOperand(0);
4681 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4683 for (unsigned i = 0; i != NumElts; ++i) {
4684 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4685 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4690 if (isIdentity) return N->getOperand(1);
4692 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4694 bool isUnary = true;
4695 bool isSplat = true;
4697 unsigned BaseIdx = 0;
4698 for (unsigned i = 0; i != NumElts; ++i)
4699 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4700 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4701 int V = (Idx < NumElts) ? 0 : 1;
4715 SDOperand N0 = N->getOperand(0);
4716 SDOperand N1 = N->getOperand(1);
4717 // Normalize unary shuffle so the RHS is undef.
4718 if (isUnary && VecNum == 1)
4721 // If it is a splat, check if the argument vector is a build_vector with
4722 // all scalar elements the same.
4726 // If this is a bit convert that changes the element type of the vector but
4727 // not the number of vector elements, look through it. Be careful not to
4728 // look though conversions that change things like v4f32 to v2f64.
4729 if (V->getOpcode() == ISD::BIT_CONVERT) {
4730 SDOperand ConvInput = V->getOperand(0);
4731 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4735 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4736 unsigned NumElems = V->getNumOperands();
4737 if (NumElems > BaseIdx) {
4739 bool AllSame = true;
4740 for (unsigned i = 0; i != NumElems; ++i) {
4741 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4742 Base = V->getOperand(i);
4746 // Splat of <u, u, u, u>, return <u, u, u, u>
4749 for (unsigned i = 0; i != NumElems; ++i) {
4750 if (V->getOperand(i) != Base) {
4755 // Splat of <x, x, x, x>, return <x, x, x, x>
4762 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4764 if (isUnary || N0 == N1) {
4765 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4767 SmallVector<SDOperand, 8> MappedOps;
4768 for (unsigned i = 0; i != NumElts; ++i) {
4769 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4770 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4771 MappedOps.push_back(ShufMask.getOperand(i));
4774 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4775 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4778 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4779 &MappedOps[0], MappedOps.size());
4780 AddToWorkList(ShufMask.Val);
4781 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4783 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4790 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4791 /// an AND to a vector_shuffle with the destination vector and a zero vector.
4792 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4793 /// vector_shuffle V, Zero, <0, 4, 2, 4>
4794 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4795 SDOperand LHS = N->getOperand(0);
4796 SDOperand RHS = N->getOperand(1);
4797 if (N->getOpcode() == ISD::AND) {
4798 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4799 RHS = RHS.getOperand(0);
4800 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4801 std::vector<SDOperand> IdxOps;
4802 unsigned NumOps = RHS.getNumOperands();
4803 unsigned NumElts = NumOps;
4804 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4805 for (unsigned i = 0; i != NumElts; ++i) {
4806 SDOperand Elt = RHS.getOperand(i);
4807 if (!isa<ConstantSDNode>(Elt))
4809 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4810 IdxOps.push_back(DAG.getConstant(i, EVT));
4811 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4812 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4817 // Let's see if the target supports this vector_shuffle.
4818 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4821 // Return the new VECTOR_SHUFFLE node.
4822 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4823 std::vector<SDOperand> Ops;
4824 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4826 AddToWorkList(LHS.Val);
4827 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4828 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4829 &ZeroOps[0], ZeroOps.size()));
4830 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4831 &IdxOps[0], IdxOps.size()));
4832 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4833 &Ops[0], Ops.size());
4834 if (VT != LHS.getValueType()) {
4835 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4843 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4844 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4845 // After legalize, the target may be depending on adds and other
4846 // binary ops to provide legal ways to construct constants or other
4847 // things. Simplifying them may result in a loss of legality.
4848 if (AfterLegalize) return SDOperand();
4850 MVT::ValueType VT = N->getValueType(0);
4851 assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
4853 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4854 SDOperand LHS = N->getOperand(0);
4855 SDOperand RHS = N->getOperand(1);
4856 SDOperand Shuffle = XformToShuffleWithZero(N);
4857 if (Shuffle.Val) return Shuffle;
4859 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4861 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
4862 RHS.getOpcode() == ISD::BUILD_VECTOR) {
4863 SmallVector<SDOperand, 8> Ops;
4864 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4865 SDOperand LHSOp = LHS.getOperand(i);
4866 SDOperand RHSOp = RHS.getOperand(i);
4867 // If these two elements can't be folded, bail out.
4868 if ((LHSOp.getOpcode() != ISD::UNDEF &&
4869 LHSOp.getOpcode() != ISD::Constant &&
4870 LHSOp.getOpcode() != ISD::ConstantFP) ||
4871 (RHSOp.getOpcode() != ISD::UNDEF &&
4872 RHSOp.getOpcode() != ISD::Constant &&
4873 RHSOp.getOpcode() != ISD::ConstantFP))
4875 // Can't fold divide by zero.
4876 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4877 N->getOpcode() == ISD::FDIV) {
4878 if ((RHSOp.getOpcode() == ISD::Constant &&
4879 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4880 (RHSOp.getOpcode() == ISD::ConstantFP &&
4881 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
4884 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4885 AddToWorkList(Ops.back().Val);
4886 assert((Ops.back().getOpcode() == ISD::UNDEF ||
4887 Ops.back().getOpcode() == ISD::Constant ||
4888 Ops.back().getOpcode() == ISD::ConstantFP) &&
4889 "Scalar binop didn't fold!");
4892 if (Ops.size() == LHS.getNumOperands()) {
4893 MVT::ValueType VT = LHS.getValueType();
4894 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
4901 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
4902 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
4904 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
4905 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4906 // If we got a simplified select_cc node back from SimplifySelectCC, then
4907 // break it down into a new SETCC node, and a new SELECT node, and then return
4908 // the SELECT node, since we were called with a SELECT node.
4910 // Check to see if we got a select_cc back (to turn into setcc/select).
4911 // Otherwise, just return whatever node we got back, like fabs.
4912 if (SCC.getOpcode() == ISD::SELECT_CC) {
4913 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
4914 SCC.getOperand(0), SCC.getOperand(1),
4916 AddToWorkList(SETCC.Val);
4917 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
4918 SCC.getOperand(3), SETCC);
4925 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
4926 /// are the two values being selected between, see if we can simplify the
4927 /// select. Callers of this should assume that TheSelect is deleted if this
4928 /// returns true. As such, they should return the appropriate thing (e.g. the
4929 /// node) back to the top-level of the DAG combiner loop to avoid it being
4932 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
4935 // If this is a select from two identical things, try to pull the operation
4936 // through the select.
4937 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
4938 // If this is a load and the token chain is identical, replace the select
4939 // of two loads with a load through a select of the address to load from.
4940 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
4941 // constants have been dropped into the constant pool.
4942 if (LHS.getOpcode() == ISD::LOAD &&
4943 // Token chains must be identical.
4944 LHS.getOperand(0) == RHS.getOperand(0)) {
4945 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
4946 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
4948 // If this is an EXTLOAD, the VT's must match.
4949 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
4950 // FIXME: this conflates two src values, discarding one. This is not
4951 // the right thing to do, but nothing uses srcvalues now. When they do,
4952 // turn SrcValue into a list of locations.
4954 if (TheSelect->getOpcode() == ISD::SELECT) {
4955 // Check that the condition doesn't reach either load. If so, folding
4956 // this will induce a cycle into the DAG.
4957 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4958 !RLD->isPredecessor(TheSelect->getOperand(0).Val)) {
4959 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
4960 TheSelect->getOperand(0), LLD->getBasePtr(),
4964 // Check that the condition doesn't reach either load. If so, folding
4965 // this will induce a cycle into the DAG.
4966 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4967 !RLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4968 !LLD->isPredecessor(TheSelect->getOperand(1).Val) &&
4969 !RLD->isPredecessor(TheSelect->getOperand(1).Val)) {
4970 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
4971 TheSelect->getOperand(0),
4972 TheSelect->getOperand(1),
4973 LLD->getBasePtr(), RLD->getBasePtr(),
4974 TheSelect->getOperand(4));
4980 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
4981 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
4982 Addr,LLD->getSrcValue(),
4983 LLD->getSrcValueOffset(),
4985 LLD->getAlignment());
4987 Load = DAG.getExtLoad(LLD->getExtensionType(),
4988 TheSelect->getValueType(0),
4989 LLD->getChain(), Addr, LLD->getSrcValue(),
4990 LLD->getSrcValueOffset(),
4993 LLD->getAlignment());
4995 // Users of the select now use the result of the load.
4996 CombineTo(TheSelect, Load);
4998 // Users of the old loads now use the new load's chain. We know the
4999 // old-load value is dead now.
5000 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5001 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5011 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5012 SDOperand N2, SDOperand N3,
5013 ISD::CondCode CC, bool NotExtCompare) {
5015 MVT::ValueType VT = N2.getValueType();
5016 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5017 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5018 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5020 // Determine if the condition we're dealing with is constant
5021 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
5022 if (SCC.Val) AddToWorkList(SCC.Val);
5023 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5025 // fold select_cc true, x, y -> x
5026 if (SCCC && SCCC->getValue())
5028 // fold select_cc false, x, y -> y
5029 if (SCCC && SCCC->getValue() == 0)
5032 // Check to see if we can simplify the select into an fabs node
5033 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5034 // Allow either -0.0 or 0.0
5035 if (CFP->getValueAPF().isZero()) {
5036 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5037 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5038 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5039 N2 == N3.getOperand(0))
5040 return DAG.getNode(ISD::FABS, VT, N0);
5042 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5043 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5044 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5045 N2.getOperand(0) == N3)
5046 return DAG.getNode(ISD::FABS, VT, N3);
5050 // Check to see if we can perform the "gzip trick", transforming
5051 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5052 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5053 MVT::isInteger(N0.getValueType()) &&
5054 MVT::isInteger(N2.getValueType()) &&
5055 (N1C->isNullValue() || // (a < 0) ? b : 0
5056 (N1C->getValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5057 MVT::ValueType XType = N0.getValueType();
5058 MVT::ValueType AType = N2.getValueType();
5059 if (XType >= AType) {
5060 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5061 // single-bit constant.
5062 if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
5063 unsigned ShCtV = Log2_64(N2C->getValue());
5064 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
5065 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5066 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5067 AddToWorkList(Shift.Val);
5068 if (XType > AType) {
5069 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5070 AddToWorkList(Shift.Val);
5072 return DAG.getNode(ISD::AND, AType, Shift, N2);
5074 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5075 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5076 TLI.getShiftAmountTy()));
5077 AddToWorkList(Shift.Val);
5078 if (XType > AType) {
5079 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5080 AddToWorkList(Shift.Val);
5082 return DAG.getNode(ISD::AND, AType, Shift, N2);
5086 // fold select C, 16, 0 -> shl C, 4
5087 if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
5088 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5090 // If the caller doesn't want us to simplify this into a zext of a compare,
5092 if (NotExtCompare && N2C->getValue() == 1)
5095 // Get a SetCC of the condition
5096 // FIXME: Should probably make sure that setcc is legal if we ever have a
5097 // target where it isn't.
5098 SDOperand Temp, SCC;
5099 // cast from setcc result type to select result type
5100 if (AfterLegalize) {
5101 SCC = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
5102 if (N2.getValueType() < SCC.getValueType())
5103 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5105 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5107 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5108 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5110 AddToWorkList(SCC.Val);
5111 AddToWorkList(Temp.Val);
5113 if (N2C->getValue() == 1)
5115 // shl setcc result by log2 n2c
5116 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5117 DAG.getConstant(Log2_64(N2C->getValue()),
5118 TLI.getShiftAmountTy()));
5121 // Check to see if this is the equivalent of setcc
5122 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5123 // otherwise, go ahead with the folds.
5124 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
5125 MVT::ValueType XType = N0.getValueType();
5126 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
5127 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
5128 if (Res.getValueType() != VT)
5129 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5133 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5134 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5135 TLI.isOperationLegal(ISD::CTLZ, XType)) {
5136 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5137 return DAG.getNode(ISD::SRL, XType, Ctlz,
5138 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
5139 TLI.getShiftAmountTy()));
5141 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5142 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5143 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5145 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5146 DAG.getConstant(~0ULL, XType));
5147 return DAG.getNode(ISD::SRL, XType,
5148 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5149 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5150 TLI.getShiftAmountTy()));
5152 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5153 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5154 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5155 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5156 TLI.getShiftAmountTy()));
5157 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5161 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5162 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5163 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5164 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5165 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
5166 MVT::ValueType XType = N0.getValueType();
5167 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5168 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5169 TLI.getShiftAmountTy()));
5170 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5171 AddToWorkList(Shift.Val);
5172 AddToWorkList(Add.Val);
5173 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5175 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5176 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5177 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5178 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5179 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5180 MVT::ValueType XType = N0.getValueType();
5181 if (SubC->isNullValue() && MVT::isInteger(XType)) {
5182 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5183 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5184 TLI.getShiftAmountTy()));
5185 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5186 AddToWorkList(Shift.Val);
5187 AddToWorkList(Add.Val);
5188 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5196 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5197 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
5198 SDOperand N1, ISD::CondCode Cond,
5199 bool foldBooleans) {
5200 TargetLowering::DAGCombinerInfo
5201 DagCombineInfo(DAG, !AfterLegalize, false, this);
5202 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5205 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5206 /// return a DAG expression to select that will generate the same value by
5207 /// multiplying by a magic number. See:
5208 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5209 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5210 std::vector<SDNode*> Built;
5211 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5213 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5219 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5220 /// return a DAG expression to select that will generate the same value by
5221 /// multiplying by a magic number. See:
5222 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5223 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5224 std::vector<SDNode*> Built;
5225 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5227 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5233 /// FindBaseOffset - Return true if base is known not to alias with anything
5234 /// but itself. Provides base object and offset as results.
5235 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5236 // Assume it is a primitive operation.
5237 Base = Ptr; Offset = 0;
5239 // If it's an adding a simple constant then integrate the offset.
5240 if (Base.getOpcode() == ISD::ADD) {
5241 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5242 Base = Base.getOperand(0);
5243 Offset += C->getValue();
5247 // If it's any of the following then it can't alias with anything but itself.
5248 return isa<FrameIndexSDNode>(Base) ||
5249 isa<ConstantPoolSDNode>(Base) ||
5250 isa<GlobalAddressSDNode>(Base);
5253 /// isAlias - Return true if there is any possibility that the two addresses
5255 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5256 const Value *SrcValue1, int SrcValueOffset1,
5257 SDOperand Ptr2, int64_t Size2,
5258 const Value *SrcValue2, int SrcValueOffset2)
5260 // If they are the same then they must be aliases.
5261 if (Ptr1 == Ptr2) return true;
5263 // Gather base node and offset information.
5264 SDOperand Base1, Base2;
5265 int64_t Offset1, Offset2;
5266 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5267 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5269 // If they have a same base address then...
5270 if (Base1 == Base2) {
5271 // Check to see if the addresses overlap.
5272 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5275 // If we know both bases then they can't alias.
5276 if (KnownBase1 && KnownBase2) return false;
5278 if (CombinerGlobalAA) {
5279 // Use alias analysis information.
5280 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5281 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5282 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5283 AliasAnalysis::AliasResult AAResult =
5284 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5285 if (AAResult == AliasAnalysis::NoAlias)
5289 // Otherwise we have to assume they alias.
5293 /// FindAliasInfo - Extracts the relevant alias information from the memory
5294 /// node. Returns true if the operand was a load.
5295 bool DAGCombiner::FindAliasInfo(SDNode *N,
5296 SDOperand &Ptr, int64_t &Size,
5297 const Value *&SrcValue, int &SrcValueOffset) {
5298 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5299 Ptr = LD->getBasePtr();
5300 Size = MVT::getSizeInBits(LD->getMemoryVT()) >> 3;
5301 SrcValue = LD->getSrcValue();
5302 SrcValueOffset = LD->getSrcValueOffset();
5304 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5305 Ptr = ST->getBasePtr();
5306 Size = MVT::getSizeInBits(ST->getMemoryVT()) >> 3;
5307 SrcValue = ST->getSrcValue();
5308 SrcValueOffset = ST->getSrcValueOffset();
5310 assert(0 && "FindAliasInfo expected a memory operand");
5316 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5317 /// looking for aliasing nodes and adding them to the Aliases vector.
5318 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5319 SmallVector<SDOperand, 8> &Aliases) {
5320 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5321 std::set<SDNode *> Visited; // Visited node set.
5323 // Get alias information for node.
5326 const Value *SrcValue;
5328 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5331 Chains.push_back(OriginalChain);
5333 // Look at each chain and determine if it is an alias. If so, add it to the
5334 // aliases list. If not, then continue up the chain looking for the next
5336 while (!Chains.empty()) {
5337 SDOperand Chain = Chains.back();
5340 // Don't bother if we've been before.
5341 if (Visited.find(Chain.Val) != Visited.end()) continue;
5342 Visited.insert(Chain.Val);
5344 switch (Chain.getOpcode()) {
5345 case ISD::EntryToken:
5346 // Entry token is ideal chain operand, but handled in FindBetterChain.
5351 // Get alias information for Chain.
5354 const Value *OpSrcValue;
5355 int OpSrcValueOffset;
5356 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5357 OpSrcValue, OpSrcValueOffset);
5359 // If chain is alias then stop here.
5360 if (!(IsLoad && IsOpLoad) &&
5361 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5362 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5363 Aliases.push_back(Chain);
5365 // Look further up the chain.
5366 Chains.push_back(Chain.getOperand(0));
5367 // Clean up old chain.
5368 AddToWorkList(Chain.Val);
5373 case ISD::TokenFactor:
5374 // We have to check each of the operands of the token factor, so we queue
5375 // then up. Adding the operands to the queue (stack) in reverse order
5376 // maintains the original order and increases the likelihood that getNode
5377 // will find a matching token factor (CSE.)
5378 for (unsigned n = Chain.getNumOperands(); n;)
5379 Chains.push_back(Chain.getOperand(--n));
5380 // Eliminate the token factor if we can.
5381 AddToWorkList(Chain.Val);
5385 // For all other instructions we will just have to take what we can get.
5386 Aliases.push_back(Chain);
5392 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5393 /// for a better chain (aliasing node.)
5394 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5395 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5397 // Accumulate all the aliases to this node.
5398 GatherAllAliases(N, OldChain, Aliases);
5400 if (Aliases.size() == 0) {
5401 // If no operands then chain to entry token.
5402 return DAG.getEntryNode();
5403 } else if (Aliases.size() == 1) {
5404 // If a single operand then chain to it. We don't need to revisit it.
5408 // Construct a custom tailored token factor.
5409 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5410 &Aliases[0], Aliases.size());
5412 // Make sure the old chain gets cleaned up.
5413 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5418 // SelectionDAG::Combine - This is the entry point for the file.
5420 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5421 if (!RunningAfterLegalize && ViewDAGCombine1)
5423 if (RunningAfterLegalize && ViewDAGCombine2)
5425 /// run - This is the main entry point to this class.
5427 DAGCombiner(*this, AA).Run(RunningAfterLegalize);