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 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NodesCombined , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 CombinerAA("combiner-alias-analysis", cl::Hidden,
50 cl::desc("Turn on alias analysis during testing"));
53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54 cl::desc("Include global information in alias analysis"));
56 //------------------------------ DAGCombiner ---------------------------------//
60 const TargetLowering &TLI;
62 CodeGenOpt::Level OptLevel;
66 // Worklist of all of the nodes that need to be simplified.
67 std::vector<SDNode*> WorkList;
69 // AA - Used for DAG load/store alias analysis.
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(SDNode *N) {
77 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 /// visit - call the node-specific routine that knows how to fold each
83 /// particular type of node.
84 SDValue visit(SDNode *N);
87 /// AddToWorkList - Add to the work list making sure it's instance is at the
88 /// the back (next to be processed.)
89 void AddToWorkList(SDNode *N) {
90 removeFromWorkList(N);
91 WorkList.push_back(N);
94 /// removeFromWorkList - remove all instances of N from the worklist.
96 void removeFromWorkList(SDNode *N) {
97 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
101 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
104 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
105 return CombineTo(N, &Res, 1, AddTo);
108 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
110 SDValue To[] = { Res0, Res1 };
111 return CombineTo(N, To, 2, AddTo);
114 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
121 bool SimplifyDemandedBits(SDValue Op) {
122 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
123 APInt Demanded = APInt::getAllOnesValue(BitWidth);
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
132 SDValue PromoteIntBinOp(SDValue Op);
133 SDValue PromoteExtend(SDValue Op);
134 bool PromoteLoad(SDValue Op);
136 /// combine - call the node-specific routine that knows how to fold each
137 /// particular type of node. If that doesn't do anything, try the
138 /// target-specific DAG combines.
139 SDValue combine(SDNode *N);
141 // Visitation implementation - Implement dag node combining for different
142 // node types. The semantics are as follows:
144 // SDValue.getNode() == 0 - No change was made
145 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
146 // otherwise - N should be replaced by the returned Operand.
148 SDValue visitTokenFactor(SDNode *N);
149 SDValue visitMERGE_VALUES(SDNode *N);
150 SDValue visitADD(SDNode *N);
151 SDValue visitSUB(SDNode *N);
152 SDValue visitADDC(SDNode *N);
153 SDValue visitADDE(SDNode *N);
154 SDValue visitMUL(SDNode *N);
155 SDValue visitSDIV(SDNode *N);
156 SDValue visitUDIV(SDNode *N);
157 SDValue visitSREM(SDNode *N);
158 SDValue visitUREM(SDNode *N);
159 SDValue visitMULHU(SDNode *N);
160 SDValue visitMULHS(SDNode *N);
161 SDValue visitSMUL_LOHI(SDNode *N);
162 SDValue visitUMUL_LOHI(SDNode *N);
163 SDValue visitSDIVREM(SDNode *N);
164 SDValue visitUDIVREM(SDNode *N);
165 SDValue visitAND(SDNode *N);
166 SDValue visitOR(SDNode *N);
167 SDValue visitXOR(SDNode *N);
168 SDValue SimplifyVBinOp(SDNode *N);
169 SDValue visitSHL(SDNode *N);
170 SDValue visitSRA(SDNode *N);
171 SDValue visitSRL(SDNode *N);
172 SDValue visitROTL(SDNode *N);
173 SDValue visitROTR(SDNode *N);
174 SDValue visitCTLZ(SDNode *N);
175 SDValue visitCTTZ(SDNode *N);
176 SDValue visitCTPOP(SDNode *N);
177 SDValue visitSELECT(SDNode *N);
178 SDValue visitSELECT_CC(SDNode *N);
179 SDValue visitSETCC(SDNode *N);
180 SDValue visitSIGN_EXTEND(SDNode *N);
181 SDValue visitZERO_EXTEND(SDNode *N);
182 SDValue visitANY_EXTEND(SDNode *N);
183 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
184 SDValue visitTRUNCATE(SDNode *N);
185 SDValue visitBIT_CONVERT(SDNode *N);
186 SDValue visitBUILD_PAIR(SDNode *N);
187 SDValue visitFADD(SDNode *N);
188 SDValue visitFSUB(SDNode *N);
189 SDValue visitFMUL(SDNode *N);
190 SDValue visitFDIV(SDNode *N);
191 SDValue visitFREM(SDNode *N);
192 SDValue visitFCOPYSIGN(SDNode *N);
193 SDValue visitSINT_TO_FP(SDNode *N);
194 SDValue visitUINT_TO_FP(SDNode *N);
195 SDValue visitFP_TO_SINT(SDNode *N);
196 SDValue visitFP_TO_UINT(SDNode *N);
197 SDValue visitFP_ROUND(SDNode *N);
198 SDValue visitFP_ROUND_INREG(SDNode *N);
199 SDValue visitFP_EXTEND(SDNode *N);
200 SDValue visitFNEG(SDNode *N);
201 SDValue visitFABS(SDNode *N);
202 SDValue visitBRCOND(SDNode *N);
203 SDValue visitBR_CC(SDNode *N);
204 SDValue visitLOAD(SDNode *N);
205 SDValue visitSTORE(SDNode *N);
206 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
207 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
208 SDValue visitBUILD_VECTOR(SDNode *N);
209 SDValue visitCONCAT_VECTORS(SDNode *N);
210 SDValue visitVECTOR_SHUFFLE(SDNode *N);
212 SDValue XformToShuffleWithZero(SDNode *N);
213 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
215 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
217 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
218 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
219 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
220 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
221 SDValue N3, ISD::CondCode CC,
222 bool NotExtCompare = false);
223 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
224 DebugLoc DL, bool foldBooleans = true);
225 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
227 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
228 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
229 SDValue BuildSDIV(SDNode *N);
230 SDValue BuildUDIV(SDNode *N);
231 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
232 SDValue ReduceLoadWidth(SDNode *N);
233 SDValue ReduceLoadOpStoreWidth(SDNode *N);
235 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
237 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
238 /// looking for aliasing nodes and adding them to the Aliases vector.
239 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
240 SmallVector<SDValue, 8> &Aliases);
242 /// isAlias - Return true if there is any possibility that the two addresses
244 bool isAlias(SDValue Ptr1, int64_t Size1,
245 const Value *SrcValue1, int SrcValueOffset1,
246 unsigned SrcValueAlign1,
247 SDValue Ptr2, int64_t Size2,
248 const Value *SrcValue2, int SrcValueOffset2,
249 unsigned SrcValueAlign2) const;
251 /// FindAliasInfo - Extracts the relevant alias information from the memory
252 /// node. Returns true if the operand was a load.
253 bool FindAliasInfo(SDNode *N,
254 SDValue &Ptr, int64_t &Size,
255 const Value *&SrcValue, int &SrcValueOffset,
256 unsigned &SrcValueAlignment) const;
258 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
259 /// looking for a better chain (aliasing node.)
260 SDValue FindBetterChain(SDNode *N, SDValue Chain);
263 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
264 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
265 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
267 /// Run - runs the dag combiner on all nodes in the work list
268 void Run(CombineLevel AtLevel);
270 SelectionDAG &getDAG() const { return DAG; }
272 /// getShiftAmountTy - Returns a type large enough to hold any valid
273 /// shift amount - before type legalization these can be huge.
274 EVT getShiftAmountTy() {
275 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
278 /// isTypeLegal - This method returns true if we are running before type
279 /// legalization or if the specified VT is legal.
280 bool isTypeLegal(const EVT &VT) {
281 if (!LegalTypes) return true;
282 return TLI.isTypeLegal(VT);
289 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
290 /// nodes from the worklist.
291 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
294 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
296 virtual void NodeDeleted(SDNode *N, SDNode *E) {
297 DC.removeFromWorkList(N);
300 virtual void NodeUpdated(SDNode *N) {
306 //===----------------------------------------------------------------------===//
307 // TargetLowering::DAGCombinerInfo implementation
308 //===----------------------------------------------------------------------===//
310 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
311 ((DAGCombiner*)DC)->AddToWorkList(N);
314 SDValue TargetLowering::DAGCombinerInfo::
315 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
316 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
319 SDValue TargetLowering::DAGCombinerInfo::
320 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
321 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
325 SDValue TargetLowering::DAGCombinerInfo::
326 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
327 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
330 void TargetLowering::DAGCombinerInfo::
331 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
332 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
335 //===----------------------------------------------------------------------===//
337 //===----------------------------------------------------------------------===//
339 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
340 /// specified expression for the same cost as the expression itself, or 2 if we
341 /// can compute the negated form more cheaply than the expression itself.
342 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
343 unsigned Depth = 0) {
344 // No compile time optimizations on this type.
345 if (Op.getValueType() == MVT::ppcf128)
348 // fneg is removable even if it has multiple uses.
349 if (Op.getOpcode() == ISD::FNEG) return 2;
351 // Don't allow anything with multiple uses.
352 if (!Op.hasOneUse()) return 0;
354 // Don't recurse exponentially.
355 if (Depth > 6) return 0;
357 switch (Op.getOpcode()) {
358 default: return false;
359 case ISD::ConstantFP:
360 // Don't invert constant FP values after legalize. The negated constant
361 // isn't necessarily legal.
362 return LegalOperations ? 0 : 1;
364 // FIXME: determine better conditions for this xform.
365 if (!UnsafeFPMath) return 0;
367 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
368 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
370 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
371 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
373 // We can't turn -(A-B) into B-A when we honor signed zeros.
374 if (!UnsafeFPMath) return 0;
376 // fold (fneg (fsub A, B)) -> (fsub B, A)
381 if (HonorSignDependentRoundingFPMath()) return 0;
383 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
384 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
387 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
392 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
396 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
397 /// returns the newly negated expression.
398 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
399 bool LegalOperations, unsigned Depth = 0) {
400 // fneg is removable even if it has multiple uses.
401 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
403 // Don't allow anything with multiple uses.
404 assert(Op.hasOneUse() && "Unknown reuse!");
406 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
407 switch (Op.getOpcode()) {
408 default: llvm_unreachable("Unknown code");
409 case ISD::ConstantFP: {
410 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
412 return DAG.getConstantFP(V, Op.getValueType());
415 // FIXME: determine better conditions for this xform.
416 assert(UnsafeFPMath);
418 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
419 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
420 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
421 GetNegatedExpression(Op.getOperand(0), DAG,
422 LegalOperations, Depth+1),
424 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
425 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
426 GetNegatedExpression(Op.getOperand(1), DAG,
427 LegalOperations, Depth+1),
430 // We can't turn -(A-B) into B-A when we honor signed zeros.
431 assert(UnsafeFPMath);
433 // fold (fneg (fsub 0, B)) -> B
434 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
435 if (N0CFP->getValueAPF().isZero())
436 return Op.getOperand(1);
438 // fold (fneg (fsub A, B)) -> (fsub B, A)
439 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
440 Op.getOperand(1), Op.getOperand(0));
444 assert(!HonorSignDependentRoundingFPMath());
446 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
447 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
448 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
449 GetNegatedExpression(Op.getOperand(0), DAG,
450 LegalOperations, Depth+1),
453 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
454 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
456 GetNegatedExpression(Op.getOperand(1), DAG,
457 LegalOperations, Depth+1));
461 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
462 GetNegatedExpression(Op.getOperand(0), DAG,
463 LegalOperations, Depth+1));
465 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
466 GetNegatedExpression(Op.getOperand(0), DAG,
467 LegalOperations, Depth+1),
473 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
474 // that selects between the values 1 and 0, making it equivalent to a setcc.
475 // Also, set the incoming LHS, RHS, and CC references to the appropriate
476 // nodes based on the type of node we are checking. This simplifies life a
477 // bit for the callers.
478 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
480 if (N.getOpcode() == ISD::SETCC) {
481 LHS = N.getOperand(0);
482 RHS = N.getOperand(1);
483 CC = N.getOperand(2);
486 if (N.getOpcode() == ISD::SELECT_CC &&
487 N.getOperand(2).getOpcode() == ISD::Constant &&
488 N.getOperand(3).getOpcode() == ISD::Constant &&
489 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
490 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
491 LHS = N.getOperand(0);
492 RHS = N.getOperand(1);
493 CC = N.getOperand(4);
499 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
500 // one use. If this is true, it allows the users to invert the operation for
501 // free when it is profitable to do so.
502 static bool isOneUseSetCC(SDValue N) {
504 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
509 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
510 SDValue N0, SDValue N1) {
511 EVT VT = N0.getValueType();
512 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
513 if (isa<ConstantSDNode>(N1)) {
514 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
516 DAG.FoldConstantArithmetic(Opc, VT,
517 cast<ConstantSDNode>(N0.getOperand(1)),
518 cast<ConstantSDNode>(N1));
519 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
520 } else if (N0.hasOneUse()) {
521 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
522 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
523 N0.getOperand(0), N1);
524 AddToWorkList(OpNode.getNode());
525 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
529 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
530 if (isa<ConstantSDNode>(N0)) {
531 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
533 DAG.FoldConstantArithmetic(Opc, VT,
534 cast<ConstantSDNode>(N1.getOperand(1)),
535 cast<ConstantSDNode>(N0));
536 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
537 } else if (N1.hasOneUse()) {
538 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
539 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
540 N1.getOperand(0), N0);
541 AddToWorkList(OpNode.getNode());
542 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
549 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
551 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
553 DEBUG(dbgs() << "\nReplacing.1 ";
555 dbgs() << "\nWith: ";
556 To[0].getNode()->dump(&DAG);
557 dbgs() << " and " << NumTo-1 << " other values\n";
558 for (unsigned i = 0, e = NumTo; i != e; ++i)
559 assert((!To[i].getNode() ||
560 N->getValueType(i) == To[i].getValueType()) &&
561 "Cannot combine value to value of different type!"));
562 WorkListRemover DeadNodes(*this);
563 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
566 // Push the new nodes and any users onto the worklist
567 for (unsigned i = 0, e = NumTo; i != e; ++i) {
568 if (To[i].getNode()) {
569 AddToWorkList(To[i].getNode());
570 AddUsersToWorkList(To[i].getNode());
575 // Finally, if the node is now dead, remove it from the graph. The node
576 // may not be dead if the replacement process recursively simplified to
577 // something else needing this node.
578 if (N->use_empty()) {
579 // Nodes can be reintroduced into the worklist. Make sure we do not
580 // process a node that has been replaced.
581 removeFromWorkList(N);
583 // Finally, since the node is now dead, remove it from the graph.
586 return SDValue(N, 0);
590 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
591 // Replace all uses. If any nodes become isomorphic to other nodes and
592 // are deleted, make sure to remove them from our worklist.
593 WorkListRemover DeadNodes(*this);
594 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
596 // Push the new node and any (possibly new) users onto the worklist.
597 AddToWorkList(TLO.New.getNode());
598 AddUsersToWorkList(TLO.New.getNode());
600 // Finally, if the node is now dead, remove it from the graph. The node
601 // may not be dead if the replacement process recursively simplified to
602 // something else needing this node.
603 if (TLO.Old.getNode()->use_empty()) {
604 removeFromWorkList(TLO.Old.getNode());
606 // If the operands of this node are only used by the node, they will now
607 // be dead. Make sure to visit them first to delete dead nodes early.
608 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
609 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
610 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
612 DAG.DeleteNode(TLO.Old.getNode());
616 /// SimplifyDemandedBits - Check the specified integer node value to see if
617 /// it can be simplified or if things it uses can be simplified by bit
618 /// propagation. If so, return true.
619 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
620 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
621 APInt KnownZero, KnownOne;
622 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
626 AddToWorkList(Op.getNode());
628 // Replace the old value with the new one.
630 DEBUG(dbgs() << "\nReplacing.2 ";
631 TLO.Old.getNode()->dump(&DAG);
632 dbgs() << "\nWith: ";
633 TLO.New.getNode()->dump(&DAG);
636 CommitTargetLoweringOpt(TLO);
640 static SDValue SExtPromoteOperand(SDValue Op, EVT PVT, SelectionDAG &DAG,
641 const TargetLowering &TLI);
642 static SDValue ZExtPromoteOperand(SDValue Op, EVT PVT, SelectionDAG &DAG,
643 const TargetLowering &TLI);
645 static SDValue PromoteOperand(SDValue Op, EVT PVT, SelectionDAG &DAG,
646 const TargetLowering &TLI) {
647 DebugLoc dl = Op.getDebugLoc();
648 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
649 ISD::LoadExtType ExtType =
650 ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD : LD->getExtensionType();
651 return DAG.getExtLoad(ExtType, dl, PVT,
652 LD->getChain(), LD->getBasePtr(),
653 LD->getSrcValue(), LD->getSrcValueOffset(),
654 LD->getMemoryVT(), LD->isVolatile(),
655 LD->isNonTemporal(), LD->getAlignment());
658 unsigned Opc = Op.getOpcode();
659 if (Opc == ISD::AssertSext)
660 return DAG.getNode(ISD::AssertSext, dl, PVT,
661 SExtPromoteOperand(Op.getOperand(0), PVT, DAG, TLI),
663 else if (Opc == ISD::AssertZext)
664 return DAG.getNode(ISD::AssertZext, dl, PVT,
665 ZExtPromoteOperand(Op.getOperand(0), PVT, DAG, TLI),
668 unsigned ExtOpc = ISD::ANY_EXTEND;
669 if (Opc == ISD::Constant)
670 // Zero extend things like i1, sign extend everything else. It shouldn't
671 // matter in theory which one we pick, but this tends to give better code?
672 // See DAGTypeLegalizer::PromoteIntRes_Constant.
674 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
675 if (!TLI.isOperationLegal(ExtOpc, PVT))
677 return DAG.getNode(ExtOpc, dl, PVT, Op);
680 static SDValue SExtPromoteOperand(SDValue Op, EVT PVT, SelectionDAG &DAG,
681 const TargetLowering &TLI) {
682 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
684 EVT OldVT = Op.getValueType();
685 DebugLoc dl = Op.getDebugLoc();
686 Op = PromoteOperand(Op, PVT, DAG, TLI);
687 if (Op.getNode() == 0)
689 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Op.getValueType(), Op,
690 DAG.getValueType(OldVT));
693 static SDValue ZExtPromoteOperand(SDValue Op, EVT PVT, SelectionDAG &DAG,
694 const TargetLowering &TLI) {
695 EVT OldVT = Op.getValueType();
696 DebugLoc dl = Op.getDebugLoc();
697 Op = PromoteOperand(Op, PVT, DAG, TLI);
698 if (Op.getNode() == 0)
700 return DAG.getZeroExtendInReg(Op, dl, OldVT);
703 /// PromoteIntBinOp - Promote the specified integer binary operation if the
704 /// target indicates it is beneficial. e.g. On x86, it's usually better to
705 /// promote i16 operations to i32 since i16 instructions are longer.
706 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
707 if (!LegalOperations)
710 EVT VT = Op.getValueType();
711 if (VT.isVector() || !VT.isInteger())
714 // If operation type is 'undesirable', e.g. i16 on x86, consider
716 unsigned Opc = Op.getOpcode();
717 if (TLI.isTypeDesirableForOp(Opc, VT))
721 // Consult target whether it is a good idea to promote this operation and
722 // what's the right type to promote it to.
723 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
724 assert(PVT != VT && "Don't know what type to promote to!");
726 bool isShift = (Opc == ISD::SHL) || (Opc == ISD::SRA) || (Opc == ISD::SRL);
727 SDValue N0 = Op.getOperand(0);
729 N0 = SExtPromoteOperand(Op.getOperand(0), PVT, DAG, TLI);
730 else if (Opc == ISD::SRL)
731 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT, DAG, TLI);
733 N0 = PromoteOperand(N0, PVT, DAG, TLI);
734 if (N0.getNode() == 0)
737 SDValue N1 = Op.getOperand(1);
739 N1 = PromoteOperand(N1, PVT, DAG, TLI);
740 if (N1.getNode() == 0)
742 AddToWorkList(N1.getNode());
744 AddToWorkList(N0.getNode());
746 DebugLoc dl = Op.getDebugLoc();
747 return DAG.getNode(ISD::TRUNCATE, dl, VT,
748 DAG.getNode(Op.getOpcode(), dl, PVT, N0, N1));
753 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
754 if (!LegalOperations)
757 EVT VT = Op.getValueType();
758 if (VT.isVector() || !VT.isInteger())
761 // If operation type is 'undesirable', e.g. i16 on x86, consider
763 unsigned Opc = Op.getOpcode();
764 if (TLI.isTypeDesirableForOp(Opc, VT))
768 // Consult target whether it is a good idea to promote this operation and
769 // what's the right type to promote it to.
770 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
771 assert(PVT != VT && "Don't know what type to promote to!");
772 // fold (aext (aext x)) -> (aext x)
773 // fold (aext (zext x)) -> (zext x)
774 // fold (aext (sext x)) -> (sext x)
775 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
780 bool DAGCombiner::PromoteLoad(SDValue Op) {
781 if (!LegalOperations)
784 EVT VT = Op.getValueType();
785 if (VT.isVector() || !VT.isInteger())
788 // If operation type is 'undesirable', e.g. i16 on x86, consider
790 unsigned Opc = Op.getOpcode();
791 if (TLI.isTypeDesirableForOp(Opc, VT))
795 // Consult target whether it is a good idea to promote this operation and
796 // what's the right type to promote it to.
797 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
798 assert(PVT != VT && "Don't know what type to promote to!");
800 DebugLoc dl = Op.getDebugLoc();
801 SDNode *N = Op.getNode();
802 LoadSDNode *LD = cast<LoadSDNode>(N);
803 ISD::LoadExtType ExtType =
804 ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD : LD->getExtensionType();
805 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
806 LD->getChain(), LD->getBasePtr(),
807 LD->getSrcValue(), LD->getSrcValueOffset(),
808 LD->getMemoryVT(), LD->isVolatile(),
809 LD->isNonTemporal(), LD->getAlignment());
810 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
812 DEBUG(dbgs() << "\nReplacing.x ";
814 dbgs() << "\nWith: ";
815 Result.getNode()->dump(&DAG);
817 WorkListRemover DeadNodes(*this);
818 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
819 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
820 removeFromWorkList(N);
828 //===----------------------------------------------------------------------===//
829 // Main DAG Combiner implementation
830 //===----------------------------------------------------------------------===//
832 void DAGCombiner::Run(CombineLevel AtLevel) {
833 // set the instance variables, so that the various visit routines may use it.
835 LegalOperations = Level >= NoIllegalOperations;
836 LegalTypes = Level >= NoIllegalTypes;
838 // Add all the dag nodes to the worklist.
839 WorkList.reserve(DAG.allnodes_size());
840 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
841 E = DAG.allnodes_end(); I != E; ++I)
842 WorkList.push_back(I);
844 // Create a dummy node (which is not added to allnodes), that adds a reference
845 // to the root node, preventing it from being deleted, and tracking any
846 // changes of the root.
847 HandleSDNode Dummy(DAG.getRoot());
849 // The root of the dag may dangle to deleted nodes until the dag combiner is
850 // done. Set it to null to avoid confusion.
851 DAG.setRoot(SDValue());
853 // while the worklist isn't empty, inspect the node on the end of it and
854 // try and combine it.
855 while (!WorkList.empty()) {
856 SDNode *N = WorkList.back();
859 // If N has no uses, it is dead. Make sure to revisit all N's operands once
860 // N is deleted from the DAG, since they too may now be dead or may have a
861 // reduced number of uses, allowing other xforms.
862 if (N->use_empty() && N != &Dummy) {
863 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
864 AddToWorkList(N->getOperand(i).getNode());
870 SDValue RV = combine(N);
872 if (RV.getNode() == 0)
877 // If we get back the same node we passed in, rather than a new node or
878 // zero, we know that the node must have defined multiple values and
879 // CombineTo was used. Since CombineTo takes care of the worklist
880 // mechanics for us, we have no work to do in this case.
881 if (RV.getNode() == N)
884 assert(N->getOpcode() != ISD::DELETED_NODE &&
885 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
886 "Node was deleted but visit returned new node!");
888 DEBUG(dbgs() << "\nReplacing.3 ";
890 dbgs() << "\nWith: ";
891 RV.getNode()->dump(&DAG);
893 WorkListRemover DeadNodes(*this);
894 if (N->getNumValues() == RV.getNode()->getNumValues())
895 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
897 assert(N->getValueType(0) == RV.getValueType() &&
898 N->getNumValues() == 1 && "Type mismatch");
900 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
903 // Push the new node and any users onto the worklist
904 AddToWorkList(RV.getNode());
905 AddUsersToWorkList(RV.getNode());
907 // Add any uses of the old node to the worklist in case this node is the
908 // last one that uses them. They may become dead after this node is
910 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
911 AddToWorkList(N->getOperand(i).getNode());
913 // Finally, if the node is now dead, remove it from the graph. The node
914 // may not be dead if the replacement process recursively simplified to
915 // something else needing this node.
916 if (N->use_empty()) {
917 // Nodes can be reintroduced into the worklist. Make sure we do not
918 // process a node that has been replaced.
919 removeFromWorkList(N);
921 // Finally, since the node is now dead, remove it from the graph.
926 // If the root changed (e.g. it was a dead load, update the root).
927 DAG.setRoot(Dummy.getValue());
930 SDValue DAGCombiner::visit(SDNode *N) {
931 switch(N->getOpcode()) {
933 case ISD::TokenFactor: return visitTokenFactor(N);
934 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
935 case ISD::ADD: return visitADD(N);
936 case ISD::SUB: return visitSUB(N);
937 case ISD::ADDC: return visitADDC(N);
938 case ISD::ADDE: return visitADDE(N);
939 case ISD::MUL: return visitMUL(N);
940 case ISD::SDIV: return visitSDIV(N);
941 case ISD::UDIV: return visitUDIV(N);
942 case ISD::SREM: return visitSREM(N);
943 case ISD::UREM: return visitUREM(N);
944 case ISD::MULHU: return visitMULHU(N);
945 case ISD::MULHS: return visitMULHS(N);
946 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
947 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
948 case ISD::SDIVREM: return visitSDIVREM(N);
949 case ISD::UDIVREM: return visitUDIVREM(N);
950 case ISD::AND: return visitAND(N);
951 case ISD::OR: return visitOR(N);
952 case ISD::XOR: return visitXOR(N);
953 case ISD::SHL: return visitSHL(N);
954 case ISD::SRA: return visitSRA(N);
955 case ISD::SRL: return visitSRL(N);
956 case ISD::ROTL: return visitROTL(N);
957 case ISD::ROTR: return visitROTR(N);
958 case ISD::CTLZ: return visitCTLZ(N);
959 case ISD::CTTZ: return visitCTTZ(N);
960 case ISD::CTPOP: return visitCTPOP(N);
961 case ISD::SELECT: return visitSELECT(N);
962 case ISD::SELECT_CC: return visitSELECT_CC(N);
963 case ISD::SETCC: return visitSETCC(N);
964 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
965 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
966 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
967 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
968 case ISD::TRUNCATE: return visitTRUNCATE(N);
969 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
970 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
971 case ISD::FADD: return visitFADD(N);
972 case ISD::FSUB: return visitFSUB(N);
973 case ISD::FMUL: return visitFMUL(N);
974 case ISD::FDIV: return visitFDIV(N);
975 case ISD::FREM: return visitFREM(N);
976 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
977 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
978 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
979 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
980 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
981 case ISD::FP_ROUND: return visitFP_ROUND(N);
982 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
983 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
984 case ISD::FNEG: return visitFNEG(N);
985 case ISD::FABS: return visitFABS(N);
986 case ISD::BRCOND: return visitBRCOND(N);
987 case ISD::BR_CC: return visitBR_CC(N);
988 case ISD::LOAD: return visitLOAD(N);
989 case ISD::STORE: return visitSTORE(N);
990 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
991 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
992 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
993 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
994 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
999 SDValue DAGCombiner::combine(SDNode *N) {
1000 SDValue RV = visit(N);
1002 // If nothing happened, try a target-specific DAG combine.
1003 if (RV.getNode() == 0) {
1004 assert(N->getOpcode() != ISD::DELETED_NODE &&
1005 "Node was deleted but visit returned NULL!");
1007 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1008 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1010 // Expose the DAG combiner to the target combiner impls.
1011 TargetLowering::DAGCombinerInfo
1012 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1014 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1018 // If N is a commutative binary node, try commuting it to enable more
1020 if (RV.getNode() == 0 &&
1021 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1022 N->getNumValues() == 1) {
1023 SDValue N0 = N->getOperand(0);
1024 SDValue N1 = N->getOperand(1);
1026 // Constant operands are canonicalized to RHS.
1027 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1028 SDValue Ops[] = { N1, N0 };
1029 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1032 return SDValue(CSENode, 0);
1039 /// getInputChainForNode - Given a node, return its input chain if it has one,
1040 /// otherwise return a null sd operand.
1041 static SDValue getInputChainForNode(SDNode *N) {
1042 if (unsigned NumOps = N->getNumOperands()) {
1043 if (N->getOperand(0).getValueType() == MVT::Other)
1044 return N->getOperand(0);
1045 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1046 return N->getOperand(NumOps-1);
1047 for (unsigned i = 1; i < NumOps-1; ++i)
1048 if (N->getOperand(i).getValueType() == MVT::Other)
1049 return N->getOperand(i);
1054 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1055 // If N has two operands, where one has an input chain equal to the other,
1056 // the 'other' chain is redundant.
1057 if (N->getNumOperands() == 2) {
1058 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1059 return N->getOperand(0);
1060 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1061 return N->getOperand(1);
1064 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1065 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1066 SmallPtrSet<SDNode*, 16> SeenOps;
1067 bool Changed = false; // If we should replace this token factor.
1069 // Start out with this token factor.
1072 // Iterate through token factors. The TFs grows when new token factors are
1074 for (unsigned i = 0; i < TFs.size(); ++i) {
1075 SDNode *TF = TFs[i];
1077 // Check each of the operands.
1078 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1079 SDValue Op = TF->getOperand(i);
1081 switch (Op.getOpcode()) {
1082 case ISD::EntryToken:
1083 // Entry tokens don't need to be added to the list. They are
1088 case ISD::TokenFactor:
1089 if (Op.hasOneUse() &&
1090 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1091 // Queue up for processing.
1092 TFs.push_back(Op.getNode());
1093 // Clean up in case the token factor is removed.
1094 AddToWorkList(Op.getNode());
1101 // Only add if it isn't already in the list.
1102 if (SeenOps.insert(Op.getNode()))
1113 // If we've change things around then replace token factor.
1116 // The entry token is the only possible outcome.
1117 Result = DAG.getEntryNode();
1119 // New and improved token factor.
1120 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1121 MVT::Other, &Ops[0], Ops.size());
1124 // Don't add users to work list.
1125 return CombineTo(N, Result, false);
1131 /// MERGE_VALUES can always be eliminated.
1132 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1133 WorkListRemover DeadNodes(*this);
1134 // Replacing results may cause a different MERGE_VALUES to suddenly
1135 // be CSE'd with N, and carry its uses with it. Iterate until no
1136 // uses remain, to ensure that the node can be safely deleted.
1138 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1139 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1141 } while (!N->use_empty());
1142 removeFromWorkList(N);
1144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1148 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1149 SelectionDAG &DAG) {
1150 EVT VT = N0.getValueType();
1151 SDValue N00 = N0.getOperand(0);
1152 SDValue N01 = N0.getOperand(1);
1153 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1155 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1156 isa<ConstantSDNode>(N00.getOperand(1))) {
1157 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1158 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1159 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1160 N00.getOperand(0), N01),
1161 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1162 N00.getOperand(1), N01));
1163 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1169 SDValue DAGCombiner::visitADD(SDNode *N) {
1170 SDValue N0 = N->getOperand(0);
1171 SDValue N1 = N->getOperand(1);
1172 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1173 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1174 EVT VT = N0.getValueType();
1177 if (VT.isVector()) {
1178 SDValue FoldedVOp = SimplifyVBinOp(N);
1179 if (FoldedVOp.getNode()) return FoldedVOp;
1182 // fold (add x, undef) -> undef
1183 if (N0.getOpcode() == ISD::UNDEF)
1185 if (N1.getOpcode() == ISD::UNDEF)
1187 // fold (add c1, c2) -> c1+c2
1189 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1190 // canonicalize constant to RHS
1192 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1193 // fold (add x, 0) -> x
1194 if (N1C && N1C->isNullValue())
1196 // fold (add Sym, c) -> Sym+c
1197 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1198 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1199 GA->getOpcode() == ISD::GlobalAddress)
1200 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1202 (uint64_t)N1C->getSExtValue());
1203 // fold ((c1-A)+c2) -> (c1+c2)-A
1204 if (N1C && N0.getOpcode() == ISD::SUB)
1205 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1206 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1207 DAG.getConstant(N1C->getAPIntValue()+
1208 N0C->getAPIntValue(), VT),
1211 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1212 if (RADD.getNode() != 0)
1214 // fold ((0-A) + B) -> B-A
1215 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1216 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1217 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1218 // fold (A + (0-B)) -> A-B
1219 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1220 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1221 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1222 // fold (A+(B-A)) -> B
1223 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1224 return N1.getOperand(0);
1225 // fold ((B-A)+A) -> B
1226 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1227 return N0.getOperand(0);
1228 // fold (A+(B-(A+C))) to (B-C)
1229 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1230 N0 == N1.getOperand(1).getOperand(0))
1231 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1232 N1.getOperand(1).getOperand(1));
1233 // fold (A+(B-(C+A))) to (B-C)
1234 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1235 N0 == N1.getOperand(1).getOperand(1))
1236 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1237 N1.getOperand(1).getOperand(0));
1238 // fold (A+((B-A)+or-C)) to (B+or-C)
1239 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1240 N1.getOperand(0).getOpcode() == ISD::SUB &&
1241 N0 == N1.getOperand(0).getOperand(1))
1242 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1243 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1245 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1246 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1247 SDValue N00 = N0.getOperand(0);
1248 SDValue N01 = N0.getOperand(1);
1249 SDValue N10 = N1.getOperand(0);
1250 SDValue N11 = N1.getOperand(1);
1252 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1253 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1254 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1255 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1258 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1259 return SDValue(N, 0);
1261 // fold (a+b) -> (a|b) iff a and b share no bits.
1262 if (VT.isInteger() && !VT.isVector()) {
1263 APInt LHSZero, LHSOne;
1264 APInt RHSZero, RHSOne;
1265 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1266 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1268 if (LHSZero.getBoolValue()) {
1269 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1271 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1272 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1273 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1274 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1275 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1279 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1280 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1281 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1282 if (Result.getNode()) return Result;
1284 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1285 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1286 if (Result.getNode()) return Result;
1289 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1290 if (N1.getOpcode() == ISD::SHL &&
1291 N1.getOperand(0).getOpcode() == ISD::SUB)
1292 if (ConstantSDNode *C =
1293 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1294 if (C->getAPIntValue() == 0)
1295 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1296 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1297 N1.getOperand(0).getOperand(1),
1299 if (N0.getOpcode() == ISD::SHL &&
1300 N0.getOperand(0).getOpcode() == ISD::SUB)
1301 if (ConstantSDNode *C =
1302 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1303 if (C->getAPIntValue() == 0)
1304 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1305 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1306 N0.getOperand(0).getOperand(1),
1309 return PromoteIntBinOp(SDValue(N, 0));
1312 SDValue DAGCombiner::visitADDC(SDNode *N) {
1313 SDValue N0 = N->getOperand(0);
1314 SDValue N1 = N->getOperand(1);
1315 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1316 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1317 EVT VT = N0.getValueType();
1319 // If the flag result is dead, turn this into an ADD.
1320 if (N->hasNUsesOfValue(0, 1))
1321 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1322 DAG.getNode(ISD::CARRY_FALSE,
1323 N->getDebugLoc(), MVT::Flag));
1325 // canonicalize constant to RHS.
1327 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1329 // fold (addc x, 0) -> x + no carry out
1330 if (N1C && N1C->isNullValue())
1331 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1332 N->getDebugLoc(), MVT::Flag));
1334 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1335 APInt LHSZero, LHSOne;
1336 APInt RHSZero, RHSOne;
1337 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1338 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1340 if (LHSZero.getBoolValue()) {
1341 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1343 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1344 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1345 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1346 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1347 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1348 DAG.getNode(ISD::CARRY_FALSE,
1349 N->getDebugLoc(), MVT::Flag));
1355 SDValue DAGCombiner::visitADDE(SDNode *N) {
1356 SDValue N0 = N->getOperand(0);
1357 SDValue N1 = N->getOperand(1);
1358 SDValue CarryIn = N->getOperand(2);
1359 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1360 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1362 // canonicalize constant to RHS
1364 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1367 // fold (adde x, y, false) -> (addc x, y)
1368 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1369 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1374 SDValue DAGCombiner::visitSUB(SDNode *N) {
1375 SDValue N0 = N->getOperand(0);
1376 SDValue N1 = N->getOperand(1);
1377 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1378 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1379 EVT VT = N0.getValueType();
1382 if (VT.isVector()) {
1383 SDValue FoldedVOp = SimplifyVBinOp(N);
1384 if (FoldedVOp.getNode()) return FoldedVOp;
1387 // fold (sub x, x) -> 0
1389 return DAG.getConstant(0, N->getValueType(0));
1390 // fold (sub c1, c2) -> c1-c2
1392 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1393 // fold (sub x, c) -> (add x, -c)
1395 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1396 DAG.getConstant(-N1C->getAPIntValue(), VT));
1397 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1398 if (N0C && N0C->isAllOnesValue())
1399 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1400 // fold (A+B)-A -> B
1401 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1402 return N0.getOperand(1);
1403 // fold (A+B)-B -> A
1404 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1405 return N0.getOperand(0);
1406 // fold ((A+(B+or-C))-B) -> A+or-C
1407 if (N0.getOpcode() == ISD::ADD &&
1408 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1409 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1410 N0.getOperand(1).getOperand(0) == N1)
1411 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1412 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1413 // fold ((A+(C+B))-B) -> A+C
1414 if (N0.getOpcode() == ISD::ADD &&
1415 N0.getOperand(1).getOpcode() == ISD::ADD &&
1416 N0.getOperand(1).getOperand(1) == N1)
1417 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1418 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1419 // fold ((A-(B-C))-C) -> A-B
1420 if (N0.getOpcode() == ISD::SUB &&
1421 N0.getOperand(1).getOpcode() == ISD::SUB &&
1422 N0.getOperand(1).getOperand(1) == N1)
1423 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1424 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1426 // If either operand of a sub is undef, the result is undef
1427 if (N0.getOpcode() == ISD::UNDEF)
1429 if (N1.getOpcode() == ISD::UNDEF)
1432 // If the relocation model supports it, consider symbol offsets.
1433 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1434 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1435 // fold (sub Sym, c) -> Sym-c
1436 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1437 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1439 (uint64_t)N1C->getSExtValue());
1440 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1441 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1442 if (GA->getGlobal() == GB->getGlobal())
1443 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1447 return PromoteIntBinOp(SDValue(N, 0));
1450 SDValue DAGCombiner::visitMUL(SDNode *N) {
1451 SDValue N0 = N->getOperand(0);
1452 SDValue N1 = N->getOperand(1);
1453 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1454 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1455 EVT VT = N0.getValueType();
1458 if (VT.isVector()) {
1459 SDValue FoldedVOp = SimplifyVBinOp(N);
1460 if (FoldedVOp.getNode()) return FoldedVOp;
1463 // fold (mul x, undef) -> 0
1464 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1465 return DAG.getConstant(0, VT);
1466 // fold (mul c1, c2) -> c1*c2
1468 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1469 // canonicalize constant to RHS
1471 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1472 // fold (mul x, 0) -> 0
1473 if (N1C && N1C->isNullValue())
1475 // fold (mul x, -1) -> 0-x
1476 if (N1C && N1C->isAllOnesValue())
1477 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1478 DAG.getConstant(0, VT), N0);
1479 // fold (mul x, (1 << c)) -> x << c
1480 if (N1C && N1C->getAPIntValue().isPowerOf2())
1481 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1482 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1483 getShiftAmountTy()));
1484 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1485 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1486 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1487 // FIXME: If the input is something that is easily negated (e.g. a
1488 // single-use add), we should put the negate there.
1489 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1490 DAG.getConstant(0, VT),
1491 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1492 DAG.getConstant(Log2Val, getShiftAmountTy())));
1494 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1495 if (N1C && N0.getOpcode() == ISD::SHL &&
1496 isa<ConstantSDNode>(N0.getOperand(1))) {
1497 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1498 N1, N0.getOperand(1));
1499 AddToWorkList(C3.getNode());
1500 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1501 N0.getOperand(0), C3);
1504 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1507 SDValue Sh(0,0), Y(0,0);
1508 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1509 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1510 N0.getNode()->hasOneUse()) {
1512 } else if (N1.getOpcode() == ISD::SHL &&
1513 isa<ConstantSDNode>(N1.getOperand(1)) &&
1514 N1.getNode()->hasOneUse()) {
1519 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1520 Sh.getOperand(0), Y);
1521 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1522 Mul, Sh.getOperand(1));
1526 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1527 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1528 isa<ConstantSDNode>(N0.getOperand(1)))
1529 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1530 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1531 N0.getOperand(0), N1),
1532 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1533 N0.getOperand(1), N1));
1536 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1537 if (RMUL.getNode() != 0)
1540 return PromoteIntBinOp(SDValue(N, 0));
1543 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1544 SDValue N0 = N->getOperand(0);
1545 SDValue N1 = N->getOperand(1);
1546 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1547 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1548 EVT VT = N->getValueType(0);
1551 if (VT.isVector()) {
1552 SDValue FoldedVOp = SimplifyVBinOp(N);
1553 if (FoldedVOp.getNode()) return FoldedVOp;
1556 // fold (sdiv c1, c2) -> c1/c2
1557 if (N0C && N1C && !N1C->isNullValue())
1558 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1559 // fold (sdiv X, 1) -> X
1560 if (N1C && N1C->getSExtValue() == 1LL)
1562 // fold (sdiv X, -1) -> 0-X
1563 if (N1C && N1C->isAllOnesValue())
1564 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1565 DAG.getConstant(0, VT), N0);
1566 // If we know the sign bits of both operands are zero, strength reduce to a
1567 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1568 if (!VT.isVector()) {
1569 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1570 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1573 // fold (sdiv X, pow2) -> simple ops after legalize
1574 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1575 (isPowerOf2_64(N1C->getSExtValue()) ||
1576 isPowerOf2_64(-N1C->getSExtValue()))) {
1577 // If dividing by powers of two is cheap, then don't perform the following
1579 if (TLI.isPow2DivCheap())
1582 int64_t pow2 = N1C->getSExtValue();
1583 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1584 unsigned lg2 = Log2_64(abs2);
1586 // Splat the sign bit into the register
1587 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1588 DAG.getConstant(VT.getSizeInBits()-1,
1589 getShiftAmountTy()));
1590 AddToWorkList(SGN.getNode());
1592 // Add (N0 < 0) ? abs2 - 1 : 0;
1593 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1594 DAG.getConstant(VT.getSizeInBits() - lg2,
1595 getShiftAmountTy()));
1596 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1597 AddToWorkList(SRL.getNode());
1598 AddToWorkList(ADD.getNode()); // Divide by pow2
1599 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1600 DAG.getConstant(lg2, getShiftAmountTy()));
1602 // If we're dividing by a positive value, we're done. Otherwise, we must
1603 // negate the result.
1607 AddToWorkList(SRA.getNode());
1608 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1609 DAG.getConstant(0, VT), SRA);
1612 // if integer divide is expensive and we satisfy the requirements, emit an
1613 // alternate sequence.
1614 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1615 !TLI.isIntDivCheap()) {
1616 SDValue Op = BuildSDIV(N);
1617 if (Op.getNode()) return Op;
1621 if (N0.getOpcode() == ISD::UNDEF)
1622 return DAG.getConstant(0, VT);
1623 // X / undef -> undef
1624 if (N1.getOpcode() == ISD::UNDEF)
1630 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1631 SDValue N0 = N->getOperand(0);
1632 SDValue N1 = N->getOperand(1);
1633 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1634 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1635 EVT VT = N->getValueType(0);
1638 if (VT.isVector()) {
1639 SDValue FoldedVOp = SimplifyVBinOp(N);
1640 if (FoldedVOp.getNode()) return FoldedVOp;
1643 // fold (udiv c1, c2) -> c1/c2
1644 if (N0C && N1C && !N1C->isNullValue())
1645 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1646 // fold (udiv x, (1 << c)) -> x >>u c
1647 if (N1C && N1C->getAPIntValue().isPowerOf2())
1648 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1649 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1650 getShiftAmountTy()));
1651 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1652 if (N1.getOpcode() == ISD::SHL) {
1653 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1654 if (SHC->getAPIntValue().isPowerOf2()) {
1655 EVT ADDVT = N1.getOperand(1).getValueType();
1656 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1658 DAG.getConstant(SHC->getAPIntValue()
1661 AddToWorkList(Add.getNode());
1662 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1666 // fold (udiv x, c) -> alternate
1667 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1668 SDValue Op = BuildUDIV(N);
1669 if (Op.getNode()) return Op;
1673 if (N0.getOpcode() == ISD::UNDEF)
1674 return DAG.getConstant(0, VT);
1675 // X / undef -> undef
1676 if (N1.getOpcode() == ISD::UNDEF)
1682 SDValue DAGCombiner::visitSREM(SDNode *N) {
1683 SDValue N0 = N->getOperand(0);
1684 SDValue N1 = N->getOperand(1);
1685 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1686 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1687 EVT VT = N->getValueType(0);
1689 // fold (srem c1, c2) -> c1%c2
1690 if (N0C && N1C && !N1C->isNullValue())
1691 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1692 // If we know the sign bits of both operands are zero, strength reduce to a
1693 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1694 if (!VT.isVector()) {
1695 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1696 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1699 // If X/C can be simplified by the division-by-constant logic, lower
1700 // X%C to the equivalent of X-X/C*C.
1701 if (N1C && !N1C->isNullValue()) {
1702 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1703 AddToWorkList(Div.getNode());
1704 SDValue OptimizedDiv = combine(Div.getNode());
1705 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1706 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1708 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1709 AddToWorkList(Mul.getNode());
1715 if (N0.getOpcode() == ISD::UNDEF)
1716 return DAG.getConstant(0, VT);
1717 // X % undef -> undef
1718 if (N1.getOpcode() == ISD::UNDEF)
1724 SDValue DAGCombiner::visitUREM(SDNode *N) {
1725 SDValue N0 = N->getOperand(0);
1726 SDValue N1 = N->getOperand(1);
1727 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1728 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1729 EVT VT = N->getValueType(0);
1731 // fold (urem c1, c2) -> c1%c2
1732 if (N0C && N1C && !N1C->isNullValue())
1733 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1734 // fold (urem x, pow2) -> (and x, pow2-1)
1735 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1736 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1737 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1738 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1739 if (N1.getOpcode() == ISD::SHL) {
1740 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1741 if (SHC->getAPIntValue().isPowerOf2()) {
1743 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1744 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1746 AddToWorkList(Add.getNode());
1747 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1752 // If X/C can be simplified by the division-by-constant logic, lower
1753 // X%C to the equivalent of X-X/C*C.
1754 if (N1C && !N1C->isNullValue()) {
1755 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1756 AddToWorkList(Div.getNode());
1757 SDValue OptimizedDiv = combine(Div.getNode());
1758 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1759 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1761 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1762 AddToWorkList(Mul.getNode());
1768 if (N0.getOpcode() == ISD::UNDEF)
1769 return DAG.getConstant(0, VT);
1770 // X % undef -> undef
1771 if (N1.getOpcode() == ISD::UNDEF)
1777 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1778 SDValue N0 = N->getOperand(0);
1779 SDValue N1 = N->getOperand(1);
1780 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1781 EVT VT = N->getValueType(0);
1783 // fold (mulhs x, 0) -> 0
1784 if (N1C && N1C->isNullValue())
1786 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1787 if (N1C && N1C->getAPIntValue() == 1)
1788 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1789 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1790 getShiftAmountTy()));
1791 // fold (mulhs x, undef) -> 0
1792 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1793 return DAG.getConstant(0, VT);
1798 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1799 SDValue N0 = N->getOperand(0);
1800 SDValue N1 = N->getOperand(1);
1801 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1802 EVT VT = N->getValueType(0);
1804 // fold (mulhu x, 0) -> 0
1805 if (N1C && N1C->isNullValue())
1807 // fold (mulhu x, 1) -> 0
1808 if (N1C && N1C->getAPIntValue() == 1)
1809 return DAG.getConstant(0, N0.getValueType());
1810 // fold (mulhu x, undef) -> 0
1811 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1812 return DAG.getConstant(0, VT);
1817 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1818 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1819 /// that are being performed. Return true if a simplification was made.
1821 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1823 // If the high half is not needed, just compute the low half.
1824 bool HiExists = N->hasAnyUseOfValue(1);
1826 (!LegalOperations ||
1827 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1828 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1829 N->op_begin(), N->getNumOperands());
1830 return CombineTo(N, Res, Res);
1833 // If the low half is not needed, just compute the high half.
1834 bool LoExists = N->hasAnyUseOfValue(0);
1836 (!LegalOperations ||
1837 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1838 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1839 N->op_begin(), N->getNumOperands());
1840 return CombineTo(N, Res, Res);
1843 // If both halves are used, return as it is.
1844 if (LoExists && HiExists)
1847 // If the two computed results can be simplified separately, separate them.
1849 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1850 N->op_begin(), N->getNumOperands());
1851 AddToWorkList(Lo.getNode());
1852 SDValue LoOpt = combine(Lo.getNode());
1853 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1854 (!LegalOperations ||
1855 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1856 return CombineTo(N, LoOpt, LoOpt);
1860 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1861 N->op_begin(), N->getNumOperands());
1862 AddToWorkList(Hi.getNode());
1863 SDValue HiOpt = combine(Hi.getNode());
1864 if (HiOpt.getNode() && HiOpt != Hi &&
1865 (!LegalOperations ||
1866 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1867 return CombineTo(N, HiOpt, HiOpt);
1873 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1874 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1875 if (Res.getNode()) return Res;
1880 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1881 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1882 if (Res.getNode()) return Res;
1887 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1888 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1889 if (Res.getNode()) return Res;
1894 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1895 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1896 if (Res.getNode()) return Res;
1901 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1902 /// two operands of the same opcode, try to simplify it.
1903 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1904 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1905 EVT VT = N0.getValueType();
1906 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1908 // Bail early if none of these transforms apply.
1909 if (N0.getNode()->getNumOperands() == 0) return SDValue();
1911 // For each of OP in AND/OR/XOR:
1912 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1913 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1914 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1915 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1917 // do not sink logical op inside of a vector extend, since it may combine
1919 EVT Op0VT = N0.getOperand(0).getValueType();
1920 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
1921 N0.getOpcode() == ISD::SIGN_EXTEND ||
1922 // Avoid infinite looping with PromoteIntBinOp.
1923 (N0.getOpcode() == ISD::ANY_EXTEND &&
1924 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
1925 (N0.getOpcode() == ISD::TRUNCATE && TLI.isTypeLegal(Op0VT))) &&
1927 Op0VT == N1.getOperand(0).getValueType() &&
1928 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
1929 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1930 N0.getOperand(0).getValueType(),
1931 N0.getOperand(0), N1.getOperand(0));
1932 AddToWorkList(ORNode.getNode());
1933 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
1936 // For each of OP in SHL/SRL/SRA/AND...
1937 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1938 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1939 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1940 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1941 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1942 N0.getOperand(1) == N1.getOperand(1)) {
1943 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1944 N0.getOperand(0).getValueType(),
1945 N0.getOperand(0), N1.getOperand(0));
1946 AddToWorkList(ORNode.getNode());
1947 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
1948 ORNode, N0.getOperand(1));
1954 SDValue DAGCombiner::visitAND(SDNode *N) {
1955 SDValue N0 = N->getOperand(0);
1956 SDValue N1 = N->getOperand(1);
1957 SDValue LL, LR, RL, RR, CC0, CC1;
1958 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1959 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1960 EVT VT = N1.getValueType();
1961 unsigned BitWidth = VT.getScalarType().getSizeInBits();
1964 if (VT.isVector()) {
1965 SDValue FoldedVOp = SimplifyVBinOp(N);
1966 if (FoldedVOp.getNode()) return FoldedVOp;
1969 // fold (and x, undef) -> 0
1970 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1971 return DAG.getConstant(0, VT);
1972 // fold (and c1, c2) -> c1&c2
1974 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1975 // canonicalize constant to RHS
1977 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
1978 // fold (and x, -1) -> x
1979 if (N1C && N1C->isAllOnesValue())
1981 // if (and x, c) is known to be zero, return 0
1982 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1983 APInt::getAllOnesValue(BitWidth)))
1984 return DAG.getConstant(0, VT);
1986 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
1987 if (RAND.getNode() != 0)
1989 // fold (and (or x, C), D) -> D if (C & D) == D
1990 if (N1C && N0.getOpcode() == ISD::OR)
1991 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1992 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1994 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1995 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1996 SDValue N0Op0 = N0.getOperand(0);
1997 APInt Mask = ~N1C->getAPIntValue();
1998 Mask.trunc(N0Op0.getValueSizeInBits());
1999 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2000 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2001 N0.getValueType(), N0Op0);
2003 // Replace uses of the AND with uses of the Zero extend node.
2006 // We actually want to replace all uses of the any_extend with the
2007 // zero_extend, to avoid duplicating things. This will later cause this
2008 // AND to be folded.
2009 CombineTo(N0.getNode(), Zext);
2010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2013 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2014 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2015 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2016 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2018 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2019 LL.getValueType().isInteger()) {
2020 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2021 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2022 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2023 LR.getValueType(), LL, RL);
2024 AddToWorkList(ORNode.getNode());
2025 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2027 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2028 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2029 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2030 LR.getValueType(), LL, RL);
2031 AddToWorkList(ANDNode.getNode());
2032 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2034 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2035 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2036 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2037 LR.getValueType(), LL, RL);
2038 AddToWorkList(ORNode.getNode());
2039 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2042 // canonicalize equivalent to ll == rl
2043 if (LL == RR && LR == RL) {
2044 Op1 = ISD::getSetCCSwappedOperands(Op1);
2047 if (LL == RL && LR == RR) {
2048 bool isInteger = LL.getValueType().isInteger();
2049 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2050 if (Result != ISD::SETCC_INVALID &&
2051 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2052 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2057 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2058 if (N0.getOpcode() == N1.getOpcode()) {
2059 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2060 if (Tmp.getNode()) return Tmp;
2063 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2064 // fold (and (sra)) -> (and (srl)) when possible.
2065 if (!VT.isVector() &&
2066 SimplifyDemandedBits(SDValue(N, 0)))
2067 return SDValue(N, 0);
2069 // fold (zext_inreg (extload x)) -> (zextload x)
2070 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2071 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2072 EVT MemVT = LN0->getMemoryVT();
2073 // If we zero all the possible extended bits, then we can turn this into
2074 // a zextload if we are running before legalize or the operation is legal.
2075 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2076 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2077 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2078 ((!LegalOperations && !LN0->isVolatile()) ||
2079 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2080 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2081 LN0->getChain(), LN0->getBasePtr(),
2083 LN0->getSrcValueOffset(), MemVT,
2084 LN0->isVolatile(), LN0->isNonTemporal(),
2085 LN0->getAlignment());
2087 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2088 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2091 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2092 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2094 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2095 EVT MemVT = LN0->getMemoryVT();
2096 // If we zero all the possible extended bits, then we can turn this into
2097 // a zextload if we are running before legalize or the operation is legal.
2098 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2099 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2100 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2101 ((!LegalOperations && !LN0->isVolatile()) ||
2102 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2103 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2105 LN0->getBasePtr(), LN0->getSrcValue(),
2106 LN0->getSrcValueOffset(), MemVT,
2107 LN0->isVolatile(), LN0->isNonTemporal(),
2108 LN0->getAlignment());
2110 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2111 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2115 // fold (and (load x), 255) -> (zextload x, i8)
2116 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2117 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2118 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2119 (N0.getOpcode() == ISD::ANY_EXTEND &&
2120 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2121 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2122 LoadSDNode *LN0 = HasAnyExt
2123 ? cast<LoadSDNode>(N0.getOperand(0))
2124 : cast<LoadSDNode>(N0);
2125 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2126 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2127 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2128 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2129 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2130 EVT LoadedVT = LN0->getMemoryVT();
2132 if (ExtVT == LoadedVT &&
2133 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2134 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2137 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2138 LN0->getChain(), LN0->getBasePtr(),
2139 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2140 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2141 LN0->getAlignment());
2143 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2147 // Do not change the width of a volatile load.
2148 // Do not generate loads of non-round integer types since these can
2149 // be expensive (and would be wrong if the type is not byte sized).
2150 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2151 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2152 EVT PtrType = LN0->getOperand(1).getValueType();
2154 unsigned Alignment = LN0->getAlignment();
2155 SDValue NewPtr = LN0->getBasePtr();
2157 // For big endian targets, we need to add an offset to the pointer
2158 // to load the correct bytes. For little endian systems, we merely
2159 // need to read fewer bytes from the same pointer.
2160 if (TLI.isBigEndian()) {
2161 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2162 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2163 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2164 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2165 NewPtr, DAG.getConstant(PtrOff, PtrType));
2166 Alignment = MinAlign(Alignment, PtrOff);
2169 AddToWorkList(NewPtr.getNode());
2171 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2173 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2174 LN0->getChain(), NewPtr,
2175 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2176 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2179 CombineTo(LN0, Load, Load.getValue(1));
2180 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2186 return PromoteIntBinOp(SDValue(N, 0));
2189 SDValue DAGCombiner::visitOR(SDNode *N) {
2190 SDValue N0 = N->getOperand(0);
2191 SDValue N1 = N->getOperand(1);
2192 SDValue LL, LR, RL, RR, CC0, CC1;
2193 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2194 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2195 EVT VT = N1.getValueType();
2198 if (VT.isVector()) {
2199 SDValue FoldedVOp = SimplifyVBinOp(N);
2200 if (FoldedVOp.getNode()) return FoldedVOp;
2203 // fold (or x, undef) -> -1
2204 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) {
2205 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2206 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2208 // fold (or c1, c2) -> c1|c2
2210 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2211 // canonicalize constant to RHS
2213 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2214 // fold (or x, 0) -> x
2215 if (N1C && N1C->isNullValue())
2217 // fold (or x, -1) -> -1
2218 if (N1C && N1C->isAllOnesValue())
2220 // fold (or x, c) -> c iff (x & ~c) == 0
2221 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2224 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2225 if (ROR.getNode() != 0)
2227 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2228 // iff (c1 & c2) == 0.
2229 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2230 isa<ConstantSDNode>(N0.getOperand(1))) {
2231 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2232 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2233 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2234 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2235 N0.getOperand(0), N1),
2236 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2238 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2239 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2240 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2241 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2243 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2244 LL.getValueType().isInteger()) {
2245 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2246 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2247 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2248 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2249 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2250 LR.getValueType(), LL, RL);
2251 AddToWorkList(ORNode.getNode());
2252 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2254 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2255 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2256 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2257 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2258 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2259 LR.getValueType(), LL, RL);
2260 AddToWorkList(ANDNode.getNode());
2261 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2264 // canonicalize equivalent to ll == rl
2265 if (LL == RR && LR == RL) {
2266 Op1 = ISD::getSetCCSwappedOperands(Op1);
2269 if (LL == RL && LR == RR) {
2270 bool isInteger = LL.getValueType().isInteger();
2271 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2272 if (Result != ISD::SETCC_INVALID &&
2273 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2274 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2279 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2280 if (N0.getOpcode() == N1.getOpcode()) {
2281 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2282 if (Tmp.getNode()) return Tmp;
2285 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2286 if (N0.getOpcode() == ISD::AND &&
2287 N1.getOpcode() == ISD::AND &&
2288 N0.getOperand(1).getOpcode() == ISD::Constant &&
2289 N1.getOperand(1).getOpcode() == ISD::Constant &&
2290 // Don't increase # computations.
2291 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2292 // We can only do this xform if we know that bits from X that are set in C2
2293 // but not in C1 are already zero. Likewise for Y.
2294 const APInt &LHSMask =
2295 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2296 const APInt &RHSMask =
2297 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2299 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2300 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2301 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2302 N0.getOperand(0), N1.getOperand(0));
2303 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2304 DAG.getConstant(LHSMask | RHSMask, VT));
2308 // See if this is some rotate idiom.
2309 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2310 return SDValue(Rot, 0);
2312 return PromoteIntBinOp(SDValue(N, 0));
2315 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2316 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2317 if (Op.getOpcode() == ISD::AND) {
2318 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2319 Mask = Op.getOperand(1);
2320 Op = Op.getOperand(0);
2326 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2334 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2335 // idioms for rotate, and if the target supports rotation instructions, generate
2337 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2338 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2339 EVT VT = LHS.getValueType();
2340 if (!TLI.isTypeLegal(VT)) return 0;
2342 // The target must have at least one rotate flavor.
2343 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2344 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2345 if (!HasROTL && !HasROTR) return 0;
2347 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2348 SDValue LHSShift; // The shift.
2349 SDValue LHSMask; // AND value if any.
2350 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2351 return 0; // Not part of a rotate.
2353 SDValue RHSShift; // The shift.
2354 SDValue RHSMask; // AND value if any.
2355 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2356 return 0; // Not part of a rotate.
2358 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2359 return 0; // Not shifting the same value.
2361 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2362 return 0; // Shifts must disagree.
2364 // Canonicalize shl to left side in a shl/srl pair.
2365 if (RHSShift.getOpcode() == ISD::SHL) {
2366 std::swap(LHS, RHS);
2367 std::swap(LHSShift, RHSShift);
2368 std::swap(LHSMask , RHSMask );
2371 unsigned OpSizeInBits = VT.getSizeInBits();
2372 SDValue LHSShiftArg = LHSShift.getOperand(0);
2373 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2374 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2376 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2377 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2378 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2379 RHSShiftAmt.getOpcode() == ISD::Constant) {
2380 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2381 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2382 if ((LShVal + RShVal) != OpSizeInBits)
2387 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2389 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2391 // If there is an AND of either shifted operand, apply it to the result.
2392 if (LHSMask.getNode() || RHSMask.getNode()) {
2393 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2395 if (LHSMask.getNode()) {
2396 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2397 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2399 if (RHSMask.getNode()) {
2400 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2401 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2404 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2407 return Rot.getNode();
2410 // If there is a mask here, and we have a variable shift, we can't be sure
2411 // that we're masking out the right stuff.
2412 if (LHSMask.getNode() || RHSMask.getNode())
2415 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2416 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2417 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2418 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2419 if (ConstantSDNode *SUBC =
2420 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2421 if (SUBC->getAPIntValue() == OpSizeInBits) {
2423 return DAG.getNode(ISD::ROTL, DL, VT,
2424 LHSShiftArg, LHSShiftAmt).getNode();
2426 return DAG.getNode(ISD::ROTR, DL, VT,
2427 LHSShiftArg, RHSShiftAmt).getNode();
2432 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2433 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2434 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2435 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2436 if (ConstantSDNode *SUBC =
2437 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2438 if (SUBC->getAPIntValue() == OpSizeInBits) {
2440 return DAG.getNode(ISD::ROTR, DL, VT,
2441 LHSShiftArg, RHSShiftAmt).getNode();
2443 return DAG.getNode(ISD::ROTL, DL, VT,
2444 LHSShiftArg, LHSShiftAmt).getNode();
2449 // Look for sign/zext/any-extended or truncate cases:
2450 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2451 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2452 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2453 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2454 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2455 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2456 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2457 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2458 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2459 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2460 if (RExtOp0.getOpcode() == ISD::SUB &&
2461 RExtOp0.getOperand(1) == LExtOp0) {
2462 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2464 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2465 // (rotr x, (sub 32, y))
2466 if (ConstantSDNode *SUBC =
2467 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2468 if (SUBC->getAPIntValue() == OpSizeInBits) {
2469 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2471 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2474 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2475 RExtOp0 == LExtOp0.getOperand(1)) {
2476 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2478 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2479 // (rotl x, (sub 32, y))
2480 if (ConstantSDNode *SUBC =
2481 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2482 if (SUBC->getAPIntValue() == OpSizeInBits) {
2483 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2485 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2494 SDValue DAGCombiner::visitXOR(SDNode *N) {
2495 SDValue N0 = N->getOperand(0);
2496 SDValue N1 = N->getOperand(1);
2497 SDValue LHS, RHS, CC;
2498 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2499 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2500 EVT VT = N0.getValueType();
2503 if (VT.isVector()) {
2504 SDValue FoldedVOp = SimplifyVBinOp(N);
2505 if (FoldedVOp.getNode()) return FoldedVOp;
2508 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2509 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2510 return DAG.getConstant(0, VT);
2511 // fold (xor x, undef) -> undef
2512 if (N0.getOpcode() == ISD::UNDEF)
2514 if (N1.getOpcode() == ISD::UNDEF)
2516 // fold (xor c1, c2) -> c1^c2
2518 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2519 // canonicalize constant to RHS
2521 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2522 // fold (xor x, 0) -> x
2523 if (N1C && N1C->isNullValue())
2526 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2527 if (RXOR.getNode() != 0)
2530 // fold !(x cc y) -> (x !cc y)
2531 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2532 bool isInt = LHS.getValueType().isInteger();
2533 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2536 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2537 switch (N0.getOpcode()) {
2539 llvm_unreachable("Unhandled SetCC Equivalent!");
2541 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2542 case ISD::SELECT_CC:
2543 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2544 N0.getOperand(3), NotCC);
2549 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2550 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2551 N0.getNode()->hasOneUse() &&
2552 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2553 SDValue V = N0.getOperand(0);
2554 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2555 DAG.getConstant(1, V.getValueType()));
2556 AddToWorkList(V.getNode());
2557 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2560 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2561 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2562 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2563 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2564 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2565 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2566 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2567 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2568 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2569 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2572 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2573 if (N1C && N1C->isAllOnesValue() &&
2574 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2575 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2576 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2577 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2578 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2579 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2580 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2581 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2584 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2585 if (N1C && N0.getOpcode() == ISD::XOR) {
2586 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2587 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2589 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2590 DAG.getConstant(N1C->getAPIntValue() ^
2591 N00C->getAPIntValue(), VT));
2593 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2594 DAG.getConstant(N1C->getAPIntValue() ^
2595 N01C->getAPIntValue(), VT));
2597 // fold (xor x, x) -> 0
2599 if (!VT.isVector()) {
2600 return DAG.getConstant(0, VT);
2601 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2602 // Produce a vector of zeros.
2603 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2604 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2605 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2606 &Ops[0], Ops.size());
2610 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2611 if (N0.getOpcode() == N1.getOpcode()) {
2612 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2613 if (Tmp.getNode()) return Tmp;
2616 // Simplify the expression using non-local knowledge.
2617 if (!VT.isVector() &&
2618 SimplifyDemandedBits(SDValue(N, 0)))
2619 return SDValue(N, 0);
2621 return PromoteIntBinOp(SDValue(N, 0));
2624 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2625 /// the shift amount is a constant.
2626 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2627 SDNode *LHS = N->getOperand(0).getNode();
2628 if (!LHS->hasOneUse()) return SDValue();
2630 // We want to pull some binops through shifts, so that we have (and (shift))
2631 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2632 // thing happens with address calculations, so it's important to canonicalize
2634 bool HighBitSet = false; // Can we transform this if the high bit is set?
2636 switch (LHS->getOpcode()) {
2637 default: return SDValue();
2640 HighBitSet = false; // We can only transform sra if the high bit is clear.
2643 HighBitSet = true; // We can only transform sra if the high bit is set.
2646 if (N->getOpcode() != ISD::SHL)
2647 return SDValue(); // only shl(add) not sr[al](add).
2648 HighBitSet = false; // We can only transform sra if the high bit is clear.
2652 // We require the RHS of the binop to be a constant as well.
2653 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2654 if (!BinOpCst) return SDValue();
2656 // FIXME: disable this unless the input to the binop is a shift by a constant.
2657 // If it is not a shift, it pessimizes some common cases like:
2659 // void foo(int *X, int i) { X[i & 1235] = 1; }
2660 // int bar(int *X, int i) { return X[i & 255]; }
2661 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2662 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2663 BinOpLHSVal->getOpcode() != ISD::SRA &&
2664 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2665 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2668 EVT VT = N->getValueType(0);
2670 // If this is a signed shift right, and the high bit is modified by the
2671 // logical operation, do not perform the transformation. The highBitSet
2672 // boolean indicates the value of the high bit of the constant which would
2673 // cause it to be modified for this operation.
2674 if (N->getOpcode() == ISD::SRA) {
2675 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2676 if (BinOpRHSSignSet != HighBitSet)
2680 // Fold the constants, shifting the binop RHS by the shift amount.
2681 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2683 LHS->getOperand(1), N->getOperand(1));
2685 // Create the new shift.
2686 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2687 VT, LHS->getOperand(0), N->getOperand(1));
2689 // Create the new binop.
2690 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2693 SDValue DAGCombiner::visitSHL(SDNode *N) {
2694 SDValue N0 = N->getOperand(0);
2695 SDValue N1 = N->getOperand(1);
2696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2698 EVT VT = N0.getValueType();
2699 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2701 // fold (shl c1, c2) -> c1<<c2
2703 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2704 // fold (shl 0, x) -> 0
2705 if (N0C && N0C->isNullValue())
2707 // fold (shl x, c >= size(x)) -> undef
2708 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2709 return DAG.getUNDEF(VT);
2710 // fold (shl x, 0) -> x
2711 if (N1C && N1C->isNullValue())
2713 // if (shl x, c) is known to be zero, return 0
2714 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2715 APInt::getAllOnesValue(OpSizeInBits)))
2716 return DAG.getConstant(0, VT);
2717 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2718 if (N1.getOpcode() == ISD::TRUNCATE &&
2719 N1.getOperand(0).getOpcode() == ISD::AND &&
2720 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2721 SDValue N101 = N1.getOperand(0).getOperand(1);
2722 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2723 EVT TruncVT = N1.getValueType();
2724 SDValue N100 = N1.getOperand(0).getOperand(0);
2725 APInt TruncC = N101C->getAPIntValue();
2726 TruncC.trunc(TruncVT.getSizeInBits());
2727 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2728 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2729 DAG.getNode(ISD::TRUNCATE,
2732 DAG.getConstant(TruncC, TruncVT)));
2736 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2737 return SDValue(N, 0);
2739 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2740 if (N1C && N0.getOpcode() == ISD::SHL &&
2741 N0.getOperand(1).getOpcode() == ISD::Constant) {
2742 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2743 uint64_t c2 = N1C->getZExtValue();
2744 if (c1 + c2 > OpSizeInBits)
2745 return DAG.getConstant(0, VT);
2746 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2747 DAG.getConstant(c1 + c2, N1.getValueType()));
2749 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2750 // (srl (and x, (shl -1, c1)), (sub c1, c2))
2751 if (N1C && N0.getOpcode() == ISD::SRL &&
2752 N0.getOperand(1).getOpcode() == ISD::Constant) {
2753 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2754 if (c1 < VT.getSizeInBits()) {
2755 uint64_t c2 = N1C->getZExtValue();
2756 SDValue HiBitsMask =
2757 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2758 VT.getSizeInBits() - c1),
2760 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2764 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2765 DAG.getConstant(c2-c1, N1.getValueType()));
2767 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2768 DAG.getConstant(c1-c2, N1.getValueType()));
2771 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2772 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2773 SDValue HiBitsMask =
2774 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2775 VT.getSizeInBits() -
2776 N1C->getZExtValue()),
2778 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2783 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
2784 if (NewSHL.getNode())
2788 return PromoteIntBinOp(SDValue(N, 0));
2791 SDValue DAGCombiner::visitSRA(SDNode *N) {
2792 SDValue N0 = N->getOperand(0);
2793 SDValue N1 = N->getOperand(1);
2794 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2795 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2796 EVT VT = N0.getValueType();
2797 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2799 // fold (sra c1, c2) -> (sra c1, c2)
2801 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2802 // fold (sra 0, x) -> 0
2803 if (N0C && N0C->isNullValue())
2805 // fold (sra -1, x) -> -1
2806 if (N0C && N0C->isAllOnesValue())
2808 // fold (sra x, (setge c, size(x))) -> undef
2809 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2810 return DAG.getUNDEF(VT);
2811 // fold (sra x, 0) -> x
2812 if (N1C && N1C->isNullValue())
2814 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2816 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2817 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
2818 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2820 ExtVT = EVT::getVectorVT(*DAG.getContext(),
2821 ExtVT, VT.getVectorNumElements());
2822 if ((!LegalOperations ||
2823 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
2824 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2825 N0.getOperand(0), DAG.getValueType(ExtVT));
2828 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2829 if (N1C && N0.getOpcode() == ISD::SRA) {
2830 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2831 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2832 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
2833 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2834 DAG.getConstant(Sum, N1C->getValueType(0)));
2838 // fold (sra (shl X, m), (sub result_size, n))
2839 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2840 // result_size - n != m.
2841 // If truncate is free for the target sext(shl) is likely to result in better
2843 if (N0.getOpcode() == ISD::SHL) {
2844 // Get the two constanst of the shifts, CN0 = m, CN = n.
2845 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2847 // Determine what the truncate's result bitsize and type would be.
2849 EVT::getIntegerVT(*DAG.getContext(), OpSizeInBits - N1C->getZExtValue());
2850 // Determine the residual right-shift amount.
2851 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2853 // If the shift is not a no-op (in which case this should be just a sign
2854 // extend already), the truncated to type is legal, sign_extend is legal
2855 // on that type, and the truncate to that type is both legal and free,
2856 // perform the transform.
2857 if ((ShiftAmt > 0) &&
2858 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2859 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2860 TLI.isTruncateFree(VT, TruncVT)) {
2862 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2863 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2864 N0.getOperand(0), Amt);
2865 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2867 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2868 N->getValueType(0), Trunc);
2873 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2874 if (N1.getOpcode() == ISD::TRUNCATE &&
2875 N1.getOperand(0).getOpcode() == ISD::AND &&
2876 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2877 SDValue N101 = N1.getOperand(0).getOperand(1);
2878 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2879 EVT TruncVT = N1.getValueType();
2880 SDValue N100 = N1.getOperand(0).getOperand(0);
2881 APInt TruncC = N101C->getAPIntValue();
2882 TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
2883 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2884 DAG.getNode(ISD::AND, N->getDebugLoc(),
2886 DAG.getNode(ISD::TRUNCATE,
2889 DAG.getConstant(TruncC, TruncVT)));
2893 // Simplify, based on bits shifted out of the LHS.
2894 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2895 return SDValue(N, 0);
2898 // If the sign bit is known to be zero, switch this to a SRL.
2899 if (DAG.SignBitIsZero(N0))
2900 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
2903 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
2904 if (NewSRA.getNode())
2908 return PromoteIntBinOp(SDValue(N, 0));
2911 SDValue DAGCombiner::visitSRL(SDNode *N) {
2912 SDValue N0 = N->getOperand(0);
2913 SDValue N1 = N->getOperand(1);
2914 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2915 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2916 EVT VT = N0.getValueType();
2917 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2919 // fold (srl c1, c2) -> c1 >>u c2
2921 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2922 // fold (srl 0, x) -> 0
2923 if (N0C && N0C->isNullValue())
2925 // fold (srl x, c >= size(x)) -> undef
2926 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2927 return DAG.getUNDEF(VT);
2928 // fold (srl x, 0) -> x
2929 if (N1C && N1C->isNullValue())
2931 // if (srl x, c) is known to be zero, return 0
2932 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2933 APInt::getAllOnesValue(OpSizeInBits)))
2934 return DAG.getConstant(0, VT);
2936 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
2937 if (N1C && N0.getOpcode() == ISD::SRL &&
2938 N0.getOperand(1).getOpcode() == ISD::Constant) {
2939 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2940 uint64_t c2 = N1C->getZExtValue();
2941 if (c1 + c2 > OpSizeInBits)
2942 return DAG.getConstant(0, VT);
2943 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
2944 DAG.getConstant(c1 + c2, N1.getValueType()));
2947 // fold (srl (shl x, c), c) -> (and x, cst2)
2948 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
2949 N0.getValueSizeInBits() <= 64) {
2950 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
2951 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2952 DAG.getConstant(~0ULL >> ShAmt, VT));
2956 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2957 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2958 // Shifting in all undef bits?
2959 EVT SmallVT = N0.getOperand(0).getValueType();
2960 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2961 return DAG.getUNDEF(VT);
2963 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
2964 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
2965 N0.getOperand(0), N1);
2966 AddToWorkList(SmallShift.getNode());
2967 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
2971 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2972 // bit, which is unmodified by sra.
2973 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
2974 if (N0.getOpcode() == ISD::SRA)
2975 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
2978 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2979 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2980 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2981 APInt KnownZero, KnownOne;
2982 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
2983 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2985 // If any of the input bits are KnownOne, then the input couldn't be all
2986 // zeros, thus the result of the srl will always be zero.
2987 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2989 // If all of the bits input the to ctlz node are known to be zero, then
2990 // the result of the ctlz is "32" and the result of the shift is one.
2991 APInt UnknownBits = ~KnownZero & Mask;
2992 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2994 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2995 if ((UnknownBits & (UnknownBits - 1)) == 0) {
2996 // Okay, we know that only that the single bit specified by UnknownBits
2997 // could be set on input to the CTLZ node. If this bit is set, the SRL
2998 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2999 // to an SRL/XOR pair, which is likely to simplify more.
3000 unsigned ShAmt = UnknownBits.countTrailingZeros();
3001 SDValue Op = N0.getOperand(0);
3004 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3005 DAG.getConstant(ShAmt, getShiftAmountTy()));
3006 AddToWorkList(Op.getNode());
3009 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3010 Op, DAG.getConstant(1, VT));
3014 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3015 if (N1.getOpcode() == ISD::TRUNCATE &&
3016 N1.getOperand(0).getOpcode() == ISD::AND &&
3017 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3018 SDValue N101 = N1.getOperand(0).getOperand(1);
3019 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3020 EVT TruncVT = N1.getValueType();
3021 SDValue N100 = N1.getOperand(0).getOperand(0);
3022 APInt TruncC = N101C->getAPIntValue();
3023 TruncC.trunc(TruncVT.getSizeInBits());
3024 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3025 DAG.getNode(ISD::AND, N->getDebugLoc(),
3027 DAG.getNode(ISD::TRUNCATE,
3030 DAG.getConstant(TruncC, TruncVT)));
3034 // fold operands of srl based on knowledge that the low bits are not
3036 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3037 return SDValue(N, 0);
3040 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3041 if (NewSRL.getNode())
3045 // Here is a common situation. We want to optimize:
3048 // %b = and i32 %a, 2
3049 // %c = srl i32 %b, 1
3050 // brcond i32 %c ...
3056 // %c = setcc eq %b, 0
3059 // However when after the source operand of SRL is optimized into AND, the SRL
3060 // itself may not be optimized further. Look for it and add the BRCOND into
3062 if (N->hasOneUse()) {
3063 SDNode *Use = *N->use_begin();
3064 if (Use->getOpcode() == ISD::BRCOND)
3066 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3067 // Also look pass the truncate.
3068 Use = *Use->use_begin();
3069 if (Use->getOpcode() == ISD::BRCOND)
3074 return PromoteIntBinOp(SDValue(N, 0));
3077 SDValue DAGCombiner::visitROTL(SDNode *N) {
3078 return PromoteIntBinOp(SDValue(N, 0));
3081 SDValue DAGCombiner::visitROTR(SDNode *N) {
3082 return PromoteIntBinOp(SDValue(N, 0));
3085 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3086 SDValue N0 = N->getOperand(0);
3087 EVT VT = N->getValueType(0);
3089 // fold (ctlz c1) -> c2
3090 if (isa<ConstantSDNode>(N0))
3091 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3095 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3096 SDValue N0 = N->getOperand(0);
3097 EVT VT = N->getValueType(0);
3099 // fold (cttz c1) -> c2
3100 if (isa<ConstantSDNode>(N0))
3101 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3105 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3106 SDValue N0 = N->getOperand(0);
3107 EVT VT = N->getValueType(0);
3109 // fold (ctpop c1) -> c2
3110 if (isa<ConstantSDNode>(N0))
3111 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3115 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3116 SDValue N0 = N->getOperand(0);
3117 SDValue N1 = N->getOperand(1);
3118 SDValue N2 = N->getOperand(2);
3119 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3120 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3121 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3122 EVT VT = N->getValueType(0);
3123 EVT VT0 = N0.getValueType();
3125 // fold (select C, X, X) -> X
3128 // fold (select true, X, Y) -> X
3129 if (N0C && !N0C->isNullValue())
3131 // fold (select false, X, Y) -> Y
3132 if (N0C && N0C->isNullValue())
3134 // fold (select C, 1, X) -> (or C, X)
3135 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3136 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3137 // fold (select C, 0, 1) -> (xor C, 1)
3138 if (VT.isInteger() &&
3141 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3142 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3145 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3146 N0, DAG.getConstant(1, VT0));
3147 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3148 N0, DAG.getConstant(1, VT0));
3149 AddToWorkList(XORNode.getNode());
3151 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3152 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3154 // fold (select C, 0, X) -> (and (not C), X)
3155 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3156 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3157 AddToWorkList(NOTNode.getNode());
3158 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3160 // fold (select C, X, 1) -> (or (not C), X)
3161 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3162 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3163 AddToWorkList(NOTNode.getNode());
3164 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3166 // fold (select C, X, 0) -> (and C, X)
3167 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3168 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3169 // fold (select X, X, Y) -> (or X, Y)
3170 // fold (select X, 1, Y) -> (or X, Y)
3171 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3172 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3173 // fold (select X, Y, X) -> (and X, Y)
3174 // fold (select X, Y, 0) -> (and X, Y)
3175 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3176 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3178 // If we can fold this based on the true/false value, do so.
3179 if (SimplifySelectOps(N, N1, N2))
3180 return SDValue(N, 0); // Don't revisit N.
3182 // fold selects based on a setcc into other things, such as min/max/abs
3183 if (N0.getOpcode() == ISD::SETCC) {
3185 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3186 // having to say they don't support SELECT_CC on every type the DAG knows
3187 // about, since there is no way to mark an opcode illegal at all value types
3188 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3189 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3190 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3191 N0.getOperand(0), N0.getOperand(1),
3192 N1, N2, N0.getOperand(2));
3193 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3199 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3200 SDValue N0 = N->getOperand(0);
3201 SDValue N1 = N->getOperand(1);
3202 SDValue N2 = N->getOperand(2);
3203 SDValue N3 = N->getOperand(3);
3204 SDValue N4 = N->getOperand(4);
3205 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3207 // fold select_cc lhs, rhs, x, x, cc -> x
3211 // Determine if the condition we're dealing with is constant
3212 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3213 N0, N1, CC, N->getDebugLoc(), false);
3214 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3216 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3217 if (!SCCC->isNullValue())
3218 return N2; // cond always true -> true val
3220 return N3; // cond always false -> false val
3223 // Fold to a simpler select_cc
3224 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3225 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3226 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3229 // If we can fold this based on the true/false value, do so.
3230 if (SimplifySelectOps(N, N2, N3))
3231 return SDValue(N, 0); // Don't revisit N.
3233 // fold select_cc into other things, such as min/max/abs
3234 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3237 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3238 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3239 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3243 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3244 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3245 // transformation. Returns true if extension are possible and the above
3246 // mentioned transformation is profitable.
3247 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3249 SmallVector<SDNode*, 4> &ExtendNodes,
3250 const TargetLowering &TLI) {
3251 bool HasCopyToRegUses = false;
3252 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3253 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3254 UE = N0.getNode()->use_end();
3259 if (UI.getUse().getResNo() != N0.getResNo())
3261 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3262 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3263 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3264 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3265 // Sign bits will be lost after a zext.
3268 for (unsigned i = 0; i != 2; ++i) {
3269 SDValue UseOp = User->getOperand(i);
3272 if (!isa<ConstantSDNode>(UseOp))
3277 ExtendNodes.push_back(User);
3280 // If truncates aren't free and there are users we can't
3281 // extend, it isn't worthwhile.
3284 // Remember if this value is live-out.
3285 if (User->getOpcode() == ISD::CopyToReg)
3286 HasCopyToRegUses = true;
3289 if (HasCopyToRegUses) {
3290 bool BothLiveOut = false;
3291 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3293 SDUse &Use = UI.getUse();
3294 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3300 // Both unextended and extended values are live out. There had better be
3301 // good a reason for the transformation.
3302 return ExtendNodes.size();
3307 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3308 SDValue N0 = N->getOperand(0);
3309 EVT VT = N->getValueType(0);
3311 // fold (sext c1) -> c1
3312 if (isa<ConstantSDNode>(N0))
3313 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3315 // fold (sext (sext x)) -> (sext x)
3316 // fold (sext (aext x)) -> (sext x)
3317 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3318 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3321 if (N0.getOpcode() == ISD::TRUNCATE) {
3322 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3323 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3324 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3325 if (NarrowLoad.getNode()) {
3326 if (NarrowLoad.getNode() != N0.getNode())
3327 CombineTo(N0.getNode(), NarrowLoad);
3328 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3331 // See if the value being truncated is already sign extended. If so, just
3332 // eliminate the trunc/sext pair.
3333 SDValue Op = N0.getOperand(0);
3334 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3335 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3336 unsigned DestBits = VT.getScalarType().getSizeInBits();
3337 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3339 if (OpBits == DestBits) {
3340 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3341 // bits, it is already ready.
3342 if (NumSignBits > DestBits-MidBits)
3344 } else if (OpBits < DestBits) {
3345 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3346 // bits, just sext from i32.
3347 if (NumSignBits > OpBits-MidBits)
3348 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3350 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3351 // bits, just truncate to i32.
3352 if (NumSignBits > OpBits-MidBits)
3353 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3356 // fold (sext (truncate x)) -> (sextinreg x).
3357 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3358 N0.getValueType())) {
3359 if (OpBits < DestBits)
3360 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3361 else if (OpBits > DestBits)
3362 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3363 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3364 DAG.getValueType(N0.getValueType()));
3368 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3369 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3370 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3371 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3372 bool DoXform = true;
3373 SmallVector<SDNode*, 4> SetCCs;
3374 if (!N0.hasOneUse())
3375 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3377 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3378 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3380 LN0->getBasePtr(), LN0->getSrcValue(),
3381 LN0->getSrcValueOffset(),
3383 LN0->isVolatile(), LN0->isNonTemporal(),
3384 LN0->getAlignment());
3385 CombineTo(N, ExtLoad);
3386 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3387 N0.getValueType(), ExtLoad);
3388 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3390 // Extend SetCC uses if necessary.
3391 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3392 SDNode *SetCC = SetCCs[i];
3393 SmallVector<SDValue, 4> Ops;
3395 for (unsigned j = 0; j != 2; ++j) {
3396 SDValue SOp = SetCC->getOperand(j);
3398 Ops.push_back(ExtLoad);
3400 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3401 N->getDebugLoc(), VT, SOp));
3404 Ops.push_back(SetCC->getOperand(2));
3405 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3406 SetCC->getValueType(0),
3407 &Ops[0], Ops.size()));
3410 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3414 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3415 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3416 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3417 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3418 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3419 EVT MemVT = LN0->getMemoryVT();
3420 if ((!LegalOperations && !LN0->isVolatile()) ||
3421 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3422 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3424 LN0->getBasePtr(), LN0->getSrcValue(),
3425 LN0->getSrcValueOffset(), MemVT,
3426 LN0->isVolatile(), LN0->isNonTemporal(),
3427 LN0->getAlignment());
3428 CombineTo(N, ExtLoad);
3429 CombineTo(N0.getNode(),
3430 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3431 N0.getValueType(), ExtLoad),
3432 ExtLoad.getValue(1));
3433 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3437 if (N0.getOpcode() == ISD::SETCC) {
3438 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3439 if (VT.isVector() &&
3440 // We know that the # elements of the results is the same as the
3441 // # elements of the compare (and the # elements of the compare result
3442 // for that matter). Check to see that they are the same size. If so,
3443 // we know that the element size of the sext'd result matches the
3444 // element size of the compare operands.
3445 VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3447 // Only do this before legalize for now.
3449 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3451 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3454 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3456 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3458 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3459 NegOne, DAG.getConstant(0, VT),
3460 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3461 if (SCC.getNode()) return SCC;
3462 if (!LegalOperations ||
3463 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3464 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3465 DAG.getSetCC(N->getDebugLoc(),
3466 TLI.getSetCCResultType(VT),
3467 N0.getOperand(0), N0.getOperand(1),
3468 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3469 NegOne, DAG.getConstant(0, VT));
3474 // fold (sext x) -> (zext x) if the sign bit is known zero.
3475 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3476 DAG.SignBitIsZero(N0))
3477 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3479 return PromoteExtend(SDValue(N, 0));
3482 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3483 SDValue N0 = N->getOperand(0);
3484 EVT VT = N->getValueType(0);
3486 // fold (zext c1) -> c1
3487 if (isa<ConstantSDNode>(N0))
3488 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3489 // fold (zext (zext x)) -> (zext x)
3490 // fold (zext (aext x)) -> (zext x)
3491 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3492 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3495 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3496 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3497 if (N0.getOpcode() == ISD::TRUNCATE) {
3498 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3499 if (NarrowLoad.getNode()) {
3500 if (NarrowLoad.getNode() != N0.getNode())
3501 CombineTo(N0.getNode(), NarrowLoad);
3502 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3506 // fold (zext (truncate x)) -> (and x, mask)
3507 if (N0.getOpcode() == ISD::TRUNCATE &&
3508 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) &&
3509 (!TLI.isTruncateFree(N0.getOperand(0).getValueType(),
3510 N0.getValueType()) ||
3511 !TLI.isZExtFree(N0.getValueType(), VT))) {
3512 SDValue Op = N0.getOperand(0);
3513 if (Op.getValueType().bitsLT(VT)) {
3514 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3515 } else if (Op.getValueType().bitsGT(VT)) {
3516 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3518 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3519 N0.getValueType().getScalarType());
3522 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3523 // if either of the casts is not free.
3524 if (N0.getOpcode() == ISD::AND &&
3525 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3526 N0.getOperand(1).getOpcode() == ISD::Constant &&
3527 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3528 N0.getValueType()) ||
3529 !TLI.isZExtFree(N0.getValueType(), VT))) {
3530 SDValue X = N0.getOperand(0).getOperand(0);
3531 if (X.getValueType().bitsLT(VT)) {
3532 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3533 } else if (X.getValueType().bitsGT(VT)) {
3534 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3536 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3537 Mask.zext(VT.getSizeInBits());
3538 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3539 X, DAG.getConstant(Mask, VT));
3542 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3543 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3544 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3545 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3546 bool DoXform = true;
3547 SmallVector<SDNode*, 4> SetCCs;
3548 if (!N0.hasOneUse())
3549 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3551 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3552 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3554 LN0->getBasePtr(), LN0->getSrcValue(),
3555 LN0->getSrcValueOffset(),
3557 LN0->isVolatile(), LN0->isNonTemporal(),
3558 LN0->getAlignment());
3559 CombineTo(N, ExtLoad);
3560 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3561 N0.getValueType(), ExtLoad);
3562 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3564 // Extend SetCC uses if necessary.
3565 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3566 SDNode *SetCC = SetCCs[i];
3567 SmallVector<SDValue, 4> Ops;
3569 for (unsigned j = 0; j != 2; ++j) {
3570 SDValue SOp = SetCC->getOperand(j);
3572 Ops.push_back(ExtLoad);
3574 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3575 N->getDebugLoc(), VT, SOp));
3578 Ops.push_back(SetCC->getOperand(2));
3579 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3580 SetCC->getValueType(0),
3581 &Ops[0], Ops.size()));
3584 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3588 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3589 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3590 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3591 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3592 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3593 EVT MemVT = LN0->getMemoryVT();
3594 if ((!LegalOperations && !LN0->isVolatile()) ||
3595 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3596 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3598 LN0->getBasePtr(), LN0->getSrcValue(),
3599 LN0->getSrcValueOffset(), MemVT,
3600 LN0->isVolatile(), LN0->isNonTemporal(),
3601 LN0->getAlignment());
3602 CombineTo(N, ExtLoad);
3603 CombineTo(N0.getNode(),
3604 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3606 ExtLoad.getValue(1));
3607 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3611 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3612 if (N0.getOpcode() == ISD::SETCC) {
3614 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3615 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3616 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3617 if (SCC.getNode()) return SCC;
3620 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3621 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3622 isa<ConstantSDNode>(N0.getOperand(1)) &&
3623 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
3625 if (N0.getOpcode() == ISD::SHL) {
3626 // If the original shl may be shifting out bits, do not perform this
3628 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3629 unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
3630 N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
3631 if (ShAmt > KnownZeroBits)
3634 DebugLoc dl = N->getDebugLoc();
3635 return DAG.getNode(N0.getOpcode(), dl, VT,
3636 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
3637 DAG.getNode(ISD::ZERO_EXTEND, dl,
3638 N0.getOperand(1).getValueType(),
3642 return PromoteExtend(SDValue(N, 0));
3645 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3646 SDValue N0 = N->getOperand(0);
3647 EVT VT = N->getValueType(0);
3649 // fold (aext c1) -> c1
3650 if (isa<ConstantSDNode>(N0))
3651 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3652 // fold (aext (aext x)) -> (aext x)
3653 // fold (aext (zext x)) -> (zext x)
3654 // fold (aext (sext x)) -> (sext x)
3655 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3656 N0.getOpcode() == ISD::ZERO_EXTEND ||
3657 N0.getOpcode() == ISD::SIGN_EXTEND)
3658 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3660 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3661 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3662 if (N0.getOpcode() == ISD::TRUNCATE) {
3663 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3664 if (NarrowLoad.getNode()) {
3665 if (NarrowLoad.getNode() != N0.getNode())
3666 CombineTo(N0.getNode(), NarrowLoad);
3667 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3671 // fold (aext (truncate x))
3672 if (N0.getOpcode() == ISD::TRUNCATE) {
3673 SDValue TruncOp = N0.getOperand(0);
3674 if (TruncOp.getValueType() == VT)
3675 return TruncOp; // x iff x size == zext size.
3676 if (TruncOp.getValueType().bitsGT(VT))
3677 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3678 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3681 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3682 // if the trunc is not free.
3683 if (N0.getOpcode() == ISD::AND &&
3684 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3685 N0.getOperand(1).getOpcode() == ISD::Constant &&
3686 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3687 N0.getValueType())) {
3688 SDValue X = N0.getOperand(0).getOperand(0);
3689 if (X.getValueType().bitsLT(VT)) {
3690 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3691 } else if (X.getValueType().bitsGT(VT)) {
3692 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3694 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3695 Mask.zext(VT.getSizeInBits());
3696 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3697 X, DAG.getConstant(Mask, VT));
3700 // fold (aext (load x)) -> (aext (truncate (extload x)))
3701 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3702 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3703 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3704 bool DoXform = true;
3705 SmallVector<SDNode*, 4> SetCCs;
3706 if (!N0.hasOneUse())
3707 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3709 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3710 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3712 LN0->getBasePtr(), LN0->getSrcValue(),
3713 LN0->getSrcValueOffset(),
3715 LN0->isVolatile(), LN0->isNonTemporal(),
3716 LN0->getAlignment());
3717 CombineTo(N, ExtLoad);
3718 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3719 N0.getValueType(), ExtLoad);
3720 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3722 // Extend SetCC uses if necessary.
3723 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3724 SDNode *SetCC = SetCCs[i];
3725 SmallVector<SDValue, 4> Ops;
3727 for (unsigned j = 0; j != 2; ++j) {
3728 SDValue SOp = SetCC->getOperand(j);
3730 Ops.push_back(ExtLoad);
3732 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3733 N->getDebugLoc(), VT, SOp));
3736 Ops.push_back(SetCC->getOperand(2));
3737 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3738 SetCC->getValueType(0),
3739 &Ops[0], Ops.size()));
3742 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3746 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3747 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3748 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3749 if (N0.getOpcode() == ISD::LOAD &&
3750 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3752 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3753 EVT MemVT = LN0->getMemoryVT();
3754 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3755 VT, LN0->getChain(), LN0->getBasePtr(),
3757 LN0->getSrcValueOffset(), MemVT,
3758 LN0->isVolatile(), LN0->isNonTemporal(),
3759 LN0->getAlignment());
3760 CombineTo(N, ExtLoad);
3761 CombineTo(N0.getNode(),
3762 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3763 N0.getValueType(), ExtLoad),
3764 ExtLoad.getValue(1));
3765 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3768 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3769 if (N0.getOpcode() == ISD::SETCC) {
3771 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3772 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3773 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3778 return PromoteExtend(SDValue(N, 0));
3781 /// GetDemandedBits - See if the specified operand can be simplified with the
3782 /// knowledge that only the bits specified by Mask are used. If so, return the
3783 /// simpler operand, otherwise return a null SDValue.
3784 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3785 switch (V.getOpcode()) {
3789 // If the LHS or RHS don't contribute bits to the or, drop them.
3790 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3791 return V.getOperand(1);
3792 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3793 return V.getOperand(0);
3796 // Only look at single-use SRLs.
3797 if (!V.getNode()->hasOneUse())
3799 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3800 // See if we can recursively simplify the LHS.
3801 unsigned Amt = RHSC->getZExtValue();
3803 // Watch out for shift count overflow though.
3804 if (Amt >= Mask.getBitWidth()) break;
3805 APInt NewMask = Mask << Amt;
3806 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3807 if (SimplifyLHS.getNode())
3808 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3809 SimplifyLHS, V.getOperand(1));
3815 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3816 /// bits and then truncated to a narrower type and where N is a multiple
3817 /// of number of bits of the narrower type, transform it to a narrower load
3818 /// from address + N / num of bits of new type. If the result is to be
3819 /// extended, also fold the extension to form a extending load.
3820 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3821 unsigned Opc = N->getOpcode();
3822 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3823 SDValue N0 = N->getOperand(0);
3824 EVT VT = N->getValueType(0);
3827 // This transformation isn't valid for vector loads.
3831 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
3833 if (Opc == ISD::SIGN_EXTEND_INREG) {
3834 ExtType = ISD::SEXTLOAD;
3835 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3836 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3840 unsigned EVTBits = ExtVT.getSizeInBits();
3842 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3843 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3844 ShAmt = N01->getZExtValue();
3845 // Is the shift amount a multiple of size of VT?
3846 if ((ShAmt & (EVTBits-1)) == 0) {
3847 N0 = N0.getOperand(0);
3848 // Is the load width a multiple of size of VT?
3849 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3855 // Do not generate loads of non-round integer types since these can
3856 // be expensive (and would be wrong if the type is not byte sized).
3857 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3858 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() >= EVTBits &&
3859 // Do not change the width of a volatile load.
3860 !cast<LoadSDNode>(N0)->isVolatile()) {
3861 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3862 EVT PtrType = N0.getOperand(1).getValueType();
3864 // For big endian targets, we need to adjust the offset to the pointer to
3865 // load the correct bytes.
3866 if (TLI.isBigEndian()) {
3867 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3868 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3869 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3872 uint64_t PtrOff = ShAmt / 8;
3873 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3874 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3875 PtrType, LN0->getBasePtr(),
3876 DAG.getConstant(PtrOff, PtrType));
3877 AddToWorkList(NewPtr.getNode());
3879 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3880 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3881 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3882 LN0->isVolatile(), LN0->isNonTemporal(), NewAlign)
3883 : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3884 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3885 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3888 // Replace the old load's chain with the new load's chain.
3889 WorkListRemover DeadNodes(*this);
3890 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3893 // Return the new loaded value.
3900 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3901 SDValue N0 = N->getOperand(0);
3902 SDValue N1 = N->getOperand(1);
3903 EVT VT = N->getValueType(0);
3904 EVT EVT = cast<VTSDNode>(N1)->getVT();
3905 unsigned VTBits = VT.getScalarType().getSizeInBits();
3906 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
3908 // fold (sext_in_reg c1) -> c1
3909 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3910 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
3912 // If the input is already sign extended, just drop the extension.
3913 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
3916 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3917 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3918 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3919 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3920 N0.getOperand(0), N1);
3923 // fold (sext_in_reg (sext x)) -> (sext x)
3924 // fold (sext_in_reg (aext x)) -> (sext x)
3925 // if x is small enough.
3926 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3927 SDValue N00 = N0.getOperand(0);
3928 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
3929 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
3930 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
3933 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3934 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3935 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
3937 // fold operands of sext_in_reg based on knowledge that the top bits are not
3939 if (SimplifyDemandedBits(SDValue(N, 0)))
3940 return SDValue(N, 0);
3942 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3943 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3944 SDValue NarrowLoad = ReduceLoadWidth(N);
3945 if (NarrowLoad.getNode())
3948 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
3949 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
3950 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3951 if (N0.getOpcode() == ISD::SRL) {
3952 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3953 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
3954 // We can turn this into an SRA iff the input to the SRL is already sign
3956 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3957 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3958 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
3959 N0.getOperand(0), N0.getOperand(1));
3963 // fold (sext_inreg (extload x)) -> (sextload x)
3964 if (ISD::isEXTLoad(N0.getNode()) &&
3965 ISD::isUNINDEXEDLoad(N0.getNode()) &&
3966 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3967 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3968 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3969 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3970 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3972 LN0->getBasePtr(), LN0->getSrcValue(),
3973 LN0->getSrcValueOffset(), EVT,
3974 LN0->isVolatile(), LN0->isNonTemporal(),
3975 LN0->getAlignment());
3976 CombineTo(N, ExtLoad);
3977 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3978 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3980 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3981 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3983 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3984 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3985 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3987 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3989 LN0->getBasePtr(), LN0->getSrcValue(),
3990 LN0->getSrcValueOffset(), EVT,
3991 LN0->isVolatile(), LN0->isNonTemporal(),
3992 LN0->getAlignment());
3993 CombineTo(N, ExtLoad);
3994 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3995 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4000 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4001 SDValue N0 = N->getOperand(0);
4002 EVT VT = N->getValueType(0);
4005 if (N0.getValueType() == N->getValueType(0))
4007 // fold (truncate c1) -> c1
4008 if (isa<ConstantSDNode>(N0))
4009 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4010 // fold (truncate (truncate x)) -> (truncate x)
4011 if (N0.getOpcode() == ISD::TRUNCATE)
4012 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4013 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4014 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4015 N0.getOpcode() == ISD::SIGN_EXTEND ||
4016 N0.getOpcode() == ISD::ANY_EXTEND) {
4017 if (N0.getOperand(0).getValueType().bitsLT(VT))
4018 // if the source is smaller than the dest, we still need an extend
4019 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4021 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4022 // if the source is larger than the dest, than we just need the truncate
4023 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4025 // if the source and dest are the same type, we can drop both the extend
4026 // and the truncate.
4027 return N0.getOperand(0);
4030 // See if we can simplify the input to this truncate through knowledge that
4031 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
4034 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4035 VT.getSizeInBits()));
4036 if (Shorter.getNode())
4037 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4039 // fold (truncate (load x)) -> (smaller load x)
4040 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4041 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT))
4042 return ReduceLoadWidth(N);
4046 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4047 SDValue Elt = N->getOperand(i);
4048 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4049 return Elt.getNode();
4050 return Elt.getOperand(Elt.getResNo()).getNode();
4053 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4054 /// if load locations are consecutive.
4055 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4056 assert(N->getOpcode() == ISD::BUILD_PAIR);
4058 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4059 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4060 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
4062 EVT LD1VT = LD1->getValueType(0);
4064 if (ISD::isNON_EXTLoad(LD2) &&
4066 // If both are volatile this would reduce the number of volatile loads.
4067 // If one is volatile it might be ok, but play conservative and bail out.
4068 !LD1->isVolatile() &&
4069 !LD2->isVolatile() &&
4070 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4071 unsigned Align = LD1->getAlignment();
4072 unsigned NewAlign = TLI.getTargetData()->
4073 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4075 if (NewAlign <= Align &&
4076 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4077 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4078 LD1->getBasePtr(), LD1->getSrcValue(),
4079 LD1->getSrcValueOffset(), false, false, Align);
4085 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
4086 SDValue N0 = N->getOperand(0);
4087 EVT VT = N->getValueType(0);
4089 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4090 // Only do this before legalize, since afterward the target may be depending
4091 // on the bitconvert.
4092 // First check to see if this is all constant.
4094 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4096 bool isSimple = true;
4097 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4098 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4099 N0.getOperand(i).getOpcode() != ISD::Constant &&
4100 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4105 EVT DestEltVT = N->getValueType(0).getVectorElementType();
4106 assert(!DestEltVT.isVector() &&
4107 "Element type of vector ValueType must not be vector!");
4109 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4112 // If the input is a constant, let getNode fold it.
4113 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4114 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
4115 if (Res.getNode() != N) {
4116 if (!LegalOperations ||
4117 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4120 // Folding it resulted in an illegal node, and it's too late to
4121 // do that. Clean up the old node and forego the transformation.
4122 // Ideally this won't happen very often, because instcombine
4123 // and the earlier dagcombine runs (where illegal nodes are
4124 // permitted) should have folded most of them already.
4125 DAG.DeleteNode(Res.getNode());
4129 // (conv (conv x, t1), t2) -> (conv x, t2)
4130 if (N0.getOpcode() == ISD::BIT_CONVERT)
4131 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
4134 // fold (conv (load x)) -> (load (conv*)x)
4135 // If the resultant load doesn't need a higher alignment than the original!
4136 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4137 // Do not change the width of a volatile load.
4138 !cast<LoadSDNode>(N0)->isVolatile() &&
4139 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4140 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4141 unsigned Align = TLI.getTargetData()->
4142 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4143 unsigned OrigAlign = LN0->getAlignment();
4145 if (Align <= OrigAlign) {
4146 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4148 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4149 LN0->isVolatile(), LN0->isNonTemporal(),
4152 CombineTo(N0.getNode(),
4153 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4154 N0.getValueType(), Load),
4160 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4161 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4162 // This often reduces constant pool loads.
4163 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4164 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4165 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
4167 AddToWorkList(NewConv.getNode());
4169 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4170 if (N0.getOpcode() == ISD::FNEG)
4171 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4172 NewConv, DAG.getConstant(SignBit, VT));
4173 assert(N0.getOpcode() == ISD::FABS);
4174 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4175 NewConv, DAG.getConstant(~SignBit, VT));
4178 // fold (bitconvert (fcopysign cst, x)) ->
4179 // (or (and (bitconvert x), sign), (and cst, (not sign)))
4180 // Note that we don't handle (copysign x, cst) because this can always be
4181 // folded to an fneg or fabs.
4182 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4183 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4184 VT.isInteger() && !VT.isVector()) {
4185 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4186 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4187 if (isTypeLegal(IntXVT)) {
4188 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4189 IntXVT, N0.getOperand(1));
4190 AddToWorkList(X.getNode());
4192 // If X has a different width than the result/lhs, sext it or truncate it.
4193 unsigned VTWidth = VT.getSizeInBits();
4194 if (OrigXWidth < VTWidth) {
4195 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4196 AddToWorkList(X.getNode());
4197 } else if (OrigXWidth > VTWidth) {
4198 // To get the sign bit in the right place, we have to shift it right
4199 // before truncating.
4200 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4201 X.getValueType(), X,
4202 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4203 AddToWorkList(X.getNode());
4204 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4205 AddToWorkList(X.getNode());
4208 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4209 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4210 X, DAG.getConstant(SignBit, VT));
4211 AddToWorkList(X.getNode());
4213 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4214 VT, N0.getOperand(0));
4215 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4216 Cst, DAG.getConstant(~SignBit, VT));
4217 AddToWorkList(Cst.getNode());
4219 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4223 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4224 if (N0.getOpcode() == ISD::BUILD_PAIR) {
4225 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4226 if (CombineLD.getNode())
4233 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4234 EVT VT = N->getValueType(0);
4235 return CombineConsecutiveLoads(N, VT);
4238 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
4239 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
4240 /// destination element value type.
4241 SDValue DAGCombiner::
4242 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4243 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4245 // If this is already the right type, we're done.
4246 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4248 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4249 unsigned DstBitSize = DstEltVT.getSizeInBits();
4251 // If this is a conversion of N elements of one type to N elements of another
4252 // type, convert each element. This handles FP<->INT cases.
4253 if (SrcBitSize == DstBitSize) {
4254 SmallVector<SDValue, 8> Ops;
4255 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4256 SDValue Op = BV->getOperand(i);
4257 // If the vector element type is not legal, the BUILD_VECTOR operands
4258 // are promoted and implicitly truncated. Make that explicit here.
4259 if (Op.getValueType() != SrcEltVT)
4260 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4261 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4263 AddToWorkList(Ops.back().getNode());
4265 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4266 BV->getValueType(0).getVectorNumElements());
4267 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4268 &Ops[0], Ops.size());
4271 // Otherwise, we're growing or shrinking the elements. To avoid having to
4272 // handle annoying details of growing/shrinking FP values, we convert them to
4274 if (SrcEltVT.isFloatingPoint()) {
4275 // Convert the input float vector to a int vector where the elements are the
4277 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4278 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4279 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
4283 // Now we know the input is an integer vector. If the output is a FP type,
4284 // convert to integer first, then to FP of the right size.
4285 if (DstEltVT.isFloatingPoint()) {
4286 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4287 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4288 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
4290 // Next, convert to FP elements of the same size.
4291 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
4294 // Okay, we know the src/dst types are both integers of differing types.
4295 // Handling growing first.
4296 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4297 if (SrcBitSize < DstBitSize) {
4298 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4300 SmallVector<SDValue, 8> Ops;
4301 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4302 i += NumInputsPerOutput) {
4303 bool isLE = TLI.isLittleEndian();
4304 APInt NewBits = APInt(DstBitSize, 0);
4305 bool EltIsUndef = true;
4306 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4307 // Shift the previously computed bits over.
4308 NewBits <<= SrcBitSize;
4309 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4310 if (Op.getOpcode() == ISD::UNDEF) continue;
4313 NewBits |= APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
4314 zextOrTrunc(SrcBitSize).zext(DstBitSize);
4318 Ops.push_back(DAG.getUNDEF(DstEltVT));
4320 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4323 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4324 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4325 &Ops[0], Ops.size());
4328 // Finally, this must be the case where we are shrinking elements: each input
4329 // turns into multiple outputs.
4330 bool isS2V = ISD::isScalarToVector(BV);
4331 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4332 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4333 NumOutputsPerInput*BV->getNumOperands());
4334 SmallVector<SDValue, 8> Ops;
4336 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4337 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4338 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4339 Ops.push_back(DAG.getUNDEF(DstEltVT));
4343 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
4344 getAPIntValue()).zextOrTrunc(SrcBitSize);
4346 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4347 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
4348 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4349 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
4350 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4351 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4353 OpVal = OpVal.lshr(DstBitSize);
4356 // For big endian targets, swap the order of the pieces of each element.
4357 if (TLI.isBigEndian())
4358 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4361 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4362 &Ops[0], Ops.size());
4365 SDValue DAGCombiner::visitFADD(SDNode *N) {
4366 SDValue N0 = N->getOperand(0);
4367 SDValue N1 = N->getOperand(1);
4368 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4369 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4370 EVT VT = N->getValueType(0);
4373 if (VT.isVector()) {
4374 SDValue FoldedVOp = SimplifyVBinOp(N);
4375 if (FoldedVOp.getNode()) return FoldedVOp;
4378 // fold (fadd c1, c2) -> (fadd c1, c2)
4379 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4380 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4381 // canonicalize constant to RHS
4382 if (N0CFP && !N1CFP)
4383 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4384 // fold (fadd A, 0) -> A
4385 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4387 // fold (fadd A, (fneg B)) -> (fsub A, B)
4388 if (isNegatibleForFree(N1, LegalOperations) == 2)
4389 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4390 GetNegatedExpression(N1, DAG, LegalOperations));
4391 // fold (fadd (fneg A), B) -> (fsub B, A)
4392 if (isNegatibleForFree(N0, LegalOperations) == 2)
4393 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4394 GetNegatedExpression(N0, DAG, LegalOperations));
4396 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4397 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4398 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4399 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4400 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4401 N0.getOperand(1), N1));
4406 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4407 SDValue N0 = N->getOperand(0);
4408 SDValue N1 = N->getOperand(1);
4409 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4410 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4411 EVT VT = N->getValueType(0);
4414 if (VT.isVector()) {
4415 SDValue FoldedVOp = SimplifyVBinOp(N);
4416 if (FoldedVOp.getNode()) return FoldedVOp;
4419 // fold (fsub c1, c2) -> c1-c2
4420 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4421 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4422 // fold (fsub A, 0) -> A
4423 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4425 // fold (fsub 0, B) -> -B
4426 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4427 if (isNegatibleForFree(N1, LegalOperations))
4428 return GetNegatedExpression(N1, DAG, LegalOperations);
4429 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4430 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4432 // fold (fsub A, (fneg B)) -> (fadd A, B)
4433 if (isNegatibleForFree(N1, LegalOperations))
4434 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4435 GetNegatedExpression(N1, DAG, LegalOperations));
4440 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4441 SDValue N0 = N->getOperand(0);
4442 SDValue N1 = N->getOperand(1);
4443 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4444 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4445 EVT VT = N->getValueType(0);
4448 if (VT.isVector()) {
4449 SDValue FoldedVOp = SimplifyVBinOp(N);
4450 if (FoldedVOp.getNode()) return FoldedVOp;
4453 // fold (fmul c1, c2) -> c1*c2
4454 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4455 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4456 // canonicalize constant to RHS
4457 if (N0CFP && !N1CFP)
4458 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4459 // fold (fmul A, 0) -> 0
4460 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4462 // fold (fmul A, 0) -> 0, vector edition.
4463 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4465 // fold (fmul X, 2.0) -> (fadd X, X)
4466 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4467 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4468 // fold (fmul X, -1.0) -> (fneg X)
4469 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4470 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4471 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4473 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4474 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4475 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4476 // Both can be negated for free, check to see if at least one is cheaper
4478 if (LHSNeg == 2 || RHSNeg == 2)
4479 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4480 GetNegatedExpression(N0, DAG, LegalOperations),
4481 GetNegatedExpression(N1, DAG, LegalOperations));
4485 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4486 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4487 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4488 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4489 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4490 N0.getOperand(1), N1));
4495 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4496 SDValue N0 = N->getOperand(0);
4497 SDValue N1 = N->getOperand(1);
4498 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4499 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4500 EVT VT = N->getValueType(0);
4503 if (VT.isVector()) {
4504 SDValue FoldedVOp = SimplifyVBinOp(N);
4505 if (FoldedVOp.getNode()) return FoldedVOp;
4508 // fold (fdiv c1, c2) -> c1/c2
4509 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4510 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4513 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4514 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4515 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4516 // Both can be negated for free, check to see if at least one is cheaper
4518 if (LHSNeg == 2 || RHSNeg == 2)
4519 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4520 GetNegatedExpression(N0, DAG, LegalOperations),
4521 GetNegatedExpression(N1, DAG, LegalOperations));
4528 SDValue DAGCombiner::visitFREM(SDNode *N) {
4529 SDValue N0 = N->getOperand(0);
4530 SDValue N1 = N->getOperand(1);
4531 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4532 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4533 EVT VT = N->getValueType(0);
4535 // fold (frem c1, c2) -> fmod(c1,c2)
4536 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4537 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4542 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4543 SDValue N0 = N->getOperand(0);
4544 SDValue N1 = N->getOperand(1);
4545 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4546 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4547 EVT VT = N->getValueType(0);
4549 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
4550 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4553 const APFloat& V = N1CFP->getValueAPF();
4554 // copysign(x, c1) -> fabs(x) iff ispos(c1)
4555 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4556 if (!V.isNegative()) {
4557 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4558 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4560 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4561 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4562 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4566 // copysign(fabs(x), y) -> copysign(x, y)
4567 // copysign(fneg(x), y) -> copysign(x, y)
4568 // copysign(copysign(x,z), y) -> copysign(x, y)
4569 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4570 N0.getOpcode() == ISD::FCOPYSIGN)
4571 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4572 N0.getOperand(0), N1);
4574 // copysign(x, abs(y)) -> abs(x)
4575 if (N1.getOpcode() == ISD::FABS)
4576 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4578 // copysign(x, copysign(y,z)) -> copysign(x, z)
4579 if (N1.getOpcode() == ISD::FCOPYSIGN)
4580 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4581 N0, N1.getOperand(1));
4583 // copysign(x, fp_extend(y)) -> copysign(x, y)
4584 // copysign(x, fp_round(y)) -> copysign(x, y)
4585 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4586 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4587 N0, N1.getOperand(0));
4592 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4593 SDValue N0 = N->getOperand(0);
4594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4595 EVT VT = N->getValueType(0);
4596 EVT OpVT = N0.getValueType();
4598 // fold (sint_to_fp c1) -> c1fp
4599 if (N0C && OpVT != MVT::ppcf128)
4600 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4602 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4603 // but UINT_TO_FP is legal on this target, try to convert.
4604 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4605 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4606 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4607 if (DAG.SignBitIsZero(N0))
4608 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4614 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4615 SDValue N0 = N->getOperand(0);
4616 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4617 EVT VT = N->getValueType(0);
4618 EVT OpVT = N0.getValueType();
4620 // fold (uint_to_fp c1) -> c1fp
4621 if (N0C && OpVT != MVT::ppcf128)
4622 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4624 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4625 // but SINT_TO_FP is legal on this target, try to convert.
4626 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4627 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4628 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4629 if (DAG.SignBitIsZero(N0))
4630 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4636 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4637 SDValue N0 = N->getOperand(0);
4638 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4639 EVT VT = N->getValueType(0);
4641 // fold (fp_to_sint c1fp) -> c1
4643 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4648 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4649 SDValue N0 = N->getOperand(0);
4650 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4651 EVT VT = N->getValueType(0);
4653 // fold (fp_to_uint c1fp) -> c1
4654 if (N0CFP && VT != MVT::ppcf128)
4655 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4660 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4661 SDValue N0 = N->getOperand(0);
4662 SDValue N1 = N->getOperand(1);
4663 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4664 EVT VT = N->getValueType(0);
4666 // fold (fp_round c1fp) -> c1fp
4667 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4668 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4670 // fold (fp_round (fp_extend x)) -> x
4671 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4672 return N0.getOperand(0);
4674 // fold (fp_round (fp_round x)) -> (fp_round x)
4675 if (N0.getOpcode() == ISD::FP_ROUND) {
4676 // This is a value preserving truncation if both round's are.
4677 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4678 N0.getNode()->getConstantOperandVal(1) == 1;
4679 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4680 DAG.getIntPtrConstant(IsTrunc));
4683 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4684 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4685 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4686 N0.getOperand(0), N1);
4687 AddToWorkList(Tmp.getNode());
4688 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4689 Tmp, N0.getOperand(1));
4695 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4696 SDValue N0 = N->getOperand(0);
4697 EVT VT = N->getValueType(0);
4698 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4699 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4701 // fold (fp_round_inreg c1fp) -> c1fp
4702 if (N0CFP && isTypeLegal(EVT)) {
4703 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4704 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4710 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4711 SDValue N0 = N->getOperand(0);
4712 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4713 EVT VT = N->getValueType(0);
4715 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4716 if (N->hasOneUse() &&
4717 N->use_begin()->getOpcode() == ISD::FP_ROUND)
4720 // fold (fp_extend c1fp) -> c1fp
4721 if (N0CFP && VT != MVT::ppcf128)
4722 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4724 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4726 if (N0.getOpcode() == ISD::FP_ROUND
4727 && N0.getNode()->getConstantOperandVal(1) == 1) {
4728 SDValue In = N0.getOperand(0);
4729 if (In.getValueType() == VT) return In;
4730 if (VT.bitsLT(In.getValueType()))
4731 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4732 In, N0.getOperand(1));
4733 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4736 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4737 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4738 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4739 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4740 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4741 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4743 LN0->getBasePtr(), LN0->getSrcValue(),
4744 LN0->getSrcValueOffset(),
4746 LN0->isVolatile(), LN0->isNonTemporal(),
4747 LN0->getAlignment());
4748 CombineTo(N, ExtLoad);
4749 CombineTo(N0.getNode(),
4750 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4751 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4752 ExtLoad.getValue(1));
4753 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4759 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4760 SDValue N0 = N->getOperand(0);
4761 EVT VT = N->getValueType(0);
4763 if (isNegatibleForFree(N0, LegalOperations))
4764 return GetNegatedExpression(N0, DAG, LegalOperations);
4766 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4767 // constant pool values.
4768 if (N0.getOpcode() == ISD::BIT_CONVERT &&
4770 N0.getNode()->hasOneUse() &&
4771 N0.getOperand(0).getValueType().isInteger()) {
4772 SDValue Int = N0.getOperand(0);
4773 EVT IntVT = Int.getValueType();
4774 if (IntVT.isInteger() && !IntVT.isVector()) {
4775 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4776 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4777 AddToWorkList(Int.getNode());
4778 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4786 SDValue DAGCombiner::visitFABS(SDNode *N) {
4787 SDValue N0 = N->getOperand(0);
4788 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4789 EVT VT = N->getValueType(0);
4791 // fold (fabs c1) -> fabs(c1)
4792 if (N0CFP && VT != MVT::ppcf128)
4793 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4794 // fold (fabs (fabs x)) -> (fabs x)
4795 if (N0.getOpcode() == ISD::FABS)
4796 return N->getOperand(0);
4797 // fold (fabs (fneg x)) -> (fabs x)
4798 // fold (fabs (fcopysign x, y)) -> (fabs x)
4799 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4800 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4802 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4803 // constant pool values.
4804 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4805 N0.getOperand(0).getValueType().isInteger() &&
4806 !N0.getOperand(0).getValueType().isVector()) {
4807 SDValue Int = N0.getOperand(0);
4808 EVT IntVT = Int.getValueType();
4809 if (IntVT.isInteger() && !IntVT.isVector()) {
4810 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4811 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4812 AddToWorkList(Int.getNode());
4813 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4814 N->getValueType(0), Int);
4821 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4822 SDValue Chain = N->getOperand(0);
4823 SDValue N1 = N->getOperand(1);
4824 SDValue N2 = N->getOperand(2);
4826 // If N is a constant we could fold this into a fallthrough or unconditional
4827 // branch. However that doesn't happen very often in normal code, because
4828 // Instcombine/SimplifyCFG should have handled the available opportunities.
4829 // If we did this folding here, it would be necessary to update the
4830 // MachineBasicBlock CFG, which is awkward.
4832 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4834 if (N1.getOpcode() == ISD::SETCC &&
4835 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4836 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4837 Chain, N1.getOperand(2),
4838 N1.getOperand(0), N1.getOperand(1), N2);
4842 if (N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) {
4843 // Look past truncate.
4844 Trunc = N1.getNode();
4845 N1 = N1.getOperand(0);
4848 if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4849 // Match this pattern so that we can generate simpler code:
4852 // %b = and i32 %a, 2
4853 // %c = srl i32 %b, 1
4854 // brcond i32 %c ...
4859 // %b = and i32 %a, 2
4860 // %c = setcc eq %b, 0
4863 // This applies only when the AND constant value has one bit set and the
4864 // SRL constant is equal to the log2 of the AND constant. The back-end is
4865 // smart enough to convert the result into a TEST/JMP sequence.
4866 SDValue Op0 = N1.getOperand(0);
4867 SDValue Op1 = N1.getOperand(1);
4869 if (Op0.getOpcode() == ISD::AND &&
4870 Op1.getOpcode() == ISD::Constant) {
4871 SDValue AndOp1 = Op0.getOperand(1);
4873 if (AndOp1.getOpcode() == ISD::Constant) {
4874 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4876 if (AndConst.isPowerOf2() &&
4877 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4879 DAG.getSetCC(N->getDebugLoc(),
4880 TLI.getSetCCResultType(Op0.getValueType()),
4881 Op0, DAG.getConstant(0, Op0.getValueType()),
4884 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4885 MVT::Other, Chain, SetCC, N2);
4886 // Don't add the new BRCond into the worklist or else SimplifySelectCC
4887 // will convert it back to (X & C1) >> C2.
4888 CombineTo(N, NewBRCond, false);
4889 // Truncate is dead.
4891 removeFromWorkList(Trunc);
4892 DAG.DeleteNode(Trunc);
4894 // Replace the uses of SRL with SETCC
4895 WorkListRemover DeadNodes(*this);
4896 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
4897 removeFromWorkList(N1.getNode());
4898 DAG.DeleteNode(N1.getNode());
4899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4905 // Transform br(xor(x, y)) -> br(x != y)
4906 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
4907 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
4908 SDNode *TheXor = N1.getNode();
4909 SDValue Op0 = TheXor->getOperand(0);
4910 SDValue Op1 = TheXor->getOperand(1);
4911 if (Op0.getOpcode() == Op1.getOpcode()) {
4912 // Avoid missing important xor optimizations.
4913 SDValue Tmp = visitXOR(TheXor);
4914 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
4915 DEBUG(dbgs() << "\nReplacing.8 ";
4917 dbgs() << "\nWith: ";
4918 Tmp.getNode()->dump(&DAG);
4920 WorkListRemover DeadNodes(*this);
4921 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
4922 removeFromWorkList(TheXor);
4923 DAG.DeleteNode(TheXor);
4924 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4925 MVT::Other, Chain, Tmp, N2);
4929 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
4931 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
4932 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
4933 Op0.getOpcode() == ISD::XOR) {
4934 TheXor = Op0.getNode();
4938 SDValue NodeToReplace = Trunc ? SDValue(Trunc, 0) : N1;
4940 EVT SetCCVT = NodeToReplace.getValueType();
4942 SetCCVT = TLI.getSetCCResultType(SetCCVT);
4943 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
4946 Equal ? ISD::SETEQ : ISD::SETNE);
4947 // Replace the uses of XOR with SETCC
4948 WorkListRemover DeadNodes(*this);
4949 DAG.ReplaceAllUsesOfValueWith(NodeToReplace, SetCC, &DeadNodes);
4950 removeFromWorkList(NodeToReplace.getNode());
4951 DAG.DeleteNode(NodeToReplace.getNode());
4952 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4953 MVT::Other, Chain, SetCC, N2);
4960 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4962 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
4963 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4964 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4966 // If N is a constant we could fold this into a fallthrough or unconditional
4967 // branch. However that doesn't happen very often in normal code, because
4968 // Instcombine/SimplifyCFG should have handled the available opportunities.
4969 // If we did this folding here, it would be necessary to update the
4970 // MachineBasicBlock CFG, which is awkward.
4972 // Use SimplifySetCC to simplify SETCC's.
4973 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
4974 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
4976 if (Simp.getNode()) AddToWorkList(Simp.getNode());
4978 // fold to a simpler setcc
4979 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4980 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4981 N->getOperand(0), Simp.getOperand(2),
4982 Simp.getOperand(0), Simp.getOperand(1),
4988 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4989 /// pre-indexed load / store when the base pointer is an add or subtract
4990 /// and it has other uses besides the load / store. After the
4991 /// transformation, the new indexed load / store has effectively folded
4992 /// the add / subtract in and all of its other uses are redirected to the
4993 /// new load / store.
4994 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4995 if (!LegalOperations)
5001 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5002 if (LD->isIndexed())
5004 VT = LD->getMemoryVT();
5005 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5006 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5008 Ptr = LD->getBasePtr();
5009 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5010 if (ST->isIndexed())
5012 VT = ST->getMemoryVT();
5013 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5014 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5016 Ptr = ST->getBasePtr();
5022 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5023 // out. There is no reason to make this a preinc/predec.
5024 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5025 Ptr.getNode()->hasOneUse())
5028 // Ask the target to do addressing mode selection.
5031 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5032 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5034 // Don't create a indexed load / store with zero offset.
5035 if (isa<ConstantSDNode>(Offset) &&
5036 cast<ConstantSDNode>(Offset)->isNullValue())
5039 // Try turning it into a pre-indexed load / store except when:
5040 // 1) The new base ptr is a frame index.
5041 // 2) If N is a store and the new base ptr is either the same as or is a
5042 // predecessor of the value being stored.
5043 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5044 // that would create a cycle.
5045 // 4) All uses are load / store ops that use it as old base ptr.
5047 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5048 // (plus the implicit offset) to a register to preinc anyway.
5049 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5054 SDValue Val = cast<StoreSDNode>(N)->getValue();
5055 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5059 // Now check for #3 and #4.
5060 bool RealUse = false;
5061 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5062 E = Ptr.getNode()->use_end(); I != E; ++I) {
5066 if (Use->isPredecessorOf(N))
5069 if (!((Use->getOpcode() == ISD::LOAD &&
5070 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5071 (Use->getOpcode() == ISD::STORE &&
5072 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5081 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5082 BasePtr, Offset, AM);
5084 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5085 BasePtr, Offset, AM);
5088 DEBUG(dbgs() << "\nReplacing.4 ";
5090 dbgs() << "\nWith: ";
5091 Result.getNode()->dump(&DAG);
5093 WorkListRemover DeadNodes(*this);
5095 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5097 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5100 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5104 // Finally, since the node is now dead, remove it from the graph.
5107 // Replace the uses of Ptr with uses of the updated base value.
5108 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5110 removeFromWorkList(Ptr.getNode());
5111 DAG.DeleteNode(Ptr.getNode());
5116 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5117 /// add / sub of the base pointer node into a post-indexed load / store.
5118 /// The transformation folded the add / subtract into the new indexed
5119 /// load / store effectively and all of its uses are redirected to the
5120 /// new load / store.
5121 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5122 if (!LegalOperations)
5128 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5129 if (LD->isIndexed())
5131 VT = LD->getMemoryVT();
5132 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5133 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5135 Ptr = LD->getBasePtr();
5136 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5137 if (ST->isIndexed())
5139 VT = ST->getMemoryVT();
5140 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5141 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5143 Ptr = ST->getBasePtr();
5149 if (Ptr.getNode()->hasOneUse())
5152 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5153 E = Ptr.getNode()->use_end(); I != E; ++I) {
5156 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5161 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5162 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5163 if (Ptr == Offset && Op->getOpcode() == ISD::ADD)
5164 std::swap(BasePtr, Offset);
5167 // Don't create a indexed load / store with zero offset.
5168 if (isa<ConstantSDNode>(Offset) &&
5169 cast<ConstantSDNode>(Offset)->isNullValue())
5172 // Try turning it into a post-indexed load / store except when
5173 // 1) All uses are load / store ops that use it as base ptr.
5174 // 2) Op must be independent of N, i.e. Op is neither a predecessor
5175 // nor a successor of N. Otherwise, if Op is folded that would
5178 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5182 bool TryNext = false;
5183 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5184 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5186 if (Use == Ptr.getNode())
5189 // If all the uses are load / store addresses, then don't do the
5191 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5192 bool RealUse = false;
5193 for (SDNode::use_iterator III = Use->use_begin(),
5194 EEE = Use->use_end(); III != EEE; ++III) {
5195 SDNode *UseUse = *III;
5196 if (!((UseUse->getOpcode() == ISD::LOAD &&
5197 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5198 (UseUse->getOpcode() == ISD::STORE &&
5199 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5214 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5215 SDValue Result = isLoad
5216 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5217 BasePtr, Offset, AM)
5218 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5219 BasePtr, Offset, AM);
5222 DEBUG(dbgs() << "\nReplacing.5 ";
5224 dbgs() << "\nWith: ";
5225 Result.getNode()->dump(&DAG);
5227 WorkListRemover DeadNodes(*this);
5229 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5231 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5234 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5238 // Finally, since the node is now dead, remove it from the graph.
5241 // Replace the uses of Use with uses of the updated base value.
5242 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5243 Result.getValue(isLoad ? 1 : 0),
5245 removeFromWorkList(Op);
5255 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5256 LoadSDNode *LD = cast<LoadSDNode>(N);
5257 SDValue Chain = LD->getChain();
5258 SDValue Ptr = LD->getBasePtr();
5260 // If load is not volatile and there are no uses of the loaded value (and
5261 // the updated indexed value in case of indexed loads), change uses of the
5262 // chain value into uses of the chain input (i.e. delete the dead load).
5263 if (!LD->isVolatile()) {
5264 if (N->getValueType(1) == MVT::Other) {
5266 if (N->hasNUsesOfValue(0, 0)) {
5267 // It's not safe to use the two value CombineTo variant here. e.g.
5268 // v1, chain2 = load chain1, loc
5269 // v2, chain3 = load chain2, loc
5271 // Now we replace use of chain2 with chain1. This makes the second load
5272 // isomorphic to the one we are deleting, and thus makes this load live.
5273 DEBUG(dbgs() << "\nReplacing.6 ";
5275 dbgs() << "\nWith chain: ";
5276 Chain.getNode()->dump(&DAG);
5278 WorkListRemover DeadNodes(*this);
5279 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5281 if (N->use_empty()) {
5282 removeFromWorkList(N);
5286 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5290 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5291 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5292 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5293 DEBUG(dbgs() << "\nReplacing.7 ";
5295 dbgs() << "\nWith: ";
5296 Undef.getNode()->dump(&DAG);
5297 dbgs() << " and 2 other values\n");
5298 WorkListRemover DeadNodes(*this);
5299 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5300 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5301 DAG.getUNDEF(N->getValueType(1)),
5303 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5304 removeFromWorkList(N);
5306 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5311 // If this load is directly stored, replace the load value with the stored
5313 // TODO: Handle store large -> read small portion.
5314 // TODO: Handle TRUNCSTORE/LOADEXT
5315 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5316 !LD->isVolatile()) {
5317 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5318 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5319 if (PrevST->getBasePtr() == Ptr &&
5320 PrevST->getValue().getValueType() == N->getValueType(0))
5321 return CombineTo(N, Chain.getOperand(1), Chain);
5325 // Try to infer better alignment information than the load already has.
5326 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5327 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5328 if (Align > LD->getAlignment())
5329 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
5330 LD->getValueType(0),
5331 Chain, Ptr, LD->getSrcValue(),
5332 LD->getSrcValueOffset(), LD->getMemoryVT(),
5333 LD->isVolatile(), LD->isNonTemporal(), Align);
5338 // Walk up chain skipping non-aliasing memory nodes.
5339 SDValue BetterChain = FindBetterChain(N, Chain);
5341 // If there is a better chain.
5342 if (Chain != BetterChain) {
5345 // Replace the chain to void dependency.
5346 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5347 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5349 LD->getSrcValue(), LD->getSrcValueOffset(),
5350 LD->isVolatile(), LD->isNonTemporal(),
5351 LD->getAlignment());
5353 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
5354 LD->getValueType(0),
5355 BetterChain, Ptr, LD->getSrcValue(),
5356 LD->getSrcValueOffset(),
5359 LD->isNonTemporal(),
5360 LD->getAlignment());
5363 // Create token factor to keep old chain connected.
5364 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5365 MVT::Other, Chain, ReplLoad.getValue(1));
5367 // Make sure the new and old chains are cleaned up.
5368 AddToWorkList(Token.getNode());
5370 // Replace uses with load result and token factor. Don't add users
5372 return CombineTo(N, ReplLoad.getValue(0), Token, false);
5376 // Try transforming N to an indexed load.
5377 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5378 return SDValue(N, 0);
5380 if (PromoteLoad(SDValue(N, 0)))
5381 return SDValue(N, 0);
5385 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5386 /// load is having specific bytes cleared out. If so, return the byte size
5387 /// being masked out and the shift amount.
5388 static std::pair<unsigned, unsigned>
5389 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5390 std::pair<unsigned, unsigned> Result(0, 0);
5392 // Check for the structure we're looking for.
5393 if (V->getOpcode() != ISD::AND ||
5394 !isa<ConstantSDNode>(V->getOperand(1)) ||
5395 !ISD::isNormalLoad(V->getOperand(0).getNode()))
5398 // Check the chain and pointer.
5399 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5400 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
5402 // The store should be chained directly to the load or be an operand of a
5404 if (LD == Chain.getNode())
5406 else if (Chain->getOpcode() != ISD::TokenFactor)
5407 return Result; // Fail.
5410 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5411 if (Chain->getOperand(i).getNode() == LD) {
5415 if (!isOk) return Result;
5418 // This only handles simple types.
5419 if (V.getValueType() != MVT::i16 &&
5420 V.getValueType() != MVT::i32 &&
5421 V.getValueType() != MVT::i64)
5424 // Check the constant mask. Invert it so that the bits being masked out are
5425 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
5426 // follow the sign bit for uniformity.
5427 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5428 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5429 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
5430 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5431 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
5432 if (NotMaskLZ == 64) return Result; // All zero mask.
5434 // See if we have a continuous run of bits. If so, we have 0*1+0*
5435 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5438 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5439 if (V.getValueType() != MVT::i64 && NotMaskLZ)
5440 NotMaskLZ -= 64-V.getValueSizeInBits();
5442 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5443 switch (MaskedBytes) {
5447 default: return Result; // All one mask, or 5-byte mask.
5450 // Verify that the first bit starts at a multiple of mask so that the access
5451 // is aligned the same as the access width.
5452 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5454 Result.first = MaskedBytes;
5455 Result.second = NotMaskTZ/8;
5460 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5461 /// provides a value as specified by MaskInfo. If so, replace the specified
5462 /// store with a narrower store of truncated IVal.
5464 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5465 SDValue IVal, StoreSDNode *St,
5467 unsigned NumBytes = MaskInfo.first;
5468 unsigned ByteShift = MaskInfo.second;
5469 SelectionDAG &DAG = DC->getDAG();
5471 // Check to see if IVal is all zeros in the part being masked in by the 'or'
5472 // that uses this. If not, this is not a replacement.
5473 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5474 ByteShift*8, (ByteShift+NumBytes)*8);
5475 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5477 // Check that it is legal on the target to do this. It is legal if the new
5478 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5480 MVT VT = MVT::getIntegerVT(NumBytes*8);
5481 if (!DC->isTypeLegal(VT))
5484 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
5485 // shifted by ByteShift and truncated down to NumBytes.
5487 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5488 DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5490 // Figure out the offset for the store and the alignment of the access.
5492 unsigned NewAlign = St->getAlignment();
5494 if (DAG.getTargetLoweringInfo().isLittleEndian())
5495 StOffset = ByteShift;
5497 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5499 SDValue Ptr = St->getBasePtr();
5501 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5502 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5503 NewAlign = MinAlign(NewAlign, StOffset);
5506 // Truncate down to the new size.
5507 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5510 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
5511 St->getSrcValue(), St->getSrcValueOffset()+StOffset,
5512 false, false, NewAlign).getNode();
5516 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5517 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5518 /// of the loaded bits, try narrowing the load and store if it would end up
5519 /// being a win for performance or code size.
5520 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5521 StoreSDNode *ST = cast<StoreSDNode>(N);
5522 if (ST->isVolatile())
5525 SDValue Chain = ST->getChain();
5526 SDValue Value = ST->getValue();
5527 SDValue Ptr = ST->getBasePtr();
5528 EVT VT = Value.getValueType();
5530 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
5533 unsigned Opc = Value.getOpcode();
5535 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
5536 // is a byte mask indicating a consecutive number of bytes, check to see if
5537 // Y is known to provide just those bytes. If so, we try to replace the
5538 // load + replace + store sequence with a single (narrower) store, which makes
5540 if (Opc == ISD::OR) {
5541 std::pair<unsigned, unsigned> MaskedLoad;
5542 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
5543 if (MaskedLoad.first)
5544 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5545 Value.getOperand(1), ST,this))
5546 return SDValue(NewST, 0);
5548 // Or is commutative, so try swapping X and Y.
5549 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
5550 if (MaskedLoad.first)
5551 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5552 Value.getOperand(0), ST,this))
5553 return SDValue(NewST, 0);
5556 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
5557 Value.getOperand(1).getOpcode() != ISD::Constant)
5560 SDValue N0 = Value.getOperand(0);
5561 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
5562 LoadSDNode *LD = cast<LoadSDNode>(N0);
5563 if (LD->getBasePtr() != Ptr)
5566 // Find the type to narrow it the load / op / store to.
5567 SDValue N1 = Value.getOperand(1);
5568 unsigned BitWidth = N1.getValueSizeInBits();
5569 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5570 if (Opc == ISD::AND)
5571 Imm ^= APInt::getAllOnesValue(BitWidth);
5572 if (Imm == 0 || Imm.isAllOnesValue())
5574 unsigned ShAmt = Imm.countTrailingZeros();
5575 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5576 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5577 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5578 while (NewBW < BitWidth &&
5579 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5580 TLI.isNarrowingProfitable(VT, NewVT))) {
5581 NewBW = NextPowerOf2(NewBW);
5582 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5584 if (NewBW >= BitWidth)
5587 // If the lsb changed does not start at the type bitwidth boundary,
5588 // start at the previous one.
5590 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5591 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5592 if ((Imm & Mask) == Imm) {
5593 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5594 if (Opc == ISD::AND)
5595 NewImm ^= APInt::getAllOnesValue(NewBW);
5596 uint64_t PtrOff = ShAmt / 8;
5597 // For big endian targets, we need to adjust the offset to the pointer to
5598 // load the correct bytes.
5599 if (TLI.isBigEndian())
5600 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5602 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5603 const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
5604 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
5607 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5608 Ptr.getValueType(), Ptr,
5609 DAG.getConstant(PtrOff, Ptr.getValueType()));
5610 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5611 LD->getChain(), NewPtr,
5612 LD->getSrcValue(), LD->getSrcValueOffset(),
5613 LD->isVolatile(), LD->isNonTemporal(),
5615 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5616 DAG.getConstant(NewImm, NewVT));
5617 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5619 ST->getSrcValue(), ST->getSrcValueOffset(),
5620 false, false, NewAlign);
5622 AddToWorkList(NewPtr.getNode());
5623 AddToWorkList(NewLD.getNode());
5624 AddToWorkList(NewVal.getNode());
5625 WorkListRemover DeadNodes(*this);
5626 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5636 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5637 StoreSDNode *ST = cast<StoreSDNode>(N);
5638 SDValue Chain = ST->getChain();
5639 SDValue Value = ST->getValue();
5640 SDValue Ptr = ST->getBasePtr();
5642 // If this is a store of a bit convert, store the input value if the
5643 // resultant store does not need a higher alignment than the original.
5644 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5645 ST->isUnindexed()) {
5646 unsigned OrigAlign = ST->getAlignment();
5647 EVT SVT = Value.getOperand(0).getValueType();
5648 unsigned Align = TLI.getTargetData()->
5649 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5650 if (Align <= OrigAlign &&
5651 ((!LegalOperations && !ST->isVolatile()) ||
5652 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5653 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5654 Ptr, ST->getSrcValue(),
5655 ST->getSrcValueOffset(), ST->isVolatile(),
5656 ST->isNonTemporal(), OrigAlign);
5659 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5660 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5661 // NOTE: If the original store is volatile, this transform must not increase
5662 // the number of stores. For example, on x86-32 an f64 can be stored in one
5663 // processor operation but an i64 (which is not legal) requires two. So the
5664 // transform should not be done in this case.
5665 if (Value.getOpcode() != ISD::TargetConstantFP) {
5667 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5668 default: llvm_unreachable("Unknown FP type");
5669 case MVT::f80: // We don't do this for these yet.
5674 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
5675 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5676 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5677 bitcastToAPInt().getZExtValue(), MVT::i32);
5678 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5679 Ptr, ST->getSrcValue(),
5680 ST->getSrcValueOffset(), ST->isVolatile(),
5681 ST->isNonTemporal(), ST->getAlignment());
5685 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
5686 !ST->isVolatile()) ||
5687 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5688 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5689 getZExtValue(), MVT::i64);
5690 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5691 Ptr, ST->getSrcValue(),
5692 ST->getSrcValueOffset(), ST->isVolatile(),
5693 ST->isNonTemporal(), ST->getAlignment());
5694 } else if (!ST->isVolatile() &&
5695 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5696 // Many FP stores are not made apparent until after legalize, e.g. for
5697 // argument passing. Since this is so common, custom legalize the
5698 // 64-bit integer store into two 32-bit stores.
5699 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5700 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5701 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5702 if (TLI.isBigEndian()) std::swap(Lo, Hi);
5704 int SVOffset = ST->getSrcValueOffset();
5705 unsigned Alignment = ST->getAlignment();
5706 bool isVolatile = ST->isVolatile();
5707 bool isNonTemporal = ST->isNonTemporal();
5709 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5710 Ptr, ST->getSrcValue(),
5711 ST->getSrcValueOffset(),
5712 isVolatile, isNonTemporal,
5713 ST->getAlignment());
5714 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5715 DAG.getConstant(4, Ptr.getValueType()));
5717 Alignment = MinAlign(Alignment, 4U);
5718 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5719 Ptr, ST->getSrcValue(),
5720 SVOffset, isVolatile, isNonTemporal,
5722 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5731 // Try to infer better alignment information than the store already has.
5732 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5733 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5734 if (Align > ST->getAlignment())
5735 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5736 Ptr, ST->getSrcValue(),
5737 ST->getSrcValueOffset(), ST->getMemoryVT(),
5738 ST->isVolatile(), ST->isNonTemporal(), Align);
5743 // Walk up chain skipping non-aliasing memory nodes.
5744 SDValue BetterChain = FindBetterChain(N, Chain);
5746 // If there is a better chain.
5747 if (Chain != BetterChain) {
5750 // Replace the chain to avoid dependency.
5751 if (ST->isTruncatingStore()) {
5752 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5753 ST->getSrcValue(),ST->getSrcValueOffset(),
5754 ST->getMemoryVT(), ST->isVolatile(),
5755 ST->isNonTemporal(), ST->getAlignment());
5757 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5758 ST->getSrcValue(), ST->getSrcValueOffset(),
5759 ST->isVolatile(), ST->isNonTemporal(),
5760 ST->getAlignment());
5763 // Create token to keep both nodes around.
5764 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5765 MVT::Other, Chain, ReplStore);
5767 // Make sure the new and old chains are cleaned up.
5768 AddToWorkList(Token.getNode());
5770 // Don't add users to work list.
5771 return CombineTo(N, Token, false);
5775 // Try transforming N to an indexed store.
5776 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5777 return SDValue(N, 0);
5779 // FIXME: is there such a thing as a truncating indexed store?
5780 if (ST->isTruncatingStore() && ST->isUnindexed() &&
5781 Value.getValueType().isInteger()) {
5782 // See if we can simplify the input to this truncstore with knowledge that
5783 // only the low bits are being used. For example:
5784 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
5786 GetDemandedBits(Value,
5787 APInt::getLowBitsSet(Value.getValueSizeInBits(),
5788 ST->getMemoryVT().getSizeInBits()));
5789 AddToWorkList(Value.getNode());
5790 if (Shorter.getNode())
5791 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5792 Ptr, ST->getSrcValue(),
5793 ST->getSrcValueOffset(), ST->getMemoryVT(),
5794 ST->isVolatile(), ST->isNonTemporal(),
5795 ST->getAlignment());
5797 // Otherwise, see if we can simplify the operation with
5798 // SimplifyDemandedBits, which only works if the value has a single use.
5799 if (SimplifyDemandedBits(Value,
5800 APInt::getLowBitsSet(
5801 Value.getValueType().getScalarType().getSizeInBits(),
5802 ST->getMemoryVT().getScalarType().getSizeInBits())))
5803 return SDValue(N, 0);
5806 // If this is a load followed by a store to the same location, then the store
5808 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5809 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5810 ST->isUnindexed() && !ST->isVolatile() &&
5811 // There can't be any side effects between the load and store, such as
5813 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5814 // The store is dead, remove it.
5819 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5820 // truncating store. We can do this even if this is already a truncstore.
5821 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5822 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5823 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5824 ST->getMemoryVT())) {
5825 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5826 Ptr, ST->getSrcValue(),
5827 ST->getSrcValueOffset(), ST->getMemoryVT(),
5828 ST->isVolatile(), ST->isNonTemporal(),
5829 ST->getAlignment());
5832 return ReduceLoadOpStoreWidth(N);
5835 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5836 SDValue InVec = N->getOperand(0);
5837 SDValue InVal = N->getOperand(1);
5838 SDValue EltNo = N->getOperand(2);
5840 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5841 // vector with the inserted element.
5842 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5843 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5844 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5845 InVec.getNode()->op_end());
5846 if (Elt < Ops.size())
5848 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5849 InVec.getValueType(), &Ops[0], Ops.size());
5851 // If the invec is an UNDEF and if EltNo is a constant, create a new
5852 // BUILD_VECTOR with undef elements and the inserted element.
5853 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
5854 isa<ConstantSDNode>(EltNo)) {
5855 EVT VT = InVec.getValueType();
5856 EVT EltVT = VT.getVectorElementType();
5857 unsigned NElts = VT.getVectorNumElements();
5858 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
5860 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5861 if (Elt < Ops.size())
5863 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5864 InVec.getValueType(), &Ops[0], Ops.size());
5869 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5870 // (vextract (scalar_to_vector val, 0) -> val
5871 SDValue InVec = N->getOperand(0);
5873 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5874 // Check if the result type doesn't match the inserted element type. A
5875 // SCALAR_TO_VECTOR may truncate the inserted element and the
5876 // EXTRACT_VECTOR_ELT may widen the extracted vector.
5877 EVT EltVT = InVec.getValueType().getVectorElementType();
5878 SDValue InOp = InVec.getOperand(0);
5879 EVT NVT = N->getValueType(0);
5880 if (InOp.getValueType() != NVT) {
5881 assert(InOp.getValueType().isInteger() && NVT.isInteger());
5882 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
5887 // Perform only after legalization to ensure build_vector / vector_shuffle
5888 // optimizations have already been done.
5889 if (!LegalOperations) return SDValue();
5891 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5892 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5893 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5894 SDValue EltNo = N->getOperand(1);
5896 if (isa<ConstantSDNode>(EltNo)) {
5897 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5898 bool NewLoad = false;
5899 bool BCNumEltsChanged = false;
5900 EVT VT = InVec.getValueType();
5901 EVT ExtVT = VT.getVectorElementType();
5904 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
5905 EVT BCVT = InVec.getOperand(0).getValueType();
5906 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
5908 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
5909 BCNumEltsChanged = true;
5910 InVec = InVec.getOperand(0);
5911 ExtVT = BCVT.getVectorElementType();
5915 LoadSDNode *LN0 = NULL;
5916 const ShuffleVectorSDNode *SVN = NULL;
5917 if (ISD::isNormalLoad(InVec.getNode())) {
5918 LN0 = cast<LoadSDNode>(InVec);
5919 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5920 InVec.getOperand(0).getValueType() == ExtVT &&
5921 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
5922 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
5923 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
5924 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
5926 // (load $addr+1*size)
5928 // If the bit convert changed the number of elements, it is unsafe
5929 // to examine the mask.
5930 if (BCNumEltsChanged)
5933 // Select the input vector, guarding against out of range extract vector.
5934 unsigned NumElems = VT.getVectorNumElements();
5935 int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
5936 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
5938 if (InVec.getOpcode() == ISD::BIT_CONVERT)
5939 InVec = InVec.getOperand(0);
5940 if (ISD::isNormalLoad(InVec.getNode())) {
5941 LN0 = cast<LoadSDNode>(InVec);
5942 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
5946 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
5949 unsigned Align = LN0->getAlignment();
5951 // Check the resultant load doesn't need a higher alignment than the
5954 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
5956 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
5962 SDValue NewPtr = LN0->getBasePtr();
5964 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
5965 EVT PtrType = NewPtr.getValueType();
5966 if (TLI.isBigEndian())
5967 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
5968 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
5969 DAG.getConstant(PtrOff, PtrType));
5972 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
5973 LN0->getSrcValue(), LN0->getSrcValueOffset(),
5974 LN0->isVolatile(), LN0->isNonTemporal(), Align);
5980 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
5981 unsigned NumInScalars = N->getNumOperands();
5982 EVT VT = N->getValueType(0);
5984 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
5985 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
5986 // at most two distinct vectors, turn this into a shuffle node.
5987 SDValue VecIn1, VecIn2;
5988 for (unsigned i = 0; i != NumInScalars; ++i) {
5989 // Ignore undef inputs.
5990 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5992 // If this input is something other than a EXTRACT_VECTOR_ELT with a
5993 // constant index, bail out.
5994 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5995 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
5996 VecIn1 = VecIn2 = SDValue(0, 0);
6000 // If the input vector type disagrees with the result of the build_vector,
6001 // we can't make a shuffle.
6002 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6003 if (ExtractedFromVec.getValueType() != VT) {
6004 VecIn1 = VecIn2 = SDValue(0, 0);
6008 // Otherwise, remember this. We allow up to two distinct input vectors.
6009 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6012 if (VecIn1.getNode() == 0) {
6013 VecIn1 = ExtractedFromVec;
6014 } else if (VecIn2.getNode() == 0) {
6015 VecIn2 = ExtractedFromVec;
6018 VecIn1 = VecIn2 = SDValue(0, 0);
6023 // If everything is good, we can make a shuffle operation.
6024 if (VecIn1.getNode()) {
6025 SmallVector<int, 8> Mask;
6026 for (unsigned i = 0; i != NumInScalars; ++i) {
6027 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6032 // If extracting from the first vector, just use the index directly.
6033 SDValue Extract = N->getOperand(i);
6034 SDValue ExtVal = Extract.getOperand(1);
6035 if (Extract.getOperand(0) == VecIn1) {
6036 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6037 if (ExtIndex > VT.getVectorNumElements())
6040 Mask.push_back(ExtIndex);
6044 // Otherwise, use InIdx + VecSize
6045 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6046 Mask.push_back(Idx+NumInScalars);
6049 // Add count and size info.
6050 if (!isTypeLegal(VT))
6053 // Return the new VECTOR_SHUFFLE node.
6056 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6057 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6063 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6064 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6065 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
6066 // inputs come from at most two distinct vectors, turn this into a shuffle
6069 // If we only have one input vector, we don't need to do any concatenation.
6070 if (N->getNumOperands() == 1)
6071 return N->getOperand(0);
6076 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6079 EVT VT = N->getValueType(0);
6080 unsigned NumElts = VT.getVectorNumElements();
6082 SDValue N0 = N->getOperand(0);
6084 assert(N0.getValueType().getVectorNumElements() == NumElts &&
6085 "Vector shuffle must be normalized in DAG");
6087 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6089 // If it is a splat, check if the argument vector is a build_vector with
6090 // all scalar elements the same.
6091 if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
6092 SDNode *V = N0.getNode();
6095 // If this is a bit convert that changes the element type of the vector but
6096 // not the number of vector elements, look through it. Be careful not to
6097 // look though conversions that change things like v4f32 to v2f64.
6098 if (V->getOpcode() == ISD::BIT_CONVERT) {
6099 SDValue ConvInput = V->getOperand(0);
6100 if (ConvInput.getValueType().isVector() &&
6101 ConvInput.getValueType().getVectorNumElements() == NumElts)
6102 V = ConvInput.getNode();
6105 if (V->getOpcode() == ISD::BUILD_VECTOR) {
6106 unsigned NumElems = V->getNumOperands();
6107 unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
6108 if (NumElems > BaseIdx) {
6110 bool AllSame = true;
6111 for (unsigned i = 0; i != NumElems; ++i) {
6112 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6113 Base = V->getOperand(i);
6117 // Splat of <u, u, u, u>, return <u, u, u, u>
6118 if (!Base.getNode())
6120 for (unsigned i = 0; i != NumElems; ++i) {
6121 if (V->getOperand(i) != Base) {
6126 // Splat of <x, x, x, x>, return <x, x, x, x>
6135 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6136 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6137 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6138 /// vector_shuffle V, Zero, <0, 4, 2, 4>
6139 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6140 EVT VT = N->getValueType(0);
6141 DebugLoc dl = N->getDebugLoc();
6142 SDValue LHS = N->getOperand(0);
6143 SDValue RHS = N->getOperand(1);
6144 if (N->getOpcode() == ISD::AND) {
6145 if (RHS.getOpcode() == ISD::BIT_CONVERT)
6146 RHS = RHS.getOperand(0);
6147 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6148 SmallVector<int, 8> Indices;
6149 unsigned NumElts = RHS.getNumOperands();
6150 for (unsigned i = 0; i != NumElts; ++i) {
6151 SDValue Elt = RHS.getOperand(i);
6152 if (!isa<ConstantSDNode>(Elt))
6154 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6155 Indices.push_back(i);
6156 else if (cast<ConstantSDNode>(Elt)->isNullValue())
6157 Indices.push_back(NumElts);
6162 // Let's see if the target supports this vector_shuffle.
6163 EVT RVT = RHS.getValueType();
6164 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6167 // Return the new VECTOR_SHUFFLE node.
6168 EVT EltVT = RVT.getVectorElementType();
6169 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6170 DAG.getConstant(0, EltVT));
6171 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6172 RVT, &ZeroOps[0], ZeroOps.size());
6173 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
6174 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6175 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
6182 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6183 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6184 // After legalize, the target may be depending on adds and other
6185 // binary ops to provide legal ways to construct constants or other
6186 // things. Simplifying them may result in a loss of legality.
6187 if (LegalOperations) return SDValue();
6189 EVT VT = N->getValueType(0);
6190 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
6192 EVT EltType = VT.getVectorElementType();
6193 SDValue LHS = N->getOperand(0);
6194 SDValue RHS = N->getOperand(1);
6195 SDValue Shuffle = XformToShuffleWithZero(N);
6196 if (Shuffle.getNode()) return Shuffle;
6198 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6200 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6201 RHS.getOpcode() == ISD::BUILD_VECTOR) {
6202 SmallVector<SDValue, 8> Ops;
6203 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6204 SDValue LHSOp = LHS.getOperand(i);
6205 SDValue RHSOp = RHS.getOperand(i);
6206 // If these two elements can't be folded, bail out.
6207 if ((LHSOp.getOpcode() != ISD::UNDEF &&
6208 LHSOp.getOpcode() != ISD::Constant &&
6209 LHSOp.getOpcode() != ISD::ConstantFP) ||
6210 (RHSOp.getOpcode() != ISD::UNDEF &&
6211 RHSOp.getOpcode() != ISD::Constant &&
6212 RHSOp.getOpcode() != ISD::ConstantFP))
6215 // Can't fold divide by zero.
6216 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6217 N->getOpcode() == ISD::FDIV) {
6218 if ((RHSOp.getOpcode() == ISD::Constant &&
6219 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6220 (RHSOp.getOpcode() == ISD::ConstantFP &&
6221 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6225 Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
6226 EltType, LHSOp, RHSOp));
6227 AddToWorkList(Ops.back().getNode());
6228 assert((Ops.back().getOpcode() == ISD::UNDEF ||
6229 Ops.back().getOpcode() == ISD::Constant ||
6230 Ops.back().getOpcode() == ISD::ConstantFP) &&
6231 "Scalar binop didn't fold!");
6234 if (Ops.size() == LHS.getNumOperands()) {
6235 EVT VT = LHS.getValueType();
6236 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
6237 &Ops[0], Ops.size());
6244 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6245 SDValue N1, SDValue N2){
6246 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6248 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6249 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6251 // If we got a simplified select_cc node back from SimplifySelectCC, then
6252 // break it down into a new SETCC node, and a new SELECT node, and then return
6253 // the SELECT node, since we were called with a SELECT node.
6254 if (SCC.getNode()) {
6255 // Check to see if we got a select_cc back (to turn into setcc/select).
6256 // Otherwise, just return whatever node we got back, like fabs.
6257 if (SCC.getOpcode() == ISD::SELECT_CC) {
6258 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6260 SCC.getOperand(0), SCC.getOperand(1),
6262 AddToWorkList(SETCC.getNode());
6263 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6264 SCC.getOperand(2), SCC.getOperand(3), SETCC);
6272 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6273 /// are the two values being selected between, see if we can simplify the
6274 /// select. Callers of this should assume that TheSelect is deleted if this
6275 /// returns true. As such, they should return the appropriate thing (e.g. the
6276 /// node) back to the top-level of the DAG combiner loop to avoid it being
6278 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6281 // If this is a select from two identical things, try to pull the operation
6282 // through the select.
6283 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
6284 // If this is a load and the token chain is identical, replace the select
6285 // of two loads with a load through a select of the address to load from.
6286 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6287 // constants have been dropped into the constant pool.
6288 if (LHS.getOpcode() == ISD::LOAD &&
6289 // Do not let this transformation reduce the number of volatile loads.
6290 !cast<LoadSDNode>(LHS)->isVolatile() &&
6291 !cast<LoadSDNode>(RHS)->isVolatile() &&
6292 // Token chains must be identical.
6293 LHS.getOperand(0) == RHS.getOperand(0)) {
6294 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6295 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6297 // If this is an EXTLOAD, the VT's must match.
6298 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
6299 // FIXME: this discards src value information. This is
6300 // over-conservative. It would be beneficial to be able to remember
6301 // both potential memory locations. Since we are discarding
6302 // src value info, don't do the transformation if the memory
6303 // locations are not in the default address space.
6304 unsigned LLDAddrSpace = 0, RLDAddrSpace = 0;
6305 if (const Value *LLDVal = LLD->getMemOperand()->getValue()) {
6306 if (const PointerType *PT = dyn_cast<PointerType>(LLDVal->getType()))
6307 LLDAddrSpace = PT->getAddressSpace();
6309 if (const Value *RLDVal = RLD->getMemOperand()->getValue()) {
6310 if (const PointerType *PT = dyn_cast<PointerType>(RLDVal->getType()))
6311 RLDAddrSpace = PT->getAddressSpace();
6314 if (LLDAddrSpace == 0 && RLDAddrSpace == 0) {
6315 if (TheSelect->getOpcode() == ISD::SELECT) {
6316 // Check that the condition doesn't reach either load. If so, folding
6317 // this will induce a cycle into the DAG.
6318 if ((!LLD->hasAnyUseOfValue(1) ||
6319 !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) &&
6320 (!RLD->hasAnyUseOfValue(1) ||
6321 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) {
6322 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6323 LLD->getBasePtr().getValueType(),
6324 TheSelect->getOperand(0), LLD->getBasePtr(),
6328 // Check that the condition doesn't reach either load. If so, folding
6329 // this will induce a cycle into the DAG.
6330 if ((!LLD->hasAnyUseOfValue(1) ||
6331 (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
6332 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) &&
6333 (!RLD->hasAnyUseOfValue(1) ||
6334 (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
6335 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) {
6336 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6337 LLD->getBasePtr().getValueType(),
6338 TheSelect->getOperand(0),
6339 TheSelect->getOperand(1),
6340 LLD->getBasePtr(), RLD->getBasePtr(),
6341 TheSelect->getOperand(4));
6346 if (Addr.getNode()) {
6348 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6349 Load = DAG.getLoad(TheSelect->getValueType(0),
6350 TheSelect->getDebugLoc(),
6354 LLD->isNonTemporal(),
6355 LLD->getAlignment());
6357 Load = DAG.getExtLoad(LLD->getExtensionType(),
6358 TheSelect->getDebugLoc(),
6359 TheSelect->getValueType(0),
6360 LLD->getChain(), Addr, 0, 0,
6363 LLD->isNonTemporal(),
6364 LLD->getAlignment());
6367 // Users of the select now use the result of the load.
6368 CombineTo(TheSelect, Load);
6370 // Users of the old loads now use the new load's chain. We know the
6371 // old-load value is dead now.
6372 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6373 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6383 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6384 /// where 'cond' is the comparison specified by CC.
6385 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6386 SDValue N2, SDValue N3,
6387 ISD::CondCode CC, bool NotExtCompare) {
6388 // (x ? y : y) -> y.
6389 if (N2 == N3) return N2;
6391 EVT VT = N2.getValueType();
6392 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6393 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6394 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6396 // Determine if the condition we're dealing with is constant
6397 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6398 N0, N1, CC, DL, false);
6399 if (SCC.getNode()) AddToWorkList(SCC.getNode());
6400 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6402 // fold select_cc true, x, y -> x
6403 if (SCCC && !SCCC->isNullValue())
6405 // fold select_cc false, x, y -> y
6406 if (SCCC && SCCC->isNullValue())
6409 // Check to see if we can simplify the select into an fabs node
6410 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
6411 // Allow either -0.0 or 0.0
6412 if (CFP->getValueAPF().isZero()) {
6413 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
6414 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
6415 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
6416 N2 == N3.getOperand(0))
6417 return DAG.getNode(ISD::FABS, DL, VT, N0);
6419 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
6420 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
6421 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
6422 N2.getOperand(0) == N3)
6423 return DAG.getNode(ISD::FABS, DL, VT, N3);
6427 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
6428 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
6429 // in it. This is a win when the constant is not otherwise available because
6430 // it replaces two constant pool loads with one. We only do this if the FP
6431 // type is known to be legal, because if it isn't, then we are before legalize
6432 // types an we want the other legalization to happen first (e.g. to avoid
6433 // messing with soft float) and if the ConstantFP is not legal, because if
6434 // it is legal, we may not need to store the FP constant in a constant pool.
6435 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
6436 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
6437 if (TLI.isTypeLegal(N2.getValueType()) &&
6438 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
6439 TargetLowering::Legal) &&
6440 // If both constants have multiple uses, then we won't need to do an
6441 // extra load, they are likely around in registers for other users.
6442 (TV->hasOneUse() || FV->hasOneUse())) {
6443 Constant *Elts[] = {
6444 const_cast<ConstantFP*>(FV->getConstantFPValue()),
6445 const_cast<ConstantFP*>(TV->getConstantFPValue())
6447 const Type *FPTy = Elts[0]->getType();
6448 const TargetData &TD = *TLI.getTargetData();
6450 // Create a ConstantArray of the two constants.
6451 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
6452 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
6453 TD.getPrefTypeAlignment(FPTy));
6454 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6456 // Get the offsets to the 0 and 1 element of the array so that we can
6457 // select between them.
6458 SDValue Zero = DAG.getIntPtrConstant(0);
6459 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
6460 SDValue One = DAG.getIntPtrConstant(EltSize);
6462 SDValue Cond = DAG.getSetCC(DL,
6463 TLI.getSetCCResultType(N0.getValueType()),
6465 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
6467 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
6469 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6470 PseudoSourceValue::getConstantPool(), 0, false,
6476 // Check to see if we can perform the "gzip trick", transforming
6477 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
6478 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
6479 N0.getValueType().isInteger() &&
6480 N2.getValueType().isInteger() &&
6481 (N1C->isNullValue() || // (a < 0) ? b : 0
6482 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
6483 EVT XType = N0.getValueType();
6484 EVT AType = N2.getValueType();
6485 if (XType.bitsGE(AType)) {
6486 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
6487 // single-bit constant.
6488 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
6489 unsigned ShCtV = N2C->getAPIntValue().logBase2();
6490 ShCtV = XType.getSizeInBits()-ShCtV-1;
6491 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
6492 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
6494 AddToWorkList(Shift.getNode());
6496 if (XType.bitsGT(AType)) {
6497 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6498 AddToWorkList(Shift.getNode());
6501 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6504 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
6506 DAG.getConstant(XType.getSizeInBits()-1,
6507 getShiftAmountTy()));
6508 AddToWorkList(Shift.getNode());
6510 if (XType.bitsGT(AType)) {
6511 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6512 AddToWorkList(Shift.getNode());
6515 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6519 // fold select C, 16, 0 -> shl C, 4
6520 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
6521 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
6523 // If the caller doesn't want us to simplify this into a zext of a compare,
6525 if (NotExtCompare && N2C->getAPIntValue() == 1)
6528 // Get a SetCC of the condition
6529 // FIXME: Should probably make sure that setcc is legal if we ever have a
6530 // target where it isn't.
6532 // cast from setcc result type to select result type
6534 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
6536 if (N2.getValueType().bitsLT(SCC.getValueType()))
6537 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
6539 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6540 N2.getValueType(), SCC);
6542 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
6543 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6544 N2.getValueType(), SCC);
6547 AddToWorkList(SCC.getNode());
6548 AddToWorkList(Temp.getNode());
6550 if (N2C->getAPIntValue() == 1)
6553 // shl setcc result by log2 n2c
6554 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
6555 DAG.getConstant(N2C->getAPIntValue().logBase2(),
6556 getShiftAmountTy()));
6559 // Check to see if this is the equivalent of setcc
6560 // FIXME: Turn all of these into setcc if setcc if setcc is legal
6561 // otherwise, go ahead with the folds.
6562 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
6563 EVT XType = N0.getValueType();
6564 if (!LegalOperations ||
6565 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
6566 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
6567 if (Res.getValueType() != VT)
6568 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
6572 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
6573 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
6574 (!LegalOperations ||
6575 TLI.isOperationLegal(ISD::CTLZ, XType))) {
6576 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
6577 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
6578 DAG.getConstant(Log2_32(XType.getSizeInBits()),
6579 getShiftAmountTy()));
6581 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
6582 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
6583 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
6584 XType, DAG.getConstant(0, XType), N0);
6585 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
6586 return DAG.getNode(ISD::SRL, DL, XType,
6587 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
6588 DAG.getConstant(XType.getSizeInBits()-1,
6589 getShiftAmountTy()));
6591 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6592 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6593 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6594 DAG.getConstant(XType.getSizeInBits()-1,
6595 getShiftAmountTy()));
6596 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6600 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
6601 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6602 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
6603 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
6604 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
6605 EVT XType = N0.getValueType();
6606 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
6607 DAG.getConstant(XType.getSizeInBits()-1,
6608 getShiftAmountTy()));
6609 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
6611 AddToWorkList(Shift.getNode());
6612 AddToWorkList(Add.getNode());
6613 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6615 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
6616 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6617 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
6618 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
6619 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
6620 EVT XType = N0.getValueType();
6621 if (SubC->isNullValue() && XType.isInteger()) {
6622 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6624 DAG.getConstant(XType.getSizeInBits()-1,
6625 getShiftAmountTy()));
6626 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6628 AddToWorkList(Shift.getNode());
6629 AddToWorkList(Add.getNode());
6630 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6638 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6639 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6640 SDValue N1, ISD::CondCode Cond,
6641 DebugLoc DL, bool foldBooleans) {
6642 TargetLowering::DAGCombinerInfo
6643 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6644 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6647 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6648 /// return a DAG expression to select that will generate the same value by
6649 /// multiplying by a magic number. See:
6650 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6651 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
6652 std::vector<SDNode*> Built;
6653 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6655 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6661 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6662 /// return a DAG expression to select that will generate the same value by
6663 /// multiplying by a magic number. See:
6664 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6665 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
6666 std::vector<SDNode*> Built;
6667 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6669 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6675 /// FindBaseOffset - Return true if base is a frame index, which is known not
6676 // to alias with anything but itself. Provides base object and offset as results.
6677 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
6678 const GlobalValue *&GV, void *&CV) {
6679 // Assume it is a primitive operation.
6680 Base = Ptr; Offset = 0; GV = 0; CV = 0;
6682 // If it's an adding a simple constant then integrate the offset.
6683 if (Base.getOpcode() == ISD::ADD) {
6684 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6685 Base = Base.getOperand(0);
6686 Offset += C->getZExtValue();
6690 // Return the underlying GlobalValue, and update the Offset. Return false
6691 // for GlobalAddressSDNode since the same GlobalAddress may be represented
6692 // by multiple nodes with different offsets.
6693 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
6694 GV = G->getGlobal();
6695 Offset += G->getOffset();
6699 // Return the underlying Constant value, and update the Offset. Return false
6700 // for ConstantSDNodes since the same constant pool entry may be represented
6701 // by multiple nodes with different offsets.
6702 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
6703 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
6704 : (void *)C->getConstVal();
6705 Offset += C->getOffset();
6708 // If it's any of the following then it can't alias with anything but itself.
6709 return isa<FrameIndexSDNode>(Base);
6712 /// isAlias - Return true if there is any possibility that the two addresses
6714 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6715 const Value *SrcValue1, int SrcValueOffset1,
6716 unsigned SrcValueAlign1,
6717 SDValue Ptr2, int64_t Size2,
6718 const Value *SrcValue2, int SrcValueOffset2,
6719 unsigned SrcValueAlign2) const {
6720 // If they are the same then they must be aliases.
6721 if (Ptr1 == Ptr2) return true;
6723 // Gather base node and offset information.
6724 SDValue Base1, Base2;
6725 int64_t Offset1, Offset2;
6726 const GlobalValue *GV1, *GV2;
6728 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
6729 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
6731 // If they have a same base address then check to see if they overlap.
6732 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
6733 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6735 // If we know what the bases are, and they aren't identical, then we know they
6737 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
6740 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
6741 // compared to the size and offset of the access, we may be able to prove they
6742 // do not alias. This check is conservative for now to catch cases created by
6743 // splitting vector types.
6744 if ((SrcValueAlign1 == SrcValueAlign2) &&
6745 (SrcValueOffset1 != SrcValueOffset2) &&
6746 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
6747 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
6748 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
6750 // There is no overlap between these relatively aligned accesses of similar
6751 // size, return no alias.
6752 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
6756 if (CombinerGlobalAA) {
6757 // Use alias analysis information.
6758 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6759 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6760 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6761 AliasAnalysis::AliasResult AAResult =
6762 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6763 if (AAResult == AliasAnalysis::NoAlias)
6767 // Otherwise we have to assume they alias.
6771 /// FindAliasInfo - Extracts the relevant alias information from the memory
6772 /// node. Returns true if the operand was a load.
6773 bool DAGCombiner::FindAliasInfo(SDNode *N,
6774 SDValue &Ptr, int64_t &Size,
6775 const Value *&SrcValue,
6776 int &SrcValueOffset,
6777 unsigned &SrcValueAlign) const {
6778 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6779 Ptr = LD->getBasePtr();
6780 Size = LD->getMemoryVT().getSizeInBits() >> 3;
6781 SrcValue = LD->getSrcValue();
6782 SrcValueOffset = LD->getSrcValueOffset();
6783 SrcValueAlign = LD->getOriginalAlignment();
6785 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6786 Ptr = ST->getBasePtr();
6787 Size = ST->getMemoryVT().getSizeInBits() >> 3;
6788 SrcValue = ST->getSrcValue();
6789 SrcValueOffset = ST->getSrcValueOffset();
6790 SrcValueAlign = ST->getOriginalAlignment();
6792 llvm_unreachable("FindAliasInfo expected a memory operand");
6798 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6799 /// looking for aliasing nodes and adding them to the Aliases vector.
6800 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6801 SmallVector<SDValue, 8> &Aliases) {
6802 SmallVector<SDValue, 8> Chains; // List of chains to visit.
6803 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
6805 // Get alias information for node.
6808 const Value *SrcValue;
6810 unsigned SrcValueAlign;
6811 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
6815 Chains.push_back(OriginalChain);
6818 // Look at each chain and determine if it is an alias. If so, add it to the
6819 // aliases list. If not, then continue up the chain looking for the next
6821 while (!Chains.empty()) {
6822 SDValue Chain = Chains.back();
6825 // For TokenFactor nodes, look at each operand and only continue up the
6826 // chain until we find two aliases. If we've seen two aliases, assume we'll
6827 // find more and revert to original chain since the xform is unlikely to be
6830 // FIXME: The depth check could be made to return the last non-aliasing
6831 // chain we found before we hit a tokenfactor rather than the original
6833 if (Depth > 6 || Aliases.size() == 2) {
6835 Aliases.push_back(OriginalChain);
6839 // Don't bother if we've been before.
6840 if (!Visited.insert(Chain.getNode()))
6843 switch (Chain.getOpcode()) {
6844 case ISD::EntryToken:
6845 // Entry token is ideal chain operand, but handled in FindBetterChain.
6850 // Get alias information for Chain.
6853 const Value *OpSrcValue;
6854 int OpSrcValueOffset;
6855 unsigned OpSrcValueAlign;
6856 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6857 OpSrcValue, OpSrcValueOffset,
6860 // If chain is alias then stop here.
6861 if (!(IsLoad && IsOpLoad) &&
6862 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
6863 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
6865 Aliases.push_back(Chain);
6867 // Look further up the chain.
6868 Chains.push_back(Chain.getOperand(0));
6874 case ISD::TokenFactor:
6875 // We have to check each of the operands of the token factor for "small"
6876 // token factors, so we queue them up. Adding the operands to the queue
6877 // (stack) in reverse order maintains the original order and increases the
6878 // likelihood that getNode will find a matching token factor (CSE.)
6879 if (Chain.getNumOperands() > 16) {
6880 Aliases.push_back(Chain);
6883 for (unsigned n = Chain.getNumOperands(); n;)
6884 Chains.push_back(Chain.getOperand(--n));
6889 // For all other instructions we will just have to take what we can get.
6890 Aliases.push_back(Chain);
6896 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6897 /// for a better chain (aliasing node.)
6898 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
6899 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
6901 // Accumulate all the aliases to this node.
6902 GatherAllAliases(N, OldChain, Aliases);
6904 if (Aliases.size() == 0) {
6905 // If no operands then chain to entry token.
6906 return DAG.getEntryNode();
6907 } else if (Aliases.size() == 1) {
6908 // If a single operand then chain to it. We don't need to revisit it.
6912 // Construct a custom tailored token factor.
6913 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6914 &Aliases[0], Aliases.size());
6917 // SelectionDAG::Combine - This is the entry point for the file.
6919 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
6920 CodeGenOpt::Level OptLevel) {
6921 /// run - This is the main entry point to this class.
6923 DAGCombiner(*this, AA, OptLevel).Run(Level);