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");
42 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
43 cl::desc("Pop up a window to show dags before the first "
46 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
47 cl::desc("Pop up a window to show dags before the second "
50 static const bool ViewDAGCombine1 = false;
51 static const bool ViewDAGCombine2 = false;
55 CombinerAA("combiner-alias-analysis", cl::Hidden,
56 cl::desc("Turn on alias analysis during testing"));
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60 cl::desc("Include global information in alias analysis"));
62 //------------------------------ DAGCombiner ---------------------------------//
64 class VISIBILITY_HIDDEN DAGCombiner {
69 // Worklist of all of the nodes that need to be simplified.
70 std::vector<SDNode*> WorkList;
72 // AA - Used for DAG load/store alias analysis.
75 /// AddUsersToWorkList - When an instruction is simplified, add all users of
76 /// the instruction to the work lists because they might get more simplified
79 void AddUsersToWorkList(SDNode *N) {
80 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 AddToWorkList(UI->getUser());
85 /// visit - call the node-specific routine that knows how to fold each
86 /// particular type of node.
87 SDOperand visit(SDNode *N);
90 /// AddToWorkList - Add to the work list making sure it's instance is at the
91 /// the back (next to be processed.)
92 void AddToWorkList(SDNode *N) {
93 removeFromWorkList(N);
94 WorkList.push_back(N);
97 /// removeFromWorkList - remove all instances of N from the worklist.
99 void removeFromWorkList(SDNode *N) {
100 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
104 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
107 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
108 return CombineTo(N, &Res, 1, AddTo);
111 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
113 SDOperand To[] = { Res0, Res1 };
114 return CombineTo(N, To, 2, AddTo);
119 /// SimplifyDemandedBits - Check the specified integer node value to see if
120 /// it can be simplified or if things it uses can be simplified by bit
121 /// propagation. If so, return true.
122 bool SimplifyDemandedBits(SDOperand Op) {
123 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
133 /// combine - call the node-specific routine that knows how to fold each
134 /// particular type of node. If that doesn't do anything, try the
135 /// target-specific DAG combines.
136 SDOperand combine(SDNode *N);
138 // Visitation implementation - Implement dag node combining for different
139 // node types. The semantics are as follows:
141 // SDOperand.Val == 0 - No change was made
142 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
143 // otherwise - N should be replaced by the returned Operand.
145 SDOperand visitTokenFactor(SDNode *N);
146 SDOperand visitMERGE_VALUES(SDNode *N);
147 SDOperand visitADD(SDNode *N);
148 SDOperand visitSUB(SDNode *N);
149 SDOperand visitADDC(SDNode *N);
150 SDOperand visitADDE(SDNode *N);
151 SDOperand visitMUL(SDNode *N);
152 SDOperand visitSDIV(SDNode *N);
153 SDOperand visitUDIV(SDNode *N);
154 SDOperand visitSREM(SDNode *N);
155 SDOperand visitUREM(SDNode *N);
156 SDOperand visitMULHU(SDNode *N);
157 SDOperand visitMULHS(SDNode *N);
158 SDOperand visitSMUL_LOHI(SDNode *N);
159 SDOperand visitUMUL_LOHI(SDNode *N);
160 SDOperand visitSDIVREM(SDNode *N);
161 SDOperand visitUDIVREM(SDNode *N);
162 SDOperand visitAND(SDNode *N);
163 SDOperand visitOR(SDNode *N);
164 SDOperand visitXOR(SDNode *N);
165 SDOperand SimplifyVBinOp(SDNode *N);
166 SDOperand visitSHL(SDNode *N);
167 SDOperand visitSRA(SDNode *N);
168 SDOperand visitSRL(SDNode *N);
169 SDOperand visitCTLZ(SDNode *N);
170 SDOperand visitCTTZ(SDNode *N);
171 SDOperand visitCTPOP(SDNode *N);
172 SDOperand visitSELECT(SDNode *N);
173 SDOperand visitSELECT_CC(SDNode *N);
174 SDOperand visitSETCC(SDNode *N);
175 SDOperand visitSIGN_EXTEND(SDNode *N);
176 SDOperand visitZERO_EXTEND(SDNode *N);
177 SDOperand visitANY_EXTEND(SDNode *N);
178 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
179 SDOperand visitTRUNCATE(SDNode *N);
180 SDOperand visitBIT_CONVERT(SDNode *N);
181 SDOperand visitBUILD_PAIR(SDNode *N);
182 SDOperand visitFADD(SDNode *N);
183 SDOperand visitFSUB(SDNode *N);
184 SDOperand visitFMUL(SDNode *N);
185 SDOperand visitFDIV(SDNode *N);
186 SDOperand visitFREM(SDNode *N);
187 SDOperand visitFCOPYSIGN(SDNode *N);
188 SDOperand visitSINT_TO_FP(SDNode *N);
189 SDOperand visitUINT_TO_FP(SDNode *N);
190 SDOperand visitFP_TO_SINT(SDNode *N);
191 SDOperand visitFP_TO_UINT(SDNode *N);
192 SDOperand visitFP_ROUND(SDNode *N);
193 SDOperand visitFP_ROUND_INREG(SDNode *N);
194 SDOperand visitFP_EXTEND(SDNode *N);
195 SDOperand visitFNEG(SDNode *N);
196 SDOperand visitFABS(SDNode *N);
197 SDOperand visitBRCOND(SDNode *N);
198 SDOperand visitBR_CC(SDNode *N);
199 SDOperand visitLOAD(SDNode *N);
200 SDOperand visitSTORE(SDNode *N);
201 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
202 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
203 SDOperand visitBUILD_VECTOR(SDNode *N);
204 SDOperand visitCONCAT_VECTORS(SDNode *N);
205 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
207 SDOperand XformToShuffleWithZero(SDNode *N);
208 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
210 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
212 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
213 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
214 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
215 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
216 SDOperand N3, ISD::CondCode CC,
217 bool NotExtCompare = false);
218 SDOperand SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
219 ISD::CondCode Cond, bool foldBooleans = true);
220 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
222 SDOperand CombineConsecutiveLoads(SDNode *N, MVT VT);
223 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
224 SDOperand BuildSDIV(SDNode *N);
225 SDOperand BuildUDIV(SDNode *N);
226 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
227 SDOperand ReduceLoadWidth(SDNode *N);
229 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
231 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
232 /// looking for aliasing nodes and adding them to the Aliases vector.
233 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
234 SmallVector<SDOperand, 8> &Aliases);
236 /// isAlias - Return true if there is any possibility that the two addresses
238 bool isAlias(SDOperand Ptr1, int64_t Size1,
239 const Value *SrcValue1, int SrcValueOffset1,
240 SDOperand Ptr2, int64_t Size2,
241 const Value *SrcValue2, int SrcValueOffset2);
243 /// FindAliasInfo - Extracts the relevant alias information from the memory
244 /// node. Returns true if the operand was a load.
245 bool FindAliasInfo(SDNode *N,
246 SDOperand &Ptr, int64_t &Size,
247 const Value *&SrcValue, int &SrcValueOffset);
249 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
250 /// looking for a better chain (aliasing node.)
251 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
254 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
256 TLI(D.getTargetLoweringInfo()),
257 AfterLegalize(false),
260 /// Run - runs the dag combiner on all nodes in the work list
261 void Run(bool RunningAfterLegalize);
267 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
268 /// nodes from the worklist.
269 class VISIBILITY_HIDDEN WorkListRemover :
270 public SelectionDAG::DAGUpdateListener {
273 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
275 virtual void NodeDeleted(SDNode *N, SDNode *E) {
276 DC.removeFromWorkList(N);
279 virtual void NodeUpdated(SDNode *N) {
285 //===----------------------------------------------------------------------===//
286 // TargetLowering::DAGCombinerInfo implementation
287 //===----------------------------------------------------------------------===//
289 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
290 ((DAGCombiner*)DC)->AddToWorkList(N);
293 SDOperand TargetLowering::DAGCombinerInfo::
294 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
295 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
298 SDOperand TargetLowering::DAGCombinerInfo::
299 CombineTo(SDNode *N, SDOperand Res) {
300 return ((DAGCombiner*)DC)->CombineTo(N, Res);
304 SDOperand TargetLowering::DAGCombinerInfo::
305 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
306 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
310 //===----------------------------------------------------------------------===//
312 //===----------------------------------------------------------------------===//
314 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
315 /// specified expression for the same cost as the expression itself, or 2 if we
316 /// can compute the negated form more cheaply than the expression itself.
317 static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
318 unsigned Depth = 0) {
319 // No compile time optimizations on this type.
320 if (Op.getValueType() == MVT::ppcf128)
323 // fneg is removable even if it has multiple uses.
324 if (Op.getOpcode() == ISD::FNEG) return 2;
326 // Don't allow anything with multiple uses.
327 if (!Op.hasOneUse()) return 0;
329 // Don't recurse exponentially.
330 if (Depth > 6) return 0;
332 switch (Op.getOpcode()) {
333 default: return false;
334 case ISD::ConstantFP:
335 // Don't invert constant FP values after legalize. The negated constant
336 // isn't necessarily legal.
337 return AfterLegalize ? 0 : 1;
339 // FIXME: determine better conditions for this xform.
340 if (!UnsafeFPMath) return 0;
343 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
346 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
348 // We can't turn -(A-B) into B-A when we honor signed zeros.
349 if (!UnsafeFPMath) return 0;
356 if (HonorSignDependentRoundingFPMath()) return 0;
358 // -(X*Y) -> (-X * Y) or (X*-Y)
359 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
362 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
367 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
371 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
372 /// returns the newly negated expression.
373 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
374 bool AfterLegalize, unsigned Depth = 0) {
375 // fneg is removable even if it has multiple uses.
376 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
378 // Don't allow anything with multiple uses.
379 assert(Op.hasOneUse() && "Unknown reuse!");
381 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
382 switch (Op.getOpcode()) {
383 default: assert(0 && "Unknown code");
384 case ISD::ConstantFP: {
385 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
387 return DAG.getConstantFP(V, Op.getValueType());
390 // FIXME: determine better conditions for this xform.
391 assert(UnsafeFPMath);
394 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
395 return DAG.getNode(ISD::FSUB, Op.getValueType(),
396 GetNegatedExpression(Op.getOperand(0), DAG,
397 AfterLegalize, Depth+1),
400 return DAG.getNode(ISD::FSUB, Op.getValueType(),
401 GetNegatedExpression(Op.getOperand(1), DAG,
402 AfterLegalize, Depth+1),
405 // We can't turn -(A-B) into B-A when we honor signed zeros.
406 assert(UnsafeFPMath);
409 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
410 if (N0CFP->getValueAPF().isZero())
411 return Op.getOperand(1);
414 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
419 assert(!HonorSignDependentRoundingFPMath());
422 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
423 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
424 GetNegatedExpression(Op.getOperand(0), DAG,
425 AfterLegalize, Depth+1),
429 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
431 GetNegatedExpression(Op.getOperand(1), DAG,
432 AfterLegalize, Depth+1));
436 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
437 GetNegatedExpression(Op.getOperand(0), DAG,
438 AfterLegalize, Depth+1));
440 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
441 GetNegatedExpression(Op.getOperand(0), DAG,
442 AfterLegalize, Depth+1),
448 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
449 // that selects between the values 1 and 0, making it equivalent to a setcc.
450 // Also, set the incoming LHS, RHS, and CC references to the appropriate
451 // nodes based on the type of node we are checking. This simplifies life a
452 // bit for the callers.
453 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
455 if (N.getOpcode() == ISD::SETCC) {
456 LHS = N.getOperand(0);
457 RHS = N.getOperand(1);
458 CC = N.getOperand(2);
461 if (N.getOpcode() == ISD::SELECT_CC &&
462 N.getOperand(2).getOpcode() == ISD::Constant &&
463 N.getOperand(3).getOpcode() == ISD::Constant &&
464 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
465 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
466 LHS = N.getOperand(0);
467 RHS = N.getOperand(1);
468 CC = N.getOperand(4);
474 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
475 // one use. If this is true, it allows the users to invert the operation for
476 // free when it is profitable to do so.
477 static bool isOneUseSetCC(SDOperand N) {
478 SDOperand N0, N1, N2;
479 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
484 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
485 MVT VT = N0.getValueType();
486 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
487 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
488 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
489 if (isa<ConstantSDNode>(N1)) {
490 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
491 AddToWorkList(OpNode.Val);
492 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
493 } else if (N0.hasOneUse()) {
494 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
495 AddToWorkList(OpNode.Val);
496 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
499 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
500 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
501 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
502 if (isa<ConstantSDNode>(N0)) {
503 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
504 AddToWorkList(OpNode.Val);
505 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
506 } else if (N1.hasOneUse()) {
507 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
508 AddToWorkList(OpNode.Val);
509 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
515 SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
517 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
519 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
520 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
521 DOUT << " and " << NumTo-1 << " other values\n";
522 WorkListRemover DeadNodes(*this);
523 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
526 // Push the new nodes and any users onto the worklist
527 for (unsigned i = 0, e = NumTo; i != e; ++i) {
528 AddToWorkList(To[i].Val);
529 AddUsersToWorkList(To[i].Val);
533 // Nodes can be reintroduced into the worklist. Make sure we do not
534 // process a node that has been replaced.
535 removeFromWorkList(N);
537 // Finally, since the node is now dead, remove it from the graph.
539 return SDOperand(N, 0);
542 /// SimplifyDemandedBits - Check the specified integer node value to see if
543 /// it can be simplified or if things it uses can be simplified by bit
544 /// propagation. If so, return true.
545 bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
546 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
547 APInt KnownZero, KnownOne;
548 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
552 AddToWorkList(Op.Val);
554 // Replace the old value with the new one.
556 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
557 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
560 // Replace all uses. If any nodes become isomorphic to other nodes and
561 // are deleted, make sure to remove them from our worklist.
562 WorkListRemover DeadNodes(*this);
563 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
565 // Push the new node and any (possibly new) users onto the worklist.
566 AddToWorkList(TLO.New.Val);
567 AddUsersToWorkList(TLO.New.Val);
569 // Finally, if the node is now dead, remove it from the graph. The node
570 // may not be dead if the replacement process recursively simplified to
571 // something else needing this node.
572 if (TLO.Old.Val->use_empty()) {
573 removeFromWorkList(TLO.Old.Val);
575 // If the operands of this node are only used by the node, they will now
576 // be dead. Make sure to visit them first to delete dead nodes early.
577 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
578 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
579 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
581 DAG.DeleteNode(TLO.Old.Val);
586 //===----------------------------------------------------------------------===//
587 // Main DAG Combiner implementation
588 //===----------------------------------------------------------------------===//
590 void DAGCombiner::Run(bool RunningAfterLegalize) {
591 // set the instance variable, so that the various visit routines may use it.
592 AfterLegalize = RunningAfterLegalize;
594 // Add all the dag nodes to the worklist.
595 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
596 E = DAG.allnodes_end(); I != E; ++I)
597 WorkList.push_back(I);
599 // Create a dummy node (which is not added to allnodes), that adds a reference
600 // to the root node, preventing it from being deleted, and tracking any
601 // changes of the root.
602 HandleSDNode Dummy(DAG.getRoot());
604 // The root of the dag may dangle to deleted nodes until the dag combiner is
605 // done. Set it to null to avoid confusion.
606 DAG.setRoot(SDOperand());
608 // while the worklist isn't empty, inspect the node on the end of it and
609 // try and combine it.
610 while (!WorkList.empty()) {
611 SDNode *N = WorkList.back();
614 // If N has no uses, it is dead. Make sure to revisit all N's operands once
615 // N is deleted from the DAG, since they too may now be dead or may have a
616 // reduced number of uses, allowing other xforms.
617 if (N->use_empty() && N != &Dummy) {
618 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
619 AddToWorkList(N->getOperand(i).Val);
625 SDOperand RV = combine(N);
632 // If we get back the same node we passed in, rather than a new node or
633 // zero, we know that the node must have defined multiple values and
634 // CombineTo was used. Since CombineTo takes care of the worklist
635 // mechanics for us, we have no work to do in this case.
639 assert(N->getOpcode() != ISD::DELETED_NODE &&
640 RV.Val->getOpcode() != ISD::DELETED_NODE &&
641 "Node was deleted but visit returned new node!");
643 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
644 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
646 WorkListRemover DeadNodes(*this);
647 if (N->getNumValues() == RV.Val->getNumValues())
648 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
650 assert(N->getValueType(0) == RV.getValueType() &&
651 N->getNumValues() == 1 && "Type mismatch");
653 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
656 // Push the new node and any users onto the worklist
657 AddToWorkList(RV.Val);
658 AddUsersToWorkList(RV.Val);
660 // Add any uses of the old node to the worklist in case this node is the
661 // last one that uses them. They may become dead after this node is
663 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
664 AddToWorkList(N->getOperand(i).Val);
666 // Nodes can be reintroduced into the worklist. Make sure we do not
667 // process a node that has been replaced.
668 removeFromWorkList(N);
670 // Finally, since the node is now dead, remove it from the graph.
674 // If the root changed (e.g. it was a dead load, update the root).
675 DAG.setRoot(Dummy.getValue());
678 SDOperand DAGCombiner::visit(SDNode *N) {
679 switch(N->getOpcode()) {
681 case ISD::TokenFactor: return visitTokenFactor(N);
682 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
683 case ISD::ADD: return visitADD(N);
684 case ISD::SUB: return visitSUB(N);
685 case ISD::ADDC: return visitADDC(N);
686 case ISD::ADDE: return visitADDE(N);
687 case ISD::MUL: return visitMUL(N);
688 case ISD::SDIV: return visitSDIV(N);
689 case ISD::UDIV: return visitUDIV(N);
690 case ISD::SREM: return visitSREM(N);
691 case ISD::UREM: return visitUREM(N);
692 case ISD::MULHU: return visitMULHU(N);
693 case ISD::MULHS: return visitMULHS(N);
694 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
695 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
696 case ISD::SDIVREM: return visitSDIVREM(N);
697 case ISD::UDIVREM: return visitUDIVREM(N);
698 case ISD::AND: return visitAND(N);
699 case ISD::OR: return visitOR(N);
700 case ISD::XOR: return visitXOR(N);
701 case ISD::SHL: return visitSHL(N);
702 case ISD::SRA: return visitSRA(N);
703 case ISD::SRL: return visitSRL(N);
704 case ISD::CTLZ: return visitCTLZ(N);
705 case ISD::CTTZ: return visitCTTZ(N);
706 case ISD::CTPOP: return visitCTPOP(N);
707 case ISD::SELECT: return visitSELECT(N);
708 case ISD::SELECT_CC: return visitSELECT_CC(N);
709 case ISD::SETCC: return visitSETCC(N);
710 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
711 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
712 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
713 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
714 case ISD::TRUNCATE: return visitTRUNCATE(N);
715 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
716 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
717 case ISD::FADD: return visitFADD(N);
718 case ISD::FSUB: return visitFSUB(N);
719 case ISD::FMUL: return visitFMUL(N);
720 case ISD::FDIV: return visitFDIV(N);
721 case ISD::FREM: return visitFREM(N);
722 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
723 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
724 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
725 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
726 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
727 case ISD::FP_ROUND: return visitFP_ROUND(N);
728 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
729 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
730 case ISD::FNEG: return visitFNEG(N);
731 case ISD::FABS: return visitFABS(N);
732 case ISD::BRCOND: return visitBRCOND(N);
733 case ISD::BR_CC: return visitBR_CC(N);
734 case ISD::LOAD: return visitLOAD(N);
735 case ISD::STORE: return visitSTORE(N);
736 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
737 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
738 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
739 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
740 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
745 SDOperand DAGCombiner::combine(SDNode *N) {
747 SDOperand RV = visit(N);
749 // If nothing happened, try a target-specific DAG combine.
751 assert(N->getOpcode() != ISD::DELETED_NODE &&
752 "Node was deleted but visit returned NULL!");
754 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
755 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
757 // Expose the DAG combiner to the target combiner impls.
758 TargetLowering::DAGCombinerInfo
759 DagCombineInfo(DAG, !AfterLegalize, false, this);
761 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
765 // If N is a commutative binary node, try commuting it to enable more
768 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
769 N->getNumValues() == 1) {
770 SDOperand N0 = N->getOperand(0);
771 SDOperand N1 = N->getOperand(1);
772 // Constant operands are canonicalized to RHS.
773 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
774 SDOperand Ops[] = { N1, N0 };
775 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
778 return SDOperand(CSENode, 0);
785 /// getInputChainForNode - Given a node, return its input chain if it has one,
786 /// otherwise return a null sd operand.
787 static SDOperand getInputChainForNode(SDNode *N) {
788 if (unsigned NumOps = N->getNumOperands()) {
789 if (N->getOperand(0).getValueType() == MVT::Other)
790 return N->getOperand(0);
791 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
792 return N->getOperand(NumOps-1);
793 for (unsigned i = 1; i < NumOps-1; ++i)
794 if (N->getOperand(i).getValueType() == MVT::Other)
795 return N->getOperand(i);
797 return SDOperand(0, 0);
800 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
801 // If N has two operands, where one has an input chain equal to the other,
802 // the 'other' chain is redundant.
803 if (N->getNumOperands() == 2) {
804 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
805 return N->getOperand(0);
806 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
807 return N->getOperand(1);
810 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
811 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
812 SmallPtrSet<SDNode*, 16> SeenOps;
813 bool Changed = false; // If we should replace this token factor.
815 // Start out with this token factor.
818 // Iterate through token factors. The TFs grows when new token factors are
820 for (unsigned i = 0; i < TFs.size(); ++i) {
823 // Check each of the operands.
824 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
825 SDOperand Op = TF->getOperand(i);
827 switch (Op.getOpcode()) {
828 case ISD::EntryToken:
829 // Entry tokens don't need to be added to the list. They are
834 case ISD::TokenFactor:
835 if ((CombinerAA || Op.hasOneUse()) &&
836 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
837 // Queue up for processing.
838 TFs.push_back(Op.Val);
839 // Clean up in case the token factor is removed.
840 AddToWorkList(Op.Val);
847 // Only add if it isn't already in the list.
848 if (SeenOps.insert(Op.Val))
859 // If we've change things around then replace token factor.
862 // The entry token is the only possible outcome.
863 Result = DAG.getEntryNode();
865 // New and improved token factor.
866 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
869 // Don't add users to work list.
870 return CombineTo(N, Result, false);
876 /// MERGE_VALUES can always be eliminated.
877 SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
878 WorkListRemover DeadNodes(*this);
879 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
880 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
882 removeFromWorkList(N);
884 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
889 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
890 MVT VT = N0.getValueType();
891 SDOperand N00 = N0.getOperand(0);
892 SDOperand N01 = N0.getOperand(1);
893 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
894 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
895 isa<ConstantSDNode>(N00.getOperand(1))) {
896 N0 = DAG.getNode(ISD::ADD, VT,
897 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
898 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
899 return DAG.getNode(ISD::ADD, VT, N0, N1);
905 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
907 MVT VT = N->getValueType(0);
908 unsigned Opc = N->getOpcode();
909 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
910 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
911 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
912 ISD::CondCode CC = ISD::SETCC_INVALID;
914 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
916 SDOperand CCOp = Slct.getOperand(0);
917 if (CCOp.getOpcode() == ISD::SETCC)
918 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
921 bool DoXform = false;
923 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
925 if (LHS.getOpcode() == ISD::Constant &&
926 cast<ConstantSDNode>(LHS)->isNullValue())
928 else if (CC != ISD::SETCC_INVALID &&
929 RHS.getOpcode() == ISD::Constant &&
930 cast<ConstantSDNode>(RHS)->isNullValue()) {
932 SDOperand Op0 = Slct.getOperand(0);
933 bool isInt = (isSlctCC ? Op0.getValueType() :
934 Op0.getOperand(0).getValueType()).isInteger();
935 CC = ISD::getSetCCInverse(CC, isInt);
941 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
943 return DAG.getSelectCC(OtherOp, Result,
944 Slct.getOperand(0), Slct.getOperand(1), CC);
945 SDOperand CCOp = Slct.getOperand(0);
947 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
948 CCOp.getOperand(1), CC);
949 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
954 SDOperand DAGCombiner::visitADD(SDNode *N) {
955 SDOperand N0 = N->getOperand(0);
956 SDOperand N1 = N->getOperand(1);
957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
959 MVT VT = N0.getValueType();
963 SDOperand FoldedVOp = SimplifyVBinOp(N);
964 if (FoldedVOp.Val) return FoldedVOp;
967 // fold (add x, undef) -> undef
968 if (N0.getOpcode() == ISD::UNDEF)
970 if (N1.getOpcode() == ISD::UNDEF)
972 // fold (add c1, c2) -> c1+c2
974 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
975 // canonicalize constant to RHS
977 return DAG.getNode(ISD::ADD, VT, N1, N0);
978 // fold (add x, 0) -> x
979 if (N1C && N1C->isNullValue())
981 // fold ((c1-A)+c2) -> (c1+c2)-A
982 if (N1C && N0.getOpcode() == ISD::SUB)
983 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
984 return DAG.getNode(ISD::SUB, VT,
985 DAG.getConstant(N1C->getAPIntValue()+
986 N0C->getAPIntValue(), VT),
989 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
992 // fold ((0-A) + B) -> B-A
993 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
994 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
995 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
996 // fold (A + (0-B)) -> A-B
997 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
998 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
999 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
1000 // fold (A+(B-A)) -> B
1001 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1002 return N1.getOperand(0);
1004 if (!VT.isVector() && SimplifyDemandedBits(SDOperand(N, 0)))
1005 return SDOperand(N, 0);
1007 // fold (a+b) -> (a|b) iff a and b share no bits.
1008 if (VT.isInteger() && !VT.isVector()) {
1009 APInt LHSZero, LHSOne;
1010 APInt RHSZero, RHSOne;
1011 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1012 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1013 if (LHSZero.getBoolValue()) {
1014 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1016 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1017 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1018 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1019 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1020 return DAG.getNode(ISD::OR, VT, N0, N1);
1024 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1025 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1026 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1027 if (Result.Val) return Result;
1029 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1030 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1031 if (Result.Val) return Result;
1034 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1035 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1036 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1037 if (Result.Val) return Result;
1039 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1040 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1041 if (Result.Val) return Result;
1047 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1048 SDOperand N0 = N->getOperand(0);
1049 SDOperand N1 = N->getOperand(1);
1050 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1051 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1052 MVT VT = N0.getValueType();
1054 // If the flag result is dead, turn this into an ADD.
1055 if (N->hasNUsesOfValue(0, 1))
1056 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1057 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1059 // canonicalize constant to RHS.
1061 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1063 // fold (addc x, 0) -> x + no carry out
1064 if (N1C && N1C->isNullValue())
1065 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1067 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1068 APInt LHSZero, LHSOne;
1069 APInt RHSZero, RHSOne;
1070 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1071 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1072 if (LHSZero.getBoolValue()) {
1073 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1075 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1076 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1077 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1078 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1079 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1080 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1086 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1087 SDOperand N0 = N->getOperand(0);
1088 SDOperand N1 = N->getOperand(1);
1089 SDOperand CarryIn = N->getOperand(2);
1090 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1092 //MVT VT = N0.getValueType();
1094 // canonicalize constant to RHS
1096 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn);
1098 // fold (adde x, y, false) -> (addc x, y)
1099 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1100 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1107 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1108 SDOperand N0 = N->getOperand(0);
1109 SDOperand N1 = N->getOperand(1);
1110 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1111 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1112 MVT VT = N0.getValueType();
1115 if (VT.isVector()) {
1116 SDOperand FoldedVOp = SimplifyVBinOp(N);
1117 if (FoldedVOp.Val) return FoldedVOp;
1120 // fold (sub x, x) -> 0
1122 return DAG.getConstant(0, N->getValueType(0));
1123 // fold (sub c1, c2) -> c1-c2
1125 return DAG.getNode(ISD::SUB, VT, N0, N1);
1126 // fold (sub x, c) -> (add x, -c)
1128 return DAG.getNode(ISD::ADD, VT, N0,
1129 DAG.getConstant(-N1C->getAPIntValue(), VT));
1130 // fold (A+B)-A -> B
1131 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1132 return N0.getOperand(1);
1133 // fold (A+B)-B -> A
1134 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1135 return N0.getOperand(0);
1136 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1137 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1138 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1139 if (Result.Val) return Result;
1141 // If either operand of a sub is undef, the result is undef
1142 if (N0.getOpcode() == ISD::UNDEF)
1144 if (N1.getOpcode() == ISD::UNDEF)
1150 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1151 SDOperand N0 = N->getOperand(0);
1152 SDOperand N1 = N->getOperand(1);
1153 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1154 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1155 MVT VT = N0.getValueType();
1158 if (VT.isVector()) {
1159 SDOperand FoldedVOp = SimplifyVBinOp(N);
1160 if (FoldedVOp.Val) return FoldedVOp;
1163 // fold (mul x, undef) -> 0
1164 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1165 return DAG.getConstant(0, VT);
1166 // fold (mul c1, c2) -> c1*c2
1168 return DAG.getNode(ISD::MUL, VT, N0, N1);
1169 // canonicalize constant to RHS
1171 return DAG.getNode(ISD::MUL, VT, N1, N0);
1172 // fold (mul x, 0) -> 0
1173 if (N1C && N1C->isNullValue())
1175 // fold (mul x, -1) -> 0-x
1176 if (N1C && N1C->isAllOnesValue())
1177 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1178 // fold (mul x, (1 << c)) -> x << c
1179 if (N1C && N1C->getAPIntValue().isPowerOf2())
1180 return DAG.getNode(ISD::SHL, VT, N0,
1181 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1182 TLI.getShiftAmountTy()));
1183 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1184 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1185 // FIXME: If the input is something that is easily negated (e.g. a
1186 // single-use add), we should put the negate there.
1187 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1188 DAG.getNode(ISD::SHL, VT, N0,
1189 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1190 TLI.getShiftAmountTy())));
1193 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1194 if (N1C && N0.getOpcode() == ISD::SHL &&
1195 isa<ConstantSDNode>(N0.getOperand(1))) {
1196 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1197 AddToWorkList(C3.Val);
1198 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1201 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1204 SDOperand Sh(0,0), Y(0,0);
1205 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1206 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1207 N0.Val->hasOneUse()) {
1209 } else if (N1.getOpcode() == ISD::SHL &&
1210 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1214 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1215 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1218 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1219 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1220 isa<ConstantSDNode>(N0.getOperand(1))) {
1221 return DAG.getNode(ISD::ADD, VT,
1222 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1223 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1227 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1234 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1235 SDOperand N0 = N->getOperand(0);
1236 SDOperand N1 = N->getOperand(1);
1237 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1238 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1239 MVT VT = N->getValueType(0);
1242 if (VT.isVector()) {
1243 SDOperand FoldedVOp = SimplifyVBinOp(N);
1244 if (FoldedVOp.Val) return FoldedVOp;
1247 // fold (sdiv c1, c2) -> c1/c2
1248 if (N0C && N1C && !N1C->isNullValue())
1249 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1250 // fold (sdiv X, 1) -> X
1251 if (N1C && N1C->getSignExtended() == 1LL)
1253 // fold (sdiv X, -1) -> 0-X
1254 if (N1C && N1C->isAllOnesValue())
1255 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1256 // If we know the sign bits of both operands are zero, strength reduce to a
1257 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1258 if (!VT.isVector()) {
1259 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1260 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1262 // fold (sdiv X, pow2) -> simple ops after legalize
1263 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1264 (isPowerOf2_64(N1C->getSignExtended()) ||
1265 isPowerOf2_64(-N1C->getSignExtended()))) {
1266 // If dividing by powers of two is cheap, then don't perform the following
1268 if (TLI.isPow2DivCheap())
1270 int64_t pow2 = N1C->getSignExtended();
1271 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1272 unsigned lg2 = Log2_64(abs2);
1273 // Splat the sign bit into the register
1274 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1275 DAG.getConstant(VT.getSizeInBits()-1,
1276 TLI.getShiftAmountTy()));
1277 AddToWorkList(SGN.Val);
1278 // Add (N0 < 0) ? abs2 - 1 : 0;
1279 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1280 DAG.getConstant(VT.getSizeInBits()-lg2,
1281 TLI.getShiftAmountTy()));
1282 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1283 AddToWorkList(SRL.Val);
1284 AddToWorkList(ADD.Val); // Divide by pow2
1285 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1286 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1287 // If we're dividing by a positive value, we're done. Otherwise, we must
1288 // negate the result.
1291 AddToWorkList(SRA.Val);
1292 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1294 // if integer divide is expensive and we satisfy the requirements, emit an
1295 // alternate sequence.
1296 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1297 !TLI.isIntDivCheap()) {
1298 SDOperand Op = BuildSDIV(N);
1299 if (Op.Val) return Op;
1303 if (N0.getOpcode() == ISD::UNDEF)
1304 return DAG.getConstant(0, VT);
1305 // X / undef -> undef
1306 if (N1.getOpcode() == ISD::UNDEF)
1312 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1313 SDOperand N0 = N->getOperand(0);
1314 SDOperand N1 = N->getOperand(1);
1315 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1316 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1317 MVT VT = N->getValueType(0);
1320 if (VT.isVector()) {
1321 SDOperand FoldedVOp = SimplifyVBinOp(N);
1322 if (FoldedVOp.Val) return FoldedVOp;
1325 // fold (udiv c1, c2) -> c1/c2
1326 if (N0C && N1C && !N1C->isNullValue())
1327 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1328 // fold (udiv x, (1 << c)) -> x >>u c
1329 if (N1C && N1C->getAPIntValue().isPowerOf2())
1330 return DAG.getNode(ISD::SRL, VT, N0,
1331 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1332 TLI.getShiftAmountTy()));
1333 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1334 if (N1.getOpcode() == ISD::SHL) {
1335 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1336 if (SHC->getAPIntValue().isPowerOf2()) {
1337 MVT ADDVT = N1.getOperand(1).getValueType();
1338 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1339 DAG.getConstant(SHC->getAPIntValue()
1342 AddToWorkList(Add.Val);
1343 return DAG.getNode(ISD::SRL, VT, N0, Add);
1347 // fold (udiv x, c) -> alternate
1348 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1349 SDOperand Op = BuildUDIV(N);
1350 if (Op.Val) return Op;
1354 if (N0.getOpcode() == ISD::UNDEF)
1355 return DAG.getConstant(0, VT);
1356 // X / undef -> undef
1357 if (N1.getOpcode() == ISD::UNDEF)
1363 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1364 SDOperand N0 = N->getOperand(0);
1365 SDOperand N1 = N->getOperand(1);
1366 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1367 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1368 MVT VT = N->getValueType(0);
1370 // fold (srem c1, c2) -> c1%c2
1371 if (N0C && N1C && !N1C->isNullValue())
1372 return DAG.getNode(ISD::SREM, VT, N0, N1);
1373 // If we know the sign bits of both operands are zero, strength reduce to a
1374 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1375 if (!VT.isVector()) {
1376 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1377 return DAG.getNode(ISD::UREM, VT, N0, N1);
1380 // If X/C can be simplified by the division-by-constant logic, lower
1381 // X%C to the equivalent of X-X/C*C.
1382 if (N1C && !N1C->isNullValue()) {
1383 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1384 AddToWorkList(Div.Val);
1385 SDOperand OptimizedDiv = combine(Div.Val);
1386 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1387 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1388 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1389 AddToWorkList(Mul.Val);
1395 if (N0.getOpcode() == ISD::UNDEF)
1396 return DAG.getConstant(0, VT);
1397 // X % undef -> undef
1398 if (N1.getOpcode() == ISD::UNDEF)
1404 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1405 SDOperand N0 = N->getOperand(0);
1406 SDOperand N1 = N->getOperand(1);
1407 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1408 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1409 MVT VT = N->getValueType(0);
1411 // fold (urem c1, c2) -> c1%c2
1412 if (N0C && N1C && !N1C->isNullValue())
1413 return DAG.getNode(ISD::UREM, VT, N0, N1);
1414 // fold (urem x, pow2) -> (and x, pow2-1)
1415 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1416 return DAG.getNode(ISD::AND, VT, N0,
1417 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1418 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1419 if (N1.getOpcode() == ISD::SHL) {
1420 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1421 if (SHC->getAPIntValue().isPowerOf2()) {
1423 DAG.getNode(ISD::ADD, VT, N1,
1424 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1426 AddToWorkList(Add.Val);
1427 return DAG.getNode(ISD::AND, VT, N0, Add);
1432 // If X/C can be simplified by the division-by-constant logic, lower
1433 // X%C to the equivalent of X-X/C*C.
1434 if (N1C && !N1C->isNullValue()) {
1435 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1436 SDOperand OptimizedDiv = combine(Div.Val);
1437 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1438 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1439 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1440 AddToWorkList(Mul.Val);
1446 if (N0.getOpcode() == ISD::UNDEF)
1447 return DAG.getConstant(0, VT);
1448 // X % undef -> undef
1449 if (N1.getOpcode() == ISD::UNDEF)
1455 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1456 SDOperand N0 = N->getOperand(0);
1457 SDOperand N1 = N->getOperand(1);
1458 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1459 MVT VT = N->getValueType(0);
1461 // fold (mulhs x, 0) -> 0
1462 if (N1C && N1C->isNullValue())
1464 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1465 if (N1C && N1C->getAPIntValue() == 1)
1466 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1467 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1468 TLI.getShiftAmountTy()));
1469 // fold (mulhs x, undef) -> 0
1470 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1471 return DAG.getConstant(0, VT);
1476 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1477 SDOperand N0 = N->getOperand(0);
1478 SDOperand N1 = N->getOperand(1);
1479 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1480 MVT VT = N->getValueType(0);
1482 // fold (mulhu x, 0) -> 0
1483 if (N1C && N1C->isNullValue())
1485 // fold (mulhu x, 1) -> 0
1486 if (N1C && N1C->getAPIntValue() == 1)
1487 return DAG.getConstant(0, N0.getValueType());
1488 // fold (mulhu x, undef) -> 0
1489 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1490 return DAG.getConstant(0, VT);
1495 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1496 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1497 /// that are being performed. Return true if a simplification was made.
1499 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1501 // If the high half is not needed, just compute the low half.
1502 bool HiExists = N->hasAnyUseOfValue(1);
1505 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1506 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1507 N->getNumOperands());
1508 return CombineTo(N, Res, Res);
1511 // If the low half is not needed, just compute the high half.
1512 bool LoExists = N->hasAnyUseOfValue(0);
1515 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1516 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1517 N->getNumOperands());
1518 return CombineTo(N, Res, Res);
1521 // If both halves are used, return as it is.
1522 if (LoExists && HiExists)
1525 // If the two computed results can be simplified separately, separate them.
1527 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1528 N->op_begin(), N->getNumOperands());
1529 AddToWorkList(Lo.Val);
1530 SDOperand LoOpt = combine(Lo.Val);
1531 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1533 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1534 return CombineTo(N, LoOpt, LoOpt);
1538 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1539 N->op_begin(), N->getNumOperands());
1540 AddToWorkList(Hi.Val);
1541 SDOperand HiOpt = combine(Hi.Val);
1542 if (HiOpt.Val && HiOpt != Hi &&
1544 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1545 return CombineTo(N, HiOpt, HiOpt);
1550 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1551 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1552 if (Res.Val) return Res;
1557 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1558 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1559 if (Res.Val) return Res;
1564 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1565 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1566 if (Res.Val) return Res;
1571 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1572 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1573 if (Res.Val) return Res;
1578 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1579 /// two operands of the same opcode, try to simplify it.
1580 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1581 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1582 MVT VT = N0.getValueType();
1583 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1585 // For each of OP in AND/OR/XOR:
1586 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1587 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1588 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1589 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1590 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1591 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1592 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1593 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1594 N0.getOperand(0).getValueType(),
1595 N0.getOperand(0), N1.getOperand(0));
1596 AddToWorkList(ORNode.Val);
1597 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1600 // For each of OP in SHL/SRL/SRA/AND...
1601 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1602 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1603 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1604 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1605 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1606 N0.getOperand(1) == N1.getOperand(1)) {
1607 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1608 N0.getOperand(0).getValueType(),
1609 N0.getOperand(0), N1.getOperand(0));
1610 AddToWorkList(ORNode.Val);
1611 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1617 SDOperand DAGCombiner::visitAND(SDNode *N) {
1618 SDOperand N0 = N->getOperand(0);
1619 SDOperand N1 = N->getOperand(1);
1620 SDOperand LL, LR, RL, RR, CC0, CC1;
1621 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1622 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1623 MVT VT = N1.getValueType();
1624 unsigned BitWidth = VT.getSizeInBits();
1627 if (VT.isVector()) {
1628 SDOperand FoldedVOp = SimplifyVBinOp(N);
1629 if (FoldedVOp.Val) return FoldedVOp;
1632 // fold (and x, undef) -> 0
1633 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1634 return DAG.getConstant(0, VT);
1635 // fold (and c1, c2) -> c1&c2
1637 return DAG.getNode(ISD::AND, VT, N0, N1);
1638 // canonicalize constant to RHS
1640 return DAG.getNode(ISD::AND, VT, N1, N0);
1641 // fold (and x, -1) -> x
1642 if (N1C && N1C->isAllOnesValue())
1644 // if (and x, c) is known to be zero, return 0
1645 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1646 APInt::getAllOnesValue(BitWidth)))
1647 return DAG.getConstant(0, VT);
1649 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1652 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1653 if (N1C && N0.getOpcode() == ISD::OR)
1654 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1655 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1657 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1658 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1659 SDOperand N0Op0 = N0.getOperand(0);
1660 APInt Mask = ~N1C->getAPIntValue();
1661 Mask.trunc(N0Op0.getValueSizeInBits());
1662 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1663 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1666 // Replace uses of the AND with uses of the Zero extend node.
1669 // We actually want to replace all uses of the any_extend with the
1670 // zero_extend, to avoid duplicating things. This will later cause this
1671 // AND to be folded.
1672 CombineTo(N0.Val, Zext);
1673 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1676 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1677 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1678 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1679 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1681 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1682 LL.getValueType().isInteger()) {
1683 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1684 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1685 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1686 AddToWorkList(ORNode.Val);
1687 return DAG.getSetCC(VT, ORNode, LR, Op1);
1689 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1690 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1691 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1692 AddToWorkList(ANDNode.Val);
1693 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1695 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1696 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1697 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1698 AddToWorkList(ORNode.Val);
1699 return DAG.getSetCC(VT, ORNode, LR, Op1);
1702 // canonicalize equivalent to ll == rl
1703 if (LL == RR && LR == RL) {
1704 Op1 = ISD::getSetCCSwappedOperands(Op1);
1707 if (LL == RL && LR == RR) {
1708 bool isInteger = LL.getValueType().isInteger();
1709 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1710 if (Result != ISD::SETCC_INVALID)
1711 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1715 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1716 if (N0.getOpcode() == N1.getOpcode()) {
1717 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1718 if (Tmp.Val) return Tmp;
1721 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1722 // fold (and (sra)) -> (and (srl)) when possible.
1723 if (!VT.isVector() &&
1724 SimplifyDemandedBits(SDOperand(N, 0)))
1725 return SDOperand(N, 0);
1726 // fold (zext_inreg (extload x)) -> (zextload x)
1727 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1728 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1729 MVT EVT = LN0->getMemoryVT();
1730 // If we zero all the possible extended bits, then we can turn this into
1731 // a zextload if we are running before legalize or the operation is legal.
1732 unsigned BitWidth = N1.getValueSizeInBits();
1733 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1734 BitWidth - EVT.getSizeInBits())) &&
1735 ((!AfterLegalize && !LN0->isVolatile()) ||
1736 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1737 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1738 LN0->getBasePtr(), LN0->getSrcValue(),
1739 LN0->getSrcValueOffset(), EVT,
1741 LN0->getAlignment());
1743 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1744 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1747 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1748 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1750 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1751 MVT EVT = LN0->getMemoryVT();
1752 // If we zero all the possible extended bits, then we can turn this into
1753 // a zextload if we are running before legalize or the operation is legal.
1754 unsigned BitWidth = N1.getValueSizeInBits();
1755 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1756 BitWidth - EVT.getSizeInBits())) &&
1757 ((!AfterLegalize && !LN0->isVolatile()) ||
1758 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1759 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1760 LN0->getBasePtr(), LN0->getSrcValue(),
1761 LN0->getSrcValueOffset(), EVT,
1763 LN0->getAlignment());
1765 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1766 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1770 // fold (and (load x), 255) -> (zextload x, i8)
1771 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1772 if (N1C && N0.getOpcode() == ISD::LOAD) {
1773 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1774 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1775 LN0->isUnindexed() && N0.hasOneUse() &&
1776 // Do not change the width of a volatile load.
1777 !LN0->isVolatile()) {
1778 MVT EVT = MVT::Other;
1779 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1780 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1781 EVT = MVT::getIntegerVT(ActiveBits);
1783 MVT LoadedVT = LN0->getMemoryVT();
1784 // Do not generate loads of non-round integer types since these can
1785 // be expensive (and would be wrong if the type is not byte sized).
1786 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
1787 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1788 MVT PtrType = N0.getOperand(1).getValueType();
1789 // For big endian targets, we need to add an offset to the pointer to
1790 // load the correct bytes. For little endian systems, we merely need to
1791 // read fewer bytes from the same pointer.
1792 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1793 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1794 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1795 unsigned Alignment = LN0->getAlignment();
1796 SDOperand NewPtr = LN0->getBasePtr();
1797 if (TLI.isBigEndian()) {
1798 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1799 DAG.getConstant(PtrOff, PtrType));
1800 Alignment = MinAlign(Alignment, PtrOff);
1802 AddToWorkList(NewPtr.Val);
1804 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1805 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1806 LN0->isVolatile(), Alignment);
1808 CombineTo(N0.Val, Load, Load.getValue(1));
1809 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1817 SDOperand DAGCombiner::visitOR(SDNode *N) {
1818 SDOperand N0 = N->getOperand(0);
1819 SDOperand N1 = N->getOperand(1);
1820 SDOperand LL, LR, RL, RR, CC0, CC1;
1821 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1822 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1823 MVT VT = N1.getValueType();
1826 if (VT.isVector()) {
1827 SDOperand FoldedVOp = SimplifyVBinOp(N);
1828 if (FoldedVOp.Val) return FoldedVOp;
1831 // fold (or x, undef) -> -1
1832 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1833 return DAG.getConstant(~0ULL, VT);
1834 // fold (or c1, c2) -> c1|c2
1836 return DAG.getNode(ISD::OR, VT, N0, N1);
1837 // canonicalize constant to RHS
1839 return DAG.getNode(ISD::OR, VT, N1, N0);
1840 // fold (or x, 0) -> x
1841 if (N1C && N1C->isNullValue())
1843 // fold (or x, -1) -> -1
1844 if (N1C && N1C->isAllOnesValue())
1846 // fold (or x, c) -> c iff (x & ~c) == 0
1847 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1850 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1853 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1854 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1855 isa<ConstantSDNode>(N0.getOperand(1))) {
1856 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1857 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1859 DAG.getConstant(N1C->getAPIntValue() |
1860 C1->getAPIntValue(), VT));
1862 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1863 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1864 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1865 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1867 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1868 LL.getValueType().isInteger()) {
1869 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1870 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1871 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1872 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1873 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1874 AddToWorkList(ORNode.Val);
1875 return DAG.getSetCC(VT, ORNode, LR, Op1);
1877 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1878 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1879 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1880 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1881 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1882 AddToWorkList(ANDNode.Val);
1883 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1886 // canonicalize equivalent to ll == rl
1887 if (LL == RR && LR == RL) {
1888 Op1 = ISD::getSetCCSwappedOperands(Op1);
1891 if (LL == RL && LR == RR) {
1892 bool isInteger = LL.getValueType().isInteger();
1893 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1894 if (Result != ISD::SETCC_INVALID)
1895 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1899 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1900 if (N0.getOpcode() == N1.getOpcode()) {
1901 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1902 if (Tmp.Val) return Tmp;
1905 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1906 if (N0.getOpcode() == ISD::AND &&
1907 N1.getOpcode() == ISD::AND &&
1908 N0.getOperand(1).getOpcode() == ISD::Constant &&
1909 N1.getOperand(1).getOpcode() == ISD::Constant &&
1910 // Don't increase # computations.
1911 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1912 // We can only do this xform if we know that bits from X that are set in C2
1913 // but not in C1 are already zero. Likewise for Y.
1914 const APInt &LHSMask =
1915 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1916 const APInt &RHSMask =
1917 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1919 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1920 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1921 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1922 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1927 // See if this is some rotate idiom.
1928 if (SDNode *Rot = MatchRotate(N0, N1))
1929 return SDOperand(Rot, 0);
1935 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1936 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1937 if (Op.getOpcode() == ISD::AND) {
1938 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1939 Mask = Op.getOperand(1);
1940 Op = Op.getOperand(0);
1946 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1954 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1955 // idioms for rotate, and if the target supports rotation instructions, generate
1957 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1958 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
1959 MVT VT = LHS.getValueType();
1960 if (!TLI.isTypeLegal(VT)) return 0;
1962 // The target must have at least one rotate flavor.
1963 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1964 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1965 if (!HasROTL && !HasROTR) return 0;
1967 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1968 SDOperand LHSShift; // The shift.
1969 SDOperand LHSMask; // AND value if any.
1970 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1971 return 0; // Not part of a rotate.
1973 SDOperand RHSShift; // The shift.
1974 SDOperand RHSMask; // AND value if any.
1975 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1976 return 0; // Not part of a rotate.
1978 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1979 return 0; // Not shifting the same value.
1981 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1982 return 0; // Shifts must disagree.
1984 // Canonicalize shl to left side in a shl/srl pair.
1985 if (RHSShift.getOpcode() == ISD::SHL) {
1986 std::swap(LHS, RHS);
1987 std::swap(LHSShift, RHSShift);
1988 std::swap(LHSMask , RHSMask );
1991 unsigned OpSizeInBits = VT.getSizeInBits();
1992 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1993 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1994 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1996 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1997 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1998 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1999 RHSShiftAmt.getOpcode() == ISD::Constant) {
2000 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
2001 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
2002 if ((LShVal + RShVal) != OpSizeInBits)
2007 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2009 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2011 // If there is an AND of either shifted operand, apply it to the result.
2012 if (LHSMask.Val || RHSMask.Val) {
2013 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2016 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2017 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2020 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2021 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2024 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2030 // If there is a mask here, and we have a variable shift, we can't be sure
2031 // that we're masking out the right stuff.
2032 if (LHSMask.Val || RHSMask.Val)
2035 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2036 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2037 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2038 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2039 if (ConstantSDNode *SUBC =
2040 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2041 if (SUBC->getAPIntValue() == OpSizeInBits) {
2043 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2045 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2050 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2051 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2052 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2053 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2054 if (ConstantSDNode *SUBC =
2055 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2056 if (SUBC->getAPIntValue() == OpSizeInBits) {
2058 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2060 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2065 // Look for sign/zext/any-extended cases:
2066 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2067 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2068 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2069 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2070 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2071 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2072 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2073 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2074 if (RExtOp0.getOpcode() == ISD::SUB &&
2075 RExtOp0.getOperand(1) == LExtOp0) {
2076 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2078 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2079 // (rotl x, (sub 32, y))
2080 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2081 if (SUBC->getAPIntValue() == OpSizeInBits) {
2083 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2085 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2088 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2089 RExtOp0 == LExtOp0.getOperand(1)) {
2090 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2092 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2093 // (rotr x, (sub 32, y))
2094 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2095 if (SUBC->getAPIntValue() == OpSizeInBits) {
2097 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2099 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2109 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2110 SDOperand N0 = N->getOperand(0);
2111 SDOperand N1 = N->getOperand(1);
2112 SDOperand LHS, RHS, CC;
2113 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2114 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2115 MVT VT = N0.getValueType();
2118 if (VT.isVector()) {
2119 SDOperand FoldedVOp = SimplifyVBinOp(N);
2120 if (FoldedVOp.Val) return FoldedVOp;
2123 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2124 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2125 return DAG.getConstant(0, VT);
2126 // fold (xor x, undef) -> undef
2127 if (N0.getOpcode() == ISD::UNDEF)
2129 if (N1.getOpcode() == ISD::UNDEF)
2131 // fold (xor c1, c2) -> c1^c2
2133 return DAG.getNode(ISD::XOR, VT, N0, N1);
2134 // canonicalize constant to RHS
2136 return DAG.getNode(ISD::XOR, VT, N1, N0);
2137 // fold (xor x, 0) -> x
2138 if (N1C && N1C->isNullValue())
2141 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2144 // fold !(x cc y) -> (x !cc y)
2145 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2146 bool isInt = LHS.getValueType().isInteger();
2147 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2149 if (N0.getOpcode() == ISD::SETCC)
2150 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2151 if (N0.getOpcode() == ISD::SELECT_CC)
2152 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2153 assert(0 && "Unhandled SetCC Equivalent!");
2156 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2157 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2158 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2159 SDOperand V = N0.getOperand(0);
2160 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2161 DAG.getConstant(1, V.getValueType()));
2162 AddToWorkList(V.Val);
2163 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2166 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2167 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2168 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2169 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2170 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2171 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2172 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2173 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2174 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2175 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2178 // fold !(x or y) -> (!x and !y) iff x or y are constants
2179 if (N1C && N1C->isAllOnesValue() &&
2180 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2181 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2182 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2183 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2184 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2185 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2186 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2187 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2190 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2191 if (N1C && N0.getOpcode() == ISD::XOR) {
2192 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2193 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2195 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2196 DAG.getConstant(N1C->getAPIntValue()^
2197 N00C->getAPIntValue(), VT));
2199 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2200 DAG.getConstant(N1C->getAPIntValue()^
2201 N01C->getAPIntValue(), VT));
2203 // fold (xor x, x) -> 0
2205 if (!VT.isVector()) {
2206 return DAG.getConstant(0, VT);
2207 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2208 // Produce a vector of zeros.
2209 SDOperand El = DAG.getConstant(0, VT.getVectorElementType());
2210 std::vector<SDOperand> Ops(VT.getVectorNumElements(), El);
2211 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2215 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2216 if (N0.getOpcode() == N1.getOpcode()) {
2217 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2218 if (Tmp.Val) return Tmp;
2221 // Simplify the expression using non-local knowledge.
2222 if (!VT.isVector() &&
2223 SimplifyDemandedBits(SDOperand(N, 0)))
2224 return SDOperand(N, 0);
2229 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2230 /// the shift amount is a constant.
2231 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2232 SDNode *LHS = N->getOperand(0).Val;
2233 if (!LHS->hasOneUse()) return SDOperand();
2235 // We want to pull some binops through shifts, so that we have (and (shift))
2236 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2237 // thing happens with address calculations, so it's important to canonicalize
2239 bool HighBitSet = false; // Can we transform this if the high bit is set?
2241 switch (LHS->getOpcode()) {
2242 default: return SDOperand();
2245 HighBitSet = false; // We can only transform sra if the high bit is clear.
2248 HighBitSet = true; // We can only transform sra if the high bit is set.
2251 if (N->getOpcode() != ISD::SHL)
2252 return SDOperand(); // only shl(add) not sr[al](add).
2253 HighBitSet = false; // We can only transform sra if the high bit is clear.
2257 // We require the RHS of the binop to be a constant as well.
2258 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2259 if (!BinOpCst) return SDOperand();
2262 // FIXME: disable this for unless the input to the binop is a shift by a
2263 // constant. If it is not a shift, it pessimizes some common cases like:
2265 //void foo(int *X, int i) { X[i & 1235] = 1; }
2266 //int bar(int *X, int i) { return X[i & 255]; }
2267 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2268 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2269 BinOpLHSVal->getOpcode() != ISD::SRA &&
2270 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2271 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2274 MVT VT = N->getValueType(0);
2276 // If this is a signed shift right, and the high bit is modified
2277 // by the logical operation, do not perform the transformation.
2278 // The highBitSet boolean indicates the value of the high bit of
2279 // the constant which would cause it to be modified for this
2281 if (N->getOpcode() == ISD::SRA) {
2282 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2283 if (BinOpRHSSignSet != HighBitSet)
2287 // Fold the constants, shifting the binop RHS by the shift amount.
2288 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2289 LHS->getOperand(1), N->getOperand(1));
2291 // Create the new shift.
2292 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2295 // Create the new binop.
2296 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2300 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2301 SDOperand N0 = N->getOperand(0);
2302 SDOperand N1 = N->getOperand(1);
2303 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2304 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2305 MVT VT = N0.getValueType();
2306 unsigned OpSizeInBits = VT.getSizeInBits();
2308 // fold (shl c1, c2) -> c1<<c2
2310 return DAG.getNode(ISD::SHL, VT, N0, N1);
2311 // fold (shl 0, x) -> 0
2312 if (N0C && N0C->isNullValue())
2314 // fold (shl x, c >= size(x)) -> undef
2315 if (N1C && N1C->getValue() >= OpSizeInBits)
2316 return DAG.getNode(ISD::UNDEF, VT);
2317 // fold (shl x, 0) -> x
2318 if (N1C && N1C->isNullValue())
2320 // if (shl x, c) is known to be zero, return 0
2321 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2322 APInt::getAllOnesValue(VT.getSizeInBits())))
2323 return DAG.getConstant(0, VT);
2324 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2325 return SDOperand(N, 0);
2326 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2327 if (N1C && N0.getOpcode() == ISD::SHL &&
2328 N0.getOperand(1).getOpcode() == ISD::Constant) {
2329 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2330 uint64_t c2 = N1C->getValue();
2331 if (c1 + c2 > OpSizeInBits)
2332 return DAG.getConstant(0, VT);
2333 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2334 DAG.getConstant(c1 + c2, N1.getValueType()));
2336 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2337 // (srl (and x, -1 << c1), c1-c2)
2338 if (N1C && N0.getOpcode() == ISD::SRL &&
2339 N0.getOperand(1).getOpcode() == ISD::Constant) {
2340 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2341 uint64_t c2 = N1C->getValue();
2342 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2343 DAG.getConstant(~0ULL << c1, VT));
2345 return DAG.getNode(ISD::SHL, VT, Mask,
2346 DAG.getConstant(c2-c1, N1.getValueType()));
2348 return DAG.getNode(ISD::SRL, VT, Mask,
2349 DAG.getConstant(c1-c2, N1.getValueType()));
2351 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2352 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2353 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2354 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2356 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2359 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2360 SDOperand N0 = N->getOperand(0);
2361 SDOperand N1 = N->getOperand(1);
2362 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2363 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2364 MVT VT = N0.getValueType();
2366 // fold (sra c1, c2) -> c1>>c2
2368 return DAG.getNode(ISD::SRA, VT, N0, N1);
2369 // fold (sra 0, x) -> 0
2370 if (N0C && N0C->isNullValue())
2372 // fold (sra -1, x) -> -1
2373 if (N0C && N0C->isAllOnesValue())
2375 // fold (sra x, c >= size(x)) -> undef
2376 if (N1C && N1C->getValue() >= VT.getSizeInBits())
2377 return DAG.getNode(ISD::UNDEF, VT);
2378 // fold (sra x, 0) -> x
2379 if (N1C && N1C->isNullValue())
2381 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2383 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2384 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getValue();
2385 MVT EVT = MVT::getIntegerVT(LowBits);
2386 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2387 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2388 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2389 DAG.getValueType(EVT));
2392 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2393 if (N1C && N0.getOpcode() == ISD::SRA) {
2394 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2395 unsigned Sum = N1C->getValue() + C1->getValue();
2396 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2397 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2398 DAG.getConstant(Sum, N1C->getValueType(0)));
2402 // fold sra (shl X, m), result_size - n
2403 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2404 // result_size - n != m.
2405 // If truncate is free for the target sext(shl) is likely to result in better
2407 if (N0.getOpcode() == ISD::SHL) {
2408 // Get the two constanst of the shifts, CN0 = m, CN = n.
2409 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2411 // Determine what the truncate's result bitsize and type would be.
2412 unsigned VTValSize = VT.getSizeInBits();
2414 MVT::getIntegerVT(VTValSize - N1C->getValue());
2415 // Determine the residual right-shift amount.
2416 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
2418 // If the shift is not a no-op (in which case this should be just a sign
2419 // extend already), the truncated to type is legal, sign_extend is legal
2420 // on that type, and the the truncate to that type is both legal and free,
2421 // perform the transform.
2423 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2424 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2425 TLI.isTruncateFree(VT, TruncVT)) {
2427 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2428 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2429 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2430 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2435 // Simplify, based on bits shifted out of the LHS.
2436 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2437 return SDOperand(N, 0);
2440 // If the sign bit is known to be zero, switch this to a SRL.
2441 if (DAG.SignBitIsZero(N0))
2442 return DAG.getNode(ISD::SRL, VT, N0, N1);
2444 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2447 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2448 SDOperand N0 = N->getOperand(0);
2449 SDOperand N1 = N->getOperand(1);
2450 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2451 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2452 MVT VT = N0.getValueType();
2453 unsigned OpSizeInBits = VT.getSizeInBits();
2455 // fold (srl c1, c2) -> c1 >>u c2
2457 return DAG.getNode(ISD::SRL, VT, N0, N1);
2458 // fold (srl 0, x) -> 0
2459 if (N0C && N0C->isNullValue())
2461 // fold (srl x, c >= size(x)) -> undef
2462 if (N1C && N1C->getValue() >= OpSizeInBits)
2463 return DAG.getNode(ISD::UNDEF, VT);
2464 // fold (srl x, 0) -> x
2465 if (N1C && N1C->isNullValue())
2467 // if (srl x, c) is known to be zero, return 0
2468 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2469 APInt::getAllOnesValue(OpSizeInBits)))
2470 return DAG.getConstant(0, VT);
2472 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2473 if (N1C && N0.getOpcode() == ISD::SRL &&
2474 N0.getOperand(1).getOpcode() == ISD::Constant) {
2475 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2476 uint64_t c2 = N1C->getValue();
2477 if (c1 + c2 > OpSizeInBits)
2478 return DAG.getConstant(0, VT);
2479 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2480 DAG.getConstant(c1 + c2, N1.getValueType()));
2483 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2484 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2485 // Shifting in all undef bits?
2486 MVT SmallVT = N0.getOperand(0).getValueType();
2487 if (N1C->getValue() >= SmallVT.getSizeInBits())
2488 return DAG.getNode(ISD::UNDEF, VT);
2490 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2491 AddToWorkList(SmallShift.Val);
2492 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2495 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2496 // bit, which is unmodified by sra.
2497 if (N1C && N1C->getValue()+1 == VT.getSizeInBits()) {
2498 if (N0.getOpcode() == ISD::SRA)
2499 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2502 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2503 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2504 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2505 APInt KnownZero, KnownOne;
2506 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2507 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2509 // If any of the input bits are KnownOne, then the input couldn't be all
2510 // zeros, thus the result of the srl will always be zero.
2511 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2513 // If all of the bits input the to ctlz node are known to be zero, then
2514 // the result of the ctlz is "32" and the result of the shift is one.
2515 APInt UnknownBits = ~KnownZero & Mask;
2516 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2518 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2519 if ((UnknownBits & (UnknownBits-1)) == 0) {
2520 // Okay, we know that only that the single bit specified by UnknownBits
2521 // could be set on input to the CTLZ node. If this bit is set, the SRL
2522 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2523 // to an SRL,XOR pair, which is likely to simplify more.
2524 unsigned ShAmt = UnknownBits.countTrailingZeros();
2525 SDOperand Op = N0.getOperand(0);
2527 Op = DAG.getNode(ISD::SRL, VT, Op,
2528 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2529 AddToWorkList(Op.Val);
2531 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2535 // fold operands of srl based on knowledge that the low bits are not
2537 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2538 return SDOperand(N, 0);
2540 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2543 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2544 SDOperand N0 = N->getOperand(0);
2545 MVT VT = N->getValueType(0);
2547 // fold (ctlz c1) -> c2
2548 if (isa<ConstantSDNode>(N0))
2549 return DAG.getNode(ISD::CTLZ, VT, N0);
2553 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2554 SDOperand N0 = N->getOperand(0);
2555 MVT VT = N->getValueType(0);
2557 // fold (cttz c1) -> c2
2558 if (isa<ConstantSDNode>(N0))
2559 return DAG.getNode(ISD::CTTZ, VT, N0);
2563 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2564 SDOperand N0 = N->getOperand(0);
2565 MVT VT = N->getValueType(0);
2567 // fold (ctpop c1) -> c2
2568 if (isa<ConstantSDNode>(N0))
2569 return DAG.getNode(ISD::CTPOP, VT, N0);
2573 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2574 SDOperand N0 = N->getOperand(0);
2575 SDOperand N1 = N->getOperand(1);
2576 SDOperand N2 = N->getOperand(2);
2577 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2579 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2580 MVT VT = N->getValueType(0);
2581 MVT VT0 = N0.getValueType();
2583 // fold select C, X, X -> X
2586 // fold select true, X, Y -> X
2587 if (N0C && !N0C->isNullValue())
2589 // fold select false, X, Y -> Y
2590 if (N0C && N0C->isNullValue())
2592 // fold select C, 1, X -> C | X
2593 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2594 return DAG.getNode(ISD::OR, VT, N0, N2);
2595 // fold select C, 0, 1 -> ~C
2596 if (VT.isInteger() && VT0.isInteger() &&
2597 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2598 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2601 AddToWorkList(XORNode.Val);
2603 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2604 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2606 // fold select C, 0, X -> ~C & X
2607 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2608 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2609 AddToWorkList(XORNode.Val);
2610 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2612 // fold select C, X, 1 -> ~C | X
2613 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2614 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2615 AddToWorkList(XORNode.Val);
2616 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2618 // fold select C, X, 0 -> C & X
2619 // FIXME: this should check for C type == X type, not i1?
2620 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2621 return DAG.getNode(ISD::AND, VT, N0, N1);
2622 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2623 if (VT == MVT::i1 && N0 == N1)
2624 return DAG.getNode(ISD::OR, VT, N0, N2);
2625 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2626 if (VT == MVT::i1 && N0 == N2)
2627 return DAG.getNode(ISD::AND, VT, N0, N1);
2629 // If we can fold this based on the true/false value, do so.
2630 if (SimplifySelectOps(N, N1, N2))
2631 return SDOperand(N, 0); // Don't revisit N.
2633 // fold selects based on a setcc into other things, such as min/max/abs
2634 if (N0.getOpcode() == ISD::SETCC) {
2636 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2637 // having to say they don't support SELECT_CC on every type the DAG knows
2638 // about, since there is no way to mark an opcode illegal at all value types
2639 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2640 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2641 N1, N2, N0.getOperand(2));
2643 return SimplifySelect(N0, N1, N2);
2648 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2649 SDOperand N0 = N->getOperand(0);
2650 SDOperand N1 = N->getOperand(1);
2651 SDOperand N2 = N->getOperand(2);
2652 SDOperand N3 = N->getOperand(3);
2653 SDOperand N4 = N->getOperand(4);
2654 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2656 // fold select_cc lhs, rhs, x, x, cc -> x
2660 // Determine if the condition we're dealing with is constant
2661 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2662 if (SCC.Val) AddToWorkList(SCC.Val);
2664 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2665 if (!SCCC->isNullValue())
2666 return N2; // cond always true -> true val
2668 return N3; // cond always false -> false val
2671 // Fold to a simpler select_cc
2672 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2673 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2674 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2677 // If we can fold this based on the true/false value, do so.
2678 if (SimplifySelectOps(N, N2, N3))
2679 return SDOperand(N, 0); // Don't revisit N.
2681 // fold select_cc into other things, such as min/max/abs
2682 return SimplifySelectCC(N0, N1, N2, N3, CC);
2685 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2686 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2687 cast<CondCodeSDNode>(N->getOperand(2))->get());
2690 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2691 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2692 // transformation. Returns true if extension are possible and the above
2693 // mentioned transformation is profitable.
2694 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2696 SmallVector<SDNode*, 4> &ExtendNodes,
2697 TargetLowering &TLI) {
2698 bool HasCopyToRegUses = false;
2699 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2700 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2702 SDNode *User = UI->getUser();
2705 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2706 if (User->getOpcode() == ISD::SETCC) {
2707 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2708 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2709 // Sign bits will be lost after a zext.
2712 for (unsigned i = 0; i != 2; ++i) {
2713 SDOperand UseOp = User->getOperand(i);
2716 if (!isa<ConstantSDNode>(UseOp))
2721 ExtendNodes.push_back(User);
2723 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2724 SDOperand UseOp = User->getOperand(i);
2726 // If truncate from extended type to original load type is free
2727 // on this target, then it's ok to extend a CopyToReg.
2728 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2729 HasCopyToRegUses = true;
2737 if (HasCopyToRegUses) {
2738 bool BothLiveOut = false;
2739 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2741 SDNode *User = UI->getUser();
2742 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2743 SDOperand UseOp = User->getOperand(i);
2744 if (UseOp.Val == N && UseOp.ResNo == 0) {
2751 // Both unextended and extended values are live out. There had better be
2752 // good a reason for the transformation.
2753 return ExtendNodes.size();
2758 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2759 SDOperand N0 = N->getOperand(0);
2760 MVT VT = N->getValueType(0);
2762 // fold (sext c1) -> c1
2763 if (isa<ConstantSDNode>(N0))
2764 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2766 // fold (sext (sext x)) -> (sext x)
2767 // fold (sext (aext x)) -> (sext x)
2768 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2769 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2771 if (N0.getOpcode() == ISD::TRUNCATE) {
2772 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2773 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2774 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2775 if (NarrowLoad.Val) {
2776 if (NarrowLoad.Val != N0.Val)
2777 CombineTo(N0.Val, NarrowLoad);
2778 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2781 // See if the value being truncated is already sign extended. If so, just
2782 // eliminate the trunc/sext pair.
2783 SDOperand Op = N0.getOperand(0);
2784 unsigned OpBits = Op.getValueType().getSizeInBits();
2785 unsigned MidBits = N0.getValueType().getSizeInBits();
2786 unsigned DestBits = VT.getSizeInBits();
2787 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2789 if (OpBits == DestBits) {
2790 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2791 // bits, it is already ready.
2792 if (NumSignBits > DestBits-MidBits)
2794 } else if (OpBits < DestBits) {
2795 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2796 // bits, just sext from i32.
2797 if (NumSignBits > OpBits-MidBits)
2798 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2800 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2801 // bits, just truncate to i32.
2802 if (NumSignBits > OpBits-MidBits)
2803 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2806 // fold (sext (truncate x)) -> (sextinreg x).
2807 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2808 N0.getValueType())) {
2809 if (Op.getValueType().bitsLT(VT))
2810 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2811 else if (Op.getValueType().bitsGT(VT))
2812 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2813 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2814 DAG.getValueType(N0.getValueType()));
2818 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2819 if (ISD::isNON_EXTLoad(N0.Val) &&
2820 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2821 TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2822 bool DoXform = true;
2823 SmallVector<SDNode*, 4> SetCCs;
2824 if (!N0.hasOneUse())
2825 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2827 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2828 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2829 LN0->getBasePtr(), LN0->getSrcValue(),
2830 LN0->getSrcValueOffset(),
2833 LN0->getAlignment());
2834 CombineTo(N, ExtLoad);
2835 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2836 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2837 // Extend SetCC uses if necessary.
2838 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2839 SDNode *SetCC = SetCCs[i];
2840 SmallVector<SDOperand, 4> Ops;
2841 for (unsigned j = 0; j != 2; ++j) {
2842 SDOperand SOp = SetCC->getOperand(j);
2844 Ops.push_back(ExtLoad);
2846 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2848 Ops.push_back(SetCC->getOperand(2));
2849 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2850 &Ops[0], Ops.size()));
2852 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2856 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2857 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2858 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2859 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2860 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2861 MVT EVT = LN0->getMemoryVT();
2862 if ((!AfterLegalize && !LN0->isVolatile()) ||
2863 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2864 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2865 LN0->getBasePtr(), LN0->getSrcValue(),
2866 LN0->getSrcValueOffset(), EVT,
2868 LN0->getAlignment());
2869 CombineTo(N, ExtLoad);
2870 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2871 ExtLoad.getValue(1));
2872 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2876 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2877 if (N0.getOpcode() == ISD::SETCC) {
2879 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2880 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2881 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2882 if (SCC.Val) return SCC;
2885 // fold (sext x) -> (zext x) if the sign bit is known zero.
2886 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2887 DAG.SignBitIsZero(N0))
2888 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2893 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2894 SDOperand N0 = N->getOperand(0);
2895 MVT VT = N->getValueType(0);
2897 // fold (zext c1) -> c1
2898 if (isa<ConstantSDNode>(N0))
2899 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2900 // fold (zext (zext x)) -> (zext x)
2901 // fold (zext (aext x)) -> (zext x)
2902 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2903 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2905 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2906 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2907 if (N0.getOpcode() == ISD::TRUNCATE) {
2908 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2909 if (NarrowLoad.Val) {
2910 if (NarrowLoad.Val != N0.Val)
2911 CombineTo(N0.Val, NarrowLoad);
2912 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2916 // fold (zext (truncate x)) -> (and x, mask)
2917 if (N0.getOpcode() == ISD::TRUNCATE &&
2918 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2919 SDOperand Op = N0.getOperand(0);
2920 if (Op.getValueType().bitsLT(VT)) {
2921 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2922 } else if (Op.getValueType().bitsGT(VT)) {
2923 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2925 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2928 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2929 if (N0.getOpcode() == ISD::AND &&
2930 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2931 N0.getOperand(1).getOpcode() == ISD::Constant) {
2932 SDOperand X = N0.getOperand(0).getOperand(0);
2933 if (X.getValueType().bitsLT(VT)) {
2934 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2935 } else if (X.getValueType().bitsGT(VT)) {
2936 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2938 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2939 Mask.zext(VT.getSizeInBits());
2940 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2943 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2944 if (ISD::isNON_EXTLoad(N0.Val) &&
2945 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2946 TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2947 bool DoXform = true;
2948 SmallVector<SDNode*, 4> SetCCs;
2949 if (!N0.hasOneUse())
2950 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2952 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2953 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2954 LN0->getBasePtr(), LN0->getSrcValue(),
2955 LN0->getSrcValueOffset(),
2958 LN0->getAlignment());
2959 CombineTo(N, ExtLoad);
2960 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2961 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2962 // Extend SetCC uses if necessary.
2963 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2964 SDNode *SetCC = SetCCs[i];
2965 SmallVector<SDOperand, 4> Ops;
2966 for (unsigned j = 0; j != 2; ++j) {
2967 SDOperand SOp = SetCC->getOperand(j);
2969 Ops.push_back(ExtLoad);
2971 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2973 Ops.push_back(SetCC->getOperand(2));
2974 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2975 &Ops[0], Ops.size()));
2977 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2981 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2982 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2983 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2984 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2985 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2986 MVT EVT = LN0->getMemoryVT();
2987 if ((!AfterLegalize && !LN0->isVolatile()) ||
2988 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT)) {
2989 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2990 LN0->getBasePtr(), LN0->getSrcValue(),
2991 LN0->getSrcValueOffset(), EVT,
2993 LN0->getAlignment());
2994 CombineTo(N, ExtLoad);
2995 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2996 ExtLoad.getValue(1));
2997 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3001 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3002 if (N0.getOpcode() == ISD::SETCC) {
3004 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3005 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3006 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3007 if (SCC.Val) return SCC;
3013 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3014 SDOperand N0 = N->getOperand(0);
3015 MVT VT = N->getValueType(0);
3017 // fold (aext c1) -> c1
3018 if (isa<ConstantSDNode>(N0))
3019 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3020 // fold (aext (aext x)) -> (aext x)
3021 // fold (aext (zext x)) -> (zext x)
3022 // fold (aext (sext x)) -> (sext x)
3023 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3024 N0.getOpcode() == ISD::ZERO_EXTEND ||
3025 N0.getOpcode() == ISD::SIGN_EXTEND)
3026 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3028 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3029 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3030 if (N0.getOpcode() == ISD::TRUNCATE) {
3031 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3032 if (NarrowLoad.Val) {
3033 if (NarrowLoad.Val != N0.Val)
3034 CombineTo(N0.Val, NarrowLoad);
3035 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3039 // fold (aext (truncate x))
3040 if (N0.getOpcode() == ISD::TRUNCATE) {
3041 SDOperand TruncOp = N0.getOperand(0);
3042 if (TruncOp.getValueType() == VT)
3043 return TruncOp; // x iff x size == zext size.
3044 if (TruncOp.getValueType().bitsGT(VT))
3045 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3046 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3049 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3050 if (N0.getOpcode() == ISD::AND &&
3051 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3052 N0.getOperand(1).getOpcode() == ISD::Constant) {
3053 SDOperand X = N0.getOperand(0).getOperand(0);
3054 if (X.getValueType().bitsLT(VT)) {
3055 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3056 } else if (X.getValueType().bitsGT(VT)) {
3057 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3059 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3060 Mask.zext(VT.getSizeInBits());
3061 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3064 // fold (aext (load x)) -> (aext (truncate (extload x)))
3065 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3066 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3067 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3068 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3069 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3070 LN0->getBasePtr(), LN0->getSrcValue(),
3071 LN0->getSrcValueOffset(),
3074 LN0->getAlignment());
3075 CombineTo(N, ExtLoad);
3076 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3077 ExtLoad.getValue(1));
3078 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3081 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3082 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3083 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3084 if (N0.getOpcode() == ISD::LOAD &&
3085 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3087 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3088 MVT EVT = LN0->getMemoryVT();
3089 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3090 LN0->getChain(), LN0->getBasePtr(),
3092 LN0->getSrcValueOffset(), EVT,
3094 LN0->getAlignment());
3095 CombineTo(N, ExtLoad);
3096 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3097 ExtLoad.getValue(1));
3098 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3101 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3102 if (N0.getOpcode() == ISD::SETCC) {
3104 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3105 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3106 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3114 /// GetDemandedBits - See if the specified operand can be simplified with the
3115 /// knowledge that only the bits specified by Mask are used. If so, return the
3116 /// simpler operand, otherwise return a null SDOperand.
3117 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
3118 switch (V.getOpcode()) {
3122 // If the LHS or RHS don't contribute bits to the or, drop them.
3123 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3124 return V.getOperand(1);
3125 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3126 return V.getOperand(0);
3129 // Only look at single-use SRLs.
3130 if (!V.Val->hasOneUse())
3132 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3133 // See if we can recursively simplify the LHS.
3134 unsigned Amt = RHSC->getValue();
3135 APInt NewMask = Mask << Amt;
3136 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3137 if (SimplifyLHS.Val) {
3138 return DAG.getNode(ISD::SRL, V.getValueType(),
3139 SimplifyLHS, V.getOperand(1));
3146 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3147 /// bits and then truncated to a narrower type and where N is a multiple
3148 /// of number of bits of the narrower type, transform it to a narrower load
3149 /// from address + N / num of bits of new type. If the result is to be
3150 /// extended, also fold the extension to form a extending load.
3151 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3152 unsigned Opc = N->getOpcode();
3153 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3154 SDOperand N0 = N->getOperand(0);
3155 MVT VT = N->getValueType(0);
3156 MVT EVT = N->getValueType(0);
3158 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3160 if (Opc == ISD::SIGN_EXTEND_INREG) {
3161 ExtType = ISD::SEXTLOAD;
3162 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3163 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3167 unsigned EVTBits = EVT.getSizeInBits();
3169 bool CombineSRL = false;
3170 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3171 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3172 ShAmt = N01->getValue();
3173 // Is the shift amount a multiple of size of VT?
3174 if ((ShAmt & (EVTBits-1)) == 0) {
3175 N0 = N0.getOperand(0);
3176 if (N0.getValueType().getSizeInBits() <= EVTBits)
3183 // Do not generate loads of non-round integer types since these can
3184 // be expensive (and would be wrong if the type is not byte sized).
3185 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() && VT.isRound() &&
3186 // Do not change the width of a volatile load.
3187 !cast<LoadSDNode>(N0)->isVolatile()) {
3188 assert(N0.getValueType().getSizeInBits() > EVTBits &&
3189 "Cannot truncate to larger type!");
3190 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3191 MVT PtrType = N0.getOperand(1).getValueType();
3192 // For big endian targets, we need to adjust the offset to the pointer to
3193 // load the correct bytes.
3194 if (TLI.isBigEndian()) {
3195 unsigned LVTStoreBits = N0.getValueType().getStoreSizeInBits();
3196 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3197 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3199 uint64_t PtrOff = ShAmt / 8;
3200 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3201 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3202 DAG.getConstant(PtrOff, PtrType));
3203 AddToWorkList(NewPtr.Val);
3204 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3205 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3206 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3207 LN0->isVolatile(), NewAlign)
3208 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3209 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3210 LN0->isVolatile(), NewAlign);
3213 WorkListRemover DeadNodes(*this);
3214 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3216 CombineTo(N->getOperand(0).Val, Load);
3218 CombineTo(N0.Val, Load, Load.getValue(1));
3220 if (Opc == ISD::SIGN_EXTEND_INREG)
3221 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3223 return DAG.getNode(Opc, VT, Load);
3225 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3232 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3233 SDOperand N0 = N->getOperand(0);
3234 SDOperand N1 = N->getOperand(1);
3235 MVT VT = N->getValueType(0);
3236 MVT EVT = cast<VTSDNode>(N1)->getVT();
3237 unsigned VTBits = VT.getSizeInBits();
3238 unsigned EVTBits = EVT.getSizeInBits();
3240 // fold (sext_in_reg c1) -> c1
3241 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3242 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3244 // If the input is already sign extended, just drop the extension.
3245 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3248 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3249 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3250 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3251 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3254 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3255 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3256 return DAG.getZeroExtendInReg(N0, EVT);
3258 // fold operands of sext_in_reg based on knowledge that the top bits are not
3260 if (SimplifyDemandedBits(SDOperand(N, 0)))
3261 return SDOperand(N, 0);
3263 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3264 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3265 SDOperand NarrowLoad = ReduceLoadWidth(N);
3269 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3270 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3271 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3272 if (N0.getOpcode() == ISD::SRL) {
3273 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3274 if (ShAmt->getValue()+EVTBits <= VT.getSizeInBits()) {
3275 // We can turn this into an SRA iff the input to the SRL is already sign
3277 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3278 if (VT.getSizeInBits()-(ShAmt->getValue()+EVTBits) < InSignBits)
3279 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3283 // fold (sext_inreg (extload x)) -> (sextload x)
3284 if (ISD::isEXTLoad(N0.Val) &&
3285 ISD::isUNINDEXEDLoad(N0.Val) &&
3286 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3287 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3288 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3289 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3290 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3291 LN0->getBasePtr(), LN0->getSrcValue(),
3292 LN0->getSrcValueOffset(), EVT,
3294 LN0->getAlignment());
3295 CombineTo(N, ExtLoad);
3296 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3297 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3299 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3300 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3302 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3303 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3304 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3305 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3306 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3307 LN0->getBasePtr(), LN0->getSrcValue(),
3308 LN0->getSrcValueOffset(), EVT,
3310 LN0->getAlignment());
3311 CombineTo(N, ExtLoad);
3312 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3313 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3318 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3319 SDOperand N0 = N->getOperand(0);
3320 MVT VT = N->getValueType(0);
3323 if (N0.getValueType() == N->getValueType(0))
3325 // fold (truncate c1) -> c1
3326 if (isa<ConstantSDNode>(N0))
3327 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3328 // fold (truncate (truncate x)) -> (truncate x)
3329 if (N0.getOpcode() == ISD::TRUNCATE)
3330 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3331 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3332 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3333 N0.getOpcode() == ISD::ANY_EXTEND) {
3334 if (N0.getOperand(0).getValueType().bitsLT(VT))
3335 // if the source is smaller than the dest, we still need an extend
3336 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3337 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3338 // if the source is larger than the dest, than we just need the truncate
3339 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3341 // if the source and dest are the same type, we can drop both the extend
3343 return N0.getOperand(0);
3346 // See if we can simplify the input to this truncate through knowledge that
3347 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3350 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3351 VT.getSizeInBits()));
3353 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3355 // fold (truncate (load x)) -> (smaller load x)
3356 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3357 return ReduceLoadWidth(N);
3360 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3361 SDOperand Elt = N->getOperand(i);
3362 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3364 return Elt.getOperand(Elt.ResNo).Val;
3367 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3368 /// if load locations are consecutive.
3369 SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3370 assert(N->getOpcode() == ISD::BUILD_PAIR);
3372 SDNode *LD1 = getBuildPairElt(N, 0);
3373 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3375 MVT LD1VT = LD1->getValueType(0);
3376 SDNode *LD2 = getBuildPairElt(N, 1);
3377 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3378 if (ISD::isNON_EXTLoad(LD2) &&
3380 // If both are volatile this would reduce the number of volatile loads.
3381 // If one is volatile it might be ok, but play conservative and bail out.
3382 !cast<LoadSDNode>(LD1)->isVolatile() &&
3383 !cast<LoadSDNode>(LD2)->isVolatile() &&
3384 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3385 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3386 unsigned Align = LD->getAlignment();
3387 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
3388 getABITypeAlignment(VT.getTypeForMVT());
3389 if (NewAlign <= Align &&
3390 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
3391 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3392 LD->getSrcValue(), LD->getSrcValueOffset(),
3398 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3399 SDOperand N0 = N->getOperand(0);
3400 MVT VT = N->getValueType(0);
3402 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3403 // Only do this before legalize, since afterward the target may be depending
3404 // on the bitconvert.
3405 // First check to see if this is all constant.
3406 if (!AfterLegalize &&
3407 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3409 bool isSimple = true;
3410 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3411 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3412 N0.getOperand(i).getOpcode() != ISD::Constant &&
3413 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3418 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3419 assert(!DestEltVT.isVector() &&
3420 "Element type of vector ValueType must not be vector!");
3422 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3426 // If the input is a constant, let getNode() fold it.
3427 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3428 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3429 if (Res.Val != N) return Res;
3432 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3433 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3435 // fold (conv (load x)) -> (load (conv*)x)
3436 // If the resultant load doesn't need a higher alignment than the original!
3437 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3438 // Do not change the width of a volatile load.
3439 !cast<LoadSDNode>(N0)->isVolatile() &&
3440 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
3441 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3442 unsigned Align = TLI.getTargetMachine().getTargetData()->
3443 getABITypeAlignment(VT.getTypeForMVT());
3444 unsigned OrigAlign = LN0->getAlignment();
3445 if (Align <= OrigAlign) {
3446 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3447 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3448 LN0->isVolatile(), Align);
3450 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3456 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3457 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3458 // This often reduces constant pool loads.
3459 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3460 N0.Val->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3461 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3462 AddToWorkList(NewConv.Val);
3464 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3465 if (N0.getOpcode() == ISD::FNEG)
3466 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3467 assert(N0.getOpcode() == ISD::FABS);
3468 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3471 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3472 // Note that we don't handle copysign(x,cst) because this can always be folded
3473 // to an fneg or fabs.
3474 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3475 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3476 VT.isInteger() && !VT.isVector()) {
3477 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3478 SDOperand X = DAG.getNode(ISD::BIT_CONVERT,
3479 MVT::getIntegerVT(OrigXWidth),
3481 AddToWorkList(X.Val);
3483 // If X has a different width than the result/lhs, sext it or truncate it.
3484 unsigned VTWidth = VT.getSizeInBits();
3485 if (OrigXWidth < VTWidth) {
3486 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3487 AddToWorkList(X.Val);
3488 } else if (OrigXWidth > VTWidth) {
3489 // To get the sign bit in the right place, we have to shift it right
3490 // before truncating.
3491 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3492 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3493 AddToWorkList(X.Val);
3494 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3495 AddToWorkList(X.Val);
3498 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3499 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3500 AddToWorkList(X.Val);
3502 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3503 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3504 AddToWorkList(Cst.Val);
3506 return DAG.getNode(ISD::OR, VT, X, Cst);
3509 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3510 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3511 SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
3519 SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3520 MVT VT = N->getValueType(0);
3521 return CombineConsecutiveLoads(N, VT);
3524 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3525 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3526 /// destination element value type.
3527 SDOperand DAGCombiner::
3528 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3529 MVT SrcEltVT = BV->getOperand(0).getValueType();
3531 // If this is already the right type, we're done.
3532 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3534 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3535 unsigned DstBitSize = DstEltVT.getSizeInBits();
3537 // If this is a conversion of N elements of one type to N elements of another
3538 // type, convert each element. This handles FP<->INT cases.
3539 if (SrcBitSize == DstBitSize) {
3540 SmallVector<SDOperand, 8> Ops;
3541 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3542 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3543 AddToWorkList(Ops.back().Val);
3545 MVT VT = MVT::getVectorVT(DstEltVT,
3546 BV->getValueType(0).getVectorNumElements());
3547 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3550 // Otherwise, we're growing or shrinking the elements. To avoid having to
3551 // handle annoying details of growing/shrinking FP values, we convert them to
3553 if (SrcEltVT.isFloatingPoint()) {
3554 // Convert the input float vector to a int vector where the elements are the
3556 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3557 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3558 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3562 // Now we know the input is an integer vector. If the output is a FP type,
3563 // convert to integer first, then to FP of the right size.
3564 if (DstEltVT.isFloatingPoint()) {
3565 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3566 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3567 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3569 // Next, convert to FP elements of the same size.
3570 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3573 // Okay, we know the src/dst types are both integers of differing types.
3574 // Handling growing first.
3575 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3576 if (SrcBitSize < DstBitSize) {
3577 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3579 SmallVector<SDOperand, 8> Ops;
3580 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3581 i += NumInputsPerOutput) {
3582 bool isLE = TLI.isLittleEndian();
3583 APInt NewBits = APInt(DstBitSize, 0);
3584 bool EltIsUndef = true;
3585 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3586 // Shift the previously computed bits over.
3587 NewBits <<= SrcBitSize;
3588 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3589 if (Op.getOpcode() == ISD::UNDEF) continue;
3593 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3597 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3599 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3602 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3603 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3606 // Finally, this must be the case where we are shrinking elements: each input
3607 // turns into multiple outputs.
3608 bool isS2V = ISD::isScalarToVector(BV);
3609 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3610 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3611 SmallVector<SDOperand, 8> Ops;
3612 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3613 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3614 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3615 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3618 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3619 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3620 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3621 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3622 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3623 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3624 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3625 OpVal = OpVal.lshr(DstBitSize);
3628 // For big endian targets, swap the order of the pieces of each element.
3629 if (TLI.isBigEndian())
3630 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3632 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3637 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3638 SDOperand N0 = N->getOperand(0);
3639 SDOperand N1 = N->getOperand(1);
3640 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3641 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3642 MVT VT = N->getValueType(0);
3645 if (VT.isVector()) {
3646 SDOperand FoldedVOp = SimplifyVBinOp(N);
3647 if (FoldedVOp.Val) return FoldedVOp;
3650 // fold (fadd c1, c2) -> c1+c2
3651 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3652 return DAG.getNode(ISD::FADD, VT, N0, N1);
3653 // canonicalize constant to RHS
3654 if (N0CFP && !N1CFP)
3655 return DAG.getNode(ISD::FADD, VT, N1, N0);
3656 // fold (A + (-B)) -> A-B
3657 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3658 return DAG.getNode(ISD::FSUB, VT, N0,
3659 GetNegatedExpression(N1, DAG, AfterLegalize));
3660 // fold ((-A) + B) -> B-A
3661 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3662 return DAG.getNode(ISD::FSUB, VT, N1,
3663 GetNegatedExpression(N0, DAG, AfterLegalize));
3665 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3666 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3667 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3668 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3669 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3674 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3675 SDOperand N0 = N->getOperand(0);
3676 SDOperand N1 = N->getOperand(1);
3677 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3678 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3679 MVT VT = N->getValueType(0);
3682 if (VT.isVector()) {
3683 SDOperand FoldedVOp = SimplifyVBinOp(N);
3684 if (FoldedVOp.Val) return FoldedVOp;
3687 // fold (fsub c1, c2) -> c1-c2
3688 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3689 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3691 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3692 if (isNegatibleForFree(N1, AfterLegalize))
3693 return GetNegatedExpression(N1, DAG, AfterLegalize);
3694 return DAG.getNode(ISD::FNEG, VT, N1);
3696 // fold (A-(-B)) -> A+B
3697 if (isNegatibleForFree(N1, AfterLegalize))
3698 return DAG.getNode(ISD::FADD, VT, N0,
3699 GetNegatedExpression(N1, DAG, AfterLegalize));
3704 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3705 SDOperand N0 = N->getOperand(0);
3706 SDOperand N1 = N->getOperand(1);
3707 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3708 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3709 MVT VT = N->getValueType(0);
3712 if (VT.isVector()) {
3713 SDOperand FoldedVOp = SimplifyVBinOp(N);
3714 if (FoldedVOp.Val) return FoldedVOp;
3717 // fold (fmul c1, c2) -> c1*c2
3718 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3719 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3720 // canonicalize constant to RHS
3721 if (N0CFP && !N1CFP)
3722 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3723 // fold (fmul X, 2.0) -> (fadd X, X)
3724 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3725 return DAG.getNode(ISD::FADD, VT, N0, N0);
3726 // fold (fmul X, -1.0) -> (fneg X)
3727 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3728 return DAG.getNode(ISD::FNEG, VT, N0);
3731 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3732 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3733 // Both can be negated for free, check to see if at least one is cheaper
3735 if (LHSNeg == 2 || RHSNeg == 2)
3736 return DAG.getNode(ISD::FMUL, VT,
3737 GetNegatedExpression(N0, DAG, AfterLegalize),
3738 GetNegatedExpression(N1, DAG, AfterLegalize));
3742 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3743 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3744 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3745 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3746 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3751 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3752 SDOperand N0 = N->getOperand(0);
3753 SDOperand N1 = N->getOperand(1);
3754 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3755 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3756 MVT VT = N->getValueType(0);
3759 if (VT.isVector()) {
3760 SDOperand FoldedVOp = SimplifyVBinOp(N);
3761 if (FoldedVOp.Val) return FoldedVOp;
3764 // fold (fdiv c1, c2) -> c1/c2
3765 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3766 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3770 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3771 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3772 // Both can be negated for free, check to see if at least one is cheaper
3774 if (LHSNeg == 2 || RHSNeg == 2)
3775 return DAG.getNode(ISD::FDIV, VT,
3776 GetNegatedExpression(N0, DAG, AfterLegalize),
3777 GetNegatedExpression(N1, DAG, AfterLegalize));
3784 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3785 SDOperand N0 = N->getOperand(0);
3786 SDOperand N1 = N->getOperand(1);
3787 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3788 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3789 MVT VT = N->getValueType(0);
3791 // fold (frem c1, c2) -> fmod(c1,c2)
3792 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3793 return DAG.getNode(ISD::FREM, VT, N0, N1);
3798 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3799 SDOperand N0 = N->getOperand(0);
3800 SDOperand N1 = N->getOperand(1);
3801 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3802 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3803 MVT VT = N->getValueType(0);
3805 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3806 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3809 const APFloat& V = N1CFP->getValueAPF();
3810 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3811 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3812 if (!V.isNegative())
3813 return DAG.getNode(ISD::FABS, VT, N0);
3815 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3818 // copysign(fabs(x), y) -> copysign(x, y)
3819 // copysign(fneg(x), y) -> copysign(x, y)
3820 // copysign(copysign(x,z), y) -> copysign(x, y)
3821 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3822 N0.getOpcode() == ISD::FCOPYSIGN)
3823 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3825 // copysign(x, abs(y)) -> abs(x)
3826 if (N1.getOpcode() == ISD::FABS)
3827 return DAG.getNode(ISD::FABS, VT, N0);
3829 // copysign(x, copysign(y,z)) -> copysign(x, z)
3830 if (N1.getOpcode() == ISD::FCOPYSIGN)
3831 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3833 // copysign(x, fp_extend(y)) -> copysign(x, y)
3834 // copysign(x, fp_round(y)) -> copysign(x, y)
3835 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3836 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3843 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3844 SDOperand N0 = N->getOperand(0);
3845 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3846 MVT VT = N->getValueType(0);
3848 // fold (sint_to_fp c1) -> c1fp
3849 if (N0C && N0.getValueType() != MVT::ppcf128)
3850 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3854 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3855 SDOperand N0 = N->getOperand(0);
3856 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3857 MVT VT = N->getValueType(0);
3859 // fold (uint_to_fp c1) -> c1fp
3860 if (N0C && N0.getValueType() != MVT::ppcf128)
3861 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3865 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3866 SDOperand N0 = N->getOperand(0);
3867 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3868 MVT VT = N->getValueType(0);
3870 // fold (fp_to_sint c1fp) -> c1
3872 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3876 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3877 SDOperand N0 = N->getOperand(0);
3878 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3879 MVT VT = N->getValueType(0);
3881 // fold (fp_to_uint c1fp) -> c1
3882 if (N0CFP && VT != MVT::ppcf128)
3883 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3887 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3888 SDOperand N0 = N->getOperand(0);
3889 SDOperand N1 = N->getOperand(1);
3890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3891 MVT VT = N->getValueType(0);
3893 // fold (fp_round c1fp) -> c1fp
3894 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3895 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3897 // fold (fp_round (fp_extend x)) -> x
3898 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3899 return N0.getOperand(0);
3901 // fold (fp_round (fp_round x)) -> (fp_round x)
3902 if (N0.getOpcode() == ISD::FP_ROUND) {
3903 // This is a value preserving truncation if both round's are.
3904 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3905 N0.Val->getConstantOperandVal(1) == 1;
3906 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3907 DAG.getIntPtrConstant(IsTrunc));
3910 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3911 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3912 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3913 AddToWorkList(Tmp.Val);
3914 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3920 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3921 SDOperand N0 = N->getOperand(0);
3922 MVT VT = N->getValueType(0);
3923 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3924 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3926 // fold (fp_round_inreg c1fp) -> c1fp
3928 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3929 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3934 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3935 SDOperand N0 = N->getOperand(0);
3936 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3937 MVT VT = N->getValueType(0);
3939 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3940 if (N->hasOneUse() &&
3941 N->use_begin()->getSDOperand().getOpcode() == ISD::FP_ROUND)
3944 // fold (fp_extend c1fp) -> c1fp
3945 if (N0CFP && VT != MVT::ppcf128)
3946 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3948 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3950 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3951 SDOperand In = N0.getOperand(0);
3952 if (In.getValueType() == VT) return In;
3953 if (VT.bitsLT(In.getValueType()))
3954 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3955 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3958 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3959 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3960 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3961 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3962 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3963 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3964 LN0->getBasePtr(), LN0->getSrcValue(),
3965 LN0->getSrcValueOffset(),
3968 LN0->getAlignment());
3969 CombineTo(N, ExtLoad);
3970 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3971 DAG.getIntPtrConstant(1)),
3972 ExtLoad.getValue(1));
3973 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3979 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3980 SDOperand N0 = N->getOperand(0);
3982 if (isNegatibleForFree(N0, AfterLegalize))
3983 return GetNegatedExpression(N0, DAG, AfterLegalize);
3985 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3986 // constant pool values.
3987 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3988 N0.getOperand(0).getValueType().isInteger() &&
3989 !N0.getOperand(0).getValueType().isVector()) {
3990 SDOperand Int = N0.getOperand(0);
3991 MVT IntVT = Int.getValueType();
3992 if (IntVT.isInteger() && !IntVT.isVector()) {
3993 Int = DAG.getNode(ISD::XOR, IntVT, Int,
3994 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
3995 AddToWorkList(Int.Val);
3996 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4003 SDOperand DAGCombiner::visitFABS(SDNode *N) {
4004 SDOperand N0 = N->getOperand(0);
4005 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4006 MVT VT = N->getValueType(0);
4008 // fold (fabs c1) -> fabs(c1)
4009 if (N0CFP && VT != MVT::ppcf128)
4010 return DAG.getNode(ISD::FABS, VT, N0);
4011 // fold (fabs (fabs x)) -> (fabs x)
4012 if (N0.getOpcode() == ISD::FABS)
4013 return N->getOperand(0);
4014 // fold (fabs (fneg x)) -> (fabs x)
4015 // fold (fabs (fcopysign x, y)) -> (fabs x)
4016 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4017 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4019 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4020 // constant pool values.
4021 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
4022 N0.getOperand(0).getValueType().isInteger() &&
4023 !N0.getOperand(0).getValueType().isVector()) {
4024 SDOperand Int = N0.getOperand(0);
4025 MVT IntVT = Int.getValueType();
4026 if (IntVT.isInteger() && !IntVT.isVector()) {
4027 Int = DAG.getNode(ISD::AND, IntVT, Int,
4028 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4029 AddToWorkList(Int.Val);
4030 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4037 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
4038 SDOperand Chain = N->getOperand(0);
4039 SDOperand N1 = N->getOperand(1);
4040 SDOperand N2 = N->getOperand(2);
4041 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4043 // never taken branch, fold to chain
4044 if (N1C && N1C->isNullValue())
4046 // unconditional branch
4047 if (N1C && N1C->getAPIntValue() == 1)
4048 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4049 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4051 if (N1.getOpcode() == ISD::SETCC &&
4052 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4053 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4054 N1.getOperand(0), N1.getOperand(1), N2);
4059 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4061 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4062 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4063 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4065 // Use SimplifySetCC to simplify SETCC's.
4066 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4067 if (Simp.Val) AddToWorkList(Simp.Val);
4069 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4071 // fold br_cc true, dest -> br dest (unconditional branch)
4072 if (SCCC && !SCCC->isNullValue())
4073 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4075 // fold br_cc false, dest -> unconditional fall through
4076 if (SCCC && SCCC->isNullValue())
4077 return N->getOperand(0);
4079 // fold to a simpler setcc
4080 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4081 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4082 Simp.getOperand(2), Simp.getOperand(0),
4083 Simp.getOperand(1), N->getOperand(4));
4088 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4089 /// pre-indexed load / store when the base pointer is an add or subtract
4090 /// and it has other uses besides the load / store. After the
4091 /// transformation, the new indexed load / store has effectively folded
4092 /// the add / subtract in and all of its other uses are redirected to the
4093 /// new load / store.
4094 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4101 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4102 if (LD->isIndexed())
4104 VT = LD->getMemoryVT();
4105 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4106 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4108 Ptr = LD->getBasePtr();
4109 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4110 if (ST->isIndexed())
4112 VT = ST->getMemoryVT();
4113 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4114 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4116 Ptr = ST->getBasePtr();
4121 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4122 // out. There is no reason to make this a preinc/predec.
4123 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4124 Ptr.Val->hasOneUse())
4127 // Ask the target to do addressing mode selection.
4130 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4131 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4133 // Don't create a indexed load / store with zero offset.
4134 if (isa<ConstantSDNode>(Offset) &&
4135 cast<ConstantSDNode>(Offset)->isNullValue())
4138 // Try turning it into a pre-indexed load / store except when:
4139 // 1) The new base ptr is a frame index.
4140 // 2) If N is a store and the new base ptr is either the same as or is a
4141 // predecessor of the value being stored.
4142 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4143 // that would create a cycle.
4144 // 4) All uses are load / store ops that use it as old base ptr.
4146 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4147 // (plus the implicit offset) to a register to preinc anyway.
4148 if (isa<FrameIndexSDNode>(BasePtr))
4153 SDOperand Val = cast<StoreSDNode>(N)->getValue();
4154 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
4158 // Now check for #3 and #4.
4159 bool RealUse = false;
4160 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4161 E = Ptr.Val->use_end(); I != E; ++I) {
4162 SDNode *Use = I->getUser();
4165 if (Use->isPredecessorOf(N))
4168 if (!((Use->getOpcode() == ISD::LOAD &&
4169 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4170 (Use->getOpcode() == ISD::STORE &&
4171 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4179 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4181 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4184 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4185 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4187 WorkListRemover DeadNodes(*this);
4189 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4191 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4194 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4198 // Finally, since the node is now dead, remove it from the graph.
4201 // Replace the uses of Ptr with uses of the updated base value.
4202 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4204 removeFromWorkList(Ptr.Val);
4205 DAG.DeleteNode(Ptr.Val);
4210 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4211 /// add / sub of the base pointer node into a post-indexed load / store.
4212 /// The transformation folded the add / subtract into the new indexed
4213 /// load / store effectively and all of its uses are redirected to the
4214 /// new load / store.
4215 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4222 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4223 if (LD->isIndexed())
4225 VT = LD->getMemoryVT();
4226 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4227 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4229 Ptr = LD->getBasePtr();
4230 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4231 if (ST->isIndexed())
4233 VT = ST->getMemoryVT();
4234 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4235 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4237 Ptr = ST->getBasePtr();
4242 if (Ptr.Val->hasOneUse())
4245 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4246 E = Ptr.Val->use_end(); I != E; ++I) {
4247 SDNode *Op = I->getUser();
4249 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4254 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4255 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4257 std::swap(BasePtr, Offset);
4260 // Don't create a indexed load / store with zero offset.
4261 if (isa<ConstantSDNode>(Offset) &&
4262 cast<ConstantSDNode>(Offset)->isNullValue())
4265 // Try turning it into a post-indexed load / store except when
4266 // 1) All uses are load / store ops that use it as base ptr.
4267 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4268 // nor a successor of N. Otherwise, if Op is folded that would
4272 bool TryNext = false;
4273 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4274 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4275 SDNode *Use = II->getUser();
4279 // If all the uses are load / store addresses, then don't do the
4281 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4282 bool RealUse = false;
4283 for (SDNode::use_iterator III = Use->use_begin(),
4284 EEE = Use->use_end(); III != EEE; ++III) {
4285 SDNode *UseUse = III->getUser();
4286 if (!((UseUse->getOpcode() == ISD::LOAD &&
4287 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4288 (UseUse->getOpcode() == ISD::STORE &&
4289 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
4303 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4304 SDOperand Result = isLoad
4305 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4306 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4309 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4310 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4312 WorkListRemover DeadNodes(*this);
4314 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4316 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4319 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4323 // Finally, since the node is now dead, remove it from the graph.
4326 // Replace the uses of Use with uses of the updated base value.
4327 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4328 Result.getValue(isLoad ? 1 : 0),
4330 removeFromWorkList(Op);
4339 /// InferAlignment - If we can infer some alignment information from this
4340 /// pointer, return it.
4341 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4342 // If this is a direct reference to a stack slot, use information about the
4343 // stack slot's alignment.
4344 int FrameIdx = 1 << 31;
4345 int64_t FrameOffset = 0;
4346 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4347 FrameIdx = FI->getIndex();
4348 } else if (Ptr.getOpcode() == ISD::ADD &&
4349 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4350 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4351 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4352 FrameOffset = Ptr.getConstantOperandVal(1);
4355 if (FrameIdx != (1 << 31)) {
4356 // FIXME: Handle FI+CST.
4357 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4358 if (MFI.isFixedObjectIndex(FrameIdx)) {
4359 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4361 // The alignment of the frame index can be determined from its offset from
4362 // the incoming frame position. If the frame object is at offset 32 and
4363 // the stack is guaranteed to be 16-byte aligned, then we know that the
4364 // object is 16-byte aligned.
4365 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4366 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4368 // Finally, the frame object itself may have a known alignment. Factor
4369 // the alignment + offset into a new alignment. For example, if we know
4370 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4371 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4372 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4373 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4375 return std::max(Align, FIInfoAlign);
4382 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4383 LoadSDNode *LD = cast<LoadSDNode>(N);
4384 SDOperand Chain = LD->getChain();
4385 SDOperand Ptr = LD->getBasePtr();
4387 // Try to infer better alignment information than the load already has.
4388 if (LD->isUnindexed()) {
4389 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4390 if (Align > LD->getAlignment())
4391 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4392 Chain, Ptr, LD->getSrcValue(),
4393 LD->getSrcValueOffset(), LD->getMemoryVT(),
4394 LD->isVolatile(), Align);
4399 // If load is not volatile and there are no uses of the loaded value (and
4400 // the updated indexed value in case of indexed loads), change uses of the
4401 // chain value into uses of the chain input (i.e. delete the dead load).
4402 if (!LD->isVolatile()) {
4403 if (N->getValueType(1) == MVT::Other) {
4405 if (N->hasNUsesOfValue(0, 0)) {
4406 // It's not safe to use the two value CombineTo variant here. e.g.
4407 // v1, chain2 = load chain1, loc
4408 // v2, chain3 = load chain2, loc
4410 // Now we replace use of chain2 with chain1. This makes the second load
4411 // isomorphic to the one we are deleting, and thus makes this load live.
4412 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4413 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4415 WorkListRemover DeadNodes(*this);
4416 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4417 if (N->use_empty()) {
4418 removeFromWorkList(N);
4421 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4425 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4426 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4427 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4428 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4429 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4430 DOUT << " and 2 other values\n";
4431 WorkListRemover DeadNodes(*this);
4432 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4433 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4434 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4436 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4437 removeFromWorkList(N);
4439 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4444 // If this load is directly stored, replace the load value with the stored
4446 // TODO: Handle store large -> read small portion.
4447 // TODO: Handle TRUNCSTORE/LOADEXT
4448 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4449 !LD->isVolatile()) {
4450 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4451 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4452 if (PrevST->getBasePtr() == Ptr &&
4453 PrevST->getValue().getValueType() == N->getValueType(0))
4454 return CombineTo(N, Chain.getOperand(1), Chain);
4459 // Walk up chain skipping non-aliasing memory nodes.
4460 SDOperand BetterChain = FindBetterChain(N, Chain);
4462 // If there is a better chain.
4463 if (Chain != BetterChain) {
4466 // Replace the chain to void dependency.
4467 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4468 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4469 LD->getSrcValue(), LD->getSrcValueOffset(),
4470 LD->isVolatile(), LD->getAlignment());
4472 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4473 LD->getValueType(0),
4474 BetterChain, Ptr, LD->getSrcValue(),
4475 LD->getSrcValueOffset(),
4478 LD->getAlignment());
4481 // Create token factor to keep old chain connected.
4482 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4483 Chain, ReplLoad.getValue(1));
4485 // Replace uses with load result and token factor. Don't add users
4487 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4491 // Try transforming N to an indexed load.
4492 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4493 return SDOperand(N, 0);
4499 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4500 StoreSDNode *ST = cast<StoreSDNode>(N);
4501 SDOperand Chain = ST->getChain();
4502 SDOperand Value = ST->getValue();
4503 SDOperand Ptr = ST->getBasePtr();
4505 // Try to infer better alignment information than the store already has.
4506 if (ST->isUnindexed()) {
4507 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4508 if (Align > ST->getAlignment())
4509 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4510 ST->getSrcValueOffset(), ST->getMemoryVT(),
4511 ST->isVolatile(), Align);
4515 // If this is a store of a bit convert, store the input value if the
4516 // resultant store does not need a higher alignment than the original.
4517 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4518 ST->isUnindexed()) {
4519 unsigned Align = ST->getAlignment();
4520 MVT SVT = Value.getOperand(0).getValueType();
4521 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4522 getABITypeAlignment(SVT.getTypeForMVT());
4523 if (Align <= OrigAlign &&
4524 ((!AfterLegalize && !ST->isVolatile()) ||
4525 TLI.isOperationLegal(ISD::STORE, SVT)))
4526 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4527 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4530 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4531 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4532 // NOTE: If the original store is volatile, this transform must not increase
4533 // the number of stores. For example, on x86-32 an f64 can be stored in one
4534 // processor operation but an i64 (which is not legal) requires two. So the
4535 // transform should not be done in this case.
4536 if (Value.getOpcode() != ISD::TargetConstantFP) {
4538 switch (CFP->getValueType(0).getSimpleVT()) {
4539 default: assert(0 && "Unknown FP type");
4540 case MVT::f80: // We don't do this for these yet.
4545 if ((!AfterLegalize && !ST->isVolatile()) ||
4546 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4547 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4548 convertToAPInt().getZExtValue(), MVT::i32);
4549 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4550 ST->getSrcValueOffset(), ST->isVolatile(),
4551 ST->getAlignment());
4555 if ((!AfterLegalize && !ST->isVolatile()) ||
4556 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4557 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4558 getZExtValue(), MVT::i64);
4559 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4560 ST->getSrcValueOffset(), ST->isVolatile(),
4561 ST->getAlignment());
4562 } else if (!ST->isVolatile() &&
4563 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4564 // Many FP stores are not made apparent until after legalize, e.g. for
4565 // argument passing. Since this is so common, custom legalize the
4566 // 64-bit integer store into two 32-bit stores.
4567 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4568 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4569 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4570 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4572 int SVOffset = ST->getSrcValueOffset();
4573 unsigned Alignment = ST->getAlignment();
4574 bool isVolatile = ST->isVolatile();
4576 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4577 ST->getSrcValueOffset(),
4578 isVolatile, ST->getAlignment());
4579 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4580 DAG.getConstant(4, Ptr.getValueType()));
4582 Alignment = MinAlign(Alignment, 4U);
4583 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4584 SVOffset, isVolatile, Alignment);
4585 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4593 // Walk up chain skipping non-aliasing memory nodes.
4594 SDOperand BetterChain = FindBetterChain(N, Chain);
4596 // If there is a better chain.
4597 if (Chain != BetterChain) {
4598 // Replace the chain to avoid dependency.
4599 SDOperand ReplStore;
4600 if (ST->isTruncatingStore()) {
4601 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4602 ST->getSrcValue(),ST->getSrcValueOffset(),
4604 ST->isVolatile(), ST->getAlignment());
4606 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4607 ST->getSrcValue(), ST->getSrcValueOffset(),
4608 ST->isVolatile(), ST->getAlignment());
4611 // Create token to keep both nodes around.
4613 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4615 // Don't add users to work list.
4616 return CombineTo(N, Token, false);
4620 // Try transforming N to an indexed store.
4621 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4622 return SDOperand(N, 0);
4624 // FIXME: is there such a thing as a truncating indexed store?
4625 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4626 Value.getValueType().isInteger()) {
4627 // See if we can simplify the input to this truncstore with knowledge that
4628 // only the low bits are being used. For example:
4629 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4631 GetDemandedBits(Value,
4632 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4633 ST->getMemoryVT().getSizeInBits()));
4634 AddToWorkList(Value.Val);
4636 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4637 ST->getSrcValueOffset(), ST->getMemoryVT(),
4638 ST->isVolatile(), ST->getAlignment());
4640 // Otherwise, see if we can simplify the operation with
4641 // SimplifyDemandedBits, which only works if the value has a single use.
4642 if (SimplifyDemandedBits(Value,
4643 APInt::getLowBitsSet(
4644 Value.getValueSizeInBits(),
4645 ST->getMemoryVT().getSizeInBits())))
4646 return SDOperand(N, 0);
4649 // If this is a load followed by a store to the same location, then the store
4651 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4652 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4653 ST->isUnindexed() && !ST->isVolatile() &&
4654 // There can't be any side effects between the load and store, such as
4656 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4657 // The store is dead, remove it.
4662 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4663 // truncating store. We can do this even if this is already a truncstore.
4664 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4665 && Value.Val->hasOneUse() && ST->isUnindexed() &&
4666 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4667 ST->getMemoryVT())) {
4668 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4669 ST->getSrcValueOffset(), ST->getMemoryVT(),
4670 ST->isVolatile(), ST->getAlignment());
4676 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4677 SDOperand InVec = N->getOperand(0);
4678 SDOperand InVal = N->getOperand(1);
4679 SDOperand EltNo = N->getOperand(2);
4681 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4682 // vector with the inserted element.
4683 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4684 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4685 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4686 if (Elt < Ops.size())
4688 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4689 &Ops[0], Ops.size());
4695 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4696 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4697 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4698 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4700 // Perform only after legalization to ensure build_vector / vector_shuffle
4701 // optimizations have already been done.
4702 if (!AfterLegalize) return SDOperand();
4704 SDOperand InVec = N->getOperand(0);
4705 SDOperand EltNo = N->getOperand(1);
4707 if (isa<ConstantSDNode>(EltNo)) {
4708 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4709 bool NewLoad = false;
4710 MVT VT = InVec.getValueType();
4711 MVT EVT = VT.getVectorElementType();
4713 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4714 MVT BCVT = InVec.getOperand(0).getValueType();
4715 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4717 InVec = InVec.getOperand(0);
4718 EVT = BCVT.getVectorElementType();
4722 LoadSDNode *LN0 = NULL;
4723 if (ISD::isNormalLoad(InVec.Val))
4724 LN0 = cast<LoadSDNode>(InVec);
4725 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4726 InVec.getOperand(0).getValueType() == EVT &&
4727 ISD::isNormalLoad(InVec.getOperand(0).Val)) {
4728 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4729 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4730 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4732 // (load $addr+1*size)
4733 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4734 getOperand(Elt))->getValue();
4735 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4736 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4737 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4738 InVec = InVec.getOperand(0);
4739 if (ISD::isNormalLoad(InVec.Val)) {
4740 LN0 = cast<LoadSDNode>(InVec);
4741 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4744 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4747 unsigned Align = LN0->getAlignment();
4749 // Check the resultant load doesn't need a higher alignment than the
4751 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4752 getABITypeAlignment(LVT.getTypeForMVT());
4753 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4758 SDOperand NewPtr = LN0->getBasePtr();
4760 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4761 MVT PtrType = NewPtr.getValueType();
4762 if (TLI.isBigEndian())
4763 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4764 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4765 DAG.getConstant(PtrOff, PtrType));
4767 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4768 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4769 LN0->isVolatile(), Align);
4775 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4776 unsigned NumInScalars = N->getNumOperands();
4777 MVT VT = N->getValueType(0);
4778 unsigned NumElts = VT.getVectorNumElements();
4779 MVT EltType = VT.getVectorElementType();
4781 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4782 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4783 // at most two distinct vectors, turn this into a shuffle node.
4784 SDOperand VecIn1, VecIn2;
4785 for (unsigned i = 0; i != NumInScalars; ++i) {
4786 // Ignore undef inputs.
4787 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4789 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4790 // constant index, bail out.
4791 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4792 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4793 VecIn1 = VecIn2 = SDOperand(0, 0);
4797 // If the input vector type disagrees with the result of the build_vector,
4798 // we can't make a shuffle.
4799 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4800 if (ExtractedFromVec.getValueType() != VT) {
4801 VecIn1 = VecIn2 = SDOperand(0, 0);
4805 // Otherwise, remember this. We allow up to two distinct input vectors.
4806 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4809 if (VecIn1.Val == 0) {
4810 VecIn1 = ExtractedFromVec;
4811 } else if (VecIn2.Val == 0) {
4812 VecIn2 = ExtractedFromVec;
4815 VecIn1 = VecIn2 = SDOperand(0, 0);
4820 // If everything is good, we can make a shuffle operation.
4822 SmallVector<SDOperand, 8> BuildVecIndices;
4823 for (unsigned i = 0; i != NumInScalars; ++i) {
4824 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4825 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4829 SDOperand Extract = N->getOperand(i);
4831 // If extracting from the first vector, just use the index directly.
4832 if (Extract.getOperand(0) == VecIn1) {
4833 BuildVecIndices.push_back(Extract.getOperand(1));
4837 // Otherwise, use InIdx + VecSize
4838 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4839 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4842 // Add count and size info.
4843 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
4845 // Return the new VECTOR_SHUFFLE node.
4851 // Use an undef build_vector as input for the second operand.
4852 std::vector<SDOperand> UnOps(NumInScalars,
4853 DAG.getNode(ISD::UNDEF,
4855 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4856 &UnOps[0], UnOps.size());
4857 AddToWorkList(Ops[1].Val);
4859 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4860 &BuildVecIndices[0], BuildVecIndices.size());
4861 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4867 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4868 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4869 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4870 // inputs come from at most two distinct vectors, turn this into a shuffle
4873 // If we only have one input vector, we don't need to do any concatenation.
4874 if (N->getNumOperands() == 1) {
4875 return N->getOperand(0);
4881 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4882 SDOperand ShufMask = N->getOperand(2);
4883 unsigned NumElts = ShufMask.getNumOperands();
4885 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4886 bool isIdentity = true;
4887 for (unsigned i = 0; i != NumElts; ++i) {
4888 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4889 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4894 if (isIdentity) return N->getOperand(0);
4896 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4898 for (unsigned i = 0; i != NumElts; ++i) {
4899 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4900 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4905 if (isIdentity) return N->getOperand(1);
4907 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4909 bool isUnary = true;
4910 bool isSplat = true;
4912 unsigned BaseIdx = 0;
4913 for (unsigned i = 0; i != NumElts; ++i)
4914 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4915 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4916 int V = (Idx < NumElts) ? 0 : 1;
4930 SDOperand N0 = N->getOperand(0);
4931 SDOperand N1 = N->getOperand(1);
4932 // Normalize unary shuffle so the RHS is undef.
4933 if (isUnary && VecNum == 1)
4936 // If it is a splat, check if the argument vector is a build_vector with
4937 // all scalar elements the same.
4941 // If this is a bit convert that changes the element type of the vector but
4942 // not the number of vector elements, look through it. Be careful not to
4943 // look though conversions that change things like v4f32 to v2f64.
4944 if (V->getOpcode() == ISD::BIT_CONVERT) {
4945 SDOperand ConvInput = V->getOperand(0);
4946 if (ConvInput.getValueType().getVectorNumElements() == NumElts)
4950 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4951 unsigned NumElems = V->getNumOperands();
4952 if (NumElems > BaseIdx) {
4954 bool AllSame = true;
4955 for (unsigned i = 0; i != NumElems; ++i) {
4956 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4957 Base = V->getOperand(i);
4961 // Splat of <u, u, u, u>, return <u, u, u, u>
4964 for (unsigned i = 0; i != NumElems; ++i) {
4965 if (V->getOperand(i) != Base) {
4970 // Splat of <x, x, x, x>, return <x, x, x, x>
4977 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4979 if (isUnary || N0 == N1) {
4980 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4982 SmallVector<SDOperand, 8> MappedOps;
4983 for (unsigned i = 0; i != NumElts; ++i) {
4984 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4985 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4986 MappedOps.push_back(ShufMask.getOperand(i));
4989 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4990 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4993 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4994 &MappedOps[0], MappedOps.size());
4995 AddToWorkList(ShufMask.Val);
4996 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4998 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5005 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5006 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5007 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5008 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5009 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5010 SDOperand LHS = N->getOperand(0);
5011 SDOperand RHS = N->getOperand(1);
5012 if (N->getOpcode() == ISD::AND) {
5013 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5014 RHS = RHS.getOperand(0);
5015 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5016 std::vector<SDOperand> IdxOps;
5017 unsigned NumOps = RHS.getNumOperands();
5018 unsigned NumElts = NumOps;
5019 MVT EVT = RHS.getValueType().getVectorElementType();
5020 for (unsigned i = 0; i != NumElts; ++i) {
5021 SDOperand Elt = RHS.getOperand(i);
5022 if (!isa<ConstantSDNode>(Elt))
5024 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5025 IdxOps.push_back(DAG.getConstant(i, EVT));
5026 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5027 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
5032 // Let's see if the target supports this vector_shuffle.
5033 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
5036 // Return the new VECTOR_SHUFFLE node.
5037 MVT VT = MVT::getVectorVT(EVT, NumElts);
5038 std::vector<SDOperand> Ops;
5039 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5041 AddToWorkList(LHS.Val);
5042 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5043 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5044 &ZeroOps[0], ZeroOps.size()));
5045 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5046 &IdxOps[0], IdxOps.size()));
5047 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5048 &Ops[0], Ops.size());
5049 if (VT != LHS.getValueType()) {
5050 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
5058 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5059 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
5060 // After legalize, the target may be depending on adds and other
5061 // binary ops to provide legal ways to construct constants or other
5062 // things. Simplifying them may result in a loss of legality.
5063 if (AfterLegalize) return SDOperand();
5065 MVT VT = N->getValueType(0);
5066 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5068 MVT EltType = VT.getVectorElementType();
5069 SDOperand LHS = N->getOperand(0);
5070 SDOperand RHS = N->getOperand(1);
5071 SDOperand Shuffle = XformToShuffleWithZero(N);
5072 if (Shuffle.Val) return Shuffle;
5074 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5076 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5077 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5078 SmallVector<SDOperand, 8> Ops;
5079 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5080 SDOperand LHSOp = LHS.getOperand(i);
5081 SDOperand RHSOp = RHS.getOperand(i);
5082 // If these two elements can't be folded, bail out.
5083 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5084 LHSOp.getOpcode() != ISD::Constant &&
5085 LHSOp.getOpcode() != ISD::ConstantFP) ||
5086 (RHSOp.getOpcode() != ISD::UNDEF &&
5087 RHSOp.getOpcode() != ISD::Constant &&
5088 RHSOp.getOpcode() != ISD::ConstantFP))
5090 // Can't fold divide by zero.
5091 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5092 N->getOpcode() == ISD::FDIV) {
5093 if ((RHSOp.getOpcode() == ISD::Constant &&
5094 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
5095 (RHSOp.getOpcode() == ISD::ConstantFP &&
5096 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
5099 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5100 AddToWorkList(Ops.back().Val);
5101 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5102 Ops.back().getOpcode() == ISD::Constant ||
5103 Ops.back().getOpcode() == ISD::ConstantFP) &&
5104 "Scalar binop didn't fold!");
5107 if (Ops.size() == LHS.getNumOperands()) {
5108 MVT VT = LHS.getValueType();
5109 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5116 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5117 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5119 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5120 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5121 // If we got a simplified select_cc node back from SimplifySelectCC, then
5122 // break it down into a new SETCC node, and a new SELECT node, and then return
5123 // the SELECT node, since we were called with a SELECT node.
5125 // Check to see if we got a select_cc back (to turn into setcc/select).
5126 // Otherwise, just return whatever node we got back, like fabs.
5127 if (SCC.getOpcode() == ISD::SELECT_CC) {
5128 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5129 SCC.getOperand(0), SCC.getOperand(1),
5131 AddToWorkList(SETCC.Val);
5132 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5133 SCC.getOperand(3), SETCC);
5140 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5141 /// are the two values being selected between, see if we can simplify the
5142 /// select. Callers of this should assume that TheSelect is deleted if this
5143 /// returns true. As such, they should return the appropriate thing (e.g. the
5144 /// node) back to the top-level of the DAG combiner loop to avoid it being
5147 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5150 // If this is a select from two identical things, try to pull the operation
5151 // through the select.
5152 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5153 // If this is a load and the token chain is identical, replace the select
5154 // of two loads with a load through a select of the address to load from.
5155 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5156 // constants have been dropped into the constant pool.
5157 if (LHS.getOpcode() == ISD::LOAD &&
5158 // Do not let this transformation reduce the number of volatile loads.
5159 !cast<LoadSDNode>(LHS)->isVolatile() &&
5160 !cast<LoadSDNode>(RHS)->isVolatile() &&
5161 // Token chains must be identical.
5162 LHS.getOperand(0) == RHS.getOperand(0)) {
5163 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5164 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5166 // If this is an EXTLOAD, the VT's must match.
5167 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5168 // FIXME: this conflates two src values, discarding one. This is not
5169 // the right thing to do, but nothing uses srcvalues now. When they do,
5170 // turn SrcValue into a list of locations.
5172 if (TheSelect->getOpcode() == ISD::SELECT) {
5173 // Check that the condition doesn't reach either load. If so, folding
5174 // this will induce a cycle into the DAG.
5175 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5176 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
5177 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5178 TheSelect->getOperand(0), LLD->getBasePtr(),
5182 // Check that the condition doesn't reach either load. If so, folding
5183 // this will induce a cycle into the DAG.
5184 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5185 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5186 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5187 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
5188 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5189 TheSelect->getOperand(0),
5190 TheSelect->getOperand(1),
5191 LLD->getBasePtr(), RLD->getBasePtr(),
5192 TheSelect->getOperand(4));
5198 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5199 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5200 Addr,LLD->getSrcValue(),
5201 LLD->getSrcValueOffset(),
5203 LLD->getAlignment());
5205 Load = DAG.getExtLoad(LLD->getExtensionType(),
5206 TheSelect->getValueType(0),
5207 LLD->getChain(), Addr, LLD->getSrcValue(),
5208 LLD->getSrcValueOffset(),
5211 LLD->getAlignment());
5213 // Users of the select now use the result of the load.
5214 CombineTo(TheSelect, Load);
5216 // Users of the old loads now use the new load's chain. We know the
5217 // old-load value is dead now.
5218 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5219 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5229 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5230 SDOperand N2, SDOperand N3,
5231 ISD::CondCode CC, bool NotExtCompare) {
5233 MVT VT = N2.getValueType();
5234 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5235 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5236 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5238 // Determine if the condition we're dealing with is constant
5239 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5240 if (SCC.Val) AddToWorkList(SCC.Val);
5241 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5243 // fold select_cc true, x, y -> x
5244 if (SCCC && !SCCC->isNullValue())
5246 // fold select_cc false, x, y -> y
5247 if (SCCC && SCCC->isNullValue())
5250 // Check to see if we can simplify the select into an fabs node
5251 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5252 // Allow either -0.0 or 0.0
5253 if (CFP->getValueAPF().isZero()) {
5254 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5255 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5256 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5257 N2 == N3.getOperand(0))
5258 return DAG.getNode(ISD::FABS, VT, N0);
5260 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5261 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5262 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5263 N2.getOperand(0) == N3)
5264 return DAG.getNode(ISD::FABS, VT, N3);
5268 // Check to see if we can perform the "gzip trick", transforming
5269 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5270 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5271 N0.getValueType().isInteger() &&
5272 N2.getValueType().isInteger() &&
5273 (N1C->isNullValue() || // (a < 0) ? b : 0
5274 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5275 MVT XType = N0.getValueType();
5276 MVT AType = N2.getValueType();
5277 if (XType.bitsGE(AType)) {
5278 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5279 // single-bit constant.
5280 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5281 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5282 ShCtV = XType.getSizeInBits()-ShCtV-1;
5283 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5284 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5285 AddToWorkList(Shift.Val);
5286 if (XType.bitsGT(AType)) {
5287 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5288 AddToWorkList(Shift.Val);
5290 return DAG.getNode(ISD::AND, AType, Shift, N2);
5292 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5293 DAG.getConstant(XType.getSizeInBits()-1,
5294 TLI.getShiftAmountTy()));
5295 AddToWorkList(Shift.Val);
5296 if (XType.bitsGT(AType)) {
5297 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5298 AddToWorkList(Shift.Val);
5300 return DAG.getNode(ISD::AND, AType, Shift, N2);
5304 // fold select C, 16, 0 -> shl C, 4
5305 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5306 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5308 // If the caller doesn't want us to simplify this into a zext of a compare,
5310 if (NotExtCompare && N2C->getAPIntValue() == 1)
5313 // Get a SetCC of the condition
5314 // FIXME: Should probably make sure that setcc is legal if we ever have a
5315 // target where it isn't.
5316 SDOperand Temp, SCC;
5317 // cast from setcc result type to select result type
5318 if (AfterLegalize) {
5319 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5320 if (N2.getValueType().bitsLT(SCC.getValueType()))
5321 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5323 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5325 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5326 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5328 AddToWorkList(SCC.Val);
5329 AddToWorkList(Temp.Val);
5331 if (N2C->getAPIntValue() == 1)
5333 // shl setcc result by log2 n2c
5334 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5335 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5336 TLI.getShiftAmountTy()));
5339 // Check to see if this is the equivalent of setcc
5340 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5341 // otherwise, go ahead with the folds.
5342 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5343 MVT XType = N0.getValueType();
5344 if (!AfterLegalize ||
5345 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5346 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5347 if (Res.getValueType() != VT)
5348 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5352 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5353 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5355 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5356 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5357 return DAG.getNode(ISD::SRL, XType, Ctlz,
5358 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5359 TLI.getShiftAmountTy()));
5361 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5362 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5363 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5365 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5366 DAG.getConstant(~0ULL, XType));
5367 return DAG.getNode(ISD::SRL, XType,
5368 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5369 DAG.getConstant(XType.getSizeInBits()-1,
5370 TLI.getShiftAmountTy()));
5372 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5373 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5374 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5375 DAG.getConstant(XType.getSizeInBits()-1,
5376 TLI.getShiftAmountTy()));
5377 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5381 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5382 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5383 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5384 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5385 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5386 MVT XType = N0.getValueType();
5387 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5388 DAG.getConstant(XType.getSizeInBits()-1,
5389 TLI.getShiftAmountTy()));
5390 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5391 AddToWorkList(Shift.Val);
5392 AddToWorkList(Add.Val);
5393 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5395 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5396 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5397 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5398 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5399 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5400 MVT XType = N0.getValueType();
5401 if (SubC->isNullValue() && XType.isInteger()) {
5402 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5403 DAG.getConstant(XType.getSizeInBits()-1,
5404 TLI.getShiftAmountTy()));
5405 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5406 AddToWorkList(Shift.Val);
5407 AddToWorkList(Add.Val);
5408 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5416 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5417 SDOperand DAGCombiner::SimplifySetCC(MVT VT, SDOperand N0,
5418 SDOperand N1, ISD::CondCode Cond,
5419 bool foldBooleans) {
5420 TargetLowering::DAGCombinerInfo
5421 DagCombineInfo(DAG, !AfterLegalize, false, this);
5422 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5425 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5426 /// return a DAG expression to select that will generate the same value by
5427 /// multiplying by a magic number. See:
5428 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5429 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5430 std::vector<SDNode*> Built;
5431 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5433 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5439 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5440 /// return a DAG expression to select that will generate the same value by
5441 /// multiplying by a magic number. See:
5442 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5443 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5444 std::vector<SDNode*> Built;
5445 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5447 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5453 /// FindBaseOffset - Return true if base is known not to alias with anything
5454 /// but itself. Provides base object and offset as results.
5455 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5456 // Assume it is a primitive operation.
5457 Base = Ptr; Offset = 0;
5459 // If it's an adding a simple constant then integrate the offset.
5460 if (Base.getOpcode() == ISD::ADD) {
5461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5462 Base = Base.getOperand(0);
5463 Offset += C->getValue();
5467 // If it's any of the following then it can't alias with anything but itself.
5468 return isa<FrameIndexSDNode>(Base) ||
5469 isa<ConstantPoolSDNode>(Base) ||
5470 isa<GlobalAddressSDNode>(Base);
5473 /// isAlias - Return true if there is any possibility that the two addresses
5475 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5476 const Value *SrcValue1, int SrcValueOffset1,
5477 SDOperand Ptr2, int64_t Size2,
5478 const Value *SrcValue2, int SrcValueOffset2)
5480 // If they are the same then they must be aliases.
5481 if (Ptr1 == Ptr2) return true;
5483 // Gather base node and offset information.
5484 SDOperand Base1, Base2;
5485 int64_t Offset1, Offset2;
5486 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5487 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5489 // If they have a same base address then...
5490 if (Base1 == Base2) {
5491 // Check to see if the addresses overlap.
5492 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5495 // If we know both bases then they can't alias.
5496 if (KnownBase1 && KnownBase2) return false;
5498 if (CombinerGlobalAA) {
5499 // Use alias analysis information.
5500 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5501 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5502 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5503 AliasAnalysis::AliasResult AAResult =
5504 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5505 if (AAResult == AliasAnalysis::NoAlias)
5509 // Otherwise we have to assume they alias.
5513 /// FindAliasInfo - Extracts the relevant alias information from the memory
5514 /// node. Returns true if the operand was a load.
5515 bool DAGCombiner::FindAliasInfo(SDNode *N,
5516 SDOperand &Ptr, int64_t &Size,
5517 const Value *&SrcValue, int &SrcValueOffset) {
5518 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5519 Ptr = LD->getBasePtr();
5520 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5521 SrcValue = LD->getSrcValue();
5522 SrcValueOffset = LD->getSrcValueOffset();
5524 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5525 Ptr = ST->getBasePtr();
5526 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5527 SrcValue = ST->getSrcValue();
5528 SrcValueOffset = ST->getSrcValueOffset();
5530 assert(0 && "FindAliasInfo expected a memory operand");
5536 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5537 /// looking for aliasing nodes and adding them to the Aliases vector.
5538 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5539 SmallVector<SDOperand, 8> &Aliases) {
5540 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5541 std::set<SDNode *> Visited; // Visited node set.
5543 // Get alias information for node.
5546 const Value *SrcValue;
5548 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5551 Chains.push_back(OriginalChain);
5553 // Look at each chain and determine if it is an alias. If so, add it to the
5554 // aliases list. If not, then continue up the chain looking for the next
5556 while (!Chains.empty()) {
5557 SDOperand Chain = Chains.back();
5560 // Don't bother if we've been before.
5561 if (Visited.find(Chain.Val) != Visited.end()) continue;
5562 Visited.insert(Chain.Val);
5564 switch (Chain.getOpcode()) {
5565 case ISD::EntryToken:
5566 // Entry token is ideal chain operand, but handled in FindBetterChain.
5571 // Get alias information for Chain.
5574 const Value *OpSrcValue;
5575 int OpSrcValueOffset;
5576 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5577 OpSrcValue, OpSrcValueOffset);
5579 // If chain is alias then stop here.
5580 if (!(IsLoad && IsOpLoad) &&
5581 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5582 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5583 Aliases.push_back(Chain);
5585 // Look further up the chain.
5586 Chains.push_back(Chain.getOperand(0));
5587 // Clean up old chain.
5588 AddToWorkList(Chain.Val);
5593 case ISD::TokenFactor:
5594 // We have to check each of the operands of the token factor, so we queue
5595 // then up. Adding the operands to the queue (stack) in reverse order
5596 // maintains the original order and increases the likelihood that getNode
5597 // will find a matching token factor (CSE.)
5598 for (unsigned n = Chain.getNumOperands(); n;)
5599 Chains.push_back(Chain.getOperand(--n));
5600 // Eliminate the token factor if we can.
5601 AddToWorkList(Chain.Val);
5605 // For all other instructions we will just have to take what we can get.
5606 Aliases.push_back(Chain);
5612 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5613 /// for a better chain (aliasing node.)
5614 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5615 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5617 // Accumulate all the aliases to this node.
5618 GatherAllAliases(N, OldChain, Aliases);
5620 if (Aliases.size() == 0) {
5621 // If no operands then chain to entry token.
5622 return DAG.getEntryNode();
5623 } else if (Aliases.size() == 1) {
5624 // If a single operand then chain to it. We don't need to revisit it.
5628 // Construct a custom tailored token factor.
5629 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5630 &Aliases[0], Aliases.size());
5632 // Make sure the old chain gets cleaned up.
5633 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5638 // SelectionDAG::Combine - This is the entry point for the file.
5640 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5641 if (!RunningAfterLegalize && ViewDAGCombine1)
5643 if (RunningAfterLegalize && ViewDAGCombine2)
5645 /// run - This is the main entry point to this class.
5647 DAGCombiner(*this, AA).Run(RunningAfterLegalize);