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"
35 STATISTIC(NodesCombined , "Number of dag nodes combined");
36 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
37 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
41 CombinerAA("combiner-alias-analysis", cl::Hidden,
42 cl::desc("Turn on alias analysis during testing"));
45 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
46 cl::desc("Include global information in alias analysis"));
48 //------------------------------ DAGCombiner ---------------------------------//
50 class VISIBILITY_HIDDEN DAGCombiner {
56 // Worklist of all of the nodes that need to be simplified.
57 std::vector<SDNode*> WorkList;
59 // AA - Used for DAG load/store alias analysis.
62 /// AddUsersToWorkList - When an instruction is simplified, add all users of
63 /// the instruction to the work lists because they might get more simplified
66 void AddUsersToWorkList(SDNode *N) {
67 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
72 /// visit - call the node-specific routine that knows how to fold each
73 /// particular type of node.
74 SDValue visit(SDNode *N);
77 /// AddToWorkList - Add to the work list making sure it's instance is at the
78 /// the back (next to be processed.)
79 void AddToWorkList(SDNode *N) {
80 removeFromWorkList(N);
81 WorkList.push_back(N);
84 /// removeFromWorkList - remove all instances of N from the worklist.
86 void removeFromWorkList(SDNode *N) {
87 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
91 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
94 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
95 return CombineTo(N, &Res, 1, AddTo);
98 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
100 SDValue To[] = { Res0, Res1 };
101 return CombineTo(N, To, 2, AddTo);
106 /// SimplifyDemandedBits - Check the specified integer node value to see if
107 /// it can be simplified or if things it uses can be simplified by bit
108 /// propagation. If so, return true.
109 bool SimplifyDemandedBits(SDValue Op) {
110 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
111 return SimplifyDemandedBits(Op, Demanded);
114 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
116 bool CombineToPreIndexedLoadStore(SDNode *N);
117 bool CombineToPostIndexedLoadStore(SDNode *N);
120 /// combine - call the node-specific routine that knows how to fold each
121 /// particular type of node. If that doesn't do anything, try the
122 /// target-specific DAG combines.
123 SDValue combine(SDNode *N);
125 // Visitation implementation - Implement dag node combining for different
126 // node types. The semantics are as follows:
128 // SDValue.getNode() == 0 - No change was made
129 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
130 // otherwise - N should be replaced by the returned Operand.
132 SDValue visitTokenFactor(SDNode *N);
133 SDValue visitMERGE_VALUES(SDNode *N);
134 SDValue visitADD(SDNode *N);
135 SDValue visitSUB(SDNode *N);
136 SDValue visitADDC(SDNode *N);
137 SDValue visitADDE(SDNode *N);
138 SDValue visitMUL(SDNode *N);
139 SDValue visitSDIV(SDNode *N);
140 SDValue visitUDIV(SDNode *N);
141 SDValue visitSREM(SDNode *N);
142 SDValue visitUREM(SDNode *N);
143 SDValue visitMULHU(SDNode *N);
144 SDValue visitMULHS(SDNode *N);
145 SDValue visitSMUL_LOHI(SDNode *N);
146 SDValue visitUMUL_LOHI(SDNode *N);
147 SDValue visitSDIVREM(SDNode *N);
148 SDValue visitUDIVREM(SDNode *N);
149 SDValue visitAND(SDNode *N);
150 SDValue visitOR(SDNode *N);
151 SDValue visitXOR(SDNode *N);
152 SDValue SimplifyVBinOp(SDNode *N);
153 SDValue visitSHL(SDNode *N);
154 SDValue visitSRA(SDNode *N);
155 SDValue visitSRL(SDNode *N);
156 SDValue visitCTLZ(SDNode *N);
157 SDValue visitCTTZ(SDNode *N);
158 SDValue visitCTPOP(SDNode *N);
159 SDValue visitSELECT(SDNode *N);
160 SDValue visitSELECT_CC(SDNode *N);
161 SDValue visitSETCC(SDNode *N);
162 SDValue visitSIGN_EXTEND(SDNode *N);
163 SDValue visitZERO_EXTEND(SDNode *N);
164 SDValue visitANY_EXTEND(SDNode *N);
165 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
166 SDValue visitTRUNCATE(SDNode *N);
167 SDValue visitBIT_CONVERT(SDNode *N);
168 SDValue visitBUILD_PAIR(SDNode *N);
169 SDValue visitFADD(SDNode *N);
170 SDValue visitFSUB(SDNode *N);
171 SDValue visitFMUL(SDNode *N);
172 SDValue visitFDIV(SDNode *N);
173 SDValue visitFREM(SDNode *N);
174 SDValue visitFCOPYSIGN(SDNode *N);
175 SDValue visitSINT_TO_FP(SDNode *N);
176 SDValue visitUINT_TO_FP(SDNode *N);
177 SDValue visitFP_TO_SINT(SDNode *N);
178 SDValue visitFP_TO_UINT(SDNode *N);
179 SDValue visitFP_ROUND(SDNode *N);
180 SDValue visitFP_ROUND_INREG(SDNode *N);
181 SDValue visitFP_EXTEND(SDNode *N);
182 SDValue visitFNEG(SDNode *N);
183 SDValue visitFABS(SDNode *N);
184 SDValue visitBRCOND(SDNode *N);
185 SDValue visitBR_CC(SDNode *N);
186 SDValue visitLOAD(SDNode *N);
187 SDValue visitSTORE(SDNode *N);
188 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
189 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
190 SDValue visitBUILD_VECTOR(SDNode *N);
191 SDValue visitCONCAT_VECTORS(SDNode *N);
192 SDValue visitVECTOR_SHUFFLE(SDNode *N);
194 SDValue XformToShuffleWithZero(SDNode *N);
195 SDValue ReassociateOps(unsigned Opc, SDValue LHS, SDValue RHS);
197 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
199 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
200 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
201 SDValue SimplifySelect(SDValue N0, SDValue N1, SDValue N2);
202 SDValue SimplifySelectCC(SDValue N0, SDValue N1, SDValue N2,
203 SDValue N3, ISD::CondCode CC,
204 bool NotExtCompare = false);
205 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1,
206 ISD::CondCode Cond, bool foldBooleans = true);
207 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
209 SDValue CombineConsecutiveLoads(SDNode *N, MVT VT);
210 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
211 SDValue BuildSDIV(SDNode *N);
212 SDValue BuildUDIV(SDNode *N);
213 SDNode *MatchRotate(SDValue LHS, SDValue RHS);
214 SDValue ReduceLoadWidth(SDNode *N);
216 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
218 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
219 /// looking for aliasing nodes and adding them to the Aliases vector.
220 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
221 SmallVector<SDValue, 8> &Aliases);
223 /// isAlias - Return true if there is any possibility that the two addresses
225 bool isAlias(SDValue Ptr1, int64_t Size1,
226 const Value *SrcValue1, int SrcValueOffset1,
227 SDValue Ptr2, int64_t Size2,
228 const Value *SrcValue2, int SrcValueOffset2);
230 /// FindAliasInfo - Extracts the relevant alias information from the memory
231 /// node. Returns true if the operand was a load.
232 bool FindAliasInfo(SDNode *N,
233 SDValue &Ptr, int64_t &Size,
234 const Value *&SrcValue, int &SrcValueOffset);
236 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
237 /// looking for a better chain (aliasing node.)
238 SDValue FindBetterChain(SDNode *N, SDValue Chain);
241 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, bool fast)
243 TLI(D.getTargetLoweringInfo()),
244 AfterLegalize(false),
248 /// Run - runs the dag combiner on all nodes in the work list
249 void Run(bool RunningAfterLegalize);
255 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
256 /// nodes from the worklist.
257 class VISIBILITY_HIDDEN WorkListRemover :
258 public SelectionDAG::DAGUpdateListener {
261 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
263 virtual void NodeDeleted(SDNode *N, SDNode *E) {
264 DC.removeFromWorkList(N);
267 virtual void NodeUpdated(SDNode *N) {
273 //===----------------------------------------------------------------------===//
274 // TargetLowering::DAGCombinerInfo implementation
275 //===----------------------------------------------------------------------===//
277 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
278 ((DAGCombiner*)DC)->AddToWorkList(N);
281 SDValue TargetLowering::DAGCombinerInfo::
282 CombineTo(SDNode *N, const std::vector<SDValue> &To) {
283 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
286 SDValue TargetLowering::DAGCombinerInfo::
287 CombineTo(SDNode *N, SDValue Res) {
288 return ((DAGCombiner*)DC)->CombineTo(N, Res);
292 SDValue TargetLowering::DAGCombinerInfo::
293 CombineTo(SDNode *N, SDValue Res0, SDValue Res1) {
294 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
298 //===----------------------------------------------------------------------===//
300 //===----------------------------------------------------------------------===//
302 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
303 /// specified expression for the same cost as the expression itself, or 2 if we
304 /// can compute the negated form more cheaply than the expression itself.
305 static char isNegatibleForFree(SDValue Op, bool AfterLegalize,
306 unsigned Depth = 0) {
307 // No compile time optimizations on this type.
308 if (Op.getValueType() == MVT::ppcf128)
311 // fneg is removable even if it has multiple uses.
312 if (Op.getOpcode() == ISD::FNEG) return 2;
314 // Don't allow anything with multiple uses.
315 if (!Op.hasOneUse()) return 0;
317 // Don't recurse exponentially.
318 if (Depth > 6) return 0;
320 switch (Op.getOpcode()) {
321 default: return false;
322 case ISD::ConstantFP:
323 // Don't invert constant FP values after legalize. The negated constant
324 // isn't necessarily legal.
325 return AfterLegalize ? 0 : 1;
327 // FIXME: determine better conditions for this xform.
328 if (!UnsafeFPMath) return 0;
331 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
334 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
336 // We can't turn -(A-B) into B-A when we honor signed zeros.
337 if (!UnsafeFPMath) return 0;
344 if (HonorSignDependentRoundingFPMath()) return 0;
346 // -(X*Y) -> (-X * Y) or (X*-Y)
347 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
350 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
355 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
359 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
360 /// returns the newly negated expression.
361 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
362 bool AfterLegalize, unsigned Depth = 0) {
363 // fneg is removable even if it has multiple uses.
364 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
366 // Don't allow anything with multiple uses.
367 assert(Op.hasOneUse() && "Unknown reuse!");
369 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
370 switch (Op.getOpcode()) {
371 default: assert(0 && "Unknown code");
372 case ISD::ConstantFP: {
373 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
375 return DAG.getConstantFP(V, Op.getValueType());
378 // FIXME: determine better conditions for this xform.
379 assert(UnsafeFPMath);
382 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
383 return DAG.getNode(ISD::FSUB, Op.getValueType(),
384 GetNegatedExpression(Op.getOperand(0), DAG,
385 AfterLegalize, Depth+1),
388 return DAG.getNode(ISD::FSUB, Op.getValueType(),
389 GetNegatedExpression(Op.getOperand(1), DAG,
390 AfterLegalize, Depth+1),
393 // We can't turn -(A-B) into B-A when we honor signed zeros.
394 assert(UnsafeFPMath);
397 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
398 if (N0CFP->getValueAPF().isZero())
399 return Op.getOperand(1);
402 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
407 assert(!HonorSignDependentRoundingFPMath());
410 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
411 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
412 GetNegatedExpression(Op.getOperand(0), DAG,
413 AfterLegalize, Depth+1),
417 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
419 GetNegatedExpression(Op.getOperand(1), DAG,
420 AfterLegalize, Depth+1));
424 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
425 GetNegatedExpression(Op.getOperand(0), DAG,
426 AfterLegalize, Depth+1));
428 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(0), DAG,
430 AfterLegalize, Depth+1),
436 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
437 // that selects between the values 1 and 0, making it equivalent to a setcc.
438 // Also, set the incoming LHS, RHS, and CC references to the appropriate
439 // nodes based on the type of node we are checking. This simplifies life a
440 // bit for the callers.
441 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
443 if (N.getOpcode() == ISD::SETCC) {
444 LHS = N.getOperand(0);
445 RHS = N.getOperand(1);
446 CC = N.getOperand(2);
449 if (N.getOpcode() == ISD::SELECT_CC &&
450 N.getOperand(2).getOpcode() == ISD::Constant &&
451 N.getOperand(3).getOpcode() == ISD::Constant &&
452 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
453 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
454 LHS = N.getOperand(0);
455 RHS = N.getOperand(1);
456 CC = N.getOperand(4);
462 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
463 // one use. If this is true, it allows the users to invert the operation for
464 // free when it is profitable to do so.
465 static bool isOneUseSetCC(SDValue N) {
467 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
472 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDValue N0, SDValue N1){
473 MVT VT = N0.getValueType();
474 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
475 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
476 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
477 if (isa<ConstantSDNode>(N1)) {
478 SDValue OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
479 AddToWorkList(OpNode.getNode());
480 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
481 } else if (N0.hasOneUse()) {
482 SDValue OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
483 AddToWorkList(OpNode.getNode());
484 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
487 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
488 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
489 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
490 if (isa<ConstantSDNode>(N0)) {
491 SDValue OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
492 AddToWorkList(OpNode.getNode());
493 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
494 } else if (N1.hasOneUse()) {
495 SDValue OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
496 AddToWorkList(OpNode.getNode());
497 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
503 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
505 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
507 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
508 DOUT << "\nWith: "; DEBUG(To[0].getNode()->dump(&DAG));
509 DOUT << " and " << NumTo-1 << " other values\n";
510 WorkListRemover DeadNodes(*this);
511 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
514 // Push the new nodes and any users onto the worklist
515 for (unsigned i = 0, e = NumTo; i != e; ++i) {
516 AddToWorkList(To[i].getNode());
517 AddUsersToWorkList(To[i].getNode());
521 // Nodes can be reintroduced into the worklist. Make sure we do not
522 // process a node that has been replaced.
523 removeFromWorkList(N);
525 // Finally, since the node is now dead, remove it from the graph.
527 return SDValue(N, 0);
530 /// SimplifyDemandedBits - Check the specified integer node value to see if
531 /// it can be simplified or if things it uses can be simplified by bit
532 /// propagation. If so, return true.
533 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
534 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
535 APInt KnownZero, KnownOne;
536 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
540 AddToWorkList(Op.getNode());
542 // Replace the old value with the new one.
544 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.getNode()->dump(&DAG));
545 DOUT << "\nWith: "; DEBUG(TLO.New.getNode()->dump(&DAG));
548 // Replace all uses. If any nodes become isomorphic to other nodes and
549 // are deleted, make sure to remove them from our worklist.
550 WorkListRemover DeadNodes(*this);
551 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
553 // Push the new node and any (possibly new) users onto the worklist.
554 AddToWorkList(TLO.New.getNode());
555 AddUsersToWorkList(TLO.New.getNode());
557 // Finally, if the node is now dead, remove it from the graph. The node
558 // may not be dead if the replacement process recursively simplified to
559 // something else needing this node.
560 if (TLO.Old.getNode()->use_empty()) {
561 removeFromWorkList(TLO.Old.getNode());
563 // If the operands of this node are only used by the node, they will now
564 // be dead. Make sure to visit them first to delete dead nodes early.
565 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
566 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
567 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
569 DAG.DeleteNode(TLO.Old.getNode());
574 //===----------------------------------------------------------------------===//
575 // Main DAG Combiner implementation
576 //===----------------------------------------------------------------------===//
578 void DAGCombiner::Run(bool RunningAfterLegalize) {
579 // set the instance variable, so that the various visit routines may use it.
580 AfterLegalize = RunningAfterLegalize;
582 // Add all the dag nodes to the worklist.
583 WorkList.reserve(DAG.allnodes_size());
584 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
585 E = DAG.allnodes_end(); I != E; ++I)
586 WorkList.push_back(I);
588 // Create a dummy node (which is not added to allnodes), that adds a reference
589 // to the root node, preventing it from being deleted, and tracking any
590 // changes of the root.
591 HandleSDNode Dummy(DAG.getRoot());
593 // The root of the dag may dangle to deleted nodes until the dag combiner is
594 // done. Set it to null to avoid confusion.
595 DAG.setRoot(SDValue());
597 // while the worklist isn't empty, inspect the node on the end of it and
598 // try and combine it.
599 while (!WorkList.empty()) {
600 SDNode *N = WorkList.back();
603 // If N has no uses, it is dead. Make sure to revisit all N's operands once
604 // N is deleted from the DAG, since they too may now be dead or may have a
605 // reduced number of uses, allowing other xforms.
606 if (N->use_empty() && N != &Dummy) {
607 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
608 AddToWorkList(N->getOperand(i).getNode());
614 SDValue RV = combine(N);
616 if (RV.getNode() == 0)
621 // If we get back the same node we passed in, rather than a new node or
622 // zero, we know that the node must have defined multiple values and
623 // CombineTo was used. Since CombineTo takes care of the worklist
624 // mechanics for us, we have no work to do in this case.
625 if (RV.getNode() == N)
628 assert(N->getOpcode() != ISD::DELETED_NODE &&
629 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
630 "Node was deleted but visit returned new node!");
632 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
633 DOUT << "\nWith: "; DEBUG(RV.getNode()->dump(&DAG));
635 WorkListRemover DeadNodes(*this);
636 if (N->getNumValues() == RV.getNode()->getNumValues())
637 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
639 assert(N->getValueType(0) == RV.getValueType() &&
640 N->getNumValues() == 1 && "Type mismatch");
642 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
645 // Push the new node and any users onto the worklist
646 AddToWorkList(RV.getNode());
647 AddUsersToWorkList(RV.getNode());
649 // Add any uses of the old node to the worklist in case this node is the
650 // last one that uses them. They may become dead after this node is
652 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
653 AddToWorkList(N->getOperand(i).getNode());
655 // Nodes can be reintroduced into the worklist. Make sure we do not
656 // process a node that has been replaced.
657 removeFromWorkList(N);
659 // Finally, since the node is now dead, remove it from the graph.
663 // If the root changed (e.g. it was a dead load, update the root).
664 DAG.setRoot(Dummy.getValue());
667 SDValue DAGCombiner::visit(SDNode *N) {
668 switch(N->getOpcode()) {
670 case ISD::TokenFactor: return visitTokenFactor(N);
671 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
672 case ISD::ADD: return visitADD(N);
673 case ISD::SUB: return visitSUB(N);
674 case ISD::ADDC: return visitADDC(N);
675 case ISD::ADDE: return visitADDE(N);
676 case ISD::MUL: return visitMUL(N);
677 case ISD::SDIV: return visitSDIV(N);
678 case ISD::UDIV: return visitUDIV(N);
679 case ISD::SREM: return visitSREM(N);
680 case ISD::UREM: return visitUREM(N);
681 case ISD::MULHU: return visitMULHU(N);
682 case ISD::MULHS: return visitMULHS(N);
683 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
684 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
685 case ISD::SDIVREM: return visitSDIVREM(N);
686 case ISD::UDIVREM: return visitUDIVREM(N);
687 case ISD::AND: return visitAND(N);
688 case ISD::OR: return visitOR(N);
689 case ISD::XOR: return visitXOR(N);
690 case ISD::SHL: return visitSHL(N);
691 case ISD::SRA: return visitSRA(N);
692 case ISD::SRL: return visitSRL(N);
693 case ISD::CTLZ: return visitCTLZ(N);
694 case ISD::CTTZ: return visitCTTZ(N);
695 case ISD::CTPOP: return visitCTPOP(N);
696 case ISD::SELECT: return visitSELECT(N);
697 case ISD::SELECT_CC: return visitSELECT_CC(N);
698 case ISD::SETCC: return visitSETCC(N);
699 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
700 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
701 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
702 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
703 case ISD::TRUNCATE: return visitTRUNCATE(N);
704 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
705 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
706 case ISD::FADD: return visitFADD(N);
707 case ISD::FSUB: return visitFSUB(N);
708 case ISD::FMUL: return visitFMUL(N);
709 case ISD::FDIV: return visitFDIV(N);
710 case ISD::FREM: return visitFREM(N);
711 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
712 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
713 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
714 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
715 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
716 case ISD::FP_ROUND: return visitFP_ROUND(N);
717 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
718 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
719 case ISD::FNEG: return visitFNEG(N);
720 case ISD::FABS: return visitFABS(N);
721 case ISD::BRCOND: return visitBRCOND(N);
722 case ISD::BR_CC: return visitBR_CC(N);
723 case ISD::LOAD: return visitLOAD(N);
724 case ISD::STORE: return visitSTORE(N);
725 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
726 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
727 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
728 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
729 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
734 SDValue DAGCombiner::combine(SDNode *N) {
736 SDValue RV = visit(N);
738 // If nothing happened, try a target-specific DAG combine.
739 if (RV.getNode() == 0) {
740 assert(N->getOpcode() != ISD::DELETED_NODE &&
741 "Node was deleted but visit returned NULL!");
743 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
744 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
746 // Expose the DAG combiner to the target combiner impls.
747 TargetLowering::DAGCombinerInfo
748 DagCombineInfo(DAG, !AfterLegalize, false, this);
750 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
754 // If N is a commutative binary node, try commuting it to enable more
756 if (RV.getNode() == 0 &&
757 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
758 N->getNumValues() == 1) {
759 SDValue N0 = N->getOperand(0);
760 SDValue N1 = N->getOperand(1);
761 // Constant operands are canonicalized to RHS.
762 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
763 SDValue Ops[] = { N1, N0 };
764 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
767 return SDValue(CSENode, 0);
774 /// getInputChainForNode - Given a node, return its input chain if it has one,
775 /// otherwise return a null sd operand.
776 static SDValue getInputChainForNode(SDNode *N) {
777 if (unsigned NumOps = N->getNumOperands()) {
778 if (N->getOperand(0).getValueType() == MVT::Other)
779 return N->getOperand(0);
780 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
781 return N->getOperand(NumOps-1);
782 for (unsigned i = 1; i < NumOps-1; ++i)
783 if (N->getOperand(i).getValueType() == MVT::Other)
784 return N->getOperand(i);
786 return SDValue(0, 0);
789 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
790 // If N has two operands, where one has an input chain equal to the other,
791 // the 'other' chain is redundant.
792 if (N->getNumOperands() == 2) {
793 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
794 return N->getOperand(0);
795 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
796 return N->getOperand(1);
799 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
800 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
801 SmallPtrSet<SDNode*, 16> SeenOps;
802 bool Changed = false; // If we should replace this token factor.
804 // Start out with this token factor.
807 // Iterate through token factors. The TFs grows when new token factors are
809 for (unsigned i = 0; i < TFs.size(); ++i) {
812 // Check each of the operands.
813 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
814 SDValue Op = TF->getOperand(i);
816 switch (Op.getOpcode()) {
817 case ISD::EntryToken:
818 // Entry tokens don't need to be added to the list. They are
823 case ISD::TokenFactor:
824 if ((CombinerAA || Op.hasOneUse()) &&
825 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
826 // Queue up for processing.
827 TFs.push_back(Op.getNode());
828 // Clean up in case the token factor is removed.
829 AddToWorkList(Op.getNode());
836 // Only add if it isn't already in the list.
837 if (SeenOps.insert(Op.getNode()))
848 // If we've change things around then replace token factor.
851 // The entry token is the only possible outcome.
852 Result = DAG.getEntryNode();
854 // New and improved token factor.
855 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
858 // Don't add users to work list.
859 return CombineTo(N, Result, false);
865 /// MERGE_VALUES can always be eliminated.
866 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
867 WorkListRemover DeadNodes(*this);
868 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
869 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
871 removeFromWorkList(N);
873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
878 SDValue combineShlAddConstant(SDValue N0, SDValue N1, SelectionDAG &DAG) {
879 MVT VT = N0.getValueType();
880 SDValue N00 = N0.getOperand(0);
881 SDValue N01 = N0.getOperand(1);
882 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
883 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
884 isa<ConstantSDNode>(N00.getOperand(1))) {
885 N0 = DAG.getNode(ISD::ADD, VT,
886 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
887 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
888 return DAG.getNode(ISD::ADD, VT, N0, N1);
894 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
896 MVT VT = N->getValueType(0);
897 unsigned Opc = N->getOpcode();
898 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
899 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
900 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
901 ISD::CondCode CC = ISD::SETCC_INVALID;
903 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
905 SDValue CCOp = Slct.getOperand(0);
906 if (CCOp.getOpcode() == ISD::SETCC)
907 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
910 bool DoXform = false;
912 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
914 if (LHS.getOpcode() == ISD::Constant &&
915 cast<ConstantSDNode>(LHS)->isNullValue())
917 else if (CC != ISD::SETCC_INVALID &&
918 RHS.getOpcode() == ISD::Constant &&
919 cast<ConstantSDNode>(RHS)->isNullValue()) {
921 SDValue Op0 = Slct.getOperand(0);
922 bool isInt = (isSlctCC ? Op0.getValueType() :
923 Op0.getOperand(0).getValueType()).isInteger();
924 CC = ISD::getSetCCInverse(CC, isInt);
930 SDValue Result = DAG.getNode(Opc, VT, OtherOp, RHS);
932 return DAG.getSelectCC(OtherOp, Result,
933 Slct.getOperand(0), Slct.getOperand(1), CC);
934 SDValue CCOp = Slct.getOperand(0);
936 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
937 CCOp.getOperand(1), CC);
938 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
943 SDValue DAGCombiner::visitADD(SDNode *N) {
944 SDValue N0 = N->getOperand(0);
945 SDValue N1 = N->getOperand(1);
946 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
947 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
948 MVT VT = N0.getValueType();
952 SDValue FoldedVOp = SimplifyVBinOp(N);
953 if (FoldedVOp.getNode()) return FoldedVOp;
956 // fold (add x, undef) -> undef
957 if (N0.getOpcode() == ISD::UNDEF)
959 if (N1.getOpcode() == ISD::UNDEF)
961 // fold (add c1, c2) -> c1+c2
963 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
964 // canonicalize constant to RHS
966 return DAG.getNode(ISD::ADD, VT, N1, N0);
967 // fold (add x, 0) -> x
968 if (N1C && N1C->isNullValue())
970 // fold (add Sym, c) -> Sym+c
971 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
972 if (!AfterLegalize && TLI.isOffsetFoldingLegal(GA) && N1C &&
973 GA->getOpcode() == ISD::GlobalAddress)
974 return DAG.getGlobalAddress(GA->getGlobal(), VT,
976 (uint64_t)N1C->getSExtValue());
977 // fold ((c1-A)+c2) -> (c1+c2)-A
978 if (N1C && N0.getOpcode() == ISD::SUB)
979 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
980 return DAG.getNode(ISD::SUB, VT,
981 DAG.getConstant(N1C->getAPIntValue()+
982 N0C->getAPIntValue(), VT),
985 SDValue RADD = ReassociateOps(ISD::ADD, N0, N1);
986 if (RADD.getNode() != 0)
988 // fold ((0-A) + B) -> B-A
989 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
990 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
991 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
992 // fold (A + (0-B)) -> A-B
993 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
994 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
995 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
996 // fold (A+(B-A)) -> B
997 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
998 return N1.getOperand(0);
1000 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1001 return SDValue(N, 0);
1003 // fold (a+b) -> (a|b) iff a and b share no bits.
1004 if (VT.isInteger() && !VT.isVector()) {
1005 APInt LHSZero, LHSOne;
1006 APInt RHSZero, RHSOne;
1007 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1008 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1009 if (LHSZero.getBoolValue()) {
1010 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1012 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1013 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1014 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1015 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1016 return DAG.getNode(ISD::OR, VT, N0, N1);
1020 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1021 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1022 SDValue Result = combineShlAddConstant(N0, N1, DAG);
1023 if (Result.getNode()) return Result;
1025 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1026 SDValue Result = combineShlAddConstant(N1, N0, DAG);
1027 if (Result.getNode()) return Result;
1030 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1031 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
1032 SDValue Result = combineSelectAndUse(N, N0, N1, DAG);
1033 if (Result.getNode()) return Result;
1035 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1036 SDValue Result = combineSelectAndUse(N, N1, N0, DAG);
1037 if (Result.getNode()) return Result;
1043 SDValue DAGCombiner::visitADDC(SDNode *N) {
1044 SDValue N0 = N->getOperand(0);
1045 SDValue N1 = N->getOperand(1);
1046 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1048 MVT VT = N0.getValueType();
1050 // If the flag result is dead, turn this into an ADD.
1051 if (N->hasNUsesOfValue(0, 1))
1052 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1053 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1055 // canonicalize constant to RHS.
1057 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1059 // fold (addc x, 0) -> x + no carry out
1060 if (N1C && N1C->isNullValue())
1061 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1063 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1064 APInt LHSZero, LHSOne;
1065 APInt RHSZero, RHSOne;
1066 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1067 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1068 if (LHSZero.getBoolValue()) {
1069 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1071 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1072 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1073 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1074 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1075 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1076 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1082 SDValue DAGCombiner::visitADDE(SDNode *N) {
1083 SDValue N0 = N->getOperand(0);
1084 SDValue N1 = N->getOperand(1);
1085 SDValue CarryIn = N->getOperand(2);
1086 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1087 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1088 //MVT VT = N0.getValueType();
1090 // canonicalize constant to RHS
1092 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn);
1094 // fold (adde x, y, false) -> (addc x, y)
1095 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1096 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1103 SDValue DAGCombiner::visitSUB(SDNode *N) {
1104 SDValue N0 = N->getOperand(0);
1105 SDValue N1 = N->getOperand(1);
1106 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1107 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1108 MVT VT = N0.getValueType();
1111 if (VT.isVector()) {
1112 SDValue FoldedVOp = SimplifyVBinOp(N);
1113 if (FoldedVOp.getNode()) return FoldedVOp;
1116 // fold (sub x, x) -> 0
1118 return DAG.getConstant(0, N->getValueType(0));
1119 // fold (sub c1, c2) -> c1-c2
1121 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1122 // fold (sub x, c) -> (add x, -c)
1124 return DAG.getNode(ISD::ADD, VT, N0,
1125 DAG.getConstant(-N1C->getAPIntValue(), VT));
1126 // fold (A+B)-A -> B
1127 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1128 return N0.getOperand(1);
1129 // fold (A+B)-B -> A
1130 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1131 return N0.getOperand(0);
1132 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1133 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1134 SDValue Result = combineSelectAndUse(N, N1, N0, DAG);
1135 if (Result.getNode()) return Result;
1137 // If either operand of a sub is undef, the result is undef
1138 if (N0.getOpcode() == ISD::UNDEF)
1140 if (N1.getOpcode() == ISD::UNDEF)
1143 // If the relocation model supports it, consider symbol offsets.
1144 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1145 if (!AfterLegalize && TLI.isOffsetFoldingLegal(GA)) {
1146 // fold (sub Sym, c) -> Sym-c
1147 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1148 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1150 (uint64_t)N1C->getSExtValue());
1151 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1152 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1153 if (GA->getGlobal() == GB->getGlobal())
1154 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1161 SDValue DAGCombiner::visitMUL(SDNode *N) {
1162 SDValue N0 = N->getOperand(0);
1163 SDValue N1 = N->getOperand(1);
1164 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1165 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1166 MVT VT = N0.getValueType();
1169 if (VT.isVector()) {
1170 SDValue FoldedVOp = SimplifyVBinOp(N);
1171 if (FoldedVOp.getNode()) return FoldedVOp;
1174 // fold (mul x, undef) -> 0
1175 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1176 return DAG.getConstant(0, VT);
1177 // fold (mul c1, c2) -> c1*c2
1179 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1180 // canonicalize constant to RHS
1182 return DAG.getNode(ISD::MUL, VT, N1, N0);
1183 // fold (mul x, 0) -> 0
1184 if (N1C && N1C->isNullValue())
1186 // fold (mul x, -1) -> 0-x
1187 if (N1C && N1C->isAllOnesValue())
1188 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1189 // fold (mul x, (1 << c)) -> x << c
1190 if (N1C && N1C->getAPIntValue().isPowerOf2())
1191 return DAG.getNode(ISD::SHL, VT, N0,
1192 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1193 TLI.getShiftAmountTy()));
1194 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1195 if (N1C && isPowerOf2_64(-N1C->getSExtValue())) {
1196 // FIXME: If the input is something that is easily negated (e.g. a
1197 // single-use add), we should put the negate there.
1198 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1199 DAG.getNode(ISD::SHL, VT, N0,
1200 DAG.getConstant(Log2_64(-N1C->getSExtValue()),
1201 TLI.getShiftAmountTy())));
1204 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1205 if (N1C && N0.getOpcode() == ISD::SHL &&
1206 isa<ConstantSDNode>(N0.getOperand(1))) {
1207 SDValue C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1208 AddToWorkList(C3.getNode());
1209 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1212 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1215 SDValue Sh(0,0), Y(0,0);
1216 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1217 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1218 N0.getNode()->hasOneUse()) {
1220 } else if (N1.getOpcode() == ISD::SHL &&
1221 isa<ConstantSDNode>(N1.getOperand(1)) &&
1222 N1.getNode()->hasOneUse()) {
1226 SDValue Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1227 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1230 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1231 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1232 isa<ConstantSDNode>(N0.getOperand(1))) {
1233 return DAG.getNode(ISD::ADD, VT,
1234 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1235 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1239 SDValue RMUL = ReassociateOps(ISD::MUL, N0, N1);
1240 if (RMUL.getNode() != 0)
1246 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1247 SDValue N0 = N->getOperand(0);
1248 SDValue N1 = N->getOperand(1);
1249 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1250 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1251 MVT VT = N->getValueType(0);
1254 if (VT.isVector()) {
1255 SDValue FoldedVOp = SimplifyVBinOp(N);
1256 if (FoldedVOp.getNode()) return FoldedVOp;
1259 // fold (sdiv c1, c2) -> c1/c2
1260 if (N0C && N1C && !N1C->isNullValue())
1261 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1262 // fold (sdiv X, 1) -> X
1263 if (N1C && N1C->getSExtValue() == 1LL)
1265 // fold (sdiv X, -1) -> 0-X
1266 if (N1C && N1C->isAllOnesValue())
1267 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1268 // If we know the sign bits of both operands are zero, strength reduce to a
1269 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1270 if (!VT.isVector()) {
1271 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1272 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1274 // fold (sdiv X, pow2) -> simple ops after legalize
1275 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1276 (isPowerOf2_64(N1C->getSExtValue()) ||
1277 isPowerOf2_64(-N1C->getSExtValue()))) {
1278 // If dividing by powers of two is cheap, then don't perform the following
1280 if (TLI.isPow2DivCheap())
1282 int64_t pow2 = N1C->getSExtValue();
1283 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1284 unsigned lg2 = Log2_64(abs2);
1285 // Splat the sign bit into the register
1286 SDValue SGN = DAG.getNode(ISD::SRA, VT, N0,
1287 DAG.getConstant(VT.getSizeInBits()-1,
1288 TLI.getShiftAmountTy()));
1289 AddToWorkList(SGN.getNode());
1290 // Add (N0 < 0) ? abs2 - 1 : 0;
1291 SDValue SRL = DAG.getNode(ISD::SRL, VT, SGN,
1292 DAG.getConstant(VT.getSizeInBits()-lg2,
1293 TLI.getShiftAmountTy()));
1294 SDValue ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1295 AddToWorkList(SRL.getNode());
1296 AddToWorkList(ADD.getNode()); // Divide by pow2
1297 SDValue SRA = DAG.getNode(ISD::SRA, VT, ADD,
1298 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1299 // If we're dividing by a positive value, we're done. Otherwise, we must
1300 // negate the result.
1303 AddToWorkList(SRA.getNode());
1304 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1306 // if integer divide is expensive and we satisfy the requirements, emit an
1307 // alternate sequence.
1308 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1309 !TLI.isIntDivCheap()) {
1310 SDValue Op = BuildSDIV(N);
1311 if (Op.getNode()) return Op;
1315 if (N0.getOpcode() == ISD::UNDEF)
1316 return DAG.getConstant(0, VT);
1317 // X / undef -> undef
1318 if (N1.getOpcode() == ISD::UNDEF)
1324 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1325 SDValue N0 = N->getOperand(0);
1326 SDValue N1 = N->getOperand(1);
1327 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1328 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1329 MVT VT = N->getValueType(0);
1332 if (VT.isVector()) {
1333 SDValue FoldedVOp = SimplifyVBinOp(N);
1334 if (FoldedVOp.getNode()) return FoldedVOp;
1337 // fold (udiv c1, c2) -> c1/c2
1338 if (N0C && N1C && !N1C->isNullValue())
1339 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1340 // fold (udiv x, (1 << c)) -> x >>u c
1341 if (N1C && N1C->getAPIntValue().isPowerOf2())
1342 return DAG.getNode(ISD::SRL, VT, N0,
1343 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1344 TLI.getShiftAmountTy()));
1345 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1346 if (N1.getOpcode() == ISD::SHL) {
1347 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1348 if (SHC->getAPIntValue().isPowerOf2()) {
1349 MVT ADDVT = N1.getOperand(1).getValueType();
1350 SDValue Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1351 DAG.getConstant(SHC->getAPIntValue()
1354 AddToWorkList(Add.getNode());
1355 return DAG.getNode(ISD::SRL, VT, N0, Add);
1359 // fold (udiv x, c) -> alternate
1360 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1361 SDValue Op = BuildUDIV(N);
1362 if (Op.getNode()) return Op;
1366 if (N0.getOpcode() == ISD::UNDEF)
1367 return DAG.getConstant(0, VT);
1368 // X / undef -> undef
1369 if (N1.getOpcode() == ISD::UNDEF)
1375 SDValue DAGCombiner::visitSREM(SDNode *N) {
1376 SDValue N0 = N->getOperand(0);
1377 SDValue N1 = N->getOperand(1);
1378 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1379 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1380 MVT VT = N->getValueType(0);
1382 // fold (srem c1, c2) -> c1%c2
1383 if (N0C && N1C && !N1C->isNullValue())
1384 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1385 // If we know the sign bits of both operands are zero, strength reduce to a
1386 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1387 if (!VT.isVector()) {
1388 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1389 return DAG.getNode(ISD::UREM, VT, N0, N1);
1392 // If X/C can be simplified by the division-by-constant logic, lower
1393 // X%C to the equivalent of X-X/C*C.
1394 if (N1C && !N1C->isNullValue()) {
1395 SDValue Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1396 AddToWorkList(Div.getNode());
1397 SDValue OptimizedDiv = combine(Div.getNode());
1398 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1399 SDValue Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1400 SDValue Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1401 AddToWorkList(Mul.getNode());
1407 if (N0.getOpcode() == ISD::UNDEF)
1408 return DAG.getConstant(0, VT);
1409 // X % undef -> undef
1410 if (N1.getOpcode() == ISD::UNDEF)
1416 SDValue DAGCombiner::visitUREM(SDNode *N) {
1417 SDValue N0 = N->getOperand(0);
1418 SDValue N1 = N->getOperand(1);
1419 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1420 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1421 MVT VT = N->getValueType(0);
1423 // fold (urem c1, c2) -> c1%c2
1424 if (N0C && N1C && !N1C->isNullValue())
1425 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1426 // fold (urem x, pow2) -> (and x, pow2-1)
1427 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1428 return DAG.getNode(ISD::AND, VT, N0,
1429 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1430 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1431 if (N1.getOpcode() == ISD::SHL) {
1432 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1433 if (SHC->getAPIntValue().isPowerOf2()) {
1435 DAG.getNode(ISD::ADD, VT, N1,
1436 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1438 AddToWorkList(Add.getNode());
1439 return DAG.getNode(ISD::AND, VT, N0, Add);
1444 // If X/C can be simplified by the division-by-constant logic, lower
1445 // X%C to the equivalent of X-X/C*C.
1446 if (N1C && !N1C->isNullValue()) {
1447 SDValue Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1448 AddToWorkList(Div.getNode());
1449 SDValue OptimizedDiv = combine(Div.getNode());
1450 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1451 SDValue Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1452 SDValue Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1453 AddToWorkList(Mul.getNode());
1459 if (N0.getOpcode() == ISD::UNDEF)
1460 return DAG.getConstant(0, VT);
1461 // X % undef -> undef
1462 if (N1.getOpcode() == ISD::UNDEF)
1468 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1469 SDValue N0 = N->getOperand(0);
1470 SDValue N1 = N->getOperand(1);
1471 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1472 MVT VT = N->getValueType(0);
1474 // fold (mulhs x, 0) -> 0
1475 if (N1C && N1C->isNullValue())
1477 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1478 if (N1C && N1C->getAPIntValue() == 1)
1479 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1480 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1481 TLI.getShiftAmountTy()));
1482 // fold (mulhs x, undef) -> 0
1483 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1484 return DAG.getConstant(0, VT);
1489 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1490 SDValue N0 = N->getOperand(0);
1491 SDValue N1 = N->getOperand(1);
1492 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1493 MVT VT = N->getValueType(0);
1495 // fold (mulhu x, 0) -> 0
1496 if (N1C && N1C->isNullValue())
1498 // fold (mulhu x, 1) -> 0
1499 if (N1C && N1C->getAPIntValue() == 1)
1500 return DAG.getConstant(0, N0.getValueType());
1501 // fold (mulhu x, undef) -> 0
1502 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1503 return DAG.getConstant(0, VT);
1508 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1509 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1510 /// that are being performed. Return true if a simplification was made.
1512 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1514 // If the high half is not needed, just compute the low half.
1515 bool HiExists = N->hasAnyUseOfValue(1);
1518 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1519 SDValue Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1520 N->getNumOperands());
1521 return CombineTo(N, Res, Res);
1524 // If the low half is not needed, just compute the high half.
1525 bool LoExists = N->hasAnyUseOfValue(0);
1528 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1529 SDValue Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1530 N->getNumOperands());
1531 return CombineTo(N, Res, Res);
1534 // If both halves are used, return as it is.
1535 if (LoExists && HiExists)
1538 // If the two computed results can be simplified separately, separate them.
1540 SDValue Lo = DAG.getNode(LoOp, N->getValueType(0),
1541 N->op_begin(), N->getNumOperands());
1542 AddToWorkList(Lo.getNode());
1543 SDValue LoOpt = combine(Lo.getNode());
1544 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1546 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1547 return CombineTo(N, LoOpt, LoOpt);
1551 SDValue Hi = DAG.getNode(HiOp, N->getValueType(1),
1552 N->op_begin(), N->getNumOperands());
1553 AddToWorkList(Hi.getNode());
1554 SDValue HiOpt = combine(Hi.getNode());
1555 if (HiOpt.getNode() && HiOpt != Hi &&
1557 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1558 return CombineTo(N, HiOpt, HiOpt);
1563 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1564 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1565 if (Res.getNode()) return Res;
1570 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1571 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1572 if (Res.getNode()) return Res;
1577 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1578 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1579 if (Res.getNode()) return Res;
1584 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1585 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1586 if (Res.getNode()) return Res;
1591 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1592 /// two operands of the same opcode, try to simplify it.
1593 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1594 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1595 MVT VT = N0.getValueType();
1596 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1598 // For each of OP in AND/OR/XOR:
1599 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1600 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1601 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1602 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1603 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1604 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1605 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1606 SDValue ORNode = DAG.getNode(N->getOpcode(),
1607 N0.getOperand(0).getValueType(),
1608 N0.getOperand(0), N1.getOperand(0));
1609 AddToWorkList(ORNode.getNode());
1610 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1613 // For each of OP in SHL/SRL/SRA/AND...
1614 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1615 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1616 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1617 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1618 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1619 N0.getOperand(1) == N1.getOperand(1)) {
1620 SDValue ORNode = DAG.getNode(N->getOpcode(),
1621 N0.getOperand(0).getValueType(),
1622 N0.getOperand(0), N1.getOperand(0));
1623 AddToWorkList(ORNode.getNode());
1624 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1630 SDValue DAGCombiner::visitAND(SDNode *N) {
1631 SDValue N0 = N->getOperand(0);
1632 SDValue N1 = N->getOperand(1);
1633 SDValue LL, LR, RL, RR, CC0, CC1;
1634 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1635 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1636 MVT VT = N1.getValueType();
1637 unsigned BitWidth = VT.getSizeInBits();
1640 if (VT.isVector()) {
1641 SDValue FoldedVOp = SimplifyVBinOp(N);
1642 if (FoldedVOp.getNode()) return FoldedVOp;
1645 // fold (and x, undef) -> 0
1646 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1647 return DAG.getConstant(0, VT);
1648 // fold (and c1, c2) -> c1&c2
1650 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1651 // canonicalize constant to RHS
1653 return DAG.getNode(ISD::AND, VT, N1, N0);
1654 // fold (and x, -1) -> x
1655 if (N1C && N1C->isAllOnesValue())
1657 // if (and x, c) is known to be zero, return 0
1658 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1659 APInt::getAllOnesValue(BitWidth)))
1660 return DAG.getConstant(0, VT);
1662 SDValue RAND = ReassociateOps(ISD::AND, N0, N1);
1663 if (RAND.getNode() != 0)
1665 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1666 if (N1C && N0.getOpcode() == ISD::OR)
1667 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1668 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1670 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1671 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1672 SDValue N0Op0 = N0.getOperand(0);
1673 APInt Mask = ~N1C->getAPIntValue();
1674 Mask.trunc(N0Op0.getValueSizeInBits());
1675 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1676 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1679 // Replace uses of the AND with uses of the Zero extend node.
1682 // We actually want to replace all uses of the any_extend with the
1683 // zero_extend, to avoid duplicating things. This will later cause this
1684 // AND to be folded.
1685 CombineTo(N0.getNode(), Zext);
1686 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1689 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1690 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1691 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1692 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1694 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1695 LL.getValueType().isInteger()) {
1696 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1697 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1698 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1699 AddToWorkList(ORNode.getNode());
1700 return DAG.getSetCC(VT, ORNode, LR, Op1);
1702 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1703 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1704 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1705 AddToWorkList(ANDNode.getNode());
1706 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1708 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1709 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1710 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1711 AddToWorkList(ORNode.getNode());
1712 return DAG.getSetCC(VT, ORNode, LR, Op1);
1715 // canonicalize equivalent to ll == rl
1716 if (LL == RR && LR == RL) {
1717 Op1 = ISD::getSetCCSwappedOperands(Op1);
1720 if (LL == RL && LR == RR) {
1721 bool isInteger = LL.getValueType().isInteger();
1722 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1723 if (Result != ISD::SETCC_INVALID)
1724 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1728 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1729 if (N0.getOpcode() == N1.getOpcode()) {
1730 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1731 if (Tmp.getNode()) return Tmp;
1734 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1735 // fold (and (sra)) -> (and (srl)) when possible.
1736 if (!VT.isVector() &&
1737 SimplifyDemandedBits(SDValue(N, 0)))
1738 return SDValue(N, 0);
1739 // fold (zext_inreg (extload x)) -> (zextload x)
1740 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
1741 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1742 MVT EVT = LN0->getMemoryVT();
1743 // If we zero all the possible extended bits, then we can turn this into
1744 // a zextload if we are running before legalize or the operation is legal.
1745 unsigned BitWidth = N1.getValueSizeInBits();
1746 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1747 BitWidth - EVT.getSizeInBits())) &&
1748 ((!AfterLegalize && !LN0->isVolatile()) ||
1749 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1750 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1751 LN0->getBasePtr(), LN0->getSrcValue(),
1752 LN0->getSrcValueOffset(), EVT,
1754 LN0->getAlignment());
1756 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1757 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1760 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1761 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
1763 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1764 MVT EVT = LN0->getMemoryVT();
1765 // If we zero all the possible extended bits, then we can turn this into
1766 // a zextload if we are running before legalize or the operation is legal.
1767 unsigned BitWidth = N1.getValueSizeInBits();
1768 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1769 BitWidth - EVT.getSizeInBits())) &&
1770 ((!AfterLegalize && !LN0->isVolatile()) ||
1771 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1772 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1773 LN0->getBasePtr(), LN0->getSrcValue(),
1774 LN0->getSrcValueOffset(), EVT,
1776 LN0->getAlignment());
1778 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1779 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1783 // fold (and (load x), 255) -> (zextload x, i8)
1784 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1785 if (N1C && N0.getOpcode() == ISD::LOAD) {
1786 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1787 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1788 LN0->isUnindexed() && N0.hasOneUse() &&
1789 // Do not change the width of a volatile load.
1790 !LN0->isVolatile()) {
1791 MVT EVT = MVT::Other;
1792 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1793 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1794 EVT = MVT::getIntegerVT(ActiveBits);
1796 MVT LoadedVT = LN0->getMemoryVT();
1797 // Do not generate loads of non-round integer types since these can
1798 // be expensive (and would be wrong if the type is not byte sized).
1799 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
1800 (!AfterLegalize || TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1801 MVT PtrType = N0.getOperand(1).getValueType();
1802 // For big endian targets, we need to add an offset to the pointer to
1803 // load the correct bytes. For little endian systems, we merely need to
1804 // read fewer bytes from the same pointer.
1805 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1806 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1807 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1808 unsigned Alignment = LN0->getAlignment();
1809 SDValue NewPtr = LN0->getBasePtr();
1810 if (TLI.isBigEndian()) {
1811 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1812 DAG.getConstant(PtrOff, PtrType));
1813 Alignment = MinAlign(Alignment, PtrOff);
1815 AddToWorkList(NewPtr.getNode());
1817 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1818 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1819 LN0->isVolatile(), Alignment);
1821 CombineTo(N0.getNode(), Load, Load.getValue(1));
1822 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1830 SDValue DAGCombiner::visitOR(SDNode *N) {
1831 SDValue N0 = N->getOperand(0);
1832 SDValue N1 = N->getOperand(1);
1833 SDValue LL, LR, RL, RR, CC0, CC1;
1834 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1836 MVT VT = N1.getValueType();
1839 if (VT.isVector()) {
1840 SDValue FoldedVOp = SimplifyVBinOp(N);
1841 if (FoldedVOp.getNode()) return FoldedVOp;
1844 // fold (or x, undef) -> -1
1845 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1846 return DAG.getConstant(~0ULL, VT);
1847 // fold (or c1, c2) -> c1|c2
1849 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
1850 // canonicalize constant to RHS
1852 return DAG.getNode(ISD::OR, VT, N1, N0);
1853 // fold (or x, 0) -> x
1854 if (N1C && N1C->isNullValue())
1856 // fold (or x, -1) -> -1
1857 if (N1C && N1C->isAllOnesValue())
1859 // fold (or x, c) -> c iff (x & ~c) == 0
1860 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1863 SDValue ROR = ReassociateOps(ISD::OR, N0, N1);
1864 if (ROR.getNode() != 0)
1866 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1867 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1868 isa<ConstantSDNode>(N0.getOperand(1))) {
1869 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1870 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1872 DAG.getConstant(N1C->getAPIntValue() |
1873 C1->getAPIntValue(), VT));
1875 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1876 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1877 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1878 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1880 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1881 LL.getValueType().isInteger()) {
1882 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1883 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1884 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1885 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1886 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1887 AddToWorkList(ORNode.getNode());
1888 return DAG.getSetCC(VT, ORNode, LR, Op1);
1890 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1891 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1892 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1893 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1894 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1895 AddToWorkList(ANDNode.getNode());
1896 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1899 // canonicalize equivalent to ll == rl
1900 if (LL == RR && LR == RL) {
1901 Op1 = ISD::getSetCCSwappedOperands(Op1);
1904 if (LL == RL && LR == RR) {
1905 bool isInteger = LL.getValueType().isInteger();
1906 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1907 if (Result != ISD::SETCC_INVALID)
1908 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1912 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1913 if (N0.getOpcode() == N1.getOpcode()) {
1914 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1915 if (Tmp.getNode()) return Tmp;
1918 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1919 if (N0.getOpcode() == ISD::AND &&
1920 N1.getOpcode() == ISD::AND &&
1921 N0.getOperand(1).getOpcode() == ISD::Constant &&
1922 N1.getOperand(1).getOpcode() == ISD::Constant &&
1923 // Don't increase # computations.
1924 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
1925 // We can only do this xform if we know that bits from X that are set in C2
1926 // but not in C1 are already zero. Likewise for Y.
1927 const APInt &LHSMask =
1928 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1929 const APInt &RHSMask =
1930 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1932 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1933 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1934 SDValue X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1935 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1940 // See if this is some rotate idiom.
1941 if (SDNode *Rot = MatchRotate(N0, N1))
1942 return SDValue(Rot, 0);
1948 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1949 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
1950 if (Op.getOpcode() == ISD::AND) {
1951 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1952 Mask = Op.getOperand(1);
1953 Op = Op.getOperand(0);
1959 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1967 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1968 // idioms for rotate, and if the target supports rotation instructions, generate
1970 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS) {
1971 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
1972 MVT VT = LHS.getValueType();
1973 if (!TLI.isTypeLegal(VT)) return 0;
1975 // The target must have at least one rotate flavor.
1976 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1977 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1978 if (!HasROTL && !HasROTR) return 0;
1980 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1981 SDValue LHSShift; // The shift.
1982 SDValue LHSMask; // AND value if any.
1983 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1984 return 0; // Not part of a rotate.
1986 SDValue RHSShift; // The shift.
1987 SDValue RHSMask; // AND value if any.
1988 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1989 return 0; // Not part of a rotate.
1991 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1992 return 0; // Not shifting the same value.
1994 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1995 return 0; // Shifts must disagree.
1997 // Canonicalize shl to left side in a shl/srl pair.
1998 if (RHSShift.getOpcode() == ISD::SHL) {
1999 std::swap(LHS, RHS);
2000 std::swap(LHSShift, RHSShift);
2001 std::swap(LHSMask , RHSMask );
2004 unsigned OpSizeInBits = VT.getSizeInBits();
2005 SDValue LHSShiftArg = LHSShift.getOperand(0);
2006 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2007 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2009 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2010 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2011 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2012 RHSShiftAmt.getOpcode() == ISD::Constant) {
2013 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2014 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2015 if ((LShVal + RShVal) != OpSizeInBits)
2020 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2022 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2024 // If there is an AND of either shifted operand, apply it to the result.
2025 if (LHSMask.getNode() || RHSMask.getNode()) {
2026 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2028 if (LHSMask.getNode()) {
2029 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2030 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2032 if (RHSMask.getNode()) {
2033 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2034 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2037 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2040 return Rot.getNode();
2043 // If there is a mask here, and we have a variable shift, we can't be sure
2044 // that we're masking out the right stuff.
2045 if (LHSMask.getNode() || RHSMask.getNode())
2048 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2049 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2050 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2051 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2052 if (ConstantSDNode *SUBC =
2053 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2054 if (SUBC->getAPIntValue() == OpSizeInBits) {
2056 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode();
2058 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode();
2063 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2064 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2065 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2066 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2067 if (ConstantSDNode *SUBC =
2068 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2069 if (SUBC->getAPIntValue() == OpSizeInBits) {
2071 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode();
2073 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode();
2078 // Look for sign/zext/any-extended or truncate cases:
2079 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2080 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2081 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2082 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2083 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2084 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2085 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2086 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2087 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2088 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2089 if (RExtOp0.getOpcode() == ISD::SUB &&
2090 RExtOp0.getOperand(1) == LExtOp0) {
2091 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2093 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2094 // (rotr x, (sub 32, y))
2095 if (ConstantSDNode *SUBC =
2096 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2097 if (SUBC->getAPIntValue() == OpSizeInBits) {
2098 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, VT, LHSShiftArg,
2099 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2102 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2103 RExtOp0 == LExtOp0.getOperand(1)) {
2104 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2106 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2107 // (rotl x, (sub 32, y))
2108 if (ConstantSDNode *SUBC =
2109 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2110 if (SUBC->getAPIntValue() == OpSizeInBits) {
2111 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, VT, LHSShiftArg,
2112 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2122 SDValue DAGCombiner::visitXOR(SDNode *N) {
2123 SDValue N0 = N->getOperand(0);
2124 SDValue N1 = N->getOperand(1);
2125 SDValue LHS, RHS, CC;
2126 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2127 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2128 MVT VT = N0.getValueType();
2131 if (VT.isVector()) {
2132 SDValue FoldedVOp = SimplifyVBinOp(N);
2133 if (FoldedVOp.getNode()) return FoldedVOp;
2136 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2137 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2138 return DAG.getConstant(0, VT);
2139 // fold (xor x, undef) -> undef
2140 if (N0.getOpcode() == ISD::UNDEF)
2142 if (N1.getOpcode() == ISD::UNDEF)
2144 // fold (xor c1, c2) -> c1^c2
2146 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2147 // canonicalize constant to RHS
2149 return DAG.getNode(ISD::XOR, VT, N1, N0);
2150 // fold (xor x, 0) -> x
2151 if (N1C && N1C->isNullValue())
2154 SDValue RXOR = ReassociateOps(ISD::XOR, N0, N1);
2155 if (RXOR.getNode() != 0)
2157 // fold !(x cc y) -> (x !cc y)
2158 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2159 bool isInt = LHS.getValueType().isInteger();
2160 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2162 if (N0.getOpcode() == ISD::SETCC)
2163 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2164 if (N0.getOpcode() == ISD::SELECT_CC)
2165 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2166 assert(0 && "Unhandled SetCC Equivalent!");
2169 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2170 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2171 N0.getNode()->hasOneUse() &&
2172 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2173 SDValue V = N0.getOperand(0);
2174 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2175 DAG.getConstant(1, V.getValueType()));
2176 AddToWorkList(V.getNode());
2177 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2180 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2181 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2182 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2183 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2184 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2185 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2186 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2187 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2188 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2189 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2192 // fold !(x or y) -> (!x and !y) iff x or y are constants
2193 if (N1C && N1C->isAllOnesValue() &&
2194 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2195 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2196 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2197 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2198 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2199 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2200 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2201 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2204 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2205 if (N1C && N0.getOpcode() == ISD::XOR) {
2206 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2207 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2209 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2210 DAG.getConstant(N1C->getAPIntValue()^
2211 N00C->getAPIntValue(), VT));
2213 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2214 DAG.getConstant(N1C->getAPIntValue()^
2215 N01C->getAPIntValue(), VT));
2217 // fold (xor x, x) -> 0
2219 if (!VT.isVector()) {
2220 return DAG.getConstant(0, VT);
2221 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2222 // Produce a vector of zeros.
2223 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2224 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2225 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2229 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2230 if (N0.getOpcode() == N1.getOpcode()) {
2231 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2232 if (Tmp.getNode()) return Tmp;
2235 // Simplify the expression using non-local knowledge.
2236 if (!VT.isVector() &&
2237 SimplifyDemandedBits(SDValue(N, 0)))
2238 return SDValue(N, 0);
2243 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2244 /// the shift amount is a constant.
2245 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2246 SDNode *LHS = N->getOperand(0).getNode();
2247 if (!LHS->hasOneUse()) return SDValue();
2249 // We want to pull some binops through shifts, so that we have (and (shift))
2250 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2251 // thing happens with address calculations, so it's important to canonicalize
2253 bool HighBitSet = false; // Can we transform this if the high bit is set?
2255 switch (LHS->getOpcode()) {
2256 default: return SDValue();
2259 HighBitSet = false; // We can only transform sra if the high bit is clear.
2262 HighBitSet = true; // We can only transform sra if the high bit is set.
2265 if (N->getOpcode() != ISD::SHL)
2266 return SDValue(); // only shl(add) not sr[al](add).
2267 HighBitSet = false; // We can only transform sra if the high bit is clear.
2271 // We require the RHS of the binop to be a constant as well.
2272 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2273 if (!BinOpCst) return SDValue();
2276 // FIXME: disable this for unless the input to the binop is a shift by a
2277 // constant. If it is not a shift, it pessimizes some common cases like:
2279 //void foo(int *X, int i) { X[i & 1235] = 1; }
2280 //int bar(int *X, int i) { return X[i & 255]; }
2281 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2282 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2283 BinOpLHSVal->getOpcode() != ISD::SRA &&
2284 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2285 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2288 MVT VT = N->getValueType(0);
2290 // If this is a signed shift right, and the high bit is modified
2291 // by the logical operation, do not perform the transformation.
2292 // The highBitSet boolean indicates the value of the high bit of
2293 // the constant which would cause it to be modified for this
2295 if (N->getOpcode() == ISD::SRA) {
2296 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2297 if (BinOpRHSSignSet != HighBitSet)
2301 // Fold the constants, shifting the binop RHS by the shift amount.
2302 SDValue NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2303 LHS->getOperand(1), N->getOperand(1));
2305 // Create the new shift.
2306 SDValue NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2309 // Create the new binop.
2310 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2314 SDValue DAGCombiner::visitSHL(SDNode *N) {
2315 SDValue N0 = N->getOperand(0);
2316 SDValue N1 = N->getOperand(1);
2317 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2318 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2319 MVT VT = N0.getValueType();
2320 unsigned OpSizeInBits = VT.getSizeInBits();
2322 // fold (shl c1, c2) -> c1<<c2
2324 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2325 // fold (shl 0, x) -> 0
2326 if (N0C && N0C->isNullValue())
2328 // fold (shl x, c >= size(x)) -> undef
2329 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2330 return DAG.getNode(ISD::UNDEF, VT);
2331 // fold (shl x, 0) -> x
2332 if (N1C && N1C->isNullValue())
2334 // if (shl x, c) is known to be zero, return 0
2335 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2336 APInt::getAllOnesValue(VT.getSizeInBits())))
2337 return DAG.getConstant(0, VT);
2338 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), c))
2339 // iff (trunc c) == c
2340 if (N1.getOpcode() == ISD::TRUNCATE &&
2341 N1.getOperand(0).getOpcode() == ISD::AND &&
2342 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2343 SDValue N101 = N1.getOperand(0).getOperand(1);
2344 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2345 MVT TruncVT = N1.getValueType();
2346 SDValue N100 = N1.getOperand(0).getOperand(0);
2347 return DAG.getNode(ISD::SHL, VT, N0,
2348 DAG.getNode(ISD::AND, TruncVT,
2349 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2350 DAG.getConstant(N101C->getZExtValue(),
2355 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2356 return SDValue(N, 0);
2357 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2358 if (N1C && N0.getOpcode() == ISD::SHL &&
2359 N0.getOperand(1).getOpcode() == ISD::Constant) {
2360 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2361 uint64_t c2 = N1C->getZExtValue();
2362 if (c1 + c2 > OpSizeInBits)
2363 return DAG.getConstant(0, VT);
2364 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2365 DAG.getConstant(c1 + c2, N1.getValueType()));
2367 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2368 // (srl (and x, -1 << c1), c1-c2)
2369 if (N1C && N0.getOpcode() == ISD::SRL &&
2370 N0.getOperand(1).getOpcode() == ISD::Constant) {
2371 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2372 uint64_t c2 = N1C->getZExtValue();
2373 SDValue Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2374 DAG.getConstant(~0ULL << c1, VT));
2376 return DAG.getNode(ISD::SHL, VT, Mask,
2377 DAG.getConstant(c2-c1, N1.getValueType()));
2379 return DAG.getNode(ISD::SRL, VT, Mask,
2380 DAG.getConstant(c1-c2, N1.getValueType()));
2382 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2383 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2384 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2385 DAG.getConstant(~0ULL << N1C->getZExtValue(), VT));
2387 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2390 SDValue DAGCombiner::visitSRA(SDNode *N) {
2391 SDValue N0 = N->getOperand(0);
2392 SDValue N1 = N->getOperand(1);
2393 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2394 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2395 MVT VT = N0.getValueType();
2397 // fold (sra c1, c2) -> c1>>c2
2399 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2400 // fold (sra 0, x) -> 0
2401 if (N0C && N0C->isNullValue())
2403 // fold (sra -1, x) -> -1
2404 if (N0C && N0C->isAllOnesValue())
2406 // fold (sra x, c >= size(x)) -> undef
2407 if (N1C && N1C->getZExtValue() >= VT.getSizeInBits())
2408 return DAG.getNode(ISD::UNDEF, VT);
2409 // fold (sra x, 0) -> x
2410 if (N1C && N1C->isNullValue())
2412 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2414 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2415 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getZExtValue();
2416 MVT EVT = MVT::getIntegerVT(LowBits);
2417 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2418 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2419 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2420 DAG.getValueType(EVT));
2423 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2424 if (N1C && N0.getOpcode() == ISD::SRA) {
2425 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2426 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2427 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2428 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2429 DAG.getConstant(Sum, N1C->getValueType(0)));
2433 // fold sra (shl X, m), result_size - n
2434 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2435 // result_size - n != m.
2436 // If truncate is free for the target sext(shl) is likely to result in better
2438 if (N0.getOpcode() == ISD::SHL) {
2439 // Get the two constanst of the shifts, CN0 = m, CN = n.
2440 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2442 // Determine what the truncate's result bitsize and type would be.
2443 unsigned VTValSize = VT.getSizeInBits();
2445 MVT::getIntegerVT(VTValSize - N1C->getZExtValue());
2446 // Determine the residual right-shift amount.
2447 unsigned ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2449 // If the shift is not a no-op (in which case this should be just a sign
2450 // extend already), the truncated to type is legal, sign_extend is legal
2451 // on that type, and the the truncate to that type is both legal and free,
2452 // perform the transform.
2454 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2455 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2456 TLI.isTruncateFree(VT, TruncVT)) {
2458 SDValue Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2459 SDValue Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2460 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2461 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2466 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), c))
2467 // iff (trunc c) == c
2468 if (N1.getOpcode() == ISD::TRUNCATE &&
2469 N1.getOperand(0).getOpcode() == ISD::AND &&
2470 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2471 SDValue N101 = N1.getOperand(0).getOperand(1);
2472 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2473 MVT TruncVT = N1.getValueType();
2474 SDValue N100 = N1.getOperand(0).getOperand(0);
2475 return DAG.getNode(ISD::SRA, VT, N0,
2476 DAG.getNode(ISD::AND, TruncVT,
2477 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2478 DAG.getConstant(N101C->getZExtValue(),
2483 // Simplify, based on bits shifted out of the LHS.
2484 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2485 return SDValue(N, 0);
2488 // If the sign bit is known to be zero, switch this to a SRL.
2489 if (DAG.SignBitIsZero(N0))
2490 return DAG.getNode(ISD::SRL, VT, N0, N1);
2492 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2495 SDValue DAGCombiner::visitSRL(SDNode *N) {
2496 SDValue N0 = N->getOperand(0);
2497 SDValue N1 = N->getOperand(1);
2498 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2499 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2500 MVT VT = N0.getValueType();
2501 unsigned OpSizeInBits = VT.getSizeInBits();
2503 // fold (srl c1, c2) -> c1 >>u c2
2505 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2506 // fold (srl 0, x) -> 0
2507 if (N0C && N0C->isNullValue())
2509 // fold (srl x, c >= size(x)) -> undef
2510 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2511 return DAG.getNode(ISD::UNDEF, VT);
2512 // fold (srl x, 0) -> x
2513 if (N1C && N1C->isNullValue())
2515 // if (srl x, c) is known to be zero, return 0
2516 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2517 APInt::getAllOnesValue(OpSizeInBits)))
2518 return DAG.getConstant(0, VT);
2520 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2521 if (N1C && N0.getOpcode() == ISD::SRL &&
2522 N0.getOperand(1).getOpcode() == ISD::Constant) {
2523 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2524 uint64_t c2 = N1C->getZExtValue();
2525 if (c1 + c2 > OpSizeInBits)
2526 return DAG.getConstant(0, VT);
2527 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2528 DAG.getConstant(c1 + c2, N1.getValueType()));
2531 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2532 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2533 // Shifting in all undef bits?
2534 MVT SmallVT = N0.getOperand(0).getValueType();
2535 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2536 return DAG.getNode(ISD::UNDEF, VT);
2538 SDValue SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2539 AddToWorkList(SmallShift.getNode());
2540 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2543 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2544 // bit, which is unmodified by sra.
2545 if (N1C && N1C->getZExtValue()+1 == VT.getSizeInBits()) {
2546 if (N0.getOpcode() == ISD::SRA)
2547 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2550 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2551 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2552 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2553 APInt KnownZero, KnownOne;
2554 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2555 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2557 // If any of the input bits are KnownOne, then the input couldn't be all
2558 // zeros, thus the result of the srl will always be zero.
2559 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2561 // If all of the bits input the to ctlz node are known to be zero, then
2562 // the result of the ctlz is "32" and the result of the shift is one.
2563 APInt UnknownBits = ~KnownZero & Mask;
2564 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2566 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2567 if ((UnknownBits & (UnknownBits-1)) == 0) {
2568 // Okay, we know that only that the single bit specified by UnknownBits
2569 // could be set on input to the CTLZ node. If this bit is set, the SRL
2570 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2571 // to an SRL,XOR pair, which is likely to simplify more.
2572 unsigned ShAmt = UnknownBits.countTrailingZeros();
2573 SDValue Op = N0.getOperand(0);
2575 Op = DAG.getNode(ISD::SRL, VT, Op,
2576 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2577 AddToWorkList(Op.getNode());
2579 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2583 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), c))
2584 // iff (trunc c) == c
2585 if (N1.getOpcode() == ISD::TRUNCATE &&
2586 N1.getOperand(0).getOpcode() == ISD::AND &&
2587 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2588 SDValue N101 = N1.getOperand(0).getOperand(1);
2589 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2590 MVT TruncVT = N1.getValueType();
2591 SDValue N100 = N1.getOperand(0).getOperand(0);
2592 return DAG.getNode(ISD::SRL, VT, N0,
2593 DAG.getNode(ISD::AND, TruncVT,
2594 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2595 DAG.getConstant(N101C->getZExtValue(),
2600 // fold operands of srl based on knowledge that the low bits are not
2602 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2603 return SDValue(N, 0);
2605 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2608 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
2609 SDValue N0 = N->getOperand(0);
2610 MVT VT = N->getValueType(0);
2612 // fold (ctlz c1) -> c2
2613 if (isa<ConstantSDNode>(N0))
2614 return DAG.getNode(ISD::CTLZ, VT, N0);
2618 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
2619 SDValue N0 = N->getOperand(0);
2620 MVT VT = N->getValueType(0);
2622 // fold (cttz c1) -> c2
2623 if (isa<ConstantSDNode>(N0))
2624 return DAG.getNode(ISD::CTTZ, VT, N0);
2628 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
2629 SDValue N0 = N->getOperand(0);
2630 MVT VT = N->getValueType(0);
2632 // fold (ctpop c1) -> c2
2633 if (isa<ConstantSDNode>(N0))
2634 return DAG.getNode(ISD::CTPOP, VT, N0);
2638 SDValue DAGCombiner::visitSELECT(SDNode *N) {
2639 SDValue N0 = N->getOperand(0);
2640 SDValue N1 = N->getOperand(1);
2641 SDValue N2 = N->getOperand(2);
2642 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2643 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2644 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2645 MVT VT = N->getValueType(0);
2646 MVT VT0 = N0.getValueType();
2648 // fold select C, X, X -> X
2651 // fold select true, X, Y -> X
2652 if (N0C && !N0C->isNullValue())
2654 // fold select false, X, Y -> Y
2655 if (N0C && N0C->isNullValue())
2657 // fold select C, 1, X -> C | X
2658 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2659 return DAG.getNode(ISD::OR, VT, N0, N2);
2660 // fold select C, 0, 1 -> ~C
2661 if (VT.isInteger() && VT0.isInteger() &&
2662 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2663 SDValue XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2666 AddToWorkList(XORNode.getNode());
2668 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2669 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2671 // fold select C, 0, X -> ~C & X
2672 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2673 SDValue XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2674 AddToWorkList(XORNode.getNode());
2675 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2677 // fold select C, X, 1 -> ~C | X
2678 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2679 SDValue XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2680 AddToWorkList(XORNode.getNode());
2681 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2683 // fold select C, X, 0 -> C & X
2684 // FIXME: this should check for C type == X type, not i1?
2685 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2686 return DAG.getNode(ISD::AND, VT, N0, N1);
2687 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2688 if (VT == MVT::i1 && N0 == N1)
2689 return DAG.getNode(ISD::OR, VT, N0, N2);
2690 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2691 if (VT == MVT::i1 && N0 == N2)
2692 return DAG.getNode(ISD::AND, VT, N0, N1);
2694 // If we can fold this based on the true/false value, do so.
2695 if (SimplifySelectOps(N, N1, N2))
2696 return SDValue(N, 0); // Don't revisit N.
2698 // fold selects based on a setcc into other things, such as min/max/abs
2699 if (N0.getOpcode() == ISD::SETCC) {
2701 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2702 // having to say they don't support SELECT_CC on every type the DAG knows
2703 // about, since there is no way to mark an opcode illegal at all value types
2704 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2705 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2706 N1, N2, N0.getOperand(2));
2708 return SimplifySelect(N0, N1, N2);
2713 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
2714 SDValue N0 = N->getOperand(0);
2715 SDValue N1 = N->getOperand(1);
2716 SDValue N2 = N->getOperand(2);
2717 SDValue N3 = N->getOperand(3);
2718 SDValue N4 = N->getOperand(4);
2719 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2721 // fold select_cc lhs, rhs, x, x, cc -> x
2725 // Determine if the condition we're dealing with is constant
2726 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2727 if (SCC.getNode()) AddToWorkList(SCC.getNode());
2729 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
2730 if (!SCCC->isNullValue())
2731 return N2; // cond always true -> true val
2733 return N3; // cond always false -> false val
2736 // Fold to a simpler select_cc
2737 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
2738 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2739 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2742 // If we can fold this based on the true/false value, do so.
2743 if (SimplifySelectOps(N, N2, N3))
2744 return SDValue(N, 0); // Don't revisit N.
2746 // fold select_cc into other things, such as min/max/abs
2747 return SimplifySelectCC(N0, N1, N2, N3, CC);
2750 SDValue DAGCombiner::visitSETCC(SDNode *N) {
2751 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2752 cast<CondCodeSDNode>(N->getOperand(2))->get());
2755 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2756 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2757 // transformation. Returns true if extension are possible and the above
2758 // mentioned transformation is profitable.
2759 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
2761 SmallVector<SDNode*, 4> &ExtendNodes,
2762 TargetLowering &TLI) {
2763 bool HasCopyToRegUses = false;
2764 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2765 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
2766 UE = N0.getNode()->use_end();
2771 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2772 if (User->getOpcode() == ISD::SETCC) {
2773 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2774 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2775 // Sign bits will be lost after a zext.
2778 for (unsigned i = 0; i != 2; ++i) {
2779 SDValue UseOp = User->getOperand(i);
2782 if (!isa<ConstantSDNode>(UseOp))
2787 ExtendNodes.push_back(User);
2789 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2790 SDValue UseOp = User->getOperand(i);
2792 // If truncate from extended type to original load type is free
2793 // on this target, then it's ok to extend a CopyToReg.
2794 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2795 HasCopyToRegUses = true;
2803 if (HasCopyToRegUses) {
2804 bool BothLiveOut = false;
2805 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2808 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2809 SDValue UseOp = User->getOperand(i);
2810 if (UseOp.getNode() == N && UseOp.getResNo() == 0) {
2817 // Both unextended and extended values are live out. There had better be
2818 // good a reason for the transformation.
2819 return ExtendNodes.size();
2824 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2825 SDValue N0 = N->getOperand(0);
2826 MVT VT = N->getValueType(0);
2828 // fold (sext c1) -> c1
2829 if (isa<ConstantSDNode>(N0))
2830 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2832 // fold (sext (sext x)) -> (sext x)
2833 // fold (sext (aext x)) -> (sext x)
2834 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2835 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2837 if (N0.getOpcode() == ISD::TRUNCATE) {
2838 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2839 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2840 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
2841 if (NarrowLoad.getNode()) {
2842 if (NarrowLoad.getNode() != N0.getNode())
2843 CombineTo(N0.getNode(), NarrowLoad);
2844 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2847 // See if the value being truncated is already sign extended. If so, just
2848 // eliminate the trunc/sext pair.
2849 SDValue Op = N0.getOperand(0);
2850 unsigned OpBits = Op.getValueType().getSizeInBits();
2851 unsigned MidBits = N0.getValueType().getSizeInBits();
2852 unsigned DestBits = VT.getSizeInBits();
2853 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2855 if (OpBits == DestBits) {
2856 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2857 // bits, it is already ready.
2858 if (NumSignBits > DestBits-MidBits)
2860 } else if (OpBits < DestBits) {
2861 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2862 // bits, just sext from i32.
2863 if (NumSignBits > OpBits-MidBits)
2864 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2866 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2867 // bits, just truncate to i32.
2868 if (NumSignBits > OpBits-MidBits)
2869 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2872 // fold (sext (truncate x)) -> (sextinreg x).
2873 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2874 N0.getValueType())) {
2875 if (Op.getValueType().bitsLT(VT))
2876 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2877 else if (Op.getValueType().bitsGT(VT))
2878 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2879 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2880 DAG.getValueType(N0.getValueType()));
2884 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2885 if (ISD::isNON_EXTLoad(N0.getNode()) &&
2886 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2887 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2888 bool DoXform = true;
2889 SmallVector<SDNode*, 4> SetCCs;
2890 if (!N0.hasOneUse())
2891 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2893 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2894 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2895 LN0->getBasePtr(), LN0->getSrcValue(),
2896 LN0->getSrcValueOffset(),
2899 LN0->getAlignment());
2900 CombineTo(N, ExtLoad);
2901 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2902 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
2903 // Extend SetCC uses if necessary.
2904 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2905 SDNode *SetCC = SetCCs[i];
2906 SmallVector<SDValue, 4> Ops;
2907 for (unsigned j = 0; j != 2; ++j) {
2908 SDValue SOp = SetCC->getOperand(j);
2910 Ops.push_back(ExtLoad);
2912 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2914 Ops.push_back(SetCC->getOperand(2));
2915 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2916 &Ops[0], Ops.size()));
2918 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2922 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2923 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2924 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
2925 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
2926 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2927 MVT EVT = LN0->getMemoryVT();
2928 if ((!AfterLegalize && !LN0->isVolatile()) ||
2929 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT)) {
2930 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2931 LN0->getBasePtr(), LN0->getSrcValue(),
2932 LN0->getSrcValueOffset(), EVT,
2934 LN0->getAlignment());
2935 CombineTo(N, ExtLoad);
2936 CombineTo(N0.getNode(),
2937 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2938 ExtLoad.getValue(1));
2939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2943 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2944 if (N0.getOpcode() == ISD::SETCC) {
2946 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2947 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2948 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2949 if (SCC.getNode()) return SCC;
2952 // fold (sext x) -> (zext x) if the sign bit is known zero.
2953 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2954 DAG.SignBitIsZero(N0))
2955 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2960 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2961 SDValue N0 = N->getOperand(0);
2962 MVT VT = N->getValueType(0);
2964 // fold (zext c1) -> c1
2965 if (isa<ConstantSDNode>(N0))
2966 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2967 // fold (zext (zext x)) -> (zext x)
2968 // fold (zext (aext x)) -> (zext x)
2969 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2970 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2972 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2973 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2974 if (N0.getOpcode() == ISD::TRUNCATE) {
2975 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
2976 if (NarrowLoad.getNode()) {
2977 if (NarrowLoad.getNode() != N0.getNode())
2978 CombineTo(N0.getNode(), NarrowLoad);
2979 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2983 // fold (zext (truncate x)) -> (and x, mask)
2984 if (N0.getOpcode() == ISD::TRUNCATE &&
2985 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2986 SDValue Op = N0.getOperand(0);
2987 if (Op.getValueType().bitsLT(VT)) {
2988 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2989 } else if (Op.getValueType().bitsGT(VT)) {
2990 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2992 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2995 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2996 if (N0.getOpcode() == ISD::AND &&
2997 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2998 N0.getOperand(1).getOpcode() == ISD::Constant) {
2999 SDValue X = N0.getOperand(0).getOperand(0);
3000 if (X.getValueType().bitsLT(VT)) {
3001 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3002 } else if (X.getValueType().bitsGT(VT)) {
3003 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3005 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3006 Mask.zext(VT.getSizeInBits());
3007 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3010 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3011 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3012 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3013 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3014 bool DoXform = true;
3015 SmallVector<SDNode*, 4> SetCCs;
3016 if (!N0.hasOneUse())
3017 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3019 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3020 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
3021 LN0->getBasePtr(), LN0->getSrcValue(),
3022 LN0->getSrcValueOffset(),
3025 LN0->getAlignment());
3026 CombineTo(N, ExtLoad);
3027 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
3028 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3029 // Extend SetCC uses if necessary.
3030 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3031 SDNode *SetCC = SetCCs[i];
3032 SmallVector<SDValue, 4> Ops;
3033 for (unsigned j = 0; j != 2; ++j) {
3034 SDValue SOp = SetCC->getOperand(j);
3036 Ops.push_back(ExtLoad);
3038 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
3040 Ops.push_back(SetCC->getOperand(2));
3041 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
3042 &Ops[0], Ops.size()));
3044 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3048 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3049 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3050 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3051 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3052 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3053 MVT EVT = LN0->getMemoryVT();
3054 if ((!AfterLegalize && !LN0->isVolatile()) ||
3055 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT)) {
3056 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
3057 LN0->getBasePtr(), LN0->getSrcValue(),
3058 LN0->getSrcValueOffset(), EVT,
3060 LN0->getAlignment());
3061 CombineTo(N, ExtLoad);
3062 CombineTo(N0.getNode(),
3063 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3064 ExtLoad.getValue(1));
3065 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3069 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3070 if (N0.getOpcode() == ISD::SETCC) {
3072 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3073 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3074 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3075 if (SCC.getNode()) return SCC;
3081 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3082 SDValue N0 = N->getOperand(0);
3083 MVT VT = N->getValueType(0);
3085 // fold (aext c1) -> c1
3086 if (isa<ConstantSDNode>(N0))
3087 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3088 // fold (aext (aext x)) -> (aext x)
3089 // fold (aext (zext x)) -> (zext x)
3090 // fold (aext (sext x)) -> (sext x)
3091 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3092 N0.getOpcode() == ISD::ZERO_EXTEND ||
3093 N0.getOpcode() == ISD::SIGN_EXTEND)
3094 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3096 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3097 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3098 if (N0.getOpcode() == ISD::TRUNCATE) {
3099 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3100 if (NarrowLoad.getNode()) {
3101 if (NarrowLoad.getNode() != N0.getNode())
3102 CombineTo(N0.getNode(), NarrowLoad);
3103 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3107 // fold (aext (truncate x))
3108 if (N0.getOpcode() == ISD::TRUNCATE) {
3109 SDValue TruncOp = N0.getOperand(0);
3110 if (TruncOp.getValueType() == VT)
3111 return TruncOp; // x iff x size == zext size.
3112 if (TruncOp.getValueType().bitsGT(VT))
3113 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3114 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3117 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3118 if (N0.getOpcode() == ISD::AND &&
3119 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3120 N0.getOperand(1).getOpcode() == ISD::Constant) {
3121 SDValue X = N0.getOperand(0).getOperand(0);
3122 if (X.getValueType().bitsLT(VT)) {
3123 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3124 } else if (X.getValueType().bitsGT(VT)) {
3125 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3127 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3128 Mask.zext(VT.getSizeInBits());
3129 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3132 // fold (aext (load x)) -> (aext (truncate (extload x)))
3133 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
3134 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3135 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3136 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3137 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3138 LN0->getBasePtr(), LN0->getSrcValue(),
3139 LN0->getSrcValueOffset(),
3142 LN0->getAlignment());
3143 CombineTo(N, ExtLoad);
3144 // Redirect any chain users to the new load.
3145 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1),
3146 SDValue(ExtLoad.getNode(), 1));
3147 // If any node needs the original loaded value, recompute it.
3148 if (!LN0->use_empty())
3149 CombineTo(LN0, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3150 ExtLoad.getValue(1));
3151 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3154 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3155 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3156 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3157 if (N0.getOpcode() == ISD::LOAD &&
3158 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3160 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3161 MVT EVT = LN0->getMemoryVT();
3162 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3163 LN0->getChain(), LN0->getBasePtr(),
3165 LN0->getSrcValueOffset(), EVT,
3167 LN0->getAlignment());
3168 CombineTo(N, ExtLoad);
3169 CombineTo(N0.getNode(),
3170 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3171 ExtLoad.getValue(1));
3172 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3175 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3176 if (N0.getOpcode() == ISD::SETCC) {
3178 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3179 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3180 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3188 /// GetDemandedBits - See if the specified operand can be simplified with the
3189 /// knowledge that only the bits specified by Mask are used. If so, return the
3190 /// simpler operand, otherwise return a null SDValue.
3191 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3192 switch (V.getOpcode()) {
3196 // If the LHS or RHS don't contribute bits to the or, drop them.
3197 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3198 return V.getOperand(1);
3199 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3200 return V.getOperand(0);
3203 // Only look at single-use SRLs.
3204 if (!V.getNode()->hasOneUse())
3206 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3207 // See if we can recursively simplify the LHS.
3208 unsigned Amt = RHSC->getZExtValue();
3209 APInt NewMask = Mask << Amt;
3210 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3211 if (SimplifyLHS.getNode()) {
3212 return DAG.getNode(ISD::SRL, V.getValueType(),
3213 SimplifyLHS, V.getOperand(1));
3220 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3221 /// bits and then truncated to a narrower type and where N is a multiple
3222 /// of number of bits of the narrower type, transform it to a narrower load
3223 /// from address + N / num of bits of new type. If the result is to be
3224 /// extended, also fold the extension to form a extending load.
3225 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3226 unsigned Opc = N->getOpcode();
3227 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3228 SDValue N0 = N->getOperand(0);
3229 MVT VT = N->getValueType(0);
3230 MVT EVT = N->getValueType(0);
3232 // This transformation isn't valid for vector loads.
3236 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3238 if (Opc == ISD::SIGN_EXTEND_INREG) {
3239 ExtType = ISD::SEXTLOAD;
3240 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3241 if (AfterLegalize && !TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))
3245 unsigned EVTBits = EVT.getSizeInBits();
3247 bool CombineSRL = false;
3248 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3249 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3250 ShAmt = N01->getZExtValue();
3251 // Is the shift amount a multiple of size of VT?
3252 if ((ShAmt & (EVTBits-1)) == 0) {
3253 N0 = N0.getOperand(0);
3254 if (N0.getValueType().getSizeInBits() <= EVTBits)
3261 // Do not generate loads of non-round integer types since these can
3262 // be expensive (and would be wrong if the type is not byte sized).
3263 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && VT.isRound() &&
3264 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
3265 // Do not change the width of a volatile load.
3266 !cast<LoadSDNode>(N0)->isVolatile()) {
3267 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3268 MVT PtrType = N0.getOperand(1).getValueType();
3269 // For big endian targets, we need to adjust the offset to the pointer to
3270 // load the correct bytes.
3271 if (TLI.isBigEndian()) {
3272 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3273 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3274 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3276 uint64_t PtrOff = ShAmt / 8;
3277 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3278 SDValue NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3279 DAG.getConstant(PtrOff, PtrType));
3280 AddToWorkList(NewPtr.getNode());
3281 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3282 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3283 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3284 LN0->isVolatile(), NewAlign)
3285 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3286 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3287 EVT, LN0->isVolatile(), NewAlign);
3290 WorkListRemover DeadNodes(*this);
3291 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3293 CombineTo(N->getOperand(0).getNode(), Load);
3295 CombineTo(N0.getNode(), Load, Load.getValue(1));
3297 if (Opc == ISD::SIGN_EXTEND_INREG)
3298 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3300 return DAG.getNode(Opc, VT, Load);
3302 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3309 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3310 SDValue N0 = N->getOperand(0);
3311 SDValue N1 = N->getOperand(1);
3312 MVT VT = N->getValueType(0);
3313 MVT EVT = cast<VTSDNode>(N1)->getVT();
3314 unsigned VTBits = VT.getSizeInBits();
3315 unsigned EVTBits = EVT.getSizeInBits();
3317 // fold (sext_in_reg c1) -> c1
3318 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3319 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3321 // If the input is already sign extended, just drop the extension.
3322 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3325 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3326 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3327 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3328 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3331 // fold (sext_in_reg (sext x)) -> (sext x)
3332 // fold (sext_in_reg (aext x)) -> (sext x)
3333 // if x is small enough.
3334 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3335 SDValue N00 = N0.getOperand(0);
3336 if (N00.getValueType().getSizeInBits() < EVTBits)
3337 return DAG.getNode(ISD::SIGN_EXTEND, VT, N00, N1);
3340 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3341 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3342 return DAG.getZeroExtendInReg(N0, EVT);
3344 // fold operands of sext_in_reg based on knowledge that the top bits are not
3346 if (SimplifyDemandedBits(SDValue(N, 0)))
3347 return SDValue(N, 0);
3349 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3350 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3351 SDValue NarrowLoad = ReduceLoadWidth(N);
3352 if (NarrowLoad.getNode())
3355 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3356 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3357 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3358 if (N0.getOpcode() == ISD::SRL) {
3359 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3360 if (ShAmt->getZExtValue()+EVTBits <= VT.getSizeInBits()) {
3361 // We can turn this into an SRA iff the input to the SRL is already sign
3363 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3364 if (VT.getSizeInBits()-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3365 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3369 // fold (sext_inreg (extload x)) -> (sextload x)
3370 if (ISD::isEXTLoad(N0.getNode()) &&
3371 ISD::isUNINDEXEDLoad(N0.getNode()) &&
3372 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3373 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3374 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3375 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3376 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3377 LN0->getBasePtr(), LN0->getSrcValue(),
3378 LN0->getSrcValueOffset(), EVT,
3380 LN0->getAlignment());
3381 CombineTo(N, ExtLoad);
3382 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3383 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3385 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3386 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3388 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3389 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3390 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3391 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3392 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3393 LN0->getBasePtr(), LN0->getSrcValue(),
3394 LN0->getSrcValueOffset(), EVT,
3396 LN0->getAlignment());
3397 CombineTo(N, ExtLoad);
3398 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3399 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3404 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
3405 SDValue N0 = N->getOperand(0);
3406 MVT VT = N->getValueType(0);
3409 if (N0.getValueType() == N->getValueType(0))
3411 // fold (truncate c1) -> c1
3412 if (isa<ConstantSDNode>(N0))
3413 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3414 // fold (truncate (truncate x)) -> (truncate x)
3415 if (N0.getOpcode() == ISD::TRUNCATE)
3416 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3417 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3418 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3419 N0.getOpcode() == ISD::ANY_EXTEND) {
3420 if (N0.getOperand(0).getValueType().bitsLT(VT))
3421 // if the source is smaller than the dest, we still need an extend
3422 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3423 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3424 // if the source is larger than the dest, than we just need the truncate
3425 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3427 // if the source and dest are the same type, we can drop both the extend
3429 return N0.getOperand(0);
3432 // See if we can simplify the input to this truncate through knowledge that
3433 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3436 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3437 VT.getSizeInBits()));
3438 if (Shorter.getNode())
3439 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3441 // fold (truncate (load x)) -> (smaller load x)
3442 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3443 return ReduceLoadWidth(N);
3446 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3447 SDValue Elt = N->getOperand(i);
3448 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3449 return Elt.getNode();
3450 return Elt.getOperand(Elt.getResNo()).getNode();
3453 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3454 /// if load locations are consecutive.
3455 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3456 assert(N->getOpcode() == ISD::BUILD_PAIR);
3458 SDNode *LD1 = getBuildPairElt(N, 0);
3459 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3461 MVT LD1VT = LD1->getValueType(0);
3462 SDNode *LD2 = getBuildPairElt(N, 1);
3463 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3464 if (ISD::isNON_EXTLoad(LD2) &&
3466 // If both are volatile this would reduce the number of volatile loads.
3467 // If one is volatile it might be ok, but play conservative and bail out.
3468 !cast<LoadSDNode>(LD1)->isVolatile() &&
3469 !cast<LoadSDNode>(LD2)->isVolatile() &&
3470 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3471 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3472 unsigned Align = LD->getAlignment();
3473 unsigned NewAlign = TLI.getTargetData()->
3474 getABITypeAlignment(VT.getTypeForMVT());
3475 if (NewAlign <= Align &&
3476 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
3477 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3478 LD->getSrcValue(), LD->getSrcValueOffset(),
3484 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3485 SDValue N0 = N->getOperand(0);
3486 MVT VT = N->getValueType(0);
3488 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3489 // Only do this before legalize, since afterward the target may be depending
3490 // on the bitconvert.
3491 // First check to see if this is all constant.
3492 if (!AfterLegalize &&
3493 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
3495 bool isSimple = true;
3496 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3497 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3498 N0.getOperand(i).getOpcode() != ISD::Constant &&
3499 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3504 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3505 assert(!DestEltVT.isVector() &&
3506 "Element type of vector ValueType must not be vector!");
3508 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
3512 // If the input is a constant, let getNode fold it.
3513 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3514 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3515 if (Res.getNode() != N) return Res;
3518 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3519 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3521 // fold (conv (load x)) -> (load (conv*)x)
3522 // If the resultant load doesn't need a higher alignment than the original!
3523 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
3524 // Do not change the width of a volatile load.
3525 !cast<LoadSDNode>(N0)->isVolatile() &&
3526 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
3527 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3528 unsigned Align = TLI.getTargetData()->
3529 getABITypeAlignment(VT.getTypeForMVT());
3530 unsigned OrigAlign = LN0->getAlignment();
3531 if (Align <= OrigAlign) {
3532 SDValue Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3533 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3534 LN0->isVolatile(), OrigAlign);
3536 CombineTo(N0.getNode(),
3537 DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3543 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3544 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3545 // This often reduces constant pool loads.
3546 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3547 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3548 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3549 AddToWorkList(NewConv.getNode());
3551 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3552 if (N0.getOpcode() == ISD::FNEG)
3553 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3554 assert(N0.getOpcode() == ISD::FABS);
3555 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3558 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3559 // Note that we don't handle copysign(x,cst) because this can always be folded
3560 // to an fneg or fabs.
3561 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
3562 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3563 VT.isInteger() && !VT.isVector()) {
3564 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3565 SDValue X = DAG.getNode(ISD::BIT_CONVERT,
3566 MVT::getIntegerVT(OrigXWidth),
3568 AddToWorkList(X.getNode());
3570 // If X has a different width than the result/lhs, sext it or truncate it.
3571 unsigned VTWidth = VT.getSizeInBits();
3572 if (OrigXWidth < VTWidth) {
3573 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3574 AddToWorkList(X.getNode());
3575 } else if (OrigXWidth > VTWidth) {
3576 // To get the sign bit in the right place, we have to shift it right
3577 // before truncating.
3578 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3579 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3580 AddToWorkList(X.getNode());
3581 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3582 AddToWorkList(X.getNode());
3585 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3586 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3587 AddToWorkList(X.getNode());
3589 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3590 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3591 AddToWorkList(Cst.getNode());
3593 return DAG.getNode(ISD::OR, VT, X, Cst);
3596 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3597 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3598 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
3599 if (CombineLD.getNode())
3606 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3607 MVT VT = N->getValueType(0);
3608 return CombineConsecutiveLoads(N, VT);
3611 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3612 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3613 /// destination element value type.
3614 SDValue DAGCombiner::
3615 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3616 MVT SrcEltVT = BV->getOperand(0).getValueType();
3618 // If this is already the right type, we're done.
3619 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
3621 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3622 unsigned DstBitSize = DstEltVT.getSizeInBits();
3624 // If this is a conversion of N elements of one type to N elements of another
3625 // type, convert each element. This handles FP<->INT cases.
3626 if (SrcBitSize == DstBitSize) {
3627 SmallVector<SDValue, 8> Ops;
3628 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3629 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3630 AddToWorkList(Ops.back().getNode());
3632 MVT VT = MVT::getVectorVT(DstEltVT,
3633 BV->getValueType(0).getVectorNumElements());
3634 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3637 // Otherwise, we're growing or shrinking the elements. To avoid having to
3638 // handle annoying details of growing/shrinking FP values, we convert them to
3640 if (SrcEltVT.isFloatingPoint()) {
3641 // Convert the input float vector to a int vector where the elements are the
3643 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3644 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3645 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
3649 // Now we know the input is an integer vector. If the output is a FP type,
3650 // convert to integer first, then to FP of the right size.
3651 if (DstEltVT.isFloatingPoint()) {
3652 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3653 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3654 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
3656 // Next, convert to FP elements of the same size.
3657 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3660 // Okay, we know the src/dst types are both integers of differing types.
3661 // Handling growing first.
3662 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3663 if (SrcBitSize < DstBitSize) {
3664 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3666 SmallVector<SDValue, 8> Ops;
3667 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3668 i += NumInputsPerOutput) {
3669 bool isLE = TLI.isLittleEndian();
3670 APInt NewBits = APInt(DstBitSize, 0);
3671 bool EltIsUndef = true;
3672 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3673 // Shift the previously computed bits over.
3674 NewBits <<= SrcBitSize;
3675 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3676 if (Op.getOpcode() == ISD::UNDEF) continue;
3680 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3684 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3686 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3689 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3690 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3693 // Finally, this must be the case where we are shrinking elements: each input
3694 // turns into multiple outputs.
3695 bool isS2V = ISD::isScalarToVector(BV);
3696 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3697 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3698 SmallVector<SDValue, 8> Ops;
3699 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3700 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3701 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3702 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3705 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3706 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3707 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3708 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3709 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3710 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3711 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3712 OpVal = OpVal.lshr(DstBitSize);
3715 // For big endian targets, swap the order of the pieces of each element.
3716 if (TLI.isBigEndian())
3717 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3719 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3724 SDValue DAGCombiner::visitFADD(SDNode *N) {
3725 SDValue N0 = N->getOperand(0);
3726 SDValue N1 = N->getOperand(1);
3727 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3728 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3729 MVT VT = N->getValueType(0);
3732 if (VT.isVector()) {
3733 SDValue FoldedVOp = SimplifyVBinOp(N);
3734 if (FoldedVOp.getNode()) return FoldedVOp;
3737 // fold (fadd c1, c2) -> c1+c2
3738 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3739 return DAG.getNode(ISD::FADD, VT, N0, N1);
3740 // canonicalize constant to RHS
3741 if (N0CFP && !N1CFP)
3742 return DAG.getNode(ISD::FADD, VT, N1, N0);
3743 // fold (A + (-B)) -> A-B
3744 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3745 return DAG.getNode(ISD::FSUB, VT, N0,
3746 GetNegatedExpression(N1, DAG, AfterLegalize));
3747 // fold ((-A) + B) -> B-A
3748 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3749 return DAG.getNode(ISD::FSUB, VT, N1,
3750 GetNegatedExpression(N0, DAG, AfterLegalize));
3752 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3753 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3754 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3755 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3756 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3761 SDValue DAGCombiner::visitFSUB(SDNode *N) {
3762 SDValue N0 = N->getOperand(0);
3763 SDValue N1 = N->getOperand(1);
3764 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3765 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3766 MVT VT = N->getValueType(0);
3769 if (VT.isVector()) {
3770 SDValue FoldedVOp = SimplifyVBinOp(N);
3771 if (FoldedVOp.getNode()) return FoldedVOp;
3774 // fold (fsub c1, c2) -> c1-c2
3775 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3776 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3778 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3779 if (isNegatibleForFree(N1, AfterLegalize))
3780 return GetNegatedExpression(N1, DAG, AfterLegalize);
3781 return DAG.getNode(ISD::FNEG, VT, N1);
3783 // fold (A-(-B)) -> A+B
3784 if (isNegatibleForFree(N1, AfterLegalize))
3785 return DAG.getNode(ISD::FADD, VT, N0,
3786 GetNegatedExpression(N1, DAG, AfterLegalize));
3791 SDValue DAGCombiner::visitFMUL(SDNode *N) {
3792 SDValue N0 = N->getOperand(0);
3793 SDValue N1 = N->getOperand(1);
3794 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3795 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3796 MVT VT = N->getValueType(0);
3799 if (VT.isVector()) {
3800 SDValue FoldedVOp = SimplifyVBinOp(N);
3801 if (FoldedVOp.getNode()) return FoldedVOp;
3804 // fold (fmul c1, c2) -> c1*c2
3805 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3806 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3807 // canonicalize constant to RHS
3808 if (N0CFP && !N1CFP)
3809 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3810 // fold (fmul X, 2.0) -> (fadd X, X)
3811 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3812 return DAG.getNode(ISD::FADD, VT, N0, N0);
3813 // fold (fmul X, -1.0) -> (fneg X)
3814 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3815 return DAG.getNode(ISD::FNEG, VT, N0);
3818 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3819 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3820 // Both can be negated for free, check to see if at least one is cheaper
3822 if (LHSNeg == 2 || RHSNeg == 2)
3823 return DAG.getNode(ISD::FMUL, VT,
3824 GetNegatedExpression(N0, DAG, AfterLegalize),
3825 GetNegatedExpression(N1, DAG, AfterLegalize));
3829 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3830 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3831 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3832 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3833 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3838 SDValue DAGCombiner::visitFDIV(SDNode *N) {
3839 SDValue N0 = N->getOperand(0);
3840 SDValue N1 = N->getOperand(1);
3841 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3842 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3843 MVT VT = N->getValueType(0);
3846 if (VT.isVector()) {
3847 SDValue FoldedVOp = SimplifyVBinOp(N);
3848 if (FoldedVOp.getNode()) return FoldedVOp;
3851 // fold (fdiv c1, c2) -> c1/c2
3852 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3853 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3857 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3858 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3859 // Both can be negated for free, check to see if at least one is cheaper
3861 if (LHSNeg == 2 || RHSNeg == 2)
3862 return DAG.getNode(ISD::FDIV, VT,
3863 GetNegatedExpression(N0, DAG, AfterLegalize),
3864 GetNegatedExpression(N1, DAG, AfterLegalize));
3871 SDValue DAGCombiner::visitFREM(SDNode *N) {
3872 SDValue N0 = N->getOperand(0);
3873 SDValue N1 = N->getOperand(1);
3874 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3875 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3876 MVT VT = N->getValueType(0);
3878 // fold (frem c1, c2) -> fmod(c1,c2)
3879 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3880 return DAG.getNode(ISD::FREM, VT, N0, N1);
3885 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3886 SDValue N0 = N->getOperand(0);
3887 SDValue N1 = N->getOperand(1);
3888 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3889 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3890 MVT VT = N->getValueType(0);
3892 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3893 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3896 const APFloat& V = N1CFP->getValueAPF();
3897 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3898 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3899 if (!V.isNegative())
3900 return DAG.getNode(ISD::FABS, VT, N0);
3902 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3905 // copysign(fabs(x), y) -> copysign(x, y)
3906 // copysign(fneg(x), y) -> copysign(x, y)
3907 // copysign(copysign(x,z), y) -> copysign(x, y)
3908 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3909 N0.getOpcode() == ISD::FCOPYSIGN)
3910 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3912 // copysign(x, abs(y)) -> abs(x)
3913 if (N1.getOpcode() == ISD::FABS)
3914 return DAG.getNode(ISD::FABS, VT, N0);
3916 // copysign(x, copysign(y,z)) -> copysign(x, z)
3917 if (N1.getOpcode() == ISD::FCOPYSIGN)
3918 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3920 // copysign(x, fp_extend(y)) -> copysign(x, y)
3921 // copysign(x, fp_round(y)) -> copysign(x, y)
3922 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3923 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3930 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3931 SDValue N0 = N->getOperand(0);
3932 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3933 MVT VT = N->getValueType(0);
3934 MVT OpVT = N0.getValueType();
3936 // fold (sint_to_fp c1) -> c1fp
3937 if (N0C && OpVT != MVT::ppcf128)
3938 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3940 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
3941 // but UINT_TO_FP is legal on this target, try to convert.
3942 if (!TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT) &&
3943 TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT)) {
3944 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
3945 if (DAG.SignBitIsZero(N0))
3946 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3953 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3954 SDValue N0 = N->getOperand(0);
3955 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3956 MVT VT = N->getValueType(0);
3957 MVT OpVT = N0.getValueType();
3959 // fold (uint_to_fp c1) -> c1fp
3960 if (N0C && OpVT != MVT::ppcf128)
3961 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3963 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
3964 // but SINT_TO_FP is legal on this target, try to convert.
3965 if (!TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT) &&
3966 TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT)) {
3967 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
3968 if (DAG.SignBitIsZero(N0))
3969 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3975 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3976 SDValue N0 = N->getOperand(0);
3977 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3978 MVT VT = N->getValueType(0);
3980 // fold (fp_to_sint c1fp) -> c1
3982 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3986 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3987 SDValue N0 = N->getOperand(0);
3988 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3989 MVT VT = N->getValueType(0);
3991 // fold (fp_to_uint c1fp) -> c1
3992 if (N0CFP && VT != MVT::ppcf128)
3993 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3997 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
3998 SDValue N0 = N->getOperand(0);
3999 SDValue N1 = N->getOperand(1);
4000 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4001 MVT VT = N->getValueType(0);
4003 // fold (fp_round c1fp) -> c1fp
4004 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4005 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
4007 // fold (fp_round (fp_extend x)) -> x
4008 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4009 return N0.getOperand(0);
4011 // fold (fp_round (fp_round x)) -> (fp_round x)
4012 if (N0.getOpcode() == ISD::FP_ROUND) {
4013 // This is a value preserving truncation if both round's are.
4014 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4015 N0.getNode()->getConstantOperandVal(1) == 1;
4016 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
4017 DAG.getIntPtrConstant(IsTrunc));
4020 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4021 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4022 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
4023 AddToWorkList(Tmp.getNode());
4024 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
4030 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4031 SDValue N0 = N->getOperand(0);
4032 MVT VT = N->getValueType(0);
4033 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4034 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4036 // fold (fp_round_inreg c1fp) -> c1fp
4038 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4039 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
4044 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4045 SDValue N0 = N->getOperand(0);
4046 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4047 MVT VT = N->getValueType(0);
4049 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4050 if (N->hasOneUse() &&
4051 N->use_begin().getUse().getSDValue().getOpcode() == ISD::FP_ROUND)
4054 // fold (fp_extend c1fp) -> c1fp
4055 if (N0CFP && VT != MVT::ppcf128)
4056 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
4058 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4060 if (N0.getOpcode() == ISD::FP_ROUND
4061 && N0.getNode()->getConstantOperandVal(1) == 1) {
4062 SDValue In = N0.getOperand(0);
4063 if (In.getValueType() == VT) return In;
4064 if (VT.bitsLT(In.getValueType()))
4065 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
4066 return DAG.getNode(ISD::FP_EXTEND, VT, In);
4069 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4070 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4071 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
4072 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4073 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4074 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
4075 LN0->getBasePtr(), LN0->getSrcValue(),
4076 LN0->getSrcValueOffset(),
4079 LN0->getAlignment());
4080 CombineTo(N, ExtLoad);
4081 CombineTo(N0.getNode(), DAG.getNode(ISD::FP_ROUND, N0.getValueType(),
4082 ExtLoad, DAG.getIntPtrConstant(1)),
4083 ExtLoad.getValue(1));
4084 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4090 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4091 SDValue N0 = N->getOperand(0);
4093 if (isNegatibleForFree(N0, AfterLegalize))
4094 return GetNegatedExpression(N0, DAG, AfterLegalize);
4096 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4097 // constant pool values.
4098 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4099 N0.getOperand(0).getValueType().isInteger() &&
4100 !N0.getOperand(0).getValueType().isVector()) {
4101 SDValue Int = N0.getOperand(0);
4102 MVT IntVT = Int.getValueType();
4103 if (IntVT.isInteger() && !IntVT.isVector()) {
4104 Int = DAG.getNode(ISD::XOR, IntVT, Int,
4105 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
4106 AddToWorkList(Int.getNode());
4107 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4114 SDValue DAGCombiner::visitFABS(SDNode *N) {
4115 SDValue N0 = N->getOperand(0);
4116 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4117 MVT VT = N->getValueType(0);
4119 // fold (fabs c1) -> fabs(c1)
4120 if (N0CFP && VT != MVT::ppcf128)
4121 return DAG.getNode(ISD::FABS, VT, N0);
4122 // fold (fabs (fabs x)) -> (fabs x)
4123 if (N0.getOpcode() == ISD::FABS)
4124 return N->getOperand(0);
4125 // fold (fabs (fneg x)) -> (fabs x)
4126 // fold (fabs (fcopysign x, y)) -> (fabs x)
4127 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4128 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4130 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4131 // constant pool values.
4132 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4133 N0.getOperand(0).getValueType().isInteger() &&
4134 !N0.getOperand(0).getValueType().isVector()) {
4135 SDValue Int = N0.getOperand(0);
4136 MVT IntVT = Int.getValueType();
4137 if (IntVT.isInteger() && !IntVT.isVector()) {
4138 Int = DAG.getNode(ISD::AND, IntVT, Int,
4139 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4140 AddToWorkList(Int.getNode());
4141 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4148 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4149 SDValue Chain = N->getOperand(0);
4150 SDValue N1 = N->getOperand(1);
4151 SDValue N2 = N->getOperand(2);
4152 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4154 // never taken branch, fold to chain
4155 if (N1C && N1C->isNullValue())
4157 // unconditional branch
4158 if (N1C && N1C->getAPIntValue() == 1)
4159 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4160 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4162 if (N1.getOpcode() == ISD::SETCC &&
4163 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4164 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4165 N1.getOperand(0), N1.getOperand(1), N2);
4170 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4172 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
4173 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4174 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4176 // Use SimplifySetCC to simplify SETCC's.
4177 SDValue Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4178 if (Simp.getNode()) AddToWorkList(Simp.getNode());
4180 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.getNode());
4182 // fold br_cc true, dest -> br dest (unconditional branch)
4183 if (SCCC && !SCCC->isNullValue())
4184 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4186 // fold br_cc false, dest -> unconditional fall through
4187 if (SCCC && SCCC->isNullValue())
4188 return N->getOperand(0);
4190 // fold to a simpler setcc
4191 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4192 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4193 Simp.getOperand(2), Simp.getOperand(0),
4194 Simp.getOperand(1), N->getOperand(4));
4199 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4200 /// pre-indexed load / store when the base pointer is an add or subtract
4201 /// and it has other uses besides the load / store. After the
4202 /// transformation, the new indexed load / store has effectively folded
4203 /// the add / subtract in and all of its other uses are redirected to the
4204 /// new load / store.
4205 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4212 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4213 if (LD->isIndexed())
4215 VT = LD->getMemoryVT();
4216 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4217 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4219 Ptr = LD->getBasePtr();
4220 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4221 if (ST->isIndexed())
4223 VT = ST->getMemoryVT();
4224 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4225 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4227 Ptr = ST->getBasePtr();
4232 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4233 // out. There is no reason to make this a preinc/predec.
4234 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4235 Ptr.getNode()->hasOneUse())
4238 // Ask the target to do addressing mode selection.
4241 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4242 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4244 // Don't create a indexed load / store with zero offset.
4245 if (isa<ConstantSDNode>(Offset) &&
4246 cast<ConstantSDNode>(Offset)->isNullValue())
4249 // Try turning it into a pre-indexed load / store except when:
4250 // 1) The new base ptr is a frame index.
4251 // 2) If N is a store and the new base ptr is either the same as or is a
4252 // predecessor of the value being stored.
4253 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4254 // that would create a cycle.
4255 // 4) All uses are load / store ops that use it as old base ptr.
4257 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4258 // (plus the implicit offset) to a register to preinc anyway.
4259 if (isa<FrameIndexSDNode>(BasePtr))
4264 SDValue Val = cast<StoreSDNode>(N)->getValue();
4265 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
4269 // Now check for #3 and #4.
4270 bool RealUse = false;
4271 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4272 E = Ptr.getNode()->use_end(); I != E; ++I) {
4276 if (Use->isPredecessorOf(N))
4279 if (!((Use->getOpcode() == ISD::LOAD &&
4280 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4281 (Use->getOpcode() == ISD::STORE &&
4282 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4290 Result = DAG.getIndexedLoad(SDValue(N,0), BasePtr, Offset, AM);
4292 Result = DAG.getIndexedStore(SDValue(N,0), BasePtr, Offset, AM);
4295 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4296 DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
4298 WorkListRemover DeadNodes(*this);
4300 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4302 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4305 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4309 // Finally, since the node is now dead, remove it from the graph.
4312 // Replace the uses of Ptr with uses of the updated base value.
4313 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4315 removeFromWorkList(Ptr.getNode());
4316 DAG.DeleteNode(Ptr.getNode());
4321 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4322 /// add / sub of the base pointer node into a post-indexed load / store.
4323 /// The transformation folded the add / subtract into the new indexed
4324 /// load / store effectively and all of its uses are redirected to the
4325 /// new load / store.
4326 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4333 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4334 if (LD->isIndexed())
4336 VT = LD->getMemoryVT();
4337 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4338 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4340 Ptr = LD->getBasePtr();
4341 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4342 if (ST->isIndexed())
4344 VT = ST->getMemoryVT();
4345 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4346 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4348 Ptr = ST->getBasePtr();
4353 if (Ptr.getNode()->hasOneUse())
4356 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4357 E = Ptr.getNode()->use_end(); I != E; ++I) {
4360 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4365 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4366 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4368 std::swap(BasePtr, Offset);
4371 // Don't create a indexed load / store with zero offset.
4372 if (isa<ConstantSDNode>(Offset) &&
4373 cast<ConstantSDNode>(Offset)->isNullValue())
4376 // Try turning it into a post-indexed load / store except when
4377 // 1) All uses are load / store ops that use it as base ptr.
4378 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4379 // nor a successor of N. Otherwise, if Op is folded that would
4383 bool TryNext = false;
4384 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
4385 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
4387 if (Use == Ptr.getNode())
4390 // If all the uses are load / store addresses, then don't do the
4392 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4393 bool RealUse = false;
4394 for (SDNode::use_iterator III = Use->use_begin(),
4395 EEE = Use->use_end(); III != EEE; ++III) {
4396 SDNode *UseUse = *III;
4397 if (!((UseUse->getOpcode() == ISD::LOAD &&
4398 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
4399 (UseUse->getOpcode() == ISD::STORE &&
4400 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
4414 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4415 SDValue Result = isLoad
4416 ? DAG.getIndexedLoad(SDValue(N,0), BasePtr, Offset, AM)
4417 : DAG.getIndexedStore(SDValue(N,0), BasePtr, Offset, AM);
4420 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4421 DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
4423 WorkListRemover DeadNodes(*this);
4425 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4427 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4430 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4434 // Finally, since the node is now dead, remove it from the graph.
4437 // Replace the uses of Use with uses of the updated base value.
4438 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
4439 Result.getValue(isLoad ? 1 : 0),
4441 removeFromWorkList(Op);
4450 /// InferAlignment - If we can infer some alignment information from this
4451 /// pointer, return it.
4452 static unsigned InferAlignment(SDValue Ptr, SelectionDAG &DAG) {
4453 // If this is a direct reference to a stack slot, use information about the
4454 // stack slot's alignment.
4455 int FrameIdx = 1 << 31;
4456 int64_t FrameOffset = 0;
4457 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4458 FrameIdx = FI->getIndex();
4459 } else if (Ptr.getOpcode() == ISD::ADD &&
4460 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4461 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4462 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4463 FrameOffset = Ptr.getConstantOperandVal(1);
4466 if (FrameIdx != (1 << 31)) {
4467 // FIXME: Handle FI+CST.
4468 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4469 if (MFI.isFixedObjectIndex(FrameIdx)) {
4470 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
4472 // The alignment of the frame index can be determined from its offset from
4473 // the incoming frame position. If the frame object is at offset 32 and
4474 // the stack is guaranteed to be 16-byte aligned, then we know that the
4475 // object is 16-byte aligned.
4476 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4477 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4479 // Finally, the frame object itself may have a known alignment. Factor
4480 // the alignment + offset into a new alignment. For example, if we know
4481 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4482 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4483 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4484 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4486 return std::max(Align, FIInfoAlign);
4493 SDValue DAGCombiner::visitLOAD(SDNode *N) {
4494 LoadSDNode *LD = cast<LoadSDNode>(N);
4495 SDValue Chain = LD->getChain();
4496 SDValue Ptr = LD->getBasePtr();
4498 // Try to infer better alignment information than the load already has.
4499 if (!Fast && LD->isUnindexed()) {
4500 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4501 if (Align > LD->getAlignment())
4502 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4503 Chain, Ptr, LD->getSrcValue(),
4504 LD->getSrcValueOffset(), LD->getMemoryVT(),
4505 LD->isVolatile(), Align);
4510 // If load is not volatile and there are no uses of the loaded value (and
4511 // the updated indexed value in case of indexed loads), change uses of the
4512 // chain value into uses of the chain input (i.e. delete the dead load).
4513 if (!LD->isVolatile()) {
4514 if (N->getValueType(1) == MVT::Other) {
4516 if (N->hasNUsesOfValue(0, 0)) {
4517 // It's not safe to use the two value CombineTo variant here. e.g.
4518 // v1, chain2 = load chain1, loc
4519 // v2, chain3 = load chain2, loc
4521 // Now we replace use of chain2 with chain1. This makes the second load
4522 // isomorphic to the one we are deleting, and thus makes this load live.
4523 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4524 DOUT << "\nWith chain: "; DEBUG(Chain.getNode()->dump(&DAG));
4526 WorkListRemover DeadNodes(*this);
4527 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
4528 if (N->use_empty()) {
4529 removeFromWorkList(N);
4532 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4536 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4537 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4538 SDValue Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4539 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4540 DOUT << "\nWith: "; DEBUG(Undef.getNode()->dump(&DAG));
4541 DOUT << " and 2 other values\n";
4542 WorkListRemover DeadNodes(*this);
4543 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
4544 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
4545 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4547 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
4548 removeFromWorkList(N);
4550 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4555 // If this load is directly stored, replace the load value with the stored
4557 // TODO: Handle store large -> read small portion.
4558 // TODO: Handle TRUNCSTORE/LOADEXT
4559 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4560 !LD->isVolatile()) {
4561 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
4562 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4563 if (PrevST->getBasePtr() == Ptr &&
4564 PrevST->getValue().getValueType() == N->getValueType(0))
4565 return CombineTo(N, Chain.getOperand(1), Chain);
4570 // Walk up chain skipping non-aliasing memory nodes.
4571 SDValue BetterChain = FindBetterChain(N, Chain);
4573 // If there is a better chain.
4574 if (Chain != BetterChain) {
4577 // Replace the chain to void dependency.
4578 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4579 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4580 LD->getSrcValue(), LD->getSrcValueOffset(),
4581 LD->isVolatile(), LD->getAlignment());
4583 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4584 LD->getValueType(0),
4585 BetterChain, Ptr, LD->getSrcValue(),
4586 LD->getSrcValueOffset(),
4589 LD->getAlignment());
4592 // Create token factor to keep old chain connected.
4593 SDValue Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4594 Chain, ReplLoad.getValue(1));
4596 // Replace uses with load result and token factor. Don't add users
4598 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4602 // Try transforming N to an indexed load.
4603 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4604 return SDValue(N, 0);
4610 SDValue DAGCombiner::visitSTORE(SDNode *N) {
4611 StoreSDNode *ST = cast<StoreSDNode>(N);
4612 SDValue Chain = ST->getChain();
4613 SDValue Value = ST->getValue();
4614 SDValue Ptr = ST->getBasePtr();
4616 // Try to infer better alignment information than the store already has.
4617 if (!Fast && ST->isUnindexed()) {
4618 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4619 if (Align > ST->getAlignment())
4620 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4621 ST->getSrcValueOffset(), ST->getMemoryVT(),
4622 ST->isVolatile(), Align);
4626 // If this is a store of a bit convert, store the input value if the
4627 // resultant store does not need a higher alignment than the original.
4628 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4629 ST->isUnindexed()) {
4630 unsigned Align = ST->getAlignment();
4631 MVT SVT = Value.getOperand(0).getValueType();
4632 unsigned OrigAlign = TLI.getTargetData()->
4633 getABITypeAlignment(SVT.getTypeForMVT());
4634 if (Align <= OrigAlign &&
4635 ((!AfterLegalize && !ST->isVolatile()) ||
4636 TLI.isOperationLegal(ISD::STORE, SVT)))
4637 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4638 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
4641 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4642 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4643 // NOTE: If the original store is volatile, this transform must not increase
4644 // the number of stores. For example, on x86-32 an f64 can be stored in one
4645 // processor operation but an i64 (which is not legal) requires two. So the
4646 // transform should not be done in this case.
4647 if (Value.getOpcode() != ISD::TargetConstantFP) {
4649 switch (CFP->getValueType(0).getSimpleVT()) {
4650 default: assert(0 && "Unknown FP type");
4651 case MVT::f80: // We don't do this for these yet.
4656 if ((!AfterLegalize && !ST->isVolatile()) ||
4657 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4658 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4659 bitcastToAPInt().getZExtValue(), MVT::i32);
4660 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4661 ST->getSrcValueOffset(), ST->isVolatile(),
4662 ST->getAlignment());
4666 if ((!AfterLegalize && !ST->isVolatile()) ||
4667 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4668 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
4669 getZExtValue(), MVT::i64);
4670 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4671 ST->getSrcValueOffset(), ST->isVolatile(),
4672 ST->getAlignment());
4673 } else if (!ST->isVolatile() &&
4674 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4675 // Many FP stores are not made apparent until after legalize, e.g. for
4676 // argument passing. Since this is so common, custom legalize the
4677 // 64-bit integer store into two 32-bit stores.
4678 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
4679 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4680 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
4681 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4683 int SVOffset = ST->getSrcValueOffset();
4684 unsigned Alignment = ST->getAlignment();
4685 bool isVolatile = ST->isVolatile();
4687 SDValue St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4688 ST->getSrcValueOffset(),
4689 isVolatile, ST->getAlignment());
4690 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4691 DAG.getConstant(4, Ptr.getValueType()));
4693 Alignment = MinAlign(Alignment, 4U);
4694 SDValue St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4695 SVOffset, isVolatile, Alignment);
4696 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4704 // Walk up chain skipping non-aliasing memory nodes.
4705 SDValue BetterChain = FindBetterChain(N, Chain);
4707 // If there is a better chain.
4708 if (Chain != BetterChain) {
4709 // Replace the chain to avoid dependency.
4711 if (ST->isTruncatingStore()) {
4712 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4713 ST->getSrcValue(),ST->getSrcValueOffset(),
4715 ST->isVolatile(), ST->getAlignment());
4717 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4718 ST->getSrcValue(), ST->getSrcValueOffset(),
4719 ST->isVolatile(), ST->getAlignment());
4722 // Create token to keep both nodes around.
4724 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4726 // Don't add users to work list.
4727 return CombineTo(N, Token, false);
4731 // Try transforming N to an indexed store.
4732 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4733 return SDValue(N, 0);
4735 // FIXME: is there such a thing as a truncating indexed store?
4736 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4737 Value.getValueType().isInteger()) {
4738 // See if we can simplify the input to this truncstore with knowledge that
4739 // only the low bits are being used. For example:
4740 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4742 GetDemandedBits(Value,
4743 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4744 ST->getMemoryVT().getSizeInBits()));
4745 AddToWorkList(Value.getNode());
4746 if (Shorter.getNode())
4747 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4748 ST->getSrcValueOffset(), ST->getMemoryVT(),
4749 ST->isVolatile(), ST->getAlignment());
4751 // Otherwise, see if we can simplify the operation with
4752 // SimplifyDemandedBits, which only works if the value has a single use.
4753 if (SimplifyDemandedBits(Value,
4754 APInt::getLowBitsSet(
4755 Value.getValueSizeInBits(),
4756 ST->getMemoryVT().getSizeInBits())))
4757 return SDValue(N, 0);
4760 // If this is a load followed by a store to the same location, then the store
4762 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4763 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4764 ST->isUnindexed() && !ST->isVolatile() &&
4765 // There can't be any side effects between the load and store, such as
4767 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
4768 // The store is dead, remove it.
4773 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4774 // truncating store. We can do this even if this is already a truncstore.
4775 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4776 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
4777 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4778 ST->getMemoryVT())) {
4779 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4780 ST->getSrcValueOffset(), ST->getMemoryVT(),
4781 ST->isVolatile(), ST->getAlignment());
4787 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4788 SDValue InVec = N->getOperand(0);
4789 SDValue InVal = N->getOperand(1);
4790 SDValue EltNo = N->getOperand(2);
4792 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4793 // vector with the inserted element.
4794 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4795 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
4796 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
4797 InVec.getNode()->op_end());
4798 if (Elt < Ops.size())
4800 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4801 &Ops[0], Ops.size());
4807 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4808 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4809 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4810 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4812 // Perform only after legalization to ensure build_vector / vector_shuffle
4813 // optimizations have already been done.
4814 if (!AfterLegalize) return SDValue();
4816 SDValue InVec = N->getOperand(0);
4817 SDValue EltNo = N->getOperand(1);
4819 if (isa<ConstantSDNode>(EltNo)) {
4820 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
4821 bool NewLoad = false;
4822 MVT VT = InVec.getValueType();
4823 MVT EVT = VT.getVectorElementType();
4825 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4826 MVT BCVT = InVec.getOperand(0).getValueType();
4827 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4829 InVec = InVec.getOperand(0);
4830 EVT = BCVT.getVectorElementType();
4834 LoadSDNode *LN0 = NULL;
4835 if (ISD::isNormalLoad(InVec.getNode()))
4836 LN0 = cast<LoadSDNode>(InVec);
4837 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4838 InVec.getOperand(0).getValueType() == EVT &&
4839 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
4840 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4841 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4842 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4844 // (load $addr+1*size)
4845 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4846 getOperand(Elt))->getZExtValue();
4847 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4848 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4849 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4850 InVec = InVec.getOperand(0);
4851 if (ISD::isNormalLoad(InVec.getNode())) {
4852 LN0 = cast<LoadSDNode>(InVec);
4853 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4856 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4859 unsigned Align = LN0->getAlignment();
4861 // Check the resultant load doesn't need a higher alignment than the
4863 unsigned NewAlign = TLI.getTargetData()->
4864 getABITypeAlignment(LVT.getTypeForMVT());
4865 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4870 SDValue NewPtr = LN0->getBasePtr();
4872 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4873 MVT PtrType = NewPtr.getValueType();
4874 if (TLI.isBigEndian())
4875 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4876 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4877 DAG.getConstant(PtrOff, PtrType));
4879 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4880 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4881 LN0->isVolatile(), Align);
4887 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4888 unsigned NumInScalars = N->getNumOperands();
4889 MVT VT = N->getValueType(0);
4890 unsigned NumElts = VT.getVectorNumElements();
4891 MVT EltType = VT.getVectorElementType();
4893 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4894 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4895 // at most two distinct vectors, turn this into a shuffle node.
4896 SDValue VecIn1, VecIn2;
4897 for (unsigned i = 0; i != NumInScalars; ++i) {
4898 // Ignore undef inputs.
4899 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4901 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4902 // constant index, bail out.
4903 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4904 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4905 VecIn1 = VecIn2 = SDValue(0, 0);
4909 // If the input vector type disagrees with the result of the build_vector,
4910 // we can't make a shuffle.
4911 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
4912 if (ExtractedFromVec.getValueType() != VT) {
4913 VecIn1 = VecIn2 = SDValue(0, 0);
4917 // Otherwise, remember this. We allow up to two distinct input vectors.
4918 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4921 if (VecIn1.getNode() == 0) {
4922 VecIn1 = ExtractedFromVec;
4923 } else if (VecIn2.getNode() == 0) {
4924 VecIn2 = ExtractedFromVec;
4927 VecIn1 = VecIn2 = SDValue(0, 0);
4932 // If everything is good, we can make a shuffle operation.
4933 if (VecIn1.getNode()) {
4934 SmallVector<SDValue, 8> BuildVecIndices;
4935 for (unsigned i = 0; i != NumInScalars; ++i) {
4936 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4937 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4941 SDValue Extract = N->getOperand(i);
4943 // If extracting from the first vector, just use the index directly.
4944 if (Extract.getOperand(0) == VecIn1) {
4945 BuildVecIndices.push_back(Extract.getOperand(1));
4949 // Otherwise, use InIdx + VecSize
4951 cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
4952 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4955 // Add count and size info.
4956 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
4958 // Return the new VECTOR_SHUFFLE node.
4961 if (VecIn2.getNode()) {
4964 // Use an undef build_vector as input for the second operand.
4965 std::vector<SDValue> UnOps(NumInScalars,
4966 DAG.getNode(ISD::UNDEF,
4968 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4969 &UnOps[0], UnOps.size());
4970 AddToWorkList(Ops[1].getNode());
4972 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4973 &BuildVecIndices[0], BuildVecIndices.size());
4974 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4980 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4981 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4982 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4983 // inputs come from at most two distinct vectors, turn this into a shuffle
4986 // If we only have one input vector, we don't need to do any concatenation.
4987 if (N->getNumOperands() == 1) {
4988 return N->getOperand(0);
4994 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4995 SDValue ShufMask = N->getOperand(2);
4996 unsigned NumElts = ShufMask.getNumOperands();
4998 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4999 bool isIdentity = true;
5000 for (unsigned i = 0; i != NumElts; ++i) {
5001 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
5002 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() != i) {
5007 if (isIdentity) return N->getOperand(0);
5009 // If the shuffle mask is an identity operation on the RHS, return the RHS.
5011 for (unsigned i = 0; i != NumElts; ++i) {
5012 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
5013 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() !=
5019 if (isIdentity) return N->getOperand(1);
5021 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
5023 bool isUnary = true;
5024 bool isSplat = true;
5026 unsigned BaseIdx = 0;
5027 for (unsigned i = 0; i != NumElts; ++i)
5028 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
5029 unsigned Idx=cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue();
5030 int V = (Idx < NumElts) ? 0 : 1;
5044 SDValue N0 = N->getOperand(0);
5045 SDValue N1 = N->getOperand(1);
5046 // Normalize unary shuffle so the RHS is undef.
5047 if (isUnary && VecNum == 1)
5050 // If it is a splat, check if the argument vector is a build_vector with
5051 // all scalar elements the same.
5053 SDNode *V = N0.getNode();
5055 // If this is a bit convert that changes the element type of the vector but
5056 // not the number of vector elements, look through it. Be careful not to
5057 // look though conversions that change things like v4f32 to v2f64.
5058 if (V->getOpcode() == ISD::BIT_CONVERT) {
5059 SDValue ConvInput = V->getOperand(0);
5060 if (ConvInput.getValueType().isVector() &&
5061 ConvInput.getValueType().getVectorNumElements() == NumElts)
5062 V = ConvInput.getNode();
5065 if (V->getOpcode() == ISD::BUILD_VECTOR) {
5066 unsigned NumElems = V->getNumOperands();
5067 if (NumElems > BaseIdx) {
5069 bool AllSame = true;
5070 for (unsigned i = 0; i != NumElems; ++i) {
5071 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
5072 Base = V->getOperand(i);
5076 // Splat of <u, u, u, u>, return <u, u, u, u>
5077 if (!Base.getNode())
5079 for (unsigned i = 0; i != NumElems; ++i) {
5080 if (V->getOperand(i) != Base) {
5085 // Splat of <x, x, x, x>, return <x, x, x, x>
5092 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
5094 if (isUnary || N0 == N1) {
5095 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
5097 SmallVector<SDValue, 8> MappedOps;
5098 for (unsigned i = 0; i != NumElts; ++i) {
5099 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
5100 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() <
5102 MappedOps.push_back(ShufMask.getOperand(i));
5105 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() -
5107 MappedOps.push_back(DAG.getConstant(NewIdx,
5108 ShufMask.getOperand(i).getValueType()));
5111 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
5112 &MappedOps[0], MappedOps.size());
5113 AddToWorkList(ShufMask.getNode());
5114 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5116 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5123 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5124 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5125 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5126 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5127 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5128 SDValue LHS = N->getOperand(0);
5129 SDValue RHS = N->getOperand(1);
5130 if (N->getOpcode() == ISD::AND) {
5131 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5132 RHS = RHS.getOperand(0);
5133 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5134 std::vector<SDValue> IdxOps;
5135 unsigned NumOps = RHS.getNumOperands();
5136 unsigned NumElts = NumOps;
5137 for (unsigned i = 0; i != NumElts; ++i) {
5138 SDValue Elt = RHS.getOperand(i);
5139 if (!isa<ConstantSDNode>(Elt))
5141 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5142 IdxOps.push_back(DAG.getIntPtrConstant(i));
5143 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5144 IdxOps.push_back(DAG.getIntPtrConstant(NumElts));
5149 // Let's see if the target supports this vector_shuffle.
5150 if (!TLI.isVectorClearMaskLegal(IdxOps, TLI.getPointerTy(), DAG))
5153 // Return the new VECTOR_SHUFFLE node.
5154 MVT EVT = RHS.getValueType().getVectorElementType();
5155 MVT VT = MVT::getVectorVT(EVT, NumElts);
5156 std::vector<SDValue> Ops;
5157 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5159 AddToWorkList(LHS.getNode());
5160 std::vector<SDValue> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5161 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5162 &ZeroOps[0], ZeroOps.size()));
5163 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5164 &IdxOps[0], IdxOps.size()));
5165 SDValue Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5166 &Ops[0], Ops.size());
5167 if (VT != N->getValueType(0))
5168 Result = DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Result);
5175 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5176 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
5177 // After legalize, the target may be depending on adds and other
5178 // binary ops to provide legal ways to construct constants or other
5179 // things. Simplifying them may result in a loss of legality.
5180 if (AfterLegalize) return SDValue();
5182 MVT VT = N->getValueType(0);
5183 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5185 MVT EltType = VT.getVectorElementType();
5186 SDValue LHS = N->getOperand(0);
5187 SDValue RHS = N->getOperand(1);
5188 SDValue Shuffle = XformToShuffleWithZero(N);
5189 if (Shuffle.getNode()) return Shuffle;
5191 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5193 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5194 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5195 SmallVector<SDValue, 8> Ops;
5196 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5197 SDValue LHSOp = LHS.getOperand(i);
5198 SDValue RHSOp = RHS.getOperand(i);
5199 // If these two elements can't be folded, bail out.
5200 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5201 LHSOp.getOpcode() != ISD::Constant &&
5202 LHSOp.getOpcode() != ISD::ConstantFP) ||
5203 (RHSOp.getOpcode() != ISD::UNDEF &&
5204 RHSOp.getOpcode() != ISD::Constant &&
5205 RHSOp.getOpcode() != ISD::ConstantFP))
5207 // Can't fold divide by zero.
5208 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5209 N->getOpcode() == ISD::FDIV) {
5210 if ((RHSOp.getOpcode() == ISD::Constant &&
5211 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
5212 (RHSOp.getOpcode() == ISD::ConstantFP &&
5213 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
5216 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5217 AddToWorkList(Ops.back().getNode());
5218 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5219 Ops.back().getOpcode() == ISD::Constant ||
5220 Ops.back().getOpcode() == ISD::ConstantFP) &&
5221 "Scalar binop didn't fold!");
5224 if (Ops.size() == LHS.getNumOperands()) {
5225 MVT VT = LHS.getValueType();
5226 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5233 SDValue DAGCombiner::SimplifySelect(SDValue N0, SDValue N1, SDValue N2){
5234 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5236 SDValue SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5237 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5238 // If we got a simplified select_cc node back from SimplifySelectCC, then
5239 // break it down into a new SETCC node, and a new SELECT node, and then return
5240 // the SELECT node, since we were called with a SELECT node.
5241 if (SCC.getNode()) {
5242 // Check to see if we got a select_cc back (to turn into setcc/select).
5243 // Otherwise, just return whatever node we got back, like fabs.
5244 if (SCC.getOpcode() == ISD::SELECT_CC) {
5245 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5246 SCC.getOperand(0), SCC.getOperand(1),
5248 AddToWorkList(SETCC.getNode());
5249 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5250 SCC.getOperand(3), SETCC);
5257 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5258 /// are the two values being selected between, see if we can simplify the
5259 /// select. Callers of this should assume that TheSelect is deleted if this
5260 /// returns true. As such, they should return the appropriate thing (e.g. the
5261 /// node) back to the top-level of the DAG combiner loop to avoid it being
5264 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
5267 // If this is a select from two identical things, try to pull the operation
5268 // through the select.
5269 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5270 // If this is a load and the token chain is identical, replace the select
5271 // of two loads with a load through a select of the address to load from.
5272 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5273 // constants have been dropped into the constant pool.
5274 if (LHS.getOpcode() == ISD::LOAD &&
5275 // Do not let this transformation reduce the number of volatile loads.
5276 !cast<LoadSDNode>(LHS)->isVolatile() &&
5277 !cast<LoadSDNode>(RHS)->isVolatile() &&
5278 // Token chains must be identical.
5279 LHS.getOperand(0) == RHS.getOperand(0)) {
5280 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5281 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5283 // If this is an EXTLOAD, the VT's must match.
5284 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5285 // FIXME: this conflates two src values, discarding one. This is not
5286 // the right thing to do, but nothing uses srcvalues now. When they do,
5287 // turn SrcValue into a list of locations.
5289 if (TheSelect->getOpcode() == ISD::SELECT) {
5290 // Check that the condition doesn't reach either load. If so, folding
5291 // this will induce a cycle into the DAG.
5292 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5293 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) {
5294 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5295 TheSelect->getOperand(0), LLD->getBasePtr(),
5299 // Check that the condition doesn't reach either load. If so, folding
5300 // this will induce a cycle into the DAG.
5301 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5302 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5303 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()) &&
5304 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())) {
5305 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5306 TheSelect->getOperand(0),
5307 TheSelect->getOperand(1),
5308 LLD->getBasePtr(), RLD->getBasePtr(),
5309 TheSelect->getOperand(4));
5313 if (Addr.getNode()) {
5315 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5316 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5317 Addr,LLD->getSrcValue(),
5318 LLD->getSrcValueOffset(),
5320 LLD->getAlignment());
5322 Load = DAG.getExtLoad(LLD->getExtensionType(),
5323 TheSelect->getValueType(0),
5324 LLD->getChain(), Addr, LLD->getSrcValue(),
5325 LLD->getSrcValueOffset(),
5328 LLD->getAlignment());
5330 // Users of the select now use the result of the load.
5331 CombineTo(TheSelect, Load);
5333 // Users of the old loads now use the new load's chain. We know the
5334 // old-load value is dead now.
5335 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
5336 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
5346 SDValue DAGCombiner::SimplifySelectCC(SDValue N0, SDValue N1,
5347 SDValue N2, SDValue N3,
5348 ISD::CondCode CC, bool NotExtCompare) {
5350 MVT VT = N2.getValueType();
5351 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
5352 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
5353 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
5355 // Determine if the condition we're dealing with is constant
5356 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5357 if (SCC.getNode()) AddToWorkList(SCC.getNode());
5358 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
5360 // fold select_cc true, x, y -> x
5361 if (SCCC && !SCCC->isNullValue())
5363 // fold select_cc false, x, y -> y
5364 if (SCCC && SCCC->isNullValue())
5367 // Check to see if we can simplify the select into an fabs node
5368 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5369 // Allow either -0.0 or 0.0
5370 if (CFP->getValueAPF().isZero()) {
5371 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5372 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5373 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5374 N2 == N3.getOperand(0))
5375 return DAG.getNode(ISD::FABS, VT, N0);
5377 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5378 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5379 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5380 N2.getOperand(0) == N3)
5381 return DAG.getNode(ISD::FABS, VT, N3);
5385 // Check to see if we can perform the "gzip trick", transforming
5386 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5387 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5388 N0.getValueType().isInteger() &&
5389 N2.getValueType().isInteger() &&
5390 (N1C->isNullValue() || // (a < 0) ? b : 0
5391 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5392 MVT XType = N0.getValueType();
5393 MVT AType = N2.getValueType();
5394 if (XType.bitsGE(AType)) {
5395 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5396 // single-bit constant.
5397 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5398 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5399 ShCtV = XType.getSizeInBits()-ShCtV-1;
5400 SDValue ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5401 SDValue Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5402 AddToWorkList(Shift.getNode());
5403 if (XType.bitsGT(AType)) {
5404 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5405 AddToWorkList(Shift.getNode());
5407 return DAG.getNode(ISD::AND, AType, Shift, N2);
5409 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5410 DAG.getConstant(XType.getSizeInBits()-1,
5411 TLI.getShiftAmountTy()));
5412 AddToWorkList(Shift.getNode());
5413 if (XType.bitsGT(AType)) {
5414 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5415 AddToWorkList(Shift.getNode());
5417 return DAG.getNode(ISD::AND, AType, Shift, N2);
5421 // fold select C, 16, 0 -> shl C, 4
5422 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5423 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5425 // If the caller doesn't want us to simplify this into a zext of a compare,
5427 if (NotExtCompare && N2C->getAPIntValue() == 1)
5430 // Get a SetCC of the condition
5431 // FIXME: Should probably make sure that setcc is legal if we ever have a
5432 // target where it isn't.
5434 // cast from setcc result type to select result type
5435 if (AfterLegalize) {
5436 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5437 if (N2.getValueType().bitsLT(SCC.getValueType()))
5438 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5440 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5442 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5443 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5445 AddToWorkList(SCC.getNode());
5446 AddToWorkList(Temp.getNode());
5448 if (N2C->getAPIntValue() == 1)
5450 // shl setcc result by log2 n2c
5451 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5452 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5453 TLI.getShiftAmountTy()));
5456 // Check to see if this is the equivalent of setcc
5457 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5458 // otherwise, go ahead with the folds.
5459 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5460 MVT XType = N0.getValueType();
5461 if (!AfterLegalize ||
5462 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5463 SDValue Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5464 if (Res.getValueType() != VT)
5465 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5469 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5470 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5472 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5473 SDValue Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5474 return DAG.getNode(ISD::SRL, XType, Ctlz,
5475 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5476 TLI.getShiftAmountTy()));
5478 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5479 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5480 SDValue NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5482 SDValue NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5483 DAG.getConstant(~0ULL, XType));
5484 return DAG.getNode(ISD::SRL, XType,
5485 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5486 DAG.getConstant(XType.getSizeInBits()-1,
5487 TLI.getShiftAmountTy()));
5489 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5490 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5491 SDValue Sign = DAG.getNode(ISD::SRL, XType, N0,
5492 DAG.getConstant(XType.getSizeInBits()-1,
5493 TLI.getShiftAmountTy()));
5494 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5498 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5499 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5500 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5501 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5502 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5503 MVT XType = N0.getValueType();
5504 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5505 DAG.getConstant(XType.getSizeInBits()-1,
5506 TLI.getShiftAmountTy()));
5507 SDValue Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5508 AddToWorkList(Shift.getNode());
5509 AddToWorkList(Add.getNode());
5510 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5512 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5513 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5514 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5515 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5516 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5517 MVT XType = N0.getValueType();
5518 if (SubC->isNullValue() && XType.isInteger()) {
5519 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5520 DAG.getConstant(XType.getSizeInBits()-1,
5521 TLI.getShiftAmountTy()));
5522 SDValue Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5523 AddToWorkList(Shift.getNode());
5524 AddToWorkList(Add.getNode());
5525 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5533 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5534 SDValue DAGCombiner::SimplifySetCC(MVT VT, SDValue N0,
5535 SDValue N1, ISD::CondCode Cond,
5536 bool foldBooleans) {
5537 TargetLowering::DAGCombinerInfo
5538 DagCombineInfo(DAG, !AfterLegalize, false, this);
5539 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5542 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5543 /// return a DAG expression to select that will generate the same value by
5544 /// multiplying by a magic number. See:
5545 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5546 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
5547 std::vector<SDNode*> Built;
5548 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
5550 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5556 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5557 /// return a DAG expression to select that will generate the same value by
5558 /// multiplying by a magic number. See:
5559 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5560 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
5561 std::vector<SDNode*> Built;
5562 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
5564 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5570 /// FindBaseOffset - Return true if base is known not to alias with anything
5571 /// but itself. Provides base object and offset as results.
5572 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset) {
5573 // Assume it is a primitive operation.
5574 Base = Ptr; Offset = 0;
5576 // If it's an adding a simple constant then integrate the offset.
5577 if (Base.getOpcode() == ISD::ADD) {
5578 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5579 Base = Base.getOperand(0);
5580 Offset += C->getZExtValue();
5584 // If it's any of the following then it can't alias with anything but itself.
5585 return isa<FrameIndexSDNode>(Base) ||
5586 isa<ConstantPoolSDNode>(Base) ||
5587 isa<GlobalAddressSDNode>(Base);
5590 /// isAlias - Return true if there is any possibility that the two addresses
5592 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
5593 const Value *SrcValue1, int SrcValueOffset1,
5594 SDValue Ptr2, int64_t Size2,
5595 const Value *SrcValue2, int SrcValueOffset2)
5597 // If they are the same then they must be aliases.
5598 if (Ptr1 == Ptr2) return true;
5600 // Gather base node and offset information.
5601 SDValue Base1, Base2;
5602 int64_t Offset1, Offset2;
5603 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5604 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5606 // If they have a same base address then...
5607 if (Base1 == Base2) {
5608 // Check to see if the addresses overlap.
5609 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5612 // If we know both bases then they can't alias.
5613 if (KnownBase1 && KnownBase2) return false;
5615 if (CombinerGlobalAA) {
5616 // Use alias analysis information.
5617 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5618 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5619 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5620 AliasAnalysis::AliasResult AAResult =
5621 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5622 if (AAResult == AliasAnalysis::NoAlias)
5626 // Otherwise we have to assume they alias.
5630 /// FindAliasInfo - Extracts the relevant alias information from the memory
5631 /// node. Returns true if the operand was a load.
5632 bool DAGCombiner::FindAliasInfo(SDNode *N,
5633 SDValue &Ptr, int64_t &Size,
5634 const Value *&SrcValue, int &SrcValueOffset) {
5635 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5636 Ptr = LD->getBasePtr();
5637 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5638 SrcValue = LD->getSrcValue();
5639 SrcValueOffset = LD->getSrcValueOffset();
5641 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5642 Ptr = ST->getBasePtr();
5643 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5644 SrcValue = ST->getSrcValue();
5645 SrcValueOffset = ST->getSrcValueOffset();
5647 assert(0 && "FindAliasInfo expected a memory operand");
5653 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5654 /// looking for aliasing nodes and adding them to the Aliases vector.
5655 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
5656 SmallVector<SDValue, 8> &Aliases) {
5657 SmallVector<SDValue, 8> Chains; // List of chains to visit.
5658 std::set<SDNode *> Visited; // Visited node set.
5660 // Get alias information for node.
5663 const Value *SrcValue;
5665 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5668 Chains.push_back(OriginalChain);
5670 // Look at each chain and determine if it is an alias. If so, add it to the
5671 // aliases list. If not, then continue up the chain looking for the next
5673 while (!Chains.empty()) {
5674 SDValue Chain = Chains.back();
5677 // Don't bother if we've been before.
5678 if (Visited.find(Chain.getNode()) != Visited.end()) continue;
5679 Visited.insert(Chain.getNode());
5681 switch (Chain.getOpcode()) {
5682 case ISD::EntryToken:
5683 // Entry token is ideal chain operand, but handled in FindBetterChain.
5688 // Get alias information for Chain.
5691 const Value *OpSrcValue;
5692 int OpSrcValueOffset;
5693 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
5694 OpSrcValue, OpSrcValueOffset);
5696 // If chain is alias then stop here.
5697 if (!(IsLoad && IsOpLoad) &&
5698 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5699 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5700 Aliases.push_back(Chain);
5702 // Look further up the chain.
5703 Chains.push_back(Chain.getOperand(0));
5704 // Clean up old chain.
5705 AddToWorkList(Chain.getNode());
5710 case ISD::TokenFactor:
5711 // We have to check each of the operands of the token factor, so we queue
5712 // then up. Adding the operands to the queue (stack) in reverse order
5713 // maintains the original order and increases the likelihood that getNode
5714 // will find a matching token factor (CSE.)
5715 for (unsigned n = Chain.getNumOperands(); n;)
5716 Chains.push_back(Chain.getOperand(--n));
5717 // Eliminate the token factor if we can.
5718 AddToWorkList(Chain.getNode());
5722 // For all other instructions we will just have to take what we can get.
5723 Aliases.push_back(Chain);
5729 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5730 /// for a better chain (aliasing node.)
5731 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
5732 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
5734 // Accumulate all the aliases to this node.
5735 GatherAllAliases(N, OldChain, Aliases);
5737 if (Aliases.size() == 0) {
5738 // If no operands then chain to entry token.
5739 return DAG.getEntryNode();
5740 } else if (Aliases.size() == 1) {
5741 // If a single operand then chain to it. We don't need to revisit it.
5745 // Construct a custom tailored token factor.
5746 SDValue NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5747 &Aliases[0], Aliases.size());
5749 // Make sure the old chain gets cleaned up.
5750 if (NewChain != OldChain) AddToWorkList(OldChain.getNode());
5755 // SelectionDAG::Combine - This is the entry point for the file.
5757 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA,
5759 /// run - This is the main entry point to this class.
5761 DAGCombiner(*this, AA, Fast).Run(RunningAfterLegalize);