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 WorkList.reserve(DAG.allnodes_size());
596 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
597 E = DAG.allnodes_end(); I != E; ++I)
598 WorkList.push_back(I);
600 // Create a dummy node (which is not added to allnodes), that adds a reference
601 // to the root node, preventing it from being deleted, and tracking any
602 // changes of the root.
603 HandleSDNode Dummy(DAG.getRoot());
605 // The root of the dag may dangle to deleted nodes until the dag combiner is
606 // done. Set it to null to avoid confusion.
607 DAG.setRoot(SDOperand());
609 // while the worklist isn't empty, inspect the node on the end of it and
610 // try and combine it.
611 while (!WorkList.empty()) {
612 SDNode *N = WorkList.back();
615 // If N has no uses, it is dead. Make sure to revisit all N's operands once
616 // N is deleted from the DAG, since they too may now be dead or may have a
617 // reduced number of uses, allowing other xforms.
618 if (N->use_empty() && N != &Dummy) {
619 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
620 AddToWorkList(N->getOperand(i).Val);
626 SDOperand RV = combine(N);
633 // If we get back the same node we passed in, rather than a new node or
634 // zero, we know that the node must have defined multiple values and
635 // CombineTo was used. Since CombineTo takes care of the worklist
636 // mechanics for us, we have no work to do in this case.
640 assert(N->getOpcode() != ISD::DELETED_NODE &&
641 RV.Val->getOpcode() != ISD::DELETED_NODE &&
642 "Node was deleted but visit returned new node!");
644 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
645 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
647 WorkListRemover DeadNodes(*this);
648 if (N->getNumValues() == RV.Val->getNumValues())
649 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
651 assert(N->getValueType(0) == RV.getValueType() &&
652 N->getNumValues() == 1 && "Type mismatch");
654 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
657 // Push the new node and any users onto the worklist
658 AddToWorkList(RV.Val);
659 AddUsersToWorkList(RV.Val);
661 // Add any uses of the old node to the worklist in case this node is the
662 // last one that uses them. They may become dead after this node is
664 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
665 AddToWorkList(N->getOperand(i).Val);
667 // Nodes can be reintroduced into the worklist. Make sure we do not
668 // process a node that has been replaced.
669 removeFromWorkList(N);
671 // Finally, since the node is now dead, remove it from the graph.
675 // If the root changed (e.g. it was a dead load, update the root).
676 DAG.setRoot(Dummy.getValue());
679 SDOperand DAGCombiner::visit(SDNode *N) {
680 switch(N->getOpcode()) {
682 case ISD::TokenFactor: return visitTokenFactor(N);
683 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
684 case ISD::ADD: return visitADD(N);
685 case ISD::SUB: return visitSUB(N);
686 case ISD::ADDC: return visitADDC(N);
687 case ISD::ADDE: return visitADDE(N);
688 case ISD::MUL: return visitMUL(N);
689 case ISD::SDIV: return visitSDIV(N);
690 case ISD::UDIV: return visitUDIV(N);
691 case ISD::SREM: return visitSREM(N);
692 case ISD::UREM: return visitUREM(N);
693 case ISD::MULHU: return visitMULHU(N);
694 case ISD::MULHS: return visitMULHS(N);
695 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
696 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
697 case ISD::SDIVREM: return visitSDIVREM(N);
698 case ISD::UDIVREM: return visitUDIVREM(N);
699 case ISD::AND: return visitAND(N);
700 case ISD::OR: return visitOR(N);
701 case ISD::XOR: return visitXOR(N);
702 case ISD::SHL: return visitSHL(N);
703 case ISD::SRA: return visitSRA(N);
704 case ISD::SRL: return visitSRL(N);
705 case ISD::CTLZ: return visitCTLZ(N);
706 case ISD::CTTZ: return visitCTTZ(N);
707 case ISD::CTPOP: return visitCTPOP(N);
708 case ISD::SELECT: return visitSELECT(N);
709 case ISD::SELECT_CC: return visitSELECT_CC(N);
710 case ISD::SETCC: return visitSETCC(N);
711 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
712 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
713 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
714 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
715 case ISD::TRUNCATE: return visitTRUNCATE(N);
716 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
717 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
718 case ISD::FADD: return visitFADD(N);
719 case ISD::FSUB: return visitFSUB(N);
720 case ISD::FMUL: return visitFMUL(N);
721 case ISD::FDIV: return visitFDIV(N);
722 case ISD::FREM: return visitFREM(N);
723 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
724 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
725 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
726 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
727 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
728 case ISD::FP_ROUND: return visitFP_ROUND(N);
729 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
730 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
731 case ISD::FNEG: return visitFNEG(N);
732 case ISD::FABS: return visitFABS(N);
733 case ISD::BRCOND: return visitBRCOND(N);
734 case ISD::BR_CC: return visitBR_CC(N);
735 case ISD::LOAD: return visitLOAD(N);
736 case ISD::STORE: return visitSTORE(N);
737 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
738 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
739 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
740 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
741 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
746 SDOperand DAGCombiner::combine(SDNode *N) {
748 SDOperand RV = visit(N);
750 // If nothing happened, try a target-specific DAG combine.
752 assert(N->getOpcode() != ISD::DELETED_NODE &&
753 "Node was deleted but visit returned NULL!");
755 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
756 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
758 // Expose the DAG combiner to the target combiner impls.
759 TargetLowering::DAGCombinerInfo
760 DagCombineInfo(DAG, !AfterLegalize, false, this);
762 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
766 // If N is a commutative binary node, try commuting it to enable more
769 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
770 N->getNumValues() == 1) {
771 SDOperand N0 = N->getOperand(0);
772 SDOperand N1 = N->getOperand(1);
773 // Constant operands are canonicalized to RHS.
774 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
775 SDOperand Ops[] = { N1, N0 };
776 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
779 return SDOperand(CSENode, 0);
786 /// getInputChainForNode - Given a node, return its input chain if it has one,
787 /// otherwise return a null sd operand.
788 static SDOperand getInputChainForNode(SDNode *N) {
789 if (unsigned NumOps = N->getNumOperands()) {
790 if (N->getOperand(0).getValueType() == MVT::Other)
791 return N->getOperand(0);
792 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
793 return N->getOperand(NumOps-1);
794 for (unsigned i = 1; i < NumOps-1; ++i)
795 if (N->getOperand(i).getValueType() == MVT::Other)
796 return N->getOperand(i);
798 return SDOperand(0, 0);
801 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
802 // If N has two operands, where one has an input chain equal to the other,
803 // the 'other' chain is redundant.
804 if (N->getNumOperands() == 2) {
805 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
806 return N->getOperand(0);
807 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
808 return N->getOperand(1);
811 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
812 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
813 SmallPtrSet<SDNode*, 16> SeenOps;
814 bool Changed = false; // If we should replace this token factor.
816 // Start out with this token factor.
819 // Iterate through token factors. The TFs grows when new token factors are
821 for (unsigned i = 0; i < TFs.size(); ++i) {
824 // Check each of the operands.
825 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
826 SDOperand Op = TF->getOperand(i);
828 switch (Op.getOpcode()) {
829 case ISD::EntryToken:
830 // Entry tokens don't need to be added to the list. They are
835 case ISD::TokenFactor:
836 if ((CombinerAA || Op.hasOneUse()) &&
837 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
838 // Queue up for processing.
839 TFs.push_back(Op.Val);
840 // Clean up in case the token factor is removed.
841 AddToWorkList(Op.Val);
848 // Only add if it isn't already in the list.
849 if (SeenOps.insert(Op.Val))
860 // If we've change things around then replace token factor.
863 // The entry token is the only possible outcome.
864 Result = DAG.getEntryNode();
866 // New and improved token factor.
867 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
870 // Don't add users to work list.
871 return CombineTo(N, Result, false);
877 /// MERGE_VALUES can always be eliminated.
878 SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
879 WorkListRemover DeadNodes(*this);
880 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
881 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
883 removeFromWorkList(N);
885 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
890 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
891 MVT VT = N0.getValueType();
892 SDOperand N00 = N0.getOperand(0);
893 SDOperand N01 = N0.getOperand(1);
894 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
895 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
896 isa<ConstantSDNode>(N00.getOperand(1))) {
897 N0 = DAG.getNode(ISD::ADD, VT,
898 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
899 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
900 return DAG.getNode(ISD::ADD, VT, N0, N1);
906 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
908 MVT VT = N->getValueType(0);
909 unsigned Opc = N->getOpcode();
910 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
911 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
912 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
913 ISD::CondCode CC = ISD::SETCC_INVALID;
915 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
917 SDOperand CCOp = Slct.getOperand(0);
918 if (CCOp.getOpcode() == ISD::SETCC)
919 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
922 bool DoXform = false;
924 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
926 if (LHS.getOpcode() == ISD::Constant &&
927 cast<ConstantSDNode>(LHS)->isNullValue())
929 else if (CC != ISD::SETCC_INVALID &&
930 RHS.getOpcode() == ISD::Constant &&
931 cast<ConstantSDNode>(RHS)->isNullValue()) {
933 SDOperand Op0 = Slct.getOperand(0);
934 bool isInt = (isSlctCC ? Op0.getValueType() :
935 Op0.getOperand(0).getValueType()).isInteger();
936 CC = ISD::getSetCCInverse(CC, isInt);
942 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
944 return DAG.getSelectCC(OtherOp, Result,
945 Slct.getOperand(0), Slct.getOperand(1), CC);
946 SDOperand CCOp = Slct.getOperand(0);
948 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
949 CCOp.getOperand(1), CC);
950 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
955 SDOperand DAGCombiner::visitADD(SDNode *N) {
956 SDOperand N0 = N->getOperand(0);
957 SDOperand N1 = N->getOperand(1);
958 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
959 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
960 MVT VT = N0.getValueType();
964 SDOperand FoldedVOp = SimplifyVBinOp(N);
965 if (FoldedVOp.Val) return FoldedVOp;
968 // fold (add x, undef) -> undef
969 if (N0.getOpcode() == ISD::UNDEF)
971 if (N1.getOpcode() == ISD::UNDEF)
973 // fold (add c1, c2) -> c1+c2
975 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
976 // canonicalize constant to RHS
978 return DAG.getNode(ISD::ADD, VT, N1, N0);
979 // fold (add x, 0) -> x
980 if (N1C && N1C->isNullValue())
982 // fold ((c1-A)+c2) -> (c1+c2)-A
983 if (N1C && N0.getOpcode() == ISD::SUB)
984 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
985 return DAG.getNode(ISD::SUB, VT,
986 DAG.getConstant(N1C->getAPIntValue()+
987 N0C->getAPIntValue(), VT),
990 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
993 // fold ((0-A) + B) -> B-A
994 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
995 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
996 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
997 // fold (A + (0-B)) -> A-B
998 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
999 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1000 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
1001 // fold (A+(B-A)) -> B
1002 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1003 return N1.getOperand(0);
1005 if (!VT.isVector() && SimplifyDemandedBits(SDOperand(N, 0)))
1006 return SDOperand(N, 0);
1008 // fold (a+b) -> (a|b) iff a and b share no bits.
1009 if (VT.isInteger() && !VT.isVector()) {
1010 APInt LHSZero, LHSOne;
1011 APInt RHSZero, RHSOne;
1012 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1013 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1014 if (LHSZero.getBoolValue()) {
1015 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1017 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1018 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1019 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1020 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1021 return DAG.getNode(ISD::OR, VT, N0, N1);
1025 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1026 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1027 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1028 if (Result.Val) return Result;
1030 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1031 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1032 if (Result.Val) return Result;
1035 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1036 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1037 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1038 if (Result.Val) return Result;
1040 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1041 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1042 if (Result.Val) return Result;
1048 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1049 SDOperand N0 = N->getOperand(0);
1050 SDOperand N1 = N->getOperand(1);
1051 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1052 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1053 MVT VT = N0.getValueType();
1055 // If the flag result is dead, turn this into an ADD.
1056 if (N->hasNUsesOfValue(0, 1))
1057 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1058 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1060 // canonicalize constant to RHS.
1062 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1064 // fold (addc x, 0) -> x + no carry out
1065 if (N1C && N1C->isNullValue())
1066 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1068 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1069 APInt LHSZero, LHSOne;
1070 APInt RHSZero, RHSOne;
1071 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1072 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1073 if (LHSZero.getBoolValue()) {
1074 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1076 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1077 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1078 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1079 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1080 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1081 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1087 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1088 SDOperand N0 = N->getOperand(0);
1089 SDOperand N1 = N->getOperand(1);
1090 SDOperand CarryIn = N->getOperand(2);
1091 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1092 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1093 //MVT VT = N0.getValueType();
1095 // canonicalize constant to RHS
1097 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn);
1099 // fold (adde x, y, false) -> (addc x, y)
1100 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1101 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1108 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1109 SDOperand N0 = N->getOperand(0);
1110 SDOperand N1 = N->getOperand(1);
1111 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1112 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1113 MVT VT = N0.getValueType();
1116 if (VT.isVector()) {
1117 SDOperand FoldedVOp = SimplifyVBinOp(N);
1118 if (FoldedVOp.Val) return FoldedVOp;
1121 // fold (sub x, x) -> 0
1123 return DAG.getConstant(0, N->getValueType(0));
1124 // fold (sub c1, c2) -> c1-c2
1126 return DAG.getNode(ISD::SUB, VT, N0, N1);
1127 // fold (sub x, c) -> (add x, -c)
1129 return DAG.getNode(ISD::ADD, VT, N0,
1130 DAG.getConstant(-N1C->getAPIntValue(), VT));
1131 // fold (A+B)-A -> B
1132 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1133 return N0.getOperand(1);
1134 // fold (A+B)-B -> A
1135 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1136 return N0.getOperand(0);
1137 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1138 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1139 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1140 if (Result.Val) return Result;
1142 // If either operand of a sub is undef, the result is undef
1143 if (N0.getOpcode() == ISD::UNDEF)
1145 if (N1.getOpcode() == ISD::UNDEF)
1151 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1152 SDOperand N0 = N->getOperand(0);
1153 SDOperand N1 = N->getOperand(1);
1154 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1155 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1156 MVT VT = N0.getValueType();
1159 if (VT.isVector()) {
1160 SDOperand FoldedVOp = SimplifyVBinOp(N);
1161 if (FoldedVOp.Val) return FoldedVOp;
1164 // fold (mul x, undef) -> 0
1165 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1166 return DAG.getConstant(0, VT);
1167 // fold (mul c1, c2) -> c1*c2
1169 return DAG.getNode(ISD::MUL, VT, N0, N1);
1170 // canonicalize constant to RHS
1172 return DAG.getNode(ISD::MUL, VT, N1, N0);
1173 // fold (mul x, 0) -> 0
1174 if (N1C && N1C->isNullValue())
1176 // fold (mul x, -1) -> 0-x
1177 if (N1C && N1C->isAllOnesValue())
1178 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1179 // fold (mul x, (1 << c)) -> x << c
1180 if (N1C && N1C->getAPIntValue().isPowerOf2())
1181 return DAG.getNode(ISD::SHL, VT, N0,
1182 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1183 TLI.getShiftAmountTy()));
1184 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1185 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1186 // FIXME: If the input is something that is easily negated (e.g. a
1187 // single-use add), we should put the negate there.
1188 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1189 DAG.getNode(ISD::SHL, VT, N0,
1190 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1191 TLI.getShiftAmountTy())));
1194 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1195 if (N1C && N0.getOpcode() == ISD::SHL &&
1196 isa<ConstantSDNode>(N0.getOperand(1))) {
1197 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1198 AddToWorkList(C3.Val);
1199 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1202 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1205 SDOperand Sh(0,0), Y(0,0);
1206 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1207 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1208 N0.Val->hasOneUse()) {
1210 } else if (N1.getOpcode() == ISD::SHL &&
1211 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1215 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1216 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1219 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1220 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1221 isa<ConstantSDNode>(N0.getOperand(1))) {
1222 return DAG.getNode(ISD::ADD, VT,
1223 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1224 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1228 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1235 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1236 SDOperand N0 = N->getOperand(0);
1237 SDOperand N1 = N->getOperand(1);
1238 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1239 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1240 MVT VT = N->getValueType(0);
1243 if (VT.isVector()) {
1244 SDOperand FoldedVOp = SimplifyVBinOp(N);
1245 if (FoldedVOp.Val) return FoldedVOp;
1248 // fold (sdiv c1, c2) -> c1/c2
1249 if (N0C && N1C && !N1C->isNullValue())
1250 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1251 // fold (sdiv X, 1) -> X
1252 if (N1C && N1C->getSignExtended() == 1LL)
1254 // fold (sdiv X, -1) -> 0-X
1255 if (N1C && N1C->isAllOnesValue())
1256 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1257 // If we know the sign bits of both operands are zero, strength reduce to a
1258 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1259 if (!VT.isVector()) {
1260 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1261 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1263 // fold (sdiv X, pow2) -> simple ops after legalize
1264 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1265 (isPowerOf2_64(N1C->getSignExtended()) ||
1266 isPowerOf2_64(-N1C->getSignExtended()))) {
1267 // If dividing by powers of two is cheap, then don't perform the following
1269 if (TLI.isPow2DivCheap())
1271 int64_t pow2 = N1C->getSignExtended();
1272 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1273 unsigned lg2 = Log2_64(abs2);
1274 // Splat the sign bit into the register
1275 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1276 DAG.getConstant(VT.getSizeInBits()-1,
1277 TLI.getShiftAmountTy()));
1278 AddToWorkList(SGN.Val);
1279 // Add (N0 < 0) ? abs2 - 1 : 0;
1280 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1281 DAG.getConstant(VT.getSizeInBits()-lg2,
1282 TLI.getShiftAmountTy()));
1283 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1284 AddToWorkList(SRL.Val);
1285 AddToWorkList(ADD.Val); // Divide by pow2
1286 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1287 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1288 // If we're dividing by a positive value, we're done. Otherwise, we must
1289 // negate the result.
1292 AddToWorkList(SRA.Val);
1293 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1295 // if integer divide is expensive and we satisfy the requirements, emit an
1296 // alternate sequence.
1297 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1298 !TLI.isIntDivCheap()) {
1299 SDOperand Op = BuildSDIV(N);
1300 if (Op.Val) return Op;
1304 if (N0.getOpcode() == ISD::UNDEF)
1305 return DAG.getConstant(0, VT);
1306 // X / undef -> undef
1307 if (N1.getOpcode() == ISD::UNDEF)
1313 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1314 SDOperand N0 = N->getOperand(0);
1315 SDOperand N1 = N->getOperand(1);
1316 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1317 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1318 MVT VT = N->getValueType(0);
1321 if (VT.isVector()) {
1322 SDOperand FoldedVOp = SimplifyVBinOp(N);
1323 if (FoldedVOp.Val) return FoldedVOp;
1326 // fold (udiv c1, c2) -> c1/c2
1327 if (N0C && N1C && !N1C->isNullValue())
1328 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1329 // fold (udiv x, (1 << c)) -> x >>u c
1330 if (N1C && N1C->getAPIntValue().isPowerOf2())
1331 return DAG.getNode(ISD::SRL, VT, N0,
1332 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1333 TLI.getShiftAmountTy()));
1334 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1335 if (N1.getOpcode() == ISD::SHL) {
1336 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1337 if (SHC->getAPIntValue().isPowerOf2()) {
1338 MVT ADDVT = N1.getOperand(1).getValueType();
1339 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1340 DAG.getConstant(SHC->getAPIntValue()
1343 AddToWorkList(Add.Val);
1344 return DAG.getNode(ISD::SRL, VT, N0, Add);
1348 // fold (udiv x, c) -> alternate
1349 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1350 SDOperand Op = BuildUDIV(N);
1351 if (Op.Val) return Op;
1355 if (N0.getOpcode() == ISD::UNDEF)
1356 return DAG.getConstant(0, VT);
1357 // X / undef -> undef
1358 if (N1.getOpcode() == ISD::UNDEF)
1364 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1365 SDOperand N0 = N->getOperand(0);
1366 SDOperand N1 = N->getOperand(1);
1367 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1368 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1369 MVT VT = N->getValueType(0);
1371 // fold (srem c1, c2) -> c1%c2
1372 if (N0C && N1C && !N1C->isNullValue())
1373 return DAG.getNode(ISD::SREM, VT, N0, N1);
1374 // If we know the sign bits of both operands are zero, strength reduce to a
1375 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1376 if (!VT.isVector()) {
1377 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1378 return DAG.getNode(ISD::UREM, VT, N0, N1);
1381 // If X/C can be simplified by the division-by-constant logic, lower
1382 // X%C to the equivalent of X-X/C*C.
1383 if (N1C && !N1C->isNullValue()) {
1384 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1385 AddToWorkList(Div.Val);
1386 SDOperand OptimizedDiv = combine(Div.Val);
1387 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1388 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1389 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1390 AddToWorkList(Mul.Val);
1396 if (N0.getOpcode() == ISD::UNDEF)
1397 return DAG.getConstant(0, VT);
1398 // X % undef -> undef
1399 if (N1.getOpcode() == ISD::UNDEF)
1405 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1406 SDOperand N0 = N->getOperand(0);
1407 SDOperand N1 = N->getOperand(1);
1408 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1409 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1410 MVT VT = N->getValueType(0);
1412 // fold (urem c1, c2) -> c1%c2
1413 if (N0C && N1C && !N1C->isNullValue())
1414 return DAG.getNode(ISD::UREM, VT, N0, N1);
1415 // fold (urem x, pow2) -> (and x, pow2-1)
1416 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1417 return DAG.getNode(ISD::AND, VT, N0,
1418 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1419 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1420 if (N1.getOpcode() == ISD::SHL) {
1421 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1422 if (SHC->getAPIntValue().isPowerOf2()) {
1424 DAG.getNode(ISD::ADD, VT, N1,
1425 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1427 AddToWorkList(Add.Val);
1428 return DAG.getNode(ISD::AND, VT, N0, Add);
1433 // If X/C can be simplified by the division-by-constant logic, lower
1434 // X%C to the equivalent of X-X/C*C.
1435 if (N1C && !N1C->isNullValue()) {
1436 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1437 SDOperand OptimizedDiv = combine(Div.Val);
1438 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1439 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1440 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1441 AddToWorkList(Mul.Val);
1447 if (N0.getOpcode() == ISD::UNDEF)
1448 return DAG.getConstant(0, VT);
1449 // X % undef -> undef
1450 if (N1.getOpcode() == ISD::UNDEF)
1456 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1457 SDOperand N0 = N->getOperand(0);
1458 SDOperand N1 = N->getOperand(1);
1459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1460 MVT VT = N->getValueType(0);
1462 // fold (mulhs x, 0) -> 0
1463 if (N1C && N1C->isNullValue())
1465 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1466 if (N1C && N1C->getAPIntValue() == 1)
1467 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1468 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1469 TLI.getShiftAmountTy()));
1470 // fold (mulhs x, undef) -> 0
1471 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1472 return DAG.getConstant(0, VT);
1477 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1478 SDOperand N0 = N->getOperand(0);
1479 SDOperand N1 = N->getOperand(1);
1480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1481 MVT VT = N->getValueType(0);
1483 // fold (mulhu x, 0) -> 0
1484 if (N1C && N1C->isNullValue())
1486 // fold (mulhu x, 1) -> 0
1487 if (N1C && N1C->getAPIntValue() == 1)
1488 return DAG.getConstant(0, N0.getValueType());
1489 // fold (mulhu x, undef) -> 0
1490 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1491 return DAG.getConstant(0, VT);
1496 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1497 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1498 /// that are being performed. Return true if a simplification was made.
1500 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1502 // If the high half is not needed, just compute the low half.
1503 bool HiExists = N->hasAnyUseOfValue(1);
1506 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1507 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1508 N->getNumOperands());
1509 return CombineTo(N, Res, Res);
1512 // If the low half is not needed, just compute the high half.
1513 bool LoExists = N->hasAnyUseOfValue(0);
1516 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1517 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1518 N->getNumOperands());
1519 return CombineTo(N, Res, Res);
1522 // If both halves are used, return as it is.
1523 if (LoExists && HiExists)
1526 // If the two computed results can be simplified separately, separate them.
1528 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1529 N->op_begin(), N->getNumOperands());
1530 AddToWorkList(Lo.Val);
1531 SDOperand LoOpt = combine(Lo.Val);
1532 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1534 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1535 return CombineTo(N, LoOpt, LoOpt);
1539 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1540 N->op_begin(), N->getNumOperands());
1541 AddToWorkList(Hi.Val);
1542 SDOperand HiOpt = combine(Hi.Val);
1543 if (HiOpt.Val && HiOpt != Hi &&
1545 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1546 return CombineTo(N, HiOpt, HiOpt);
1551 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1552 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1553 if (Res.Val) return Res;
1558 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1559 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1560 if (Res.Val) return Res;
1565 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1566 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1567 if (Res.Val) return Res;
1572 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1573 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1574 if (Res.Val) return Res;
1579 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1580 /// two operands of the same opcode, try to simplify it.
1581 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1582 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1583 MVT VT = N0.getValueType();
1584 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1586 // For each of OP in AND/OR/XOR:
1587 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1588 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1589 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1590 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1591 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1592 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1593 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1594 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1595 N0.getOperand(0).getValueType(),
1596 N0.getOperand(0), N1.getOperand(0));
1597 AddToWorkList(ORNode.Val);
1598 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1601 // For each of OP in SHL/SRL/SRA/AND...
1602 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1603 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1604 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1605 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1606 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1607 N0.getOperand(1) == N1.getOperand(1)) {
1608 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1609 N0.getOperand(0).getValueType(),
1610 N0.getOperand(0), N1.getOperand(0));
1611 AddToWorkList(ORNode.Val);
1612 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1618 SDOperand DAGCombiner::visitAND(SDNode *N) {
1619 SDOperand N0 = N->getOperand(0);
1620 SDOperand N1 = N->getOperand(1);
1621 SDOperand LL, LR, RL, RR, CC0, CC1;
1622 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1623 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1624 MVT VT = N1.getValueType();
1625 unsigned BitWidth = VT.getSizeInBits();
1628 if (VT.isVector()) {
1629 SDOperand FoldedVOp = SimplifyVBinOp(N);
1630 if (FoldedVOp.Val) return FoldedVOp;
1633 // fold (and x, undef) -> 0
1634 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1635 return DAG.getConstant(0, VT);
1636 // fold (and c1, c2) -> c1&c2
1638 return DAG.getNode(ISD::AND, VT, N0, N1);
1639 // canonicalize constant to RHS
1641 return DAG.getNode(ISD::AND, VT, N1, N0);
1642 // fold (and x, -1) -> x
1643 if (N1C && N1C->isAllOnesValue())
1645 // if (and x, c) is known to be zero, return 0
1646 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1647 APInt::getAllOnesValue(BitWidth)))
1648 return DAG.getConstant(0, VT);
1650 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1653 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1654 if (N1C && N0.getOpcode() == ISD::OR)
1655 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1656 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1658 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1659 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1660 SDOperand N0Op0 = N0.getOperand(0);
1661 APInt Mask = ~N1C->getAPIntValue();
1662 Mask.trunc(N0Op0.getValueSizeInBits());
1663 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1664 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1667 // Replace uses of the AND with uses of the Zero extend node.
1670 // We actually want to replace all uses of the any_extend with the
1671 // zero_extend, to avoid duplicating things. This will later cause this
1672 // AND to be folded.
1673 CombineTo(N0.Val, Zext);
1674 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1677 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1678 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1679 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1680 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1682 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1683 LL.getValueType().isInteger()) {
1684 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1685 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1686 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1687 AddToWorkList(ORNode.Val);
1688 return DAG.getSetCC(VT, ORNode, LR, Op1);
1690 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1691 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1692 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1693 AddToWorkList(ANDNode.Val);
1694 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1696 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1697 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1698 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1699 AddToWorkList(ORNode.Val);
1700 return DAG.getSetCC(VT, ORNode, LR, Op1);
1703 // canonicalize equivalent to ll == rl
1704 if (LL == RR && LR == RL) {
1705 Op1 = ISD::getSetCCSwappedOperands(Op1);
1708 if (LL == RL && LR == RR) {
1709 bool isInteger = LL.getValueType().isInteger();
1710 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1711 if (Result != ISD::SETCC_INVALID)
1712 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1716 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1717 if (N0.getOpcode() == N1.getOpcode()) {
1718 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1719 if (Tmp.Val) return Tmp;
1722 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1723 // fold (and (sra)) -> (and (srl)) when possible.
1724 if (!VT.isVector() &&
1725 SimplifyDemandedBits(SDOperand(N, 0)))
1726 return SDOperand(N, 0);
1727 // fold (zext_inreg (extload x)) -> (zextload x)
1728 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1729 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1730 MVT EVT = LN0->getMemoryVT();
1731 // If we zero all the possible extended bits, then we can turn this into
1732 // a zextload if we are running before legalize or the operation is legal.
1733 unsigned BitWidth = N1.getValueSizeInBits();
1734 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1735 BitWidth - EVT.getSizeInBits())) &&
1736 ((!AfterLegalize && !LN0->isVolatile()) ||
1737 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1738 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1739 LN0->getBasePtr(), LN0->getSrcValue(),
1740 LN0->getSrcValueOffset(), EVT,
1742 LN0->getAlignment());
1744 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1745 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1748 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1749 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1751 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1752 MVT EVT = LN0->getMemoryVT();
1753 // If we zero all the possible extended bits, then we can turn this into
1754 // a zextload if we are running before legalize or the operation is legal.
1755 unsigned BitWidth = N1.getValueSizeInBits();
1756 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1757 BitWidth - EVT.getSizeInBits())) &&
1758 ((!AfterLegalize && !LN0->isVolatile()) ||
1759 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1760 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1761 LN0->getBasePtr(), LN0->getSrcValue(),
1762 LN0->getSrcValueOffset(), EVT,
1764 LN0->getAlignment());
1766 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1767 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1771 // fold (and (load x), 255) -> (zextload x, i8)
1772 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1773 if (N1C && N0.getOpcode() == ISD::LOAD) {
1774 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1775 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1776 LN0->isUnindexed() && N0.hasOneUse() &&
1777 // Do not change the width of a volatile load.
1778 !LN0->isVolatile()) {
1779 MVT EVT = MVT::Other;
1780 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1781 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1782 EVT = MVT::getIntegerVT(ActiveBits);
1784 MVT LoadedVT = LN0->getMemoryVT();
1785 // Do not generate loads of non-round integer types since these can
1786 // be expensive (and would be wrong if the type is not byte sized).
1787 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
1788 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1789 MVT PtrType = N0.getOperand(1).getValueType();
1790 // For big endian targets, we need to add an offset to the pointer to
1791 // load the correct bytes. For little endian systems, we merely need to
1792 // read fewer bytes from the same pointer.
1793 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1794 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1795 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1796 unsigned Alignment = LN0->getAlignment();
1797 SDOperand NewPtr = LN0->getBasePtr();
1798 if (TLI.isBigEndian()) {
1799 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1800 DAG.getConstant(PtrOff, PtrType));
1801 Alignment = MinAlign(Alignment, PtrOff);
1803 AddToWorkList(NewPtr.Val);
1805 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1806 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1807 LN0->isVolatile(), Alignment);
1809 CombineTo(N0.Val, Load, Load.getValue(1));
1810 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1818 SDOperand DAGCombiner::visitOR(SDNode *N) {
1819 SDOperand N0 = N->getOperand(0);
1820 SDOperand N1 = N->getOperand(1);
1821 SDOperand LL, LR, RL, RR, CC0, CC1;
1822 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1823 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1824 MVT VT = N1.getValueType();
1827 if (VT.isVector()) {
1828 SDOperand FoldedVOp = SimplifyVBinOp(N);
1829 if (FoldedVOp.Val) return FoldedVOp;
1832 // fold (or x, undef) -> -1
1833 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1834 return DAG.getConstant(~0ULL, VT);
1835 // fold (or c1, c2) -> c1|c2
1837 return DAG.getNode(ISD::OR, VT, N0, N1);
1838 // canonicalize constant to RHS
1840 return DAG.getNode(ISD::OR, VT, N1, N0);
1841 // fold (or x, 0) -> x
1842 if (N1C && N1C->isNullValue())
1844 // fold (or x, -1) -> -1
1845 if (N1C && N1C->isAllOnesValue())
1847 // fold (or x, c) -> c iff (x & ~c) == 0
1848 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1851 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1854 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1855 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1856 isa<ConstantSDNode>(N0.getOperand(1))) {
1857 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1858 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1860 DAG.getConstant(N1C->getAPIntValue() |
1861 C1->getAPIntValue(), VT));
1863 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1864 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1865 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1866 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1868 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1869 LL.getValueType().isInteger()) {
1870 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1871 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1872 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1873 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1874 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1875 AddToWorkList(ORNode.Val);
1876 return DAG.getSetCC(VT, ORNode, LR, Op1);
1878 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1879 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1880 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1881 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1882 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1883 AddToWorkList(ANDNode.Val);
1884 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1887 // canonicalize equivalent to ll == rl
1888 if (LL == RR && LR == RL) {
1889 Op1 = ISD::getSetCCSwappedOperands(Op1);
1892 if (LL == RL && LR == RR) {
1893 bool isInteger = LL.getValueType().isInteger();
1894 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1895 if (Result != ISD::SETCC_INVALID)
1896 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1900 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1901 if (N0.getOpcode() == N1.getOpcode()) {
1902 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1903 if (Tmp.Val) return Tmp;
1906 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1907 if (N0.getOpcode() == ISD::AND &&
1908 N1.getOpcode() == ISD::AND &&
1909 N0.getOperand(1).getOpcode() == ISD::Constant &&
1910 N1.getOperand(1).getOpcode() == ISD::Constant &&
1911 // Don't increase # computations.
1912 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1913 // We can only do this xform if we know that bits from X that are set in C2
1914 // but not in C1 are already zero. Likewise for Y.
1915 const APInt &LHSMask =
1916 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1917 const APInt &RHSMask =
1918 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1920 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1921 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1922 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1923 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1928 // See if this is some rotate idiom.
1929 if (SDNode *Rot = MatchRotate(N0, N1))
1930 return SDOperand(Rot, 0);
1936 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1937 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1938 if (Op.getOpcode() == ISD::AND) {
1939 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1940 Mask = Op.getOperand(1);
1941 Op = Op.getOperand(0);
1947 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1955 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1956 // idioms for rotate, and if the target supports rotation instructions, generate
1958 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1959 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
1960 MVT VT = LHS.getValueType();
1961 if (!TLI.isTypeLegal(VT)) return 0;
1963 // The target must have at least one rotate flavor.
1964 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1965 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1966 if (!HasROTL && !HasROTR) return 0;
1968 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1969 SDOperand LHSShift; // The shift.
1970 SDOperand LHSMask; // AND value if any.
1971 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1972 return 0; // Not part of a rotate.
1974 SDOperand RHSShift; // The shift.
1975 SDOperand RHSMask; // AND value if any.
1976 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1977 return 0; // Not part of a rotate.
1979 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1980 return 0; // Not shifting the same value.
1982 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1983 return 0; // Shifts must disagree.
1985 // Canonicalize shl to left side in a shl/srl pair.
1986 if (RHSShift.getOpcode() == ISD::SHL) {
1987 std::swap(LHS, RHS);
1988 std::swap(LHSShift, RHSShift);
1989 std::swap(LHSMask , RHSMask );
1992 unsigned OpSizeInBits = VT.getSizeInBits();
1993 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1994 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1995 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1997 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1998 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1999 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2000 RHSShiftAmt.getOpcode() == ISD::Constant) {
2001 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
2002 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
2003 if ((LShVal + RShVal) != OpSizeInBits)
2008 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2010 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2012 // If there is an AND of either shifted operand, apply it to the result.
2013 if (LHSMask.Val || RHSMask.Val) {
2014 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2017 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2018 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2021 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2022 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2025 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2031 // If there is a mask here, and we have a variable shift, we can't be sure
2032 // that we're masking out the right stuff.
2033 if (LHSMask.Val || RHSMask.Val)
2036 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2037 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2038 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2039 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2040 if (ConstantSDNode *SUBC =
2041 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2042 if (SUBC->getAPIntValue() == OpSizeInBits) {
2044 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2046 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2051 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2052 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2053 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2054 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2055 if (ConstantSDNode *SUBC =
2056 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2057 if (SUBC->getAPIntValue() == OpSizeInBits) {
2059 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2061 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2066 // Look for sign/zext/any-extended cases:
2067 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2068 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2069 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2070 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2071 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2072 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2073 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2074 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2075 if (RExtOp0.getOpcode() == ISD::SUB &&
2076 RExtOp0.getOperand(1) == LExtOp0) {
2077 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2079 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2080 // (rotl x, (sub 32, y))
2081 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2082 if (SUBC->getAPIntValue() == OpSizeInBits) {
2084 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2086 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2089 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2090 RExtOp0 == LExtOp0.getOperand(1)) {
2091 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2093 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2094 // (rotr x, (sub 32, y))
2095 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2096 if (SUBC->getAPIntValue() == OpSizeInBits) {
2098 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2100 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2110 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2111 SDOperand N0 = N->getOperand(0);
2112 SDOperand N1 = N->getOperand(1);
2113 SDOperand LHS, RHS, CC;
2114 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2115 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2116 MVT VT = N0.getValueType();
2119 if (VT.isVector()) {
2120 SDOperand FoldedVOp = SimplifyVBinOp(N);
2121 if (FoldedVOp.Val) return FoldedVOp;
2124 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2125 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2126 return DAG.getConstant(0, VT);
2127 // fold (xor x, undef) -> undef
2128 if (N0.getOpcode() == ISD::UNDEF)
2130 if (N1.getOpcode() == ISD::UNDEF)
2132 // fold (xor c1, c2) -> c1^c2
2134 return DAG.getNode(ISD::XOR, VT, N0, N1);
2135 // canonicalize constant to RHS
2137 return DAG.getNode(ISD::XOR, VT, N1, N0);
2138 // fold (xor x, 0) -> x
2139 if (N1C && N1C->isNullValue())
2142 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2145 // fold !(x cc y) -> (x !cc y)
2146 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2147 bool isInt = LHS.getValueType().isInteger();
2148 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2150 if (N0.getOpcode() == ISD::SETCC)
2151 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2152 if (N0.getOpcode() == ISD::SELECT_CC)
2153 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2154 assert(0 && "Unhandled SetCC Equivalent!");
2157 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2158 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2159 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2160 SDOperand V = N0.getOperand(0);
2161 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2162 DAG.getConstant(1, V.getValueType()));
2163 AddToWorkList(V.Val);
2164 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2167 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2168 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2169 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2170 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2171 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2172 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2173 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2174 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2175 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2176 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2179 // fold !(x or y) -> (!x and !y) iff x or y are constants
2180 if (N1C && N1C->isAllOnesValue() &&
2181 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2182 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2183 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2184 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2185 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2186 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2187 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2188 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2191 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2192 if (N1C && N0.getOpcode() == ISD::XOR) {
2193 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2194 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2196 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2197 DAG.getConstant(N1C->getAPIntValue()^
2198 N00C->getAPIntValue(), VT));
2200 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2201 DAG.getConstant(N1C->getAPIntValue()^
2202 N01C->getAPIntValue(), VT));
2204 // fold (xor x, x) -> 0
2206 if (!VT.isVector()) {
2207 return DAG.getConstant(0, VT);
2208 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2209 // Produce a vector of zeros.
2210 SDOperand El = DAG.getConstant(0, VT.getVectorElementType());
2211 std::vector<SDOperand> Ops(VT.getVectorNumElements(), El);
2212 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2216 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2217 if (N0.getOpcode() == N1.getOpcode()) {
2218 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2219 if (Tmp.Val) return Tmp;
2222 // Simplify the expression using non-local knowledge.
2223 if (!VT.isVector() &&
2224 SimplifyDemandedBits(SDOperand(N, 0)))
2225 return SDOperand(N, 0);
2230 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2231 /// the shift amount is a constant.
2232 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2233 SDNode *LHS = N->getOperand(0).Val;
2234 if (!LHS->hasOneUse()) return SDOperand();
2236 // We want to pull some binops through shifts, so that we have (and (shift))
2237 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2238 // thing happens with address calculations, so it's important to canonicalize
2240 bool HighBitSet = false; // Can we transform this if the high bit is set?
2242 switch (LHS->getOpcode()) {
2243 default: return SDOperand();
2246 HighBitSet = false; // We can only transform sra if the high bit is clear.
2249 HighBitSet = true; // We can only transform sra if the high bit is set.
2252 if (N->getOpcode() != ISD::SHL)
2253 return SDOperand(); // only shl(add) not sr[al](add).
2254 HighBitSet = false; // We can only transform sra if the high bit is clear.
2258 // We require the RHS of the binop to be a constant as well.
2259 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2260 if (!BinOpCst) return SDOperand();
2263 // FIXME: disable this for unless the input to the binop is a shift by a
2264 // constant. If it is not a shift, it pessimizes some common cases like:
2266 //void foo(int *X, int i) { X[i & 1235] = 1; }
2267 //int bar(int *X, int i) { return X[i & 255]; }
2268 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2269 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2270 BinOpLHSVal->getOpcode() != ISD::SRA &&
2271 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2272 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2275 MVT VT = N->getValueType(0);
2277 // If this is a signed shift right, and the high bit is modified
2278 // by the logical operation, do not perform the transformation.
2279 // The highBitSet boolean indicates the value of the high bit of
2280 // the constant which would cause it to be modified for this
2282 if (N->getOpcode() == ISD::SRA) {
2283 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2284 if (BinOpRHSSignSet != HighBitSet)
2288 // Fold the constants, shifting the binop RHS by the shift amount.
2289 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2290 LHS->getOperand(1), N->getOperand(1));
2292 // Create the new shift.
2293 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2296 // Create the new binop.
2297 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2301 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2302 SDOperand N0 = N->getOperand(0);
2303 SDOperand N1 = N->getOperand(1);
2304 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2305 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2306 MVT VT = N0.getValueType();
2307 unsigned OpSizeInBits = VT.getSizeInBits();
2309 // fold (shl c1, c2) -> c1<<c2
2311 return DAG.getNode(ISD::SHL, VT, N0, N1);
2312 // fold (shl 0, x) -> 0
2313 if (N0C && N0C->isNullValue())
2315 // fold (shl x, c >= size(x)) -> undef
2316 if (N1C && N1C->getValue() >= OpSizeInBits)
2317 return DAG.getNode(ISD::UNDEF, VT);
2318 // fold (shl x, 0) -> x
2319 if (N1C && N1C->isNullValue())
2321 // if (shl x, c) is known to be zero, return 0
2322 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2323 APInt::getAllOnesValue(VT.getSizeInBits())))
2324 return DAG.getConstant(0, VT);
2325 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2326 return SDOperand(N, 0);
2327 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2328 if (N1C && N0.getOpcode() == ISD::SHL &&
2329 N0.getOperand(1).getOpcode() == ISD::Constant) {
2330 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2331 uint64_t c2 = N1C->getValue();
2332 if (c1 + c2 > OpSizeInBits)
2333 return DAG.getConstant(0, VT);
2334 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2335 DAG.getConstant(c1 + c2, N1.getValueType()));
2337 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2338 // (srl (and x, -1 << c1), c1-c2)
2339 if (N1C && N0.getOpcode() == ISD::SRL &&
2340 N0.getOperand(1).getOpcode() == ISD::Constant) {
2341 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2342 uint64_t c2 = N1C->getValue();
2343 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2344 DAG.getConstant(~0ULL << c1, VT));
2346 return DAG.getNode(ISD::SHL, VT, Mask,
2347 DAG.getConstant(c2-c1, N1.getValueType()));
2349 return DAG.getNode(ISD::SRL, VT, Mask,
2350 DAG.getConstant(c1-c2, N1.getValueType()));
2352 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2353 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2354 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2355 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2357 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2360 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2361 SDOperand N0 = N->getOperand(0);
2362 SDOperand N1 = N->getOperand(1);
2363 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2364 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2365 MVT VT = N0.getValueType();
2367 // fold (sra c1, c2) -> c1>>c2
2369 return DAG.getNode(ISD::SRA, VT, N0, N1);
2370 // fold (sra 0, x) -> 0
2371 if (N0C && N0C->isNullValue())
2373 // fold (sra -1, x) -> -1
2374 if (N0C && N0C->isAllOnesValue())
2376 // fold (sra x, c >= size(x)) -> undef
2377 if (N1C && N1C->getValue() >= VT.getSizeInBits())
2378 return DAG.getNode(ISD::UNDEF, VT);
2379 // fold (sra x, 0) -> x
2380 if (N1C && N1C->isNullValue())
2382 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2384 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2385 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getValue();
2386 MVT EVT = MVT::getIntegerVT(LowBits);
2387 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2388 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2389 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2390 DAG.getValueType(EVT));
2393 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2394 if (N1C && N0.getOpcode() == ISD::SRA) {
2395 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2396 unsigned Sum = N1C->getValue() + C1->getValue();
2397 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2398 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2399 DAG.getConstant(Sum, N1C->getValueType(0)));
2403 // fold sra (shl X, m), result_size - n
2404 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2405 // result_size - n != m.
2406 // If truncate is free for the target sext(shl) is likely to result in better
2408 if (N0.getOpcode() == ISD::SHL) {
2409 // Get the two constanst of the shifts, CN0 = m, CN = n.
2410 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2412 // Determine what the truncate's result bitsize and type would be.
2413 unsigned VTValSize = VT.getSizeInBits();
2415 MVT::getIntegerVT(VTValSize - N1C->getValue());
2416 // Determine the residual right-shift amount.
2417 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
2419 // If the shift is not a no-op (in which case this should be just a sign
2420 // extend already), the truncated to type is legal, sign_extend is legal
2421 // on that type, and the the truncate to that type is both legal and free,
2422 // perform the transform.
2424 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2425 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2426 TLI.isTruncateFree(VT, TruncVT)) {
2428 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2429 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2430 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2431 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2436 // Simplify, based on bits shifted out of the LHS.
2437 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2438 return SDOperand(N, 0);
2441 // If the sign bit is known to be zero, switch this to a SRL.
2442 if (DAG.SignBitIsZero(N0))
2443 return DAG.getNode(ISD::SRL, VT, N0, N1);
2445 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2448 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2449 SDOperand N0 = N->getOperand(0);
2450 SDOperand N1 = N->getOperand(1);
2451 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2452 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2453 MVT VT = N0.getValueType();
2454 unsigned OpSizeInBits = VT.getSizeInBits();
2456 // fold (srl c1, c2) -> c1 >>u c2
2458 return DAG.getNode(ISD::SRL, VT, N0, N1);
2459 // fold (srl 0, x) -> 0
2460 if (N0C && N0C->isNullValue())
2462 // fold (srl x, c >= size(x)) -> undef
2463 if (N1C && N1C->getValue() >= OpSizeInBits)
2464 return DAG.getNode(ISD::UNDEF, VT);
2465 // fold (srl x, 0) -> x
2466 if (N1C && N1C->isNullValue())
2468 // if (srl x, c) is known to be zero, return 0
2469 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2470 APInt::getAllOnesValue(OpSizeInBits)))
2471 return DAG.getConstant(0, VT);
2473 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2474 if (N1C && N0.getOpcode() == ISD::SRL &&
2475 N0.getOperand(1).getOpcode() == ISD::Constant) {
2476 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2477 uint64_t c2 = N1C->getValue();
2478 if (c1 + c2 > OpSizeInBits)
2479 return DAG.getConstant(0, VT);
2480 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2481 DAG.getConstant(c1 + c2, N1.getValueType()));
2484 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2485 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2486 // Shifting in all undef bits?
2487 MVT SmallVT = N0.getOperand(0).getValueType();
2488 if (N1C->getValue() >= SmallVT.getSizeInBits())
2489 return DAG.getNode(ISD::UNDEF, VT);
2491 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2492 AddToWorkList(SmallShift.Val);
2493 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2496 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2497 // bit, which is unmodified by sra.
2498 if (N1C && N1C->getValue()+1 == VT.getSizeInBits()) {
2499 if (N0.getOpcode() == ISD::SRA)
2500 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2503 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2504 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2505 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2506 APInt KnownZero, KnownOne;
2507 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2508 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2510 // If any of the input bits are KnownOne, then the input couldn't be all
2511 // zeros, thus the result of the srl will always be zero.
2512 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2514 // If all of the bits input the to ctlz node are known to be zero, then
2515 // the result of the ctlz is "32" and the result of the shift is one.
2516 APInt UnknownBits = ~KnownZero & Mask;
2517 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2519 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2520 if ((UnknownBits & (UnknownBits-1)) == 0) {
2521 // Okay, we know that only that the single bit specified by UnknownBits
2522 // could be set on input to the CTLZ node. If this bit is set, the SRL
2523 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2524 // to an SRL,XOR pair, which is likely to simplify more.
2525 unsigned ShAmt = UnknownBits.countTrailingZeros();
2526 SDOperand Op = N0.getOperand(0);
2528 Op = DAG.getNode(ISD::SRL, VT, Op,
2529 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2530 AddToWorkList(Op.Val);
2532 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2536 // fold operands of srl based on knowledge that the low bits are not
2538 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2539 return SDOperand(N, 0);
2541 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2544 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2545 SDOperand N0 = N->getOperand(0);
2546 MVT VT = N->getValueType(0);
2548 // fold (ctlz c1) -> c2
2549 if (isa<ConstantSDNode>(N0))
2550 return DAG.getNode(ISD::CTLZ, VT, N0);
2554 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2555 SDOperand N0 = N->getOperand(0);
2556 MVT VT = N->getValueType(0);
2558 // fold (cttz c1) -> c2
2559 if (isa<ConstantSDNode>(N0))
2560 return DAG.getNode(ISD::CTTZ, VT, N0);
2564 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2565 SDOperand N0 = N->getOperand(0);
2566 MVT VT = N->getValueType(0);
2568 // fold (ctpop c1) -> c2
2569 if (isa<ConstantSDNode>(N0))
2570 return DAG.getNode(ISD::CTPOP, VT, N0);
2574 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2575 SDOperand N0 = N->getOperand(0);
2576 SDOperand N1 = N->getOperand(1);
2577 SDOperand N2 = N->getOperand(2);
2578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2580 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2581 MVT VT = N->getValueType(0);
2582 MVT VT0 = N0.getValueType();
2584 // fold select C, X, X -> X
2587 // fold select true, X, Y -> X
2588 if (N0C && !N0C->isNullValue())
2590 // fold select false, X, Y -> Y
2591 if (N0C && N0C->isNullValue())
2593 // fold select C, 1, X -> C | X
2594 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2595 return DAG.getNode(ISD::OR, VT, N0, N2);
2596 // fold select C, 0, 1 -> ~C
2597 if (VT.isInteger() && VT0.isInteger() &&
2598 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2599 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2602 AddToWorkList(XORNode.Val);
2604 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2605 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2607 // fold select C, 0, X -> ~C & X
2608 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2609 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2610 AddToWorkList(XORNode.Val);
2611 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2613 // fold select C, X, 1 -> ~C | X
2614 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2615 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2616 AddToWorkList(XORNode.Val);
2617 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2619 // fold select C, X, 0 -> C & X
2620 // FIXME: this should check for C type == X type, not i1?
2621 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2622 return DAG.getNode(ISD::AND, VT, N0, N1);
2623 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2624 if (VT == MVT::i1 && N0 == N1)
2625 return DAG.getNode(ISD::OR, VT, N0, N2);
2626 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2627 if (VT == MVT::i1 && N0 == N2)
2628 return DAG.getNode(ISD::AND, VT, N0, N1);
2630 // If we can fold this based on the true/false value, do so.
2631 if (SimplifySelectOps(N, N1, N2))
2632 return SDOperand(N, 0); // Don't revisit N.
2634 // fold selects based on a setcc into other things, such as min/max/abs
2635 if (N0.getOpcode() == ISD::SETCC) {
2637 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2638 // having to say they don't support SELECT_CC on every type the DAG knows
2639 // about, since there is no way to mark an opcode illegal at all value types
2640 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2641 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2642 N1, N2, N0.getOperand(2));
2644 return SimplifySelect(N0, N1, N2);
2649 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2650 SDOperand N0 = N->getOperand(0);
2651 SDOperand N1 = N->getOperand(1);
2652 SDOperand N2 = N->getOperand(2);
2653 SDOperand N3 = N->getOperand(3);
2654 SDOperand N4 = N->getOperand(4);
2655 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2657 // fold select_cc lhs, rhs, x, x, cc -> x
2661 // Determine if the condition we're dealing with is constant
2662 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2663 if (SCC.Val) AddToWorkList(SCC.Val);
2665 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2666 if (!SCCC->isNullValue())
2667 return N2; // cond always true -> true val
2669 return N3; // cond always false -> false val
2672 // Fold to a simpler select_cc
2673 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2674 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2675 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2678 // If we can fold this based on the true/false value, do so.
2679 if (SimplifySelectOps(N, N2, N3))
2680 return SDOperand(N, 0); // Don't revisit N.
2682 // fold select_cc into other things, such as min/max/abs
2683 return SimplifySelectCC(N0, N1, N2, N3, CC);
2686 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2687 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2688 cast<CondCodeSDNode>(N->getOperand(2))->get());
2691 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2692 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2693 // transformation. Returns true if extension are possible and the above
2694 // mentioned transformation is profitable.
2695 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2697 SmallVector<SDNode*, 4> &ExtendNodes,
2698 TargetLowering &TLI) {
2699 bool HasCopyToRegUses = false;
2700 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2701 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2703 SDNode *User = UI->getUser();
2706 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2707 if (User->getOpcode() == ISD::SETCC) {
2708 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2709 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2710 // Sign bits will be lost after a zext.
2713 for (unsigned i = 0; i != 2; ++i) {
2714 SDOperand UseOp = User->getOperand(i);
2717 if (!isa<ConstantSDNode>(UseOp))
2722 ExtendNodes.push_back(User);
2724 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2725 SDOperand UseOp = User->getOperand(i);
2727 // If truncate from extended type to original load type is free
2728 // on this target, then it's ok to extend a CopyToReg.
2729 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2730 HasCopyToRegUses = true;
2738 if (HasCopyToRegUses) {
2739 bool BothLiveOut = false;
2740 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2742 SDNode *User = UI->getUser();
2743 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2744 SDOperand UseOp = User->getOperand(i);
2745 if (UseOp.Val == N && UseOp.ResNo == 0) {
2752 // Both unextended and extended values are live out. There had better be
2753 // good a reason for the transformation.
2754 return ExtendNodes.size();
2759 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2760 SDOperand N0 = N->getOperand(0);
2761 MVT VT = N->getValueType(0);
2763 // fold (sext c1) -> c1
2764 if (isa<ConstantSDNode>(N0))
2765 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2767 // fold (sext (sext x)) -> (sext x)
2768 // fold (sext (aext x)) -> (sext x)
2769 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2770 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2772 if (N0.getOpcode() == ISD::TRUNCATE) {
2773 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2774 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2775 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2776 if (NarrowLoad.Val) {
2777 if (NarrowLoad.Val != N0.Val)
2778 CombineTo(N0.Val, NarrowLoad);
2779 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2782 // See if the value being truncated is already sign extended. If so, just
2783 // eliminate the trunc/sext pair.
2784 SDOperand Op = N0.getOperand(0);
2785 unsigned OpBits = Op.getValueType().getSizeInBits();
2786 unsigned MidBits = N0.getValueType().getSizeInBits();
2787 unsigned DestBits = VT.getSizeInBits();
2788 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2790 if (OpBits == DestBits) {
2791 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2792 // bits, it is already ready.
2793 if (NumSignBits > DestBits-MidBits)
2795 } else if (OpBits < DestBits) {
2796 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2797 // bits, just sext from i32.
2798 if (NumSignBits > OpBits-MidBits)
2799 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2801 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2802 // bits, just truncate to i32.
2803 if (NumSignBits > OpBits-MidBits)
2804 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2807 // fold (sext (truncate x)) -> (sextinreg x).
2808 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2809 N0.getValueType())) {
2810 if (Op.getValueType().bitsLT(VT))
2811 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2812 else if (Op.getValueType().bitsGT(VT))
2813 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2814 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2815 DAG.getValueType(N0.getValueType()));
2819 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2820 if (ISD::isNON_EXTLoad(N0.Val) &&
2821 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2822 TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2823 bool DoXform = true;
2824 SmallVector<SDNode*, 4> SetCCs;
2825 if (!N0.hasOneUse())
2826 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2828 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2829 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2830 LN0->getBasePtr(), LN0->getSrcValue(),
2831 LN0->getSrcValueOffset(),
2834 LN0->getAlignment());
2835 CombineTo(N, ExtLoad);
2836 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2837 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2838 // Extend SetCC uses if necessary.
2839 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2840 SDNode *SetCC = SetCCs[i];
2841 SmallVector<SDOperand, 4> Ops;
2842 for (unsigned j = 0; j != 2; ++j) {
2843 SDOperand SOp = SetCC->getOperand(j);
2845 Ops.push_back(ExtLoad);
2847 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2849 Ops.push_back(SetCC->getOperand(2));
2850 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2851 &Ops[0], Ops.size()));
2853 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2857 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2858 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2859 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2860 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2861 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2862 MVT EVT = LN0->getMemoryVT();
2863 if ((!AfterLegalize && !LN0->isVolatile()) ||
2864 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2865 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2866 LN0->getBasePtr(), LN0->getSrcValue(),
2867 LN0->getSrcValueOffset(), EVT,
2869 LN0->getAlignment());
2870 CombineTo(N, ExtLoad);
2871 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2872 ExtLoad.getValue(1));
2873 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2877 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2878 if (N0.getOpcode() == ISD::SETCC) {
2880 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2881 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2882 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2883 if (SCC.Val) return SCC;
2886 // fold (sext x) -> (zext x) if the sign bit is known zero.
2887 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2888 DAG.SignBitIsZero(N0))
2889 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2894 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2895 SDOperand N0 = N->getOperand(0);
2896 MVT VT = N->getValueType(0);
2898 // fold (zext c1) -> c1
2899 if (isa<ConstantSDNode>(N0))
2900 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2901 // fold (zext (zext x)) -> (zext x)
2902 // fold (zext (aext x)) -> (zext x)
2903 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2904 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2906 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2907 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2908 if (N0.getOpcode() == ISD::TRUNCATE) {
2909 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2910 if (NarrowLoad.Val) {
2911 if (NarrowLoad.Val != N0.Val)
2912 CombineTo(N0.Val, NarrowLoad);
2913 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2917 // fold (zext (truncate x)) -> (and x, mask)
2918 if (N0.getOpcode() == ISD::TRUNCATE &&
2919 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2920 SDOperand Op = N0.getOperand(0);
2921 if (Op.getValueType().bitsLT(VT)) {
2922 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2923 } else if (Op.getValueType().bitsGT(VT)) {
2924 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2926 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2929 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2930 if (N0.getOpcode() == ISD::AND &&
2931 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2932 N0.getOperand(1).getOpcode() == ISD::Constant) {
2933 SDOperand X = N0.getOperand(0).getOperand(0);
2934 if (X.getValueType().bitsLT(VT)) {
2935 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2936 } else if (X.getValueType().bitsGT(VT)) {
2937 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2939 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2940 Mask.zext(VT.getSizeInBits());
2941 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2944 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2945 if (ISD::isNON_EXTLoad(N0.Val) &&
2946 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2947 TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2948 bool DoXform = true;
2949 SmallVector<SDNode*, 4> SetCCs;
2950 if (!N0.hasOneUse())
2951 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2953 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2954 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2955 LN0->getBasePtr(), LN0->getSrcValue(),
2956 LN0->getSrcValueOffset(),
2959 LN0->getAlignment());
2960 CombineTo(N, ExtLoad);
2961 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2962 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2963 // Extend SetCC uses if necessary.
2964 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2965 SDNode *SetCC = SetCCs[i];
2966 SmallVector<SDOperand, 4> Ops;
2967 for (unsigned j = 0; j != 2; ++j) {
2968 SDOperand SOp = SetCC->getOperand(j);
2970 Ops.push_back(ExtLoad);
2972 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2974 Ops.push_back(SetCC->getOperand(2));
2975 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2976 &Ops[0], Ops.size()));
2978 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2982 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2983 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2984 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2985 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2987 MVT EVT = LN0->getMemoryVT();
2988 if ((!AfterLegalize && !LN0->isVolatile()) ||
2989 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT)) {
2990 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2991 LN0->getBasePtr(), LN0->getSrcValue(),
2992 LN0->getSrcValueOffset(), EVT,
2994 LN0->getAlignment());
2995 CombineTo(N, ExtLoad);
2996 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2997 ExtLoad.getValue(1));
2998 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3002 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3003 if (N0.getOpcode() == ISD::SETCC) {
3005 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3006 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3007 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3008 if (SCC.Val) return SCC;
3014 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3015 SDOperand N0 = N->getOperand(0);
3016 MVT VT = N->getValueType(0);
3018 // fold (aext c1) -> c1
3019 if (isa<ConstantSDNode>(N0))
3020 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3021 // fold (aext (aext x)) -> (aext x)
3022 // fold (aext (zext x)) -> (zext x)
3023 // fold (aext (sext x)) -> (sext x)
3024 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3025 N0.getOpcode() == ISD::ZERO_EXTEND ||
3026 N0.getOpcode() == ISD::SIGN_EXTEND)
3027 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3029 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3030 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3031 if (N0.getOpcode() == ISD::TRUNCATE) {
3032 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3033 if (NarrowLoad.Val) {
3034 if (NarrowLoad.Val != N0.Val)
3035 CombineTo(N0.Val, NarrowLoad);
3036 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3040 // fold (aext (truncate x))
3041 if (N0.getOpcode() == ISD::TRUNCATE) {
3042 SDOperand TruncOp = N0.getOperand(0);
3043 if (TruncOp.getValueType() == VT)
3044 return TruncOp; // x iff x size == zext size.
3045 if (TruncOp.getValueType().bitsGT(VT))
3046 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3047 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3050 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3051 if (N0.getOpcode() == ISD::AND &&
3052 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3053 N0.getOperand(1).getOpcode() == ISD::Constant) {
3054 SDOperand X = N0.getOperand(0).getOperand(0);
3055 if (X.getValueType().bitsLT(VT)) {
3056 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3057 } else if (X.getValueType().bitsGT(VT)) {
3058 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3060 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3061 Mask.zext(VT.getSizeInBits());
3062 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3065 // fold (aext (load x)) -> (aext (truncate (extload x)))
3066 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3067 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3068 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3069 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3070 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3071 LN0->getBasePtr(), LN0->getSrcValue(),
3072 LN0->getSrcValueOffset(),
3075 LN0->getAlignment());
3076 CombineTo(N, ExtLoad);
3077 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3078 ExtLoad.getValue(1));
3079 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3082 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3083 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3084 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3085 if (N0.getOpcode() == ISD::LOAD &&
3086 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3088 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3089 MVT EVT = LN0->getMemoryVT();
3090 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3091 LN0->getChain(), LN0->getBasePtr(),
3093 LN0->getSrcValueOffset(), EVT,
3095 LN0->getAlignment());
3096 CombineTo(N, ExtLoad);
3097 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3098 ExtLoad.getValue(1));
3099 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3102 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3103 if (N0.getOpcode() == ISD::SETCC) {
3105 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3106 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3107 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3115 /// GetDemandedBits - See if the specified operand can be simplified with the
3116 /// knowledge that only the bits specified by Mask are used. If so, return the
3117 /// simpler operand, otherwise return a null SDOperand.
3118 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
3119 switch (V.getOpcode()) {
3123 // If the LHS or RHS don't contribute bits to the or, drop them.
3124 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3125 return V.getOperand(1);
3126 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3127 return V.getOperand(0);
3130 // Only look at single-use SRLs.
3131 if (!V.Val->hasOneUse())
3133 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3134 // See if we can recursively simplify the LHS.
3135 unsigned Amt = RHSC->getValue();
3136 APInt NewMask = Mask << Amt;
3137 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3138 if (SimplifyLHS.Val) {
3139 return DAG.getNode(ISD::SRL, V.getValueType(),
3140 SimplifyLHS, V.getOperand(1));
3147 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3148 /// bits and then truncated to a narrower type and where N is a multiple
3149 /// of number of bits of the narrower type, transform it to a narrower load
3150 /// from address + N / num of bits of new type. If the result is to be
3151 /// extended, also fold the extension to form a extending load.
3152 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3153 unsigned Opc = N->getOpcode();
3154 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3155 SDOperand N0 = N->getOperand(0);
3156 MVT VT = N->getValueType(0);
3157 MVT EVT = N->getValueType(0);
3159 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3161 if (Opc == ISD::SIGN_EXTEND_INREG) {
3162 ExtType = ISD::SEXTLOAD;
3163 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3164 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3168 unsigned EVTBits = EVT.getSizeInBits();
3170 bool CombineSRL = false;
3171 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3172 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3173 ShAmt = N01->getValue();
3174 // Is the shift amount a multiple of size of VT?
3175 if ((ShAmt & (EVTBits-1)) == 0) {
3176 N0 = N0.getOperand(0);
3177 if (N0.getValueType().getSizeInBits() <= EVTBits)
3184 // Do not generate loads of non-round integer types since these can
3185 // be expensive (and would be wrong if the type is not byte sized).
3186 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() && VT.isRound() &&
3187 // Do not change the width of a volatile load.
3188 !cast<LoadSDNode>(N0)->isVolatile()) {
3189 assert(N0.getValueType().getSizeInBits() > EVTBits &&
3190 "Cannot truncate to larger type!");
3191 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3192 MVT PtrType = N0.getOperand(1).getValueType();
3193 // For big endian targets, we need to adjust the offset to the pointer to
3194 // load the correct bytes.
3195 if (TLI.isBigEndian()) {
3196 unsigned LVTStoreBits = N0.getValueType().getStoreSizeInBits();
3197 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3198 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3200 uint64_t PtrOff = ShAmt / 8;
3201 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3202 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3203 DAG.getConstant(PtrOff, PtrType));
3204 AddToWorkList(NewPtr.Val);
3205 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3206 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3207 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3208 LN0->isVolatile(), NewAlign)
3209 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3210 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3211 LN0->isVolatile(), NewAlign);
3214 WorkListRemover DeadNodes(*this);
3215 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3217 CombineTo(N->getOperand(0).Val, Load);
3219 CombineTo(N0.Val, Load, Load.getValue(1));
3221 if (Opc == ISD::SIGN_EXTEND_INREG)
3222 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3224 return DAG.getNode(Opc, VT, Load);
3226 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3233 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3234 SDOperand N0 = N->getOperand(0);
3235 SDOperand N1 = N->getOperand(1);
3236 MVT VT = N->getValueType(0);
3237 MVT EVT = cast<VTSDNode>(N1)->getVT();
3238 unsigned VTBits = VT.getSizeInBits();
3239 unsigned EVTBits = EVT.getSizeInBits();
3241 // fold (sext_in_reg c1) -> c1
3242 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3243 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3245 // If the input is already sign extended, just drop the extension.
3246 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3249 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3250 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3251 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3252 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3255 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3256 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3257 return DAG.getZeroExtendInReg(N0, EVT);
3259 // fold operands of sext_in_reg based on knowledge that the top bits are not
3261 if (SimplifyDemandedBits(SDOperand(N, 0)))
3262 return SDOperand(N, 0);
3264 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3265 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3266 SDOperand NarrowLoad = ReduceLoadWidth(N);
3270 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3271 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3272 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3273 if (N0.getOpcode() == ISD::SRL) {
3274 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3275 if (ShAmt->getValue()+EVTBits <= VT.getSizeInBits()) {
3276 // We can turn this into an SRA iff the input to the SRL is already sign
3278 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3279 if (VT.getSizeInBits()-(ShAmt->getValue()+EVTBits) < InSignBits)
3280 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3284 // fold (sext_inreg (extload x)) -> (sextload x)
3285 if (ISD::isEXTLoad(N0.Val) &&
3286 ISD::isUNINDEXEDLoad(N0.Val) &&
3287 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3288 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3289 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3290 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3291 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3292 LN0->getBasePtr(), LN0->getSrcValue(),
3293 LN0->getSrcValueOffset(), EVT,
3295 LN0->getAlignment());
3296 CombineTo(N, ExtLoad);
3297 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3298 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3300 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3301 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3303 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3304 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3305 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3306 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3307 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3308 LN0->getBasePtr(), LN0->getSrcValue(),
3309 LN0->getSrcValueOffset(), EVT,
3311 LN0->getAlignment());
3312 CombineTo(N, ExtLoad);
3313 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3314 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3319 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3320 SDOperand N0 = N->getOperand(0);
3321 MVT VT = N->getValueType(0);
3324 if (N0.getValueType() == N->getValueType(0))
3326 // fold (truncate c1) -> c1
3327 if (isa<ConstantSDNode>(N0))
3328 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3329 // fold (truncate (truncate x)) -> (truncate x)
3330 if (N0.getOpcode() == ISD::TRUNCATE)
3331 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3332 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3333 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3334 N0.getOpcode() == ISD::ANY_EXTEND) {
3335 if (N0.getOperand(0).getValueType().bitsLT(VT))
3336 // if the source is smaller than the dest, we still need an extend
3337 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3338 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3339 // if the source is larger than the dest, than we just need the truncate
3340 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3342 // if the source and dest are the same type, we can drop both the extend
3344 return N0.getOperand(0);
3347 // See if we can simplify the input to this truncate through knowledge that
3348 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3351 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3352 VT.getSizeInBits()));
3354 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3356 // fold (truncate (load x)) -> (smaller load x)
3357 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3358 return ReduceLoadWidth(N);
3361 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3362 SDOperand Elt = N->getOperand(i);
3363 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3365 return Elt.getOperand(Elt.ResNo).Val;
3368 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3369 /// if load locations are consecutive.
3370 SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3371 assert(N->getOpcode() == ISD::BUILD_PAIR);
3373 SDNode *LD1 = getBuildPairElt(N, 0);
3374 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3376 MVT LD1VT = LD1->getValueType(0);
3377 SDNode *LD2 = getBuildPairElt(N, 1);
3378 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3379 if (ISD::isNON_EXTLoad(LD2) &&
3381 // If both are volatile this would reduce the number of volatile loads.
3382 // If one is volatile it might be ok, but play conservative and bail out.
3383 !cast<LoadSDNode>(LD1)->isVolatile() &&
3384 !cast<LoadSDNode>(LD2)->isVolatile() &&
3385 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3386 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3387 unsigned Align = LD->getAlignment();
3388 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
3389 getABITypeAlignment(VT.getTypeForMVT());
3390 if (NewAlign <= Align &&
3391 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
3392 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3393 LD->getSrcValue(), LD->getSrcValueOffset(),
3399 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3400 SDOperand N0 = N->getOperand(0);
3401 MVT VT = N->getValueType(0);
3403 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3404 // Only do this before legalize, since afterward the target may be depending
3405 // on the bitconvert.
3406 // First check to see if this is all constant.
3407 if (!AfterLegalize &&
3408 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3410 bool isSimple = true;
3411 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3412 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3413 N0.getOperand(i).getOpcode() != ISD::Constant &&
3414 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3419 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3420 assert(!DestEltVT.isVector() &&
3421 "Element type of vector ValueType must not be vector!");
3423 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3427 // If the input is a constant, let getNode() fold it.
3428 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3429 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3430 if (Res.Val != N) return Res;
3433 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3434 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3436 // fold (conv (load x)) -> (load (conv*)x)
3437 // If the resultant load doesn't need a higher alignment than the original!
3438 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3439 // Do not change the width of a volatile load.
3440 !cast<LoadSDNode>(N0)->isVolatile() &&
3441 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
3442 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3443 unsigned Align = TLI.getTargetMachine().getTargetData()->
3444 getABITypeAlignment(VT.getTypeForMVT());
3445 unsigned OrigAlign = LN0->getAlignment();
3446 if (Align <= OrigAlign) {
3447 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3448 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3449 LN0->isVolatile(), OrigAlign);
3451 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3457 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3458 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3459 // This often reduces constant pool loads.
3460 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3461 N0.Val->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3462 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3463 AddToWorkList(NewConv.Val);
3465 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3466 if (N0.getOpcode() == ISD::FNEG)
3467 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3468 assert(N0.getOpcode() == ISD::FABS);
3469 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3472 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3473 // Note that we don't handle copysign(x,cst) because this can always be folded
3474 // to an fneg or fabs.
3475 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3476 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3477 VT.isInteger() && !VT.isVector()) {
3478 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3479 SDOperand X = DAG.getNode(ISD::BIT_CONVERT,
3480 MVT::getIntegerVT(OrigXWidth),
3482 AddToWorkList(X.Val);
3484 // If X has a different width than the result/lhs, sext it or truncate it.
3485 unsigned VTWidth = VT.getSizeInBits();
3486 if (OrigXWidth < VTWidth) {
3487 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3488 AddToWorkList(X.Val);
3489 } else if (OrigXWidth > VTWidth) {
3490 // To get the sign bit in the right place, we have to shift it right
3491 // before truncating.
3492 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3493 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3494 AddToWorkList(X.Val);
3495 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3496 AddToWorkList(X.Val);
3499 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3500 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3501 AddToWorkList(X.Val);
3503 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3504 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3505 AddToWorkList(Cst.Val);
3507 return DAG.getNode(ISD::OR, VT, X, Cst);
3510 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3511 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3512 SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
3520 SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3521 MVT VT = N->getValueType(0);
3522 return CombineConsecutiveLoads(N, VT);
3525 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3526 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3527 /// destination element value type.
3528 SDOperand DAGCombiner::
3529 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3530 MVT SrcEltVT = BV->getOperand(0).getValueType();
3532 // If this is already the right type, we're done.
3533 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3535 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3536 unsigned DstBitSize = DstEltVT.getSizeInBits();
3538 // If this is a conversion of N elements of one type to N elements of another
3539 // type, convert each element. This handles FP<->INT cases.
3540 if (SrcBitSize == DstBitSize) {
3541 SmallVector<SDOperand, 8> Ops;
3542 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3543 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3544 AddToWorkList(Ops.back().Val);
3546 MVT VT = MVT::getVectorVT(DstEltVT,
3547 BV->getValueType(0).getVectorNumElements());
3548 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3551 // Otherwise, we're growing or shrinking the elements. To avoid having to
3552 // handle annoying details of growing/shrinking FP values, we convert them to
3554 if (SrcEltVT.isFloatingPoint()) {
3555 // Convert the input float vector to a int vector where the elements are the
3557 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3558 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3559 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3563 // Now we know the input is an integer vector. If the output is a FP type,
3564 // convert to integer first, then to FP of the right size.
3565 if (DstEltVT.isFloatingPoint()) {
3566 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3567 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3568 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3570 // Next, convert to FP elements of the same size.
3571 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3574 // Okay, we know the src/dst types are both integers of differing types.
3575 // Handling growing first.
3576 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3577 if (SrcBitSize < DstBitSize) {
3578 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3580 SmallVector<SDOperand, 8> Ops;
3581 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3582 i += NumInputsPerOutput) {
3583 bool isLE = TLI.isLittleEndian();
3584 APInt NewBits = APInt(DstBitSize, 0);
3585 bool EltIsUndef = true;
3586 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3587 // Shift the previously computed bits over.
3588 NewBits <<= SrcBitSize;
3589 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3590 if (Op.getOpcode() == ISD::UNDEF) continue;
3594 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3598 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3600 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3603 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3604 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3607 // Finally, this must be the case where we are shrinking elements: each input
3608 // turns into multiple outputs.
3609 bool isS2V = ISD::isScalarToVector(BV);
3610 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3611 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3612 SmallVector<SDOperand, 8> Ops;
3613 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3614 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3615 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3616 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3619 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3620 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3621 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3622 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3623 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3624 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3625 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3626 OpVal = OpVal.lshr(DstBitSize);
3629 // For big endian targets, swap the order of the pieces of each element.
3630 if (TLI.isBigEndian())
3631 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3633 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3638 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3639 SDOperand N0 = N->getOperand(0);
3640 SDOperand N1 = N->getOperand(1);
3641 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3642 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3643 MVT VT = N->getValueType(0);
3646 if (VT.isVector()) {
3647 SDOperand FoldedVOp = SimplifyVBinOp(N);
3648 if (FoldedVOp.Val) return FoldedVOp;
3651 // fold (fadd c1, c2) -> c1+c2
3652 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3653 return DAG.getNode(ISD::FADD, VT, N0, N1);
3654 // canonicalize constant to RHS
3655 if (N0CFP && !N1CFP)
3656 return DAG.getNode(ISD::FADD, VT, N1, N0);
3657 // fold (A + (-B)) -> A-B
3658 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3659 return DAG.getNode(ISD::FSUB, VT, N0,
3660 GetNegatedExpression(N1, DAG, AfterLegalize));
3661 // fold ((-A) + B) -> B-A
3662 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3663 return DAG.getNode(ISD::FSUB, VT, N1,
3664 GetNegatedExpression(N0, DAG, AfterLegalize));
3666 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3667 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3668 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3669 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3670 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3675 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3676 SDOperand N0 = N->getOperand(0);
3677 SDOperand N1 = N->getOperand(1);
3678 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3679 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3680 MVT VT = N->getValueType(0);
3683 if (VT.isVector()) {
3684 SDOperand FoldedVOp = SimplifyVBinOp(N);
3685 if (FoldedVOp.Val) return FoldedVOp;
3688 // fold (fsub c1, c2) -> c1-c2
3689 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3690 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3692 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3693 if (isNegatibleForFree(N1, AfterLegalize))
3694 return GetNegatedExpression(N1, DAG, AfterLegalize);
3695 return DAG.getNode(ISD::FNEG, VT, N1);
3697 // fold (A-(-B)) -> A+B
3698 if (isNegatibleForFree(N1, AfterLegalize))
3699 return DAG.getNode(ISD::FADD, VT, N0,
3700 GetNegatedExpression(N1, DAG, AfterLegalize));
3705 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3706 SDOperand N0 = N->getOperand(0);
3707 SDOperand N1 = N->getOperand(1);
3708 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3709 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3710 MVT VT = N->getValueType(0);
3713 if (VT.isVector()) {
3714 SDOperand FoldedVOp = SimplifyVBinOp(N);
3715 if (FoldedVOp.Val) return FoldedVOp;
3718 // fold (fmul c1, c2) -> c1*c2
3719 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3720 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3721 // canonicalize constant to RHS
3722 if (N0CFP && !N1CFP)
3723 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3724 // fold (fmul X, 2.0) -> (fadd X, X)
3725 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3726 return DAG.getNode(ISD::FADD, VT, N0, N0);
3727 // fold (fmul X, -1.0) -> (fneg X)
3728 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3729 return DAG.getNode(ISD::FNEG, VT, N0);
3732 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3733 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3734 // Both can be negated for free, check to see if at least one is cheaper
3736 if (LHSNeg == 2 || RHSNeg == 2)
3737 return DAG.getNode(ISD::FMUL, VT,
3738 GetNegatedExpression(N0, DAG, AfterLegalize),
3739 GetNegatedExpression(N1, DAG, AfterLegalize));
3743 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3744 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3745 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3746 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3747 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3752 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3753 SDOperand N0 = N->getOperand(0);
3754 SDOperand N1 = N->getOperand(1);
3755 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3756 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3757 MVT VT = N->getValueType(0);
3760 if (VT.isVector()) {
3761 SDOperand FoldedVOp = SimplifyVBinOp(N);
3762 if (FoldedVOp.Val) return FoldedVOp;
3765 // fold (fdiv c1, c2) -> c1/c2
3766 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3767 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3771 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3772 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3773 // Both can be negated for free, check to see if at least one is cheaper
3775 if (LHSNeg == 2 || RHSNeg == 2)
3776 return DAG.getNode(ISD::FDIV, VT,
3777 GetNegatedExpression(N0, DAG, AfterLegalize),
3778 GetNegatedExpression(N1, DAG, AfterLegalize));
3785 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3786 SDOperand N0 = N->getOperand(0);
3787 SDOperand N1 = N->getOperand(1);
3788 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3789 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3790 MVT VT = N->getValueType(0);
3792 // fold (frem c1, c2) -> fmod(c1,c2)
3793 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3794 return DAG.getNode(ISD::FREM, VT, N0, N1);
3799 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3800 SDOperand N0 = N->getOperand(0);
3801 SDOperand N1 = N->getOperand(1);
3802 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3803 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3804 MVT VT = N->getValueType(0);
3806 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3807 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3810 const APFloat& V = N1CFP->getValueAPF();
3811 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3812 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3813 if (!V.isNegative())
3814 return DAG.getNode(ISD::FABS, VT, N0);
3816 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3819 // copysign(fabs(x), y) -> copysign(x, y)
3820 // copysign(fneg(x), y) -> copysign(x, y)
3821 // copysign(copysign(x,z), y) -> copysign(x, y)
3822 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3823 N0.getOpcode() == ISD::FCOPYSIGN)
3824 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3826 // copysign(x, abs(y)) -> abs(x)
3827 if (N1.getOpcode() == ISD::FABS)
3828 return DAG.getNode(ISD::FABS, VT, N0);
3830 // copysign(x, copysign(y,z)) -> copysign(x, z)
3831 if (N1.getOpcode() == ISD::FCOPYSIGN)
3832 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3834 // copysign(x, fp_extend(y)) -> copysign(x, y)
3835 // copysign(x, fp_round(y)) -> copysign(x, y)
3836 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3837 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3844 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3845 SDOperand N0 = N->getOperand(0);
3846 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3847 MVT VT = N->getValueType(0);
3848 MVT OpVT = N0.getValueType();
3850 // fold (sint_to_fp c1) -> c1fp
3851 if (N0C && OpVT != MVT::ppcf128)
3852 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3854 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
3855 // but UINT_TO_FP is legal on this target, try to convert.
3856 if (!TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT) &&
3857 TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT)) {
3858 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
3859 if (DAG.SignBitIsZero(N0))
3860 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3867 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3868 SDOperand N0 = N->getOperand(0);
3869 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3870 MVT VT = N->getValueType(0);
3871 MVT OpVT = N0.getValueType();
3873 // fold (uint_to_fp c1) -> c1fp
3874 if (N0C && OpVT != MVT::ppcf128)
3875 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3877 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
3878 // but SINT_TO_FP is legal on this target, try to convert.
3879 if (!TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT) &&
3880 TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT)) {
3881 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
3882 if (DAG.SignBitIsZero(N0))
3883 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3889 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3890 SDOperand N0 = N->getOperand(0);
3891 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3892 MVT VT = N->getValueType(0);
3894 // fold (fp_to_sint c1fp) -> c1
3896 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3900 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3901 SDOperand N0 = N->getOperand(0);
3902 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3903 MVT VT = N->getValueType(0);
3905 // fold (fp_to_uint c1fp) -> c1
3906 if (N0CFP && VT != MVT::ppcf128)
3907 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3911 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3912 SDOperand N0 = N->getOperand(0);
3913 SDOperand N1 = N->getOperand(1);
3914 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3915 MVT VT = N->getValueType(0);
3917 // fold (fp_round c1fp) -> c1fp
3918 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3919 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3921 // fold (fp_round (fp_extend x)) -> x
3922 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3923 return N0.getOperand(0);
3925 // fold (fp_round (fp_round x)) -> (fp_round x)
3926 if (N0.getOpcode() == ISD::FP_ROUND) {
3927 // This is a value preserving truncation if both round's are.
3928 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3929 N0.Val->getConstantOperandVal(1) == 1;
3930 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3931 DAG.getIntPtrConstant(IsTrunc));
3934 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3935 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3936 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3937 AddToWorkList(Tmp.Val);
3938 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3944 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3945 SDOperand N0 = N->getOperand(0);
3946 MVT VT = N->getValueType(0);
3947 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3948 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3950 // fold (fp_round_inreg c1fp) -> c1fp
3952 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3953 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3958 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3959 SDOperand N0 = N->getOperand(0);
3960 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3961 MVT VT = N->getValueType(0);
3963 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3964 if (N->hasOneUse() &&
3965 N->use_begin()->getSDOperand().getOpcode() == ISD::FP_ROUND)
3968 // fold (fp_extend c1fp) -> c1fp
3969 if (N0CFP && VT != MVT::ppcf128)
3970 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3972 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3974 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3975 SDOperand In = N0.getOperand(0);
3976 if (In.getValueType() == VT) return In;
3977 if (VT.bitsLT(In.getValueType()))
3978 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3979 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3982 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3983 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3984 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3985 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3987 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3988 LN0->getBasePtr(), LN0->getSrcValue(),
3989 LN0->getSrcValueOffset(),
3992 LN0->getAlignment());
3993 CombineTo(N, ExtLoad);
3994 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3995 DAG.getIntPtrConstant(1)),
3996 ExtLoad.getValue(1));
3997 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4003 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
4004 SDOperand N0 = N->getOperand(0);
4006 if (isNegatibleForFree(N0, AfterLegalize))
4007 return GetNegatedExpression(N0, DAG, AfterLegalize);
4009 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4010 // constant pool values.
4011 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
4012 N0.getOperand(0).getValueType().isInteger() &&
4013 !N0.getOperand(0).getValueType().isVector()) {
4014 SDOperand Int = N0.getOperand(0);
4015 MVT IntVT = Int.getValueType();
4016 if (IntVT.isInteger() && !IntVT.isVector()) {
4017 Int = DAG.getNode(ISD::XOR, IntVT, Int,
4018 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
4019 AddToWorkList(Int.Val);
4020 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4027 SDOperand DAGCombiner::visitFABS(SDNode *N) {
4028 SDOperand N0 = N->getOperand(0);
4029 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4030 MVT VT = N->getValueType(0);
4032 // fold (fabs c1) -> fabs(c1)
4033 if (N0CFP && VT != MVT::ppcf128)
4034 return DAG.getNode(ISD::FABS, VT, N0);
4035 // fold (fabs (fabs x)) -> (fabs x)
4036 if (N0.getOpcode() == ISD::FABS)
4037 return N->getOperand(0);
4038 // fold (fabs (fneg x)) -> (fabs x)
4039 // fold (fabs (fcopysign x, y)) -> (fabs x)
4040 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4041 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4043 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4044 // constant pool values.
4045 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
4046 N0.getOperand(0).getValueType().isInteger() &&
4047 !N0.getOperand(0).getValueType().isVector()) {
4048 SDOperand Int = N0.getOperand(0);
4049 MVT IntVT = Int.getValueType();
4050 if (IntVT.isInteger() && !IntVT.isVector()) {
4051 Int = DAG.getNode(ISD::AND, IntVT, Int,
4052 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4053 AddToWorkList(Int.Val);
4054 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4061 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
4062 SDOperand Chain = N->getOperand(0);
4063 SDOperand N1 = N->getOperand(1);
4064 SDOperand N2 = N->getOperand(2);
4065 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4067 // never taken branch, fold to chain
4068 if (N1C && N1C->isNullValue())
4070 // unconditional branch
4071 if (N1C && N1C->getAPIntValue() == 1)
4072 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4073 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4075 if (N1.getOpcode() == ISD::SETCC &&
4076 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4077 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4078 N1.getOperand(0), N1.getOperand(1), N2);
4083 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4085 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4086 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4087 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4089 // Use SimplifySetCC to simplify SETCC's.
4090 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4091 if (Simp.Val) AddToWorkList(Simp.Val);
4093 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4095 // fold br_cc true, dest -> br dest (unconditional branch)
4096 if (SCCC && !SCCC->isNullValue())
4097 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4099 // fold br_cc false, dest -> unconditional fall through
4100 if (SCCC && SCCC->isNullValue())
4101 return N->getOperand(0);
4103 // fold to a simpler setcc
4104 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4105 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4106 Simp.getOperand(2), Simp.getOperand(0),
4107 Simp.getOperand(1), N->getOperand(4));
4112 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4113 /// pre-indexed load / store when the base pointer is an add or subtract
4114 /// and it has other uses besides the load / store. After the
4115 /// transformation, the new indexed load / store has effectively folded
4116 /// the add / subtract in and all of its other uses are redirected to the
4117 /// new load / store.
4118 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4125 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4126 if (LD->isIndexed())
4128 VT = LD->getMemoryVT();
4129 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4130 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4132 Ptr = LD->getBasePtr();
4133 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4134 if (ST->isIndexed())
4136 VT = ST->getMemoryVT();
4137 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4138 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4140 Ptr = ST->getBasePtr();
4145 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4146 // out. There is no reason to make this a preinc/predec.
4147 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4148 Ptr.Val->hasOneUse())
4151 // Ask the target to do addressing mode selection.
4154 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4155 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4157 // Don't create a indexed load / store with zero offset.
4158 if (isa<ConstantSDNode>(Offset) &&
4159 cast<ConstantSDNode>(Offset)->isNullValue())
4162 // Try turning it into a pre-indexed load / store except when:
4163 // 1) The new base ptr is a frame index.
4164 // 2) If N is a store and the new base ptr is either the same as or is a
4165 // predecessor of the value being stored.
4166 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4167 // that would create a cycle.
4168 // 4) All uses are load / store ops that use it as old base ptr.
4170 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4171 // (plus the implicit offset) to a register to preinc anyway.
4172 if (isa<FrameIndexSDNode>(BasePtr))
4177 SDOperand Val = cast<StoreSDNode>(N)->getValue();
4178 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
4182 // Now check for #3 and #4.
4183 bool RealUse = false;
4184 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4185 E = Ptr.Val->use_end(); I != E; ++I) {
4186 SDNode *Use = I->getUser();
4189 if (Use->isPredecessorOf(N))
4192 if (!((Use->getOpcode() == ISD::LOAD &&
4193 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4194 (Use->getOpcode() == ISD::STORE &&
4195 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4203 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4205 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4208 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4209 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4211 WorkListRemover DeadNodes(*this);
4213 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4215 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4218 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4222 // Finally, since the node is now dead, remove it from the graph.
4225 // Replace the uses of Ptr with uses of the updated base value.
4226 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4228 removeFromWorkList(Ptr.Val);
4229 DAG.DeleteNode(Ptr.Val);
4234 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4235 /// add / sub of the base pointer node into a post-indexed load / store.
4236 /// The transformation folded the add / subtract into the new indexed
4237 /// load / store effectively and all of its uses are redirected to the
4238 /// new load / store.
4239 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4246 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4247 if (LD->isIndexed())
4249 VT = LD->getMemoryVT();
4250 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4251 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4253 Ptr = LD->getBasePtr();
4254 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4255 if (ST->isIndexed())
4257 VT = ST->getMemoryVT();
4258 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4259 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4261 Ptr = ST->getBasePtr();
4266 if (Ptr.Val->hasOneUse())
4269 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4270 E = Ptr.Val->use_end(); I != E; ++I) {
4271 SDNode *Op = I->getUser();
4273 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4278 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4279 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4281 std::swap(BasePtr, Offset);
4284 // Don't create a indexed load / store with zero offset.
4285 if (isa<ConstantSDNode>(Offset) &&
4286 cast<ConstantSDNode>(Offset)->isNullValue())
4289 // Try turning it into a post-indexed load / store except when
4290 // 1) All uses are load / store ops that use it as base ptr.
4291 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4292 // nor a successor of N. Otherwise, if Op is folded that would
4296 bool TryNext = false;
4297 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4298 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4299 SDNode *Use = II->getUser();
4303 // If all the uses are load / store addresses, then don't do the
4305 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4306 bool RealUse = false;
4307 for (SDNode::use_iterator III = Use->use_begin(),
4308 EEE = Use->use_end(); III != EEE; ++III) {
4309 SDNode *UseUse = III->getUser();
4310 if (!((UseUse->getOpcode() == ISD::LOAD &&
4311 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4312 (UseUse->getOpcode() == ISD::STORE &&
4313 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
4327 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4328 SDOperand Result = isLoad
4329 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4330 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4333 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4334 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4336 WorkListRemover DeadNodes(*this);
4338 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4340 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4343 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4347 // Finally, since the node is now dead, remove it from the graph.
4350 // Replace the uses of Use with uses of the updated base value.
4351 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4352 Result.getValue(isLoad ? 1 : 0),
4354 removeFromWorkList(Op);
4363 /// InferAlignment - If we can infer some alignment information from this
4364 /// pointer, return it.
4365 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4366 // If this is a direct reference to a stack slot, use information about the
4367 // stack slot's alignment.
4368 int FrameIdx = 1 << 31;
4369 int64_t FrameOffset = 0;
4370 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4371 FrameIdx = FI->getIndex();
4372 } else if (Ptr.getOpcode() == ISD::ADD &&
4373 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4374 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4375 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4376 FrameOffset = Ptr.getConstantOperandVal(1);
4379 if (FrameIdx != (1 << 31)) {
4380 // FIXME: Handle FI+CST.
4381 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4382 if (MFI.isFixedObjectIndex(FrameIdx)) {
4383 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4385 // The alignment of the frame index can be determined from its offset from
4386 // the incoming frame position. If the frame object is at offset 32 and
4387 // the stack is guaranteed to be 16-byte aligned, then we know that the
4388 // object is 16-byte aligned.
4389 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4390 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4392 // Finally, the frame object itself may have a known alignment. Factor
4393 // the alignment + offset into a new alignment. For example, if we know
4394 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4395 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4396 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4397 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4399 return std::max(Align, FIInfoAlign);
4406 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4407 LoadSDNode *LD = cast<LoadSDNode>(N);
4408 SDOperand Chain = LD->getChain();
4409 SDOperand Ptr = LD->getBasePtr();
4411 // Try to infer better alignment information than the load already has.
4412 if (LD->isUnindexed()) {
4413 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4414 if (Align > LD->getAlignment())
4415 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4416 Chain, Ptr, LD->getSrcValue(),
4417 LD->getSrcValueOffset(), LD->getMemoryVT(),
4418 LD->isVolatile(), Align);
4423 // If load is not volatile and there are no uses of the loaded value (and
4424 // the updated indexed value in case of indexed loads), change uses of the
4425 // chain value into uses of the chain input (i.e. delete the dead load).
4426 if (!LD->isVolatile()) {
4427 if (N->getValueType(1) == MVT::Other) {
4429 if (N->hasNUsesOfValue(0, 0)) {
4430 // It's not safe to use the two value CombineTo variant here. e.g.
4431 // v1, chain2 = load chain1, loc
4432 // v2, chain3 = load chain2, loc
4434 // Now we replace use of chain2 with chain1. This makes the second load
4435 // isomorphic to the one we are deleting, and thus makes this load live.
4436 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4437 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4439 WorkListRemover DeadNodes(*this);
4440 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4441 if (N->use_empty()) {
4442 removeFromWorkList(N);
4445 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4449 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4450 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4451 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4452 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4453 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4454 DOUT << " and 2 other values\n";
4455 WorkListRemover DeadNodes(*this);
4456 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4457 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4458 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4460 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4461 removeFromWorkList(N);
4463 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4468 // If this load is directly stored, replace the load value with the stored
4470 // TODO: Handle store large -> read small portion.
4471 // TODO: Handle TRUNCSTORE/LOADEXT
4472 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4473 !LD->isVolatile()) {
4474 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4475 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4476 if (PrevST->getBasePtr() == Ptr &&
4477 PrevST->getValue().getValueType() == N->getValueType(0))
4478 return CombineTo(N, Chain.getOperand(1), Chain);
4483 // Walk up chain skipping non-aliasing memory nodes.
4484 SDOperand BetterChain = FindBetterChain(N, Chain);
4486 // If there is a better chain.
4487 if (Chain != BetterChain) {
4490 // Replace the chain to void dependency.
4491 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4492 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4493 LD->getSrcValue(), LD->getSrcValueOffset(),
4494 LD->isVolatile(), LD->getAlignment());
4496 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4497 LD->getValueType(0),
4498 BetterChain, Ptr, LD->getSrcValue(),
4499 LD->getSrcValueOffset(),
4502 LD->getAlignment());
4505 // Create token factor to keep old chain connected.
4506 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4507 Chain, ReplLoad.getValue(1));
4509 // Replace uses with load result and token factor. Don't add users
4511 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4515 // Try transforming N to an indexed load.
4516 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4517 return SDOperand(N, 0);
4523 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4524 StoreSDNode *ST = cast<StoreSDNode>(N);
4525 SDOperand Chain = ST->getChain();
4526 SDOperand Value = ST->getValue();
4527 SDOperand Ptr = ST->getBasePtr();
4529 // Try to infer better alignment information than the store already has.
4530 if (ST->isUnindexed()) {
4531 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4532 if (Align > ST->getAlignment())
4533 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4534 ST->getSrcValueOffset(), ST->getMemoryVT(),
4535 ST->isVolatile(), Align);
4539 // If this is a store of a bit convert, store the input value if the
4540 // resultant store does not need a higher alignment than the original.
4541 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4542 ST->isUnindexed()) {
4543 unsigned Align = ST->getAlignment();
4544 MVT SVT = Value.getOperand(0).getValueType();
4545 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4546 getABITypeAlignment(SVT.getTypeForMVT());
4547 if (Align <= OrigAlign &&
4548 ((!AfterLegalize && !ST->isVolatile()) ||
4549 TLI.isOperationLegal(ISD::STORE, SVT)))
4550 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4551 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
4554 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4555 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4556 // NOTE: If the original store is volatile, this transform must not increase
4557 // the number of stores. For example, on x86-32 an f64 can be stored in one
4558 // processor operation but an i64 (which is not legal) requires two. So the
4559 // transform should not be done in this case.
4560 if (Value.getOpcode() != ISD::TargetConstantFP) {
4562 switch (CFP->getValueType(0).getSimpleVT()) {
4563 default: assert(0 && "Unknown FP type");
4564 case MVT::f80: // We don't do this for these yet.
4569 if ((!AfterLegalize && !ST->isVolatile()) ||
4570 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4571 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4572 convertToAPInt().getZExtValue(), MVT::i32);
4573 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4574 ST->getSrcValueOffset(), ST->isVolatile(),
4575 ST->getAlignment());
4579 if ((!AfterLegalize && !ST->isVolatile()) ||
4580 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4581 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4582 getZExtValue(), MVT::i64);
4583 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4584 ST->getSrcValueOffset(), ST->isVolatile(),
4585 ST->getAlignment());
4586 } else if (!ST->isVolatile() &&
4587 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4588 // Many FP stores are not made apparent until after legalize, e.g. for
4589 // argument passing. Since this is so common, custom legalize the
4590 // 64-bit integer store into two 32-bit stores.
4591 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4592 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4593 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4594 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4596 int SVOffset = ST->getSrcValueOffset();
4597 unsigned Alignment = ST->getAlignment();
4598 bool isVolatile = ST->isVolatile();
4600 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4601 ST->getSrcValueOffset(),
4602 isVolatile, ST->getAlignment());
4603 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4604 DAG.getConstant(4, Ptr.getValueType()));
4606 Alignment = MinAlign(Alignment, 4U);
4607 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4608 SVOffset, isVolatile, Alignment);
4609 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4617 // Walk up chain skipping non-aliasing memory nodes.
4618 SDOperand BetterChain = FindBetterChain(N, Chain);
4620 // If there is a better chain.
4621 if (Chain != BetterChain) {
4622 // Replace the chain to avoid dependency.
4623 SDOperand ReplStore;
4624 if (ST->isTruncatingStore()) {
4625 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4626 ST->getSrcValue(),ST->getSrcValueOffset(),
4628 ST->isVolatile(), ST->getAlignment());
4630 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4631 ST->getSrcValue(), ST->getSrcValueOffset(),
4632 ST->isVolatile(), ST->getAlignment());
4635 // Create token to keep both nodes around.
4637 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4639 // Don't add users to work list.
4640 return CombineTo(N, Token, false);
4644 // Try transforming N to an indexed store.
4645 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4646 return SDOperand(N, 0);
4648 // FIXME: is there such a thing as a truncating indexed store?
4649 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4650 Value.getValueType().isInteger()) {
4651 // See if we can simplify the input to this truncstore with knowledge that
4652 // only the low bits are being used. For example:
4653 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4655 GetDemandedBits(Value,
4656 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4657 ST->getMemoryVT().getSizeInBits()));
4658 AddToWorkList(Value.Val);
4660 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4661 ST->getSrcValueOffset(), ST->getMemoryVT(),
4662 ST->isVolatile(), ST->getAlignment());
4664 // Otherwise, see if we can simplify the operation with
4665 // SimplifyDemandedBits, which only works if the value has a single use.
4666 if (SimplifyDemandedBits(Value,
4667 APInt::getLowBitsSet(
4668 Value.getValueSizeInBits(),
4669 ST->getMemoryVT().getSizeInBits())))
4670 return SDOperand(N, 0);
4673 // If this is a load followed by a store to the same location, then the store
4675 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4676 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4677 ST->isUnindexed() && !ST->isVolatile() &&
4678 // There can't be any side effects between the load and store, such as
4680 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4681 // The store is dead, remove it.
4686 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4687 // truncating store. We can do this even if this is already a truncstore.
4688 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4689 && Value.Val->hasOneUse() && ST->isUnindexed() &&
4690 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4691 ST->getMemoryVT())) {
4692 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4693 ST->getSrcValueOffset(), ST->getMemoryVT(),
4694 ST->isVolatile(), ST->getAlignment());
4700 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4701 SDOperand InVec = N->getOperand(0);
4702 SDOperand InVal = N->getOperand(1);
4703 SDOperand EltNo = N->getOperand(2);
4705 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4706 // vector with the inserted element.
4707 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4708 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4709 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4710 if (Elt < Ops.size())
4712 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4713 &Ops[0], Ops.size());
4719 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4720 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4721 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4722 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4724 // Perform only after legalization to ensure build_vector / vector_shuffle
4725 // optimizations have already been done.
4726 if (!AfterLegalize) return SDOperand();
4728 SDOperand InVec = N->getOperand(0);
4729 SDOperand EltNo = N->getOperand(1);
4731 if (isa<ConstantSDNode>(EltNo)) {
4732 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4733 bool NewLoad = false;
4734 MVT VT = InVec.getValueType();
4735 MVT EVT = VT.getVectorElementType();
4737 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4738 MVT BCVT = InVec.getOperand(0).getValueType();
4739 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4741 InVec = InVec.getOperand(0);
4742 EVT = BCVT.getVectorElementType();
4746 LoadSDNode *LN0 = NULL;
4747 if (ISD::isNormalLoad(InVec.Val))
4748 LN0 = cast<LoadSDNode>(InVec);
4749 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4750 InVec.getOperand(0).getValueType() == EVT &&
4751 ISD::isNormalLoad(InVec.getOperand(0).Val)) {
4752 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4753 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4754 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4756 // (load $addr+1*size)
4757 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4758 getOperand(Elt))->getValue();
4759 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4760 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4761 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4762 InVec = InVec.getOperand(0);
4763 if (ISD::isNormalLoad(InVec.Val)) {
4764 LN0 = cast<LoadSDNode>(InVec);
4765 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4768 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4771 unsigned Align = LN0->getAlignment();
4773 // Check the resultant load doesn't need a higher alignment than the
4775 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4776 getABITypeAlignment(LVT.getTypeForMVT());
4777 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4782 SDOperand NewPtr = LN0->getBasePtr();
4784 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4785 MVT PtrType = NewPtr.getValueType();
4786 if (TLI.isBigEndian())
4787 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4788 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4789 DAG.getConstant(PtrOff, PtrType));
4791 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4792 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4793 LN0->isVolatile(), Align);
4799 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4800 unsigned NumInScalars = N->getNumOperands();
4801 MVT VT = N->getValueType(0);
4802 unsigned NumElts = VT.getVectorNumElements();
4803 MVT EltType = VT.getVectorElementType();
4805 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4806 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4807 // at most two distinct vectors, turn this into a shuffle node.
4808 SDOperand VecIn1, VecIn2;
4809 for (unsigned i = 0; i != NumInScalars; ++i) {
4810 // Ignore undef inputs.
4811 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4813 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4814 // constant index, bail out.
4815 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4816 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4817 VecIn1 = VecIn2 = SDOperand(0, 0);
4821 // If the input vector type disagrees with the result of the build_vector,
4822 // we can't make a shuffle.
4823 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4824 if (ExtractedFromVec.getValueType() != VT) {
4825 VecIn1 = VecIn2 = SDOperand(0, 0);
4829 // Otherwise, remember this. We allow up to two distinct input vectors.
4830 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4833 if (VecIn1.Val == 0) {
4834 VecIn1 = ExtractedFromVec;
4835 } else if (VecIn2.Val == 0) {
4836 VecIn2 = ExtractedFromVec;
4839 VecIn1 = VecIn2 = SDOperand(0, 0);
4844 // If everything is good, we can make a shuffle operation.
4846 SmallVector<SDOperand, 8> BuildVecIndices;
4847 for (unsigned i = 0; i != NumInScalars; ++i) {
4848 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4849 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4853 SDOperand Extract = N->getOperand(i);
4855 // If extracting from the first vector, just use the index directly.
4856 if (Extract.getOperand(0) == VecIn1) {
4857 BuildVecIndices.push_back(Extract.getOperand(1));
4861 // Otherwise, use InIdx + VecSize
4862 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4863 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4866 // Add count and size info.
4867 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
4869 // Return the new VECTOR_SHUFFLE node.
4875 // Use an undef build_vector as input for the second operand.
4876 std::vector<SDOperand> UnOps(NumInScalars,
4877 DAG.getNode(ISD::UNDEF,
4879 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4880 &UnOps[0], UnOps.size());
4881 AddToWorkList(Ops[1].Val);
4883 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4884 &BuildVecIndices[0], BuildVecIndices.size());
4885 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4891 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4892 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4893 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4894 // inputs come from at most two distinct vectors, turn this into a shuffle
4897 // If we only have one input vector, we don't need to do any concatenation.
4898 if (N->getNumOperands() == 1) {
4899 return N->getOperand(0);
4905 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4906 SDOperand ShufMask = N->getOperand(2);
4907 unsigned NumElts = ShufMask.getNumOperands();
4909 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4910 bool isIdentity = true;
4911 for (unsigned i = 0; i != NumElts; ++i) {
4912 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4913 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4918 if (isIdentity) return N->getOperand(0);
4920 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4922 for (unsigned i = 0; i != NumElts; ++i) {
4923 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4924 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4929 if (isIdentity) return N->getOperand(1);
4931 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4933 bool isUnary = true;
4934 bool isSplat = true;
4936 unsigned BaseIdx = 0;
4937 for (unsigned i = 0; i != NumElts; ++i)
4938 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4939 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4940 int V = (Idx < NumElts) ? 0 : 1;
4954 SDOperand N0 = N->getOperand(0);
4955 SDOperand N1 = N->getOperand(1);
4956 // Normalize unary shuffle so the RHS is undef.
4957 if (isUnary && VecNum == 1)
4960 // If it is a splat, check if the argument vector is a build_vector with
4961 // all scalar elements the same.
4965 // If this is a bit convert that changes the element type of the vector but
4966 // not the number of vector elements, look through it. Be careful not to
4967 // look though conversions that change things like v4f32 to v2f64.
4968 if (V->getOpcode() == ISD::BIT_CONVERT) {
4969 SDOperand ConvInput = V->getOperand(0);
4970 if (ConvInput.getValueType().getVectorNumElements() == NumElts)
4974 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4975 unsigned NumElems = V->getNumOperands();
4976 if (NumElems > BaseIdx) {
4978 bool AllSame = true;
4979 for (unsigned i = 0; i != NumElems; ++i) {
4980 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4981 Base = V->getOperand(i);
4985 // Splat of <u, u, u, u>, return <u, u, u, u>
4988 for (unsigned i = 0; i != NumElems; ++i) {
4989 if (V->getOperand(i) != Base) {
4994 // Splat of <x, x, x, x>, return <x, x, x, x>
5001 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
5003 if (isUnary || N0 == N1) {
5004 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
5006 SmallVector<SDOperand, 8> MappedOps;
5007 for (unsigned i = 0; i != NumElts; ++i) {
5008 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
5009 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
5010 MappedOps.push_back(ShufMask.getOperand(i));
5013 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
5014 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
5017 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
5018 &MappedOps[0], MappedOps.size());
5019 AddToWorkList(ShufMask.Val);
5020 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5022 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5029 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5030 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5031 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5032 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5033 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5034 SDOperand LHS = N->getOperand(0);
5035 SDOperand RHS = N->getOperand(1);
5036 if (N->getOpcode() == ISD::AND) {
5037 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5038 RHS = RHS.getOperand(0);
5039 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5040 std::vector<SDOperand> IdxOps;
5041 unsigned NumOps = RHS.getNumOperands();
5042 unsigned NumElts = NumOps;
5043 MVT EVT = RHS.getValueType().getVectorElementType();
5044 for (unsigned i = 0; i != NumElts; ++i) {
5045 SDOperand Elt = RHS.getOperand(i);
5046 if (!isa<ConstantSDNode>(Elt))
5048 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5049 IdxOps.push_back(DAG.getConstant(i, EVT));
5050 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5051 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
5056 // Let's see if the target supports this vector_shuffle.
5057 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
5060 // Return the new VECTOR_SHUFFLE node.
5061 MVT VT = MVT::getVectorVT(EVT, NumElts);
5062 std::vector<SDOperand> Ops;
5063 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5065 AddToWorkList(LHS.Val);
5066 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5067 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5068 &ZeroOps[0], ZeroOps.size()));
5069 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5070 &IdxOps[0], IdxOps.size()));
5071 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5072 &Ops[0], Ops.size());
5073 if (VT != N->getValueType(0))
5074 Result = DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Result);
5081 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5082 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
5083 // After legalize, the target may be depending on adds and other
5084 // binary ops to provide legal ways to construct constants or other
5085 // things. Simplifying them may result in a loss of legality.
5086 if (AfterLegalize) return SDOperand();
5088 MVT VT = N->getValueType(0);
5089 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5091 MVT EltType = VT.getVectorElementType();
5092 SDOperand LHS = N->getOperand(0);
5093 SDOperand RHS = N->getOperand(1);
5094 SDOperand Shuffle = XformToShuffleWithZero(N);
5095 if (Shuffle.Val) return Shuffle;
5097 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5099 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5100 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5101 SmallVector<SDOperand, 8> Ops;
5102 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5103 SDOperand LHSOp = LHS.getOperand(i);
5104 SDOperand RHSOp = RHS.getOperand(i);
5105 // If these two elements can't be folded, bail out.
5106 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5107 LHSOp.getOpcode() != ISD::Constant &&
5108 LHSOp.getOpcode() != ISD::ConstantFP) ||
5109 (RHSOp.getOpcode() != ISD::UNDEF &&
5110 RHSOp.getOpcode() != ISD::Constant &&
5111 RHSOp.getOpcode() != ISD::ConstantFP))
5113 // Can't fold divide by zero.
5114 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5115 N->getOpcode() == ISD::FDIV) {
5116 if ((RHSOp.getOpcode() == ISD::Constant &&
5117 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
5118 (RHSOp.getOpcode() == ISD::ConstantFP &&
5119 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
5122 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5123 AddToWorkList(Ops.back().Val);
5124 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5125 Ops.back().getOpcode() == ISD::Constant ||
5126 Ops.back().getOpcode() == ISD::ConstantFP) &&
5127 "Scalar binop didn't fold!");
5130 if (Ops.size() == LHS.getNumOperands()) {
5131 MVT VT = LHS.getValueType();
5132 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5139 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5140 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5142 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5143 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5144 // If we got a simplified select_cc node back from SimplifySelectCC, then
5145 // break it down into a new SETCC node, and a new SELECT node, and then return
5146 // the SELECT node, since we were called with a SELECT node.
5148 // Check to see if we got a select_cc back (to turn into setcc/select).
5149 // Otherwise, just return whatever node we got back, like fabs.
5150 if (SCC.getOpcode() == ISD::SELECT_CC) {
5151 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5152 SCC.getOperand(0), SCC.getOperand(1),
5154 AddToWorkList(SETCC.Val);
5155 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5156 SCC.getOperand(3), SETCC);
5163 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5164 /// are the two values being selected between, see if we can simplify the
5165 /// select. Callers of this should assume that TheSelect is deleted if this
5166 /// returns true. As such, they should return the appropriate thing (e.g. the
5167 /// node) back to the top-level of the DAG combiner loop to avoid it being
5170 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5173 // If this is a select from two identical things, try to pull the operation
5174 // through the select.
5175 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5176 // If this is a load and the token chain is identical, replace the select
5177 // of two loads with a load through a select of the address to load from.
5178 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5179 // constants have been dropped into the constant pool.
5180 if (LHS.getOpcode() == ISD::LOAD &&
5181 // Do not let this transformation reduce the number of volatile loads.
5182 !cast<LoadSDNode>(LHS)->isVolatile() &&
5183 !cast<LoadSDNode>(RHS)->isVolatile() &&
5184 // Token chains must be identical.
5185 LHS.getOperand(0) == RHS.getOperand(0)) {
5186 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5187 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5189 // If this is an EXTLOAD, the VT's must match.
5190 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5191 // FIXME: this conflates two src values, discarding one. This is not
5192 // the right thing to do, but nothing uses srcvalues now. When they do,
5193 // turn SrcValue into a list of locations.
5195 if (TheSelect->getOpcode() == ISD::SELECT) {
5196 // Check that the condition doesn't reach either load. If so, folding
5197 // this will induce a cycle into the DAG.
5198 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5199 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
5200 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5201 TheSelect->getOperand(0), LLD->getBasePtr(),
5205 // Check that the condition doesn't reach either load. If so, folding
5206 // this will induce a cycle into the DAG.
5207 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5208 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5209 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5210 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
5211 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5212 TheSelect->getOperand(0),
5213 TheSelect->getOperand(1),
5214 LLD->getBasePtr(), RLD->getBasePtr(),
5215 TheSelect->getOperand(4));
5221 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5222 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5223 Addr,LLD->getSrcValue(),
5224 LLD->getSrcValueOffset(),
5226 LLD->getAlignment());
5228 Load = DAG.getExtLoad(LLD->getExtensionType(),
5229 TheSelect->getValueType(0),
5230 LLD->getChain(), Addr, LLD->getSrcValue(),
5231 LLD->getSrcValueOffset(),
5234 LLD->getAlignment());
5236 // Users of the select now use the result of the load.
5237 CombineTo(TheSelect, Load);
5239 // Users of the old loads now use the new load's chain. We know the
5240 // old-load value is dead now.
5241 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5242 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5252 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5253 SDOperand N2, SDOperand N3,
5254 ISD::CondCode CC, bool NotExtCompare) {
5256 MVT VT = N2.getValueType();
5257 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5258 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5259 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5261 // Determine if the condition we're dealing with is constant
5262 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5263 if (SCC.Val) AddToWorkList(SCC.Val);
5264 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5266 // fold select_cc true, x, y -> x
5267 if (SCCC && !SCCC->isNullValue())
5269 // fold select_cc false, x, y -> y
5270 if (SCCC && SCCC->isNullValue())
5273 // Check to see if we can simplify the select into an fabs node
5274 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5275 // Allow either -0.0 or 0.0
5276 if (CFP->getValueAPF().isZero()) {
5277 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5278 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5279 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5280 N2 == N3.getOperand(0))
5281 return DAG.getNode(ISD::FABS, VT, N0);
5283 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5284 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5285 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5286 N2.getOperand(0) == N3)
5287 return DAG.getNode(ISD::FABS, VT, N3);
5291 // Check to see if we can perform the "gzip trick", transforming
5292 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5293 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5294 N0.getValueType().isInteger() &&
5295 N2.getValueType().isInteger() &&
5296 (N1C->isNullValue() || // (a < 0) ? b : 0
5297 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5298 MVT XType = N0.getValueType();
5299 MVT AType = N2.getValueType();
5300 if (XType.bitsGE(AType)) {
5301 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5302 // single-bit constant.
5303 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5304 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5305 ShCtV = XType.getSizeInBits()-ShCtV-1;
5306 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5307 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5308 AddToWorkList(Shift.Val);
5309 if (XType.bitsGT(AType)) {
5310 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5311 AddToWorkList(Shift.Val);
5313 return DAG.getNode(ISD::AND, AType, Shift, N2);
5315 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5316 DAG.getConstant(XType.getSizeInBits()-1,
5317 TLI.getShiftAmountTy()));
5318 AddToWorkList(Shift.Val);
5319 if (XType.bitsGT(AType)) {
5320 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5321 AddToWorkList(Shift.Val);
5323 return DAG.getNode(ISD::AND, AType, Shift, N2);
5327 // fold select C, 16, 0 -> shl C, 4
5328 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5329 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5331 // If the caller doesn't want us to simplify this into a zext of a compare,
5333 if (NotExtCompare && N2C->getAPIntValue() == 1)
5336 // Get a SetCC of the condition
5337 // FIXME: Should probably make sure that setcc is legal if we ever have a
5338 // target where it isn't.
5339 SDOperand Temp, SCC;
5340 // cast from setcc result type to select result type
5341 if (AfterLegalize) {
5342 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5343 if (N2.getValueType().bitsLT(SCC.getValueType()))
5344 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5346 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5348 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5349 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5351 AddToWorkList(SCC.Val);
5352 AddToWorkList(Temp.Val);
5354 if (N2C->getAPIntValue() == 1)
5356 // shl setcc result by log2 n2c
5357 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5358 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5359 TLI.getShiftAmountTy()));
5362 // Check to see if this is the equivalent of setcc
5363 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5364 // otherwise, go ahead with the folds.
5365 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5366 MVT XType = N0.getValueType();
5367 if (!AfterLegalize ||
5368 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5369 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5370 if (Res.getValueType() != VT)
5371 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5375 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5376 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5378 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5379 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5380 return DAG.getNode(ISD::SRL, XType, Ctlz,
5381 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5382 TLI.getShiftAmountTy()));
5384 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5385 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5386 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5388 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5389 DAG.getConstant(~0ULL, XType));
5390 return DAG.getNode(ISD::SRL, XType,
5391 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5392 DAG.getConstant(XType.getSizeInBits()-1,
5393 TLI.getShiftAmountTy()));
5395 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5396 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5397 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5398 DAG.getConstant(XType.getSizeInBits()-1,
5399 TLI.getShiftAmountTy()));
5400 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5404 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5405 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5406 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5407 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5408 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5409 MVT XType = N0.getValueType();
5410 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5411 DAG.getConstant(XType.getSizeInBits()-1,
5412 TLI.getShiftAmountTy()));
5413 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5414 AddToWorkList(Shift.Val);
5415 AddToWorkList(Add.Val);
5416 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5418 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5419 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5420 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5421 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5422 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5423 MVT XType = N0.getValueType();
5424 if (SubC->isNullValue() && XType.isInteger()) {
5425 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5426 DAG.getConstant(XType.getSizeInBits()-1,
5427 TLI.getShiftAmountTy()));
5428 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5429 AddToWorkList(Shift.Val);
5430 AddToWorkList(Add.Val);
5431 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5439 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5440 SDOperand DAGCombiner::SimplifySetCC(MVT VT, SDOperand N0,
5441 SDOperand N1, ISD::CondCode Cond,
5442 bool foldBooleans) {
5443 TargetLowering::DAGCombinerInfo
5444 DagCombineInfo(DAG, !AfterLegalize, false, this);
5445 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5448 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5449 /// return a DAG expression to select that will generate the same value by
5450 /// multiplying by a magic number. See:
5451 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5452 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5453 std::vector<SDNode*> Built;
5454 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5456 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5462 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5463 /// return a DAG expression to select that will generate the same value by
5464 /// multiplying by a magic number. See:
5465 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5466 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5467 std::vector<SDNode*> Built;
5468 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5470 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5476 /// FindBaseOffset - Return true if base is known not to alias with anything
5477 /// but itself. Provides base object and offset as results.
5478 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5479 // Assume it is a primitive operation.
5480 Base = Ptr; Offset = 0;
5482 // If it's an adding a simple constant then integrate the offset.
5483 if (Base.getOpcode() == ISD::ADD) {
5484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5485 Base = Base.getOperand(0);
5486 Offset += C->getValue();
5490 // If it's any of the following then it can't alias with anything but itself.
5491 return isa<FrameIndexSDNode>(Base) ||
5492 isa<ConstantPoolSDNode>(Base) ||
5493 isa<GlobalAddressSDNode>(Base);
5496 /// isAlias - Return true if there is any possibility that the two addresses
5498 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5499 const Value *SrcValue1, int SrcValueOffset1,
5500 SDOperand Ptr2, int64_t Size2,
5501 const Value *SrcValue2, int SrcValueOffset2)
5503 // If they are the same then they must be aliases.
5504 if (Ptr1 == Ptr2) return true;
5506 // Gather base node and offset information.
5507 SDOperand Base1, Base2;
5508 int64_t Offset1, Offset2;
5509 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5510 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5512 // If they have a same base address then...
5513 if (Base1 == Base2) {
5514 // Check to see if the addresses overlap.
5515 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5518 // If we know both bases then they can't alias.
5519 if (KnownBase1 && KnownBase2) return false;
5521 if (CombinerGlobalAA) {
5522 // Use alias analysis information.
5523 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5524 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5525 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5526 AliasAnalysis::AliasResult AAResult =
5527 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5528 if (AAResult == AliasAnalysis::NoAlias)
5532 // Otherwise we have to assume they alias.
5536 /// FindAliasInfo - Extracts the relevant alias information from the memory
5537 /// node. Returns true if the operand was a load.
5538 bool DAGCombiner::FindAliasInfo(SDNode *N,
5539 SDOperand &Ptr, int64_t &Size,
5540 const Value *&SrcValue, int &SrcValueOffset) {
5541 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5542 Ptr = LD->getBasePtr();
5543 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5544 SrcValue = LD->getSrcValue();
5545 SrcValueOffset = LD->getSrcValueOffset();
5547 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5548 Ptr = ST->getBasePtr();
5549 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5550 SrcValue = ST->getSrcValue();
5551 SrcValueOffset = ST->getSrcValueOffset();
5553 assert(0 && "FindAliasInfo expected a memory operand");
5559 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5560 /// looking for aliasing nodes and adding them to the Aliases vector.
5561 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5562 SmallVector<SDOperand, 8> &Aliases) {
5563 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5564 std::set<SDNode *> Visited; // Visited node set.
5566 // Get alias information for node.
5569 const Value *SrcValue;
5571 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5574 Chains.push_back(OriginalChain);
5576 // Look at each chain and determine if it is an alias. If so, add it to the
5577 // aliases list. If not, then continue up the chain looking for the next
5579 while (!Chains.empty()) {
5580 SDOperand Chain = Chains.back();
5583 // Don't bother if we've been before.
5584 if (Visited.find(Chain.Val) != Visited.end()) continue;
5585 Visited.insert(Chain.Val);
5587 switch (Chain.getOpcode()) {
5588 case ISD::EntryToken:
5589 // Entry token is ideal chain operand, but handled in FindBetterChain.
5594 // Get alias information for Chain.
5597 const Value *OpSrcValue;
5598 int OpSrcValueOffset;
5599 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5600 OpSrcValue, OpSrcValueOffset);
5602 // If chain is alias then stop here.
5603 if (!(IsLoad && IsOpLoad) &&
5604 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5605 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5606 Aliases.push_back(Chain);
5608 // Look further up the chain.
5609 Chains.push_back(Chain.getOperand(0));
5610 // Clean up old chain.
5611 AddToWorkList(Chain.Val);
5616 case ISD::TokenFactor:
5617 // We have to check each of the operands of the token factor, so we queue
5618 // then up. Adding the operands to the queue (stack) in reverse order
5619 // maintains the original order and increases the likelihood that getNode
5620 // will find a matching token factor (CSE.)
5621 for (unsigned n = Chain.getNumOperands(); n;)
5622 Chains.push_back(Chain.getOperand(--n));
5623 // Eliminate the token factor if we can.
5624 AddToWorkList(Chain.Val);
5628 // For all other instructions we will just have to take what we can get.
5629 Aliases.push_back(Chain);
5635 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5636 /// for a better chain (aliasing node.)
5637 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5638 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5640 // Accumulate all the aliases to this node.
5641 GatherAllAliases(N, OldChain, Aliases);
5643 if (Aliases.size() == 0) {
5644 // If no operands then chain to entry token.
5645 return DAG.getEntryNode();
5646 } else if (Aliases.size() == 1) {
5647 // If a single operand then chain to it. We don't need to revisit it.
5651 // Construct a custom tailored token factor.
5652 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5653 &Aliases[0], Aliases.size());
5655 // Make sure the old chain gets cleaned up.
5656 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5661 // SelectionDAG::Combine - This is the entry point for the file.
5663 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5664 if (!RunningAfterLegalize && ViewDAGCombine1)
5666 if (RunningAfterLegalize && ViewDAGCombine2)
5668 /// run - This is the main entry point to this class.
5670 DAGCombiner(*this, AA).Run(RunningAfterLegalize);