Fixed some bugs.
[llvm/zpu.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
blob7154d9d691c3a848f03b5f0ad9d42e2aa0998e0b
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
39 #include <algorithm>
40 using namespace llvm;
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");
47 namespace {
48 static cl::opt<bool>
49 CombinerAA("combiner-alias-analysis", cl::Hidden,
50 cl::desc("Turn on alias analysis during testing"));
52 static cl::opt<bool>
53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54 cl::desc("Include global information in alias analysis"));
56 //------------------------------ DAGCombiner ---------------------------------//
58 class DAGCombiner {
59 SelectionDAG &DAG;
60 const TargetLowering &TLI;
61 CombineLevel Level;
62 CodeGenOpt::Level OptLevel;
63 bool LegalOperations;
64 bool LegalTypes;
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.
70 AliasAnalysis &AA;
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
76 void AddUsersToWorkList(SDNode *N) {
77 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
78 UI != UE; ++UI)
79 AddToWorkList(*UI);
82 /// visit - call the node-specific routine that knows how to fold each
83 /// particular type of node.
84 SDValue visit(SDNode *N);
86 public:
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.
95 ///
96 void removeFromWorkList(SDNode *N) {
97 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
98 WorkList.end());
101 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
102 bool AddTo = true);
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,
109 bool AddTo = true) {
110 SDValue To[] = { Res0, Res1 };
111 return CombineTo(N, To, 2, AddTo);
114 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
116 private:
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 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
133 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
134 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
135 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
136 SDValue PromoteIntBinOp(SDValue Op);
137 SDValue PromoteIntShiftOp(SDValue Op);
138 SDValue PromoteExtend(SDValue Op);
139 bool PromoteLoad(SDValue Op);
141 /// combine - call the node-specific routine that knows how to fold each
142 /// particular type of node. If that doesn't do anything, try the
143 /// target-specific DAG combines.
144 SDValue combine(SDNode *N);
146 // Visitation implementation - Implement dag node combining for different
147 // node types. The semantics are as follows:
148 // Return Value:
149 // SDValue.getNode() == 0 - No change was made
150 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
151 // otherwise - N should be replaced by the returned Operand.
153 SDValue visitTokenFactor(SDNode *N);
154 SDValue visitMERGE_VALUES(SDNode *N);
155 SDValue visitADD(SDNode *N);
156 SDValue visitSUB(SDNode *N);
157 SDValue visitADDC(SDNode *N);
158 SDValue visitADDE(SDNode *N);
159 SDValue visitMUL(SDNode *N);
160 SDValue visitSDIV(SDNode *N);
161 SDValue visitUDIV(SDNode *N);
162 SDValue visitSREM(SDNode *N);
163 SDValue visitUREM(SDNode *N);
164 SDValue visitMULHU(SDNode *N);
165 SDValue visitMULHS(SDNode *N);
166 SDValue visitSMUL_LOHI(SDNode *N);
167 SDValue visitUMUL_LOHI(SDNode *N);
168 SDValue visitSDIVREM(SDNode *N);
169 SDValue visitUDIVREM(SDNode *N);
170 SDValue visitAND(SDNode *N);
171 SDValue visitOR(SDNode *N);
172 SDValue visitXOR(SDNode *N);
173 SDValue SimplifyVBinOp(SDNode *N);
174 SDValue visitSHL(SDNode *N);
175 SDValue visitSRA(SDNode *N);
176 SDValue visitSRL(SDNode *N);
177 SDValue visitCTLZ(SDNode *N);
178 SDValue visitCTTZ(SDNode *N);
179 SDValue visitCTPOP(SDNode *N);
180 SDValue visitSELECT(SDNode *N);
181 SDValue visitSELECT_CC(SDNode *N);
182 SDValue visitSETCC(SDNode *N);
183 SDValue visitSIGN_EXTEND(SDNode *N);
184 SDValue visitZERO_EXTEND(SDNode *N);
185 SDValue visitANY_EXTEND(SDNode *N);
186 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
187 SDValue visitTRUNCATE(SDNode *N);
188 SDValue visitBIT_CONVERT(SDNode *N);
189 SDValue visitBUILD_PAIR(SDNode *N);
190 SDValue visitFADD(SDNode *N);
191 SDValue visitFSUB(SDNode *N);
192 SDValue visitFMUL(SDNode *N);
193 SDValue visitFDIV(SDNode *N);
194 SDValue visitFREM(SDNode *N);
195 SDValue visitFCOPYSIGN(SDNode *N);
196 SDValue visitSINT_TO_FP(SDNode *N);
197 SDValue visitUINT_TO_FP(SDNode *N);
198 SDValue visitFP_TO_SINT(SDNode *N);
199 SDValue visitFP_TO_UINT(SDNode *N);
200 SDValue visitFP_ROUND(SDNode *N);
201 SDValue visitFP_ROUND_INREG(SDNode *N);
202 SDValue visitFP_EXTEND(SDNode *N);
203 SDValue visitFNEG(SDNode *N);
204 SDValue visitFABS(SDNode *N);
205 SDValue visitBRCOND(SDNode *N);
206 SDValue visitBR_CC(SDNode *N);
207 SDValue visitLOAD(SDNode *N);
208 SDValue visitSTORE(SDNode *N);
209 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
210 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
211 SDValue visitBUILD_VECTOR(SDNode *N);
212 SDValue visitCONCAT_VECTORS(SDNode *N);
213 SDValue visitVECTOR_SHUFFLE(SDNode *N);
214 SDValue visitMEMBARRIER(SDNode *N);
216 SDValue XformToShuffleWithZero(SDNode *N);
217 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
219 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
221 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
222 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
223 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
224 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
225 SDValue N3, ISD::CondCode CC,
226 bool NotExtCompare = false);
227 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
228 DebugLoc DL, bool foldBooleans = true);
229 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
230 unsigned HiOp);
231 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
232 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
233 SDValue BuildSDIV(SDNode *N);
234 SDValue BuildUDIV(SDNode *N);
235 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
236 SDValue ReduceLoadWidth(SDNode *N);
237 SDValue ReduceLoadOpStoreWidth(SDNode *N);
239 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
241 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
242 /// looking for aliasing nodes and adding them to the Aliases vector.
243 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
244 SmallVector<SDValue, 8> &Aliases);
246 /// isAlias - Return true if there is any possibility that the two addresses
247 /// overlap.
248 bool isAlias(SDValue Ptr1, int64_t Size1,
249 const Value *SrcValue1, int SrcValueOffset1,
250 unsigned SrcValueAlign1,
251 const MDNode *TBAAInfo1,
252 SDValue Ptr2, int64_t Size2,
253 const Value *SrcValue2, int SrcValueOffset2,
254 unsigned SrcValueAlign2,
255 const MDNode *TBAAInfo2) const;
257 /// FindAliasInfo - Extracts the relevant alias information from the memory
258 /// node. Returns true if the operand was a load.
259 bool FindAliasInfo(SDNode *N,
260 SDValue &Ptr, int64_t &Size,
261 const Value *&SrcValue, int &SrcValueOffset,
262 unsigned &SrcValueAlignment,
263 const MDNode *&TBAAInfo) const;
265 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
266 /// looking for a better chain (aliasing node.)
267 SDValue FindBetterChain(SDNode *N, SDValue Chain);
269 public:
270 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
271 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
272 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
274 /// Run - runs the dag combiner on all nodes in the work list
275 void Run(CombineLevel AtLevel);
277 SelectionDAG &getDAG() const { return DAG; }
279 /// getShiftAmountTy - Returns a type large enough to hold any valid
280 /// shift amount - before type legalization these can be huge.
281 EVT getShiftAmountTy() {
282 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
285 /// isTypeLegal - This method returns true if we are running before type
286 /// legalization or if the specified VT is legal.
287 bool isTypeLegal(const EVT &VT) {
288 if (!LegalTypes) return true;
289 return TLI.isTypeLegal(VT);
295 namespace {
296 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
297 /// nodes from the worklist.
298 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
299 DAGCombiner &DC;
300 public:
301 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
303 virtual void NodeDeleted(SDNode *N, SDNode *E) {
304 DC.removeFromWorkList(N);
307 virtual void NodeUpdated(SDNode *N) {
308 // Ignore updates.
313 //===----------------------------------------------------------------------===//
314 // TargetLowering::DAGCombinerInfo implementation
315 //===----------------------------------------------------------------------===//
317 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
318 ((DAGCombiner*)DC)->AddToWorkList(N);
321 SDValue TargetLowering::DAGCombinerInfo::
322 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
323 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
326 SDValue TargetLowering::DAGCombinerInfo::
327 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
328 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
332 SDValue TargetLowering::DAGCombinerInfo::
333 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
334 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
337 void TargetLowering::DAGCombinerInfo::
338 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
339 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
342 //===----------------------------------------------------------------------===//
343 // Helper Functions
344 //===----------------------------------------------------------------------===//
346 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
347 /// specified expression for the same cost as the expression itself, or 2 if we
348 /// can compute the negated form more cheaply than the expression itself.
349 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
350 unsigned Depth = 0) {
351 // No compile time optimizations on this type.
352 if (Op.getValueType() == MVT::ppcf128)
353 return 0;
355 // fneg is removable even if it has multiple uses.
356 if (Op.getOpcode() == ISD::FNEG) return 2;
358 // Don't allow anything with multiple uses.
359 if (!Op.hasOneUse()) return 0;
361 // Don't recurse exponentially.
362 if (Depth > 6) return 0;
364 switch (Op.getOpcode()) {
365 default: return false;
366 case ISD::ConstantFP:
367 // Don't invert constant FP values after legalize. The negated constant
368 // isn't necessarily legal.
369 return LegalOperations ? 0 : 1;
370 case ISD::FADD:
371 // FIXME: determine better conditions for this xform.
372 if (!UnsafeFPMath) return 0;
374 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
375 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
376 return V;
377 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
378 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
379 case ISD::FSUB:
380 // We can't turn -(A-B) into B-A when we honor signed zeros.
381 if (!UnsafeFPMath) return 0;
383 // fold (fneg (fsub A, B)) -> (fsub B, A)
384 return 1;
386 case ISD::FMUL:
387 case ISD::FDIV:
388 if (HonorSignDependentRoundingFPMath()) return 0;
390 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
391 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
392 return V;
394 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
396 case ISD::FP_EXTEND:
397 case ISD::FP_ROUND:
398 case ISD::FSIN:
399 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
403 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
404 /// returns the newly negated expression.
405 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
406 bool LegalOperations, unsigned Depth = 0) {
407 // fneg is removable even if it has multiple uses.
408 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
410 // Don't allow anything with multiple uses.
411 assert(Op.hasOneUse() && "Unknown reuse!");
413 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
414 switch (Op.getOpcode()) {
415 default: llvm_unreachable("Unknown code");
416 case ISD::ConstantFP: {
417 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
418 V.changeSign();
419 return DAG.getConstantFP(V, Op.getValueType());
421 case ISD::FADD:
422 // FIXME: determine better conditions for this xform.
423 assert(UnsafeFPMath);
425 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
426 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
427 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
428 GetNegatedExpression(Op.getOperand(0), DAG,
429 LegalOperations, Depth+1),
430 Op.getOperand(1));
431 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
432 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
433 GetNegatedExpression(Op.getOperand(1), DAG,
434 LegalOperations, Depth+1),
435 Op.getOperand(0));
436 case ISD::FSUB:
437 // We can't turn -(A-B) into B-A when we honor signed zeros.
438 assert(UnsafeFPMath);
440 // fold (fneg (fsub 0, B)) -> B
441 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
442 if (N0CFP->getValueAPF().isZero())
443 return Op.getOperand(1);
445 // fold (fneg (fsub A, B)) -> (fsub B, A)
446 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
447 Op.getOperand(1), Op.getOperand(0));
449 case ISD::FMUL:
450 case ISD::FDIV:
451 assert(!HonorSignDependentRoundingFPMath());
453 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
454 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
455 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
456 GetNegatedExpression(Op.getOperand(0), DAG,
457 LegalOperations, Depth+1),
458 Op.getOperand(1));
460 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
461 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
462 Op.getOperand(0),
463 GetNegatedExpression(Op.getOperand(1), DAG,
464 LegalOperations, Depth+1));
466 case ISD::FP_EXTEND:
467 case ISD::FSIN:
468 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
469 GetNegatedExpression(Op.getOperand(0), DAG,
470 LegalOperations, Depth+1));
471 case ISD::FP_ROUND:
472 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
473 GetNegatedExpression(Op.getOperand(0), DAG,
474 LegalOperations, Depth+1),
475 Op.getOperand(1));
480 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
481 // that selects between the values 1 and 0, making it equivalent to a setcc.
482 // Also, set the incoming LHS, RHS, and CC references to the appropriate
483 // nodes based on the type of node we are checking. This simplifies life a
484 // bit for the callers.
485 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
486 SDValue &CC) {
487 if (N.getOpcode() == ISD::SETCC) {
488 LHS = N.getOperand(0);
489 RHS = N.getOperand(1);
490 CC = N.getOperand(2);
491 return true;
493 if (N.getOpcode() == ISD::SELECT_CC &&
494 N.getOperand(2).getOpcode() == ISD::Constant &&
495 N.getOperand(3).getOpcode() == ISD::Constant &&
496 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
497 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
498 LHS = N.getOperand(0);
499 RHS = N.getOperand(1);
500 CC = N.getOperand(4);
501 return true;
503 return false;
506 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
507 // one use. If this is true, it allows the users to invert the operation for
508 // free when it is profitable to do so.
509 static bool isOneUseSetCC(SDValue N) {
510 SDValue N0, N1, N2;
511 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
512 return true;
513 return false;
516 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
517 SDValue N0, SDValue N1) {
518 EVT VT = N0.getValueType();
519 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
520 if (isa<ConstantSDNode>(N1)) {
521 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
522 SDValue OpNode =
523 DAG.FoldConstantArithmetic(Opc, VT,
524 cast<ConstantSDNode>(N0.getOperand(1)),
525 cast<ConstantSDNode>(N1));
526 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
527 } else if (N0.hasOneUse()) {
528 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
529 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
530 N0.getOperand(0), N1);
531 AddToWorkList(OpNode.getNode());
532 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
536 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
537 if (isa<ConstantSDNode>(N0)) {
538 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
539 SDValue OpNode =
540 DAG.FoldConstantArithmetic(Opc, VT,
541 cast<ConstantSDNode>(N1.getOperand(1)),
542 cast<ConstantSDNode>(N0));
543 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
544 } else if (N1.hasOneUse()) {
545 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
546 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
547 N1.getOperand(0), N0);
548 AddToWorkList(OpNode.getNode());
549 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
553 return SDValue();
556 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
557 bool AddTo) {
558 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
559 ++NodesCombined;
560 DEBUG(dbgs() << "\nReplacing.1 ";
561 N->dump(&DAG);
562 dbgs() << "\nWith: ";
563 To[0].getNode()->dump(&DAG);
564 dbgs() << " and " << NumTo-1 << " other values\n";
565 for (unsigned i = 0, e = NumTo; i != e; ++i)
566 assert((!To[i].getNode() ||
567 N->getValueType(i) == To[i].getValueType()) &&
568 "Cannot combine value to value of different type!"));
569 WorkListRemover DeadNodes(*this);
570 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
572 if (AddTo) {
573 // Push the new nodes and any users onto the worklist
574 for (unsigned i = 0, e = NumTo; i != e; ++i) {
575 if (To[i].getNode()) {
576 AddToWorkList(To[i].getNode());
577 AddUsersToWorkList(To[i].getNode());
582 // Finally, if the node is now dead, remove it from the graph. The node
583 // may not be dead if the replacement process recursively simplified to
584 // something else needing this node.
585 if (N->use_empty()) {
586 // Nodes can be reintroduced into the worklist. Make sure we do not
587 // process a node that has been replaced.
588 removeFromWorkList(N);
590 // Finally, since the node is now dead, remove it from the graph.
591 DAG.DeleteNode(N);
593 return SDValue(N, 0);
596 void DAGCombiner::
597 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
598 // Replace all uses. If any nodes become isomorphic to other nodes and
599 // are deleted, make sure to remove them from our worklist.
600 WorkListRemover DeadNodes(*this);
601 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
603 // Push the new node and any (possibly new) users onto the worklist.
604 AddToWorkList(TLO.New.getNode());
605 AddUsersToWorkList(TLO.New.getNode());
607 // Finally, if the node is now dead, remove it from the graph. The node
608 // may not be dead if the replacement process recursively simplified to
609 // something else needing this node.
610 if (TLO.Old.getNode()->use_empty()) {
611 removeFromWorkList(TLO.Old.getNode());
613 // If the operands of this node are only used by the node, they will now
614 // be dead. Make sure to visit them first to delete dead nodes early.
615 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
616 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
617 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
619 DAG.DeleteNode(TLO.Old.getNode());
623 /// SimplifyDemandedBits - Check the specified integer node value to see if
624 /// it can be simplified or if things it uses can be simplified by bit
625 /// propagation. If so, return true.
626 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
627 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
628 APInt KnownZero, KnownOne;
629 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
630 return false;
632 // Revisit the node.
633 AddToWorkList(Op.getNode());
635 // Replace the old value with the new one.
636 ++NodesCombined;
637 DEBUG(dbgs() << "\nReplacing.2 ";
638 TLO.Old.getNode()->dump(&DAG);
639 dbgs() << "\nWith: ";
640 TLO.New.getNode()->dump(&DAG);
641 dbgs() << '\n');
643 CommitTargetLoweringOpt(TLO);
644 return true;
647 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
648 DebugLoc dl = Load->getDebugLoc();
649 EVT VT = Load->getValueType(0);
650 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
652 DEBUG(dbgs() << "\nReplacing.9 ";
653 Load->dump(&DAG);
654 dbgs() << "\nWith: ";
655 Trunc.getNode()->dump(&DAG);
656 dbgs() << '\n');
657 WorkListRemover DeadNodes(*this);
658 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
659 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
660 &DeadNodes);
661 removeFromWorkList(Load);
662 DAG.DeleteNode(Load);
663 AddToWorkList(Trunc.getNode());
666 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
667 Replace = false;
668 DebugLoc dl = Op.getDebugLoc();
669 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
670 EVT MemVT = LD->getMemoryVT();
671 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
672 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD : ISD::EXTLOAD)
673 : LD->getExtensionType();
674 Replace = true;
675 return DAG.getExtLoad(ExtType, PVT, dl,
676 LD->getChain(), LD->getBasePtr(),
677 LD->getPointerInfo(),
678 MemVT, LD->isVolatile(),
679 LD->isNonTemporal(), LD->getAlignment());
682 unsigned Opc = Op.getOpcode();
683 switch (Opc) {
684 default: break;
685 case ISD::AssertSext:
686 return DAG.getNode(ISD::AssertSext, dl, PVT,
687 SExtPromoteOperand(Op.getOperand(0), PVT),
688 Op.getOperand(1));
689 case ISD::AssertZext:
690 return DAG.getNode(ISD::AssertZext, dl, PVT,
691 ZExtPromoteOperand(Op.getOperand(0), PVT),
692 Op.getOperand(1));
693 case ISD::Constant: {
694 unsigned ExtOpc =
695 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
696 return DAG.getNode(ExtOpc, dl, PVT, Op);
700 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
701 return SDValue();
702 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
705 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
706 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
707 return SDValue();
708 EVT OldVT = Op.getValueType();
709 DebugLoc dl = Op.getDebugLoc();
710 bool Replace = false;
711 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
712 if (NewOp.getNode() == 0)
713 return SDValue();
714 AddToWorkList(NewOp.getNode());
716 if (Replace)
717 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
718 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
719 DAG.getValueType(OldVT));
722 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
723 EVT OldVT = Op.getValueType();
724 DebugLoc dl = Op.getDebugLoc();
725 bool Replace = false;
726 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
727 if (NewOp.getNode() == 0)
728 return SDValue();
729 AddToWorkList(NewOp.getNode());
731 if (Replace)
732 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
733 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
736 /// PromoteIntBinOp - Promote the specified integer binary operation if the
737 /// target indicates it is beneficial. e.g. On x86, it's usually better to
738 /// promote i16 operations to i32 since i16 instructions are longer.
739 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
740 if (!LegalOperations)
741 return SDValue();
743 EVT VT = Op.getValueType();
744 if (VT.isVector() || !VT.isInteger())
745 return SDValue();
747 // If operation type is 'undesirable', e.g. i16 on x86, consider
748 // promoting it.
749 unsigned Opc = Op.getOpcode();
750 if (TLI.isTypeDesirableForOp(Opc, VT))
751 return SDValue();
753 EVT PVT = VT;
754 // Consult target whether it is a good idea to promote this operation and
755 // what's the right type to promote it to.
756 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
757 assert(PVT != VT && "Don't know what type to promote to!");
759 bool Replace0 = false;
760 SDValue N0 = Op.getOperand(0);
761 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
762 if (NN0.getNode() == 0)
763 return SDValue();
765 bool Replace1 = false;
766 SDValue N1 = Op.getOperand(1);
767 SDValue NN1;
768 if (N0 == N1)
769 NN1 = NN0;
770 else {
771 NN1 = PromoteOperand(N1, PVT, Replace1);
772 if (NN1.getNode() == 0)
773 return SDValue();
776 AddToWorkList(NN0.getNode());
777 if (NN1.getNode())
778 AddToWorkList(NN1.getNode());
780 if (Replace0)
781 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
782 if (Replace1)
783 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
785 DEBUG(dbgs() << "\nPromoting ";
786 Op.getNode()->dump(&DAG));
787 DebugLoc dl = Op.getDebugLoc();
788 return DAG.getNode(ISD::TRUNCATE, dl, VT,
789 DAG.getNode(Opc, dl, PVT, NN0, NN1));
791 return SDValue();
794 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
795 /// target indicates it is beneficial. e.g. On x86, it's usually better to
796 /// promote i16 operations to i32 since i16 instructions are longer.
797 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
798 if (!LegalOperations)
799 return SDValue();
801 EVT VT = Op.getValueType();
802 if (VT.isVector() || !VT.isInteger())
803 return SDValue();
805 // If operation type is 'undesirable', e.g. i16 on x86, consider
806 // promoting it.
807 unsigned Opc = Op.getOpcode();
808 if (TLI.isTypeDesirableForOp(Opc, VT))
809 return SDValue();
811 EVT PVT = VT;
812 // Consult target whether it is a good idea to promote this operation and
813 // what's the right type to promote it to.
814 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
815 assert(PVT != VT && "Don't know what type to promote to!");
817 bool Replace = false;
818 SDValue N0 = Op.getOperand(0);
819 if (Opc == ISD::SRA)
820 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
821 else if (Opc == ISD::SRL)
822 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
823 else
824 N0 = PromoteOperand(N0, PVT, Replace);
825 if (N0.getNode() == 0)
826 return SDValue();
828 AddToWorkList(N0.getNode());
829 if (Replace)
830 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
832 DEBUG(dbgs() << "\nPromoting ";
833 Op.getNode()->dump(&DAG));
834 DebugLoc dl = Op.getDebugLoc();
835 return DAG.getNode(ISD::TRUNCATE, dl, VT,
836 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
838 return SDValue();
841 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
842 if (!LegalOperations)
843 return SDValue();
845 EVT VT = Op.getValueType();
846 if (VT.isVector() || !VT.isInteger())
847 return SDValue();
849 // If operation type is 'undesirable', e.g. i16 on x86, consider
850 // promoting it.
851 unsigned Opc = Op.getOpcode();
852 if (TLI.isTypeDesirableForOp(Opc, VT))
853 return SDValue();
855 EVT PVT = VT;
856 // Consult target whether it is a good idea to promote this operation and
857 // what's the right type to promote it to.
858 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
859 assert(PVT != VT && "Don't know what type to promote to!");
860 // fold (aext (aext x)) -> (aext x)
861 // fold (aext (zext x)) -> (zext x)
862 // fold (aext (sext x)) -> (sext x)
863 DEBUG(dbgs() << "\nPromoting ";
864 Op.getNode()->dump(&DAG));
865 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
867 return SDValue();
870 bool DAGCombiner::PromoteLoad(SDValue Op) {
871 if (!LegalOperations)
872 return false;
874 EVT VT = Op.getValueType();
875 if (VT.isVector() || !VT.isInteger())
876 return false;
878 // If operation type is 'undesirable', e.g. i16 on x86, consider
879 // promoting it.
880 unsigned Opc = Op.getOpcode();
881 if (TLI.isTypeDesirableForOp(Opc, VT))
882 return false;
884 EVT PVT = VT;
885 // Consult target whether it is a good idea to promote this operation and
886 // what's the right type to promote it to.
887 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
888 assert(PVT != VT && "Don't know what type to promote to!");
890 DebugLoc dl = Op.getDebugLoc();
891 SDNode *N = Op.getNode();
892 LoadSDNode *LD = cast<LoadSDNode>(N);
893 EVT MemVT = LD->getMemoryVT();
894 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
895 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD : ISD::EXTLOAD)
896 : LD->getExtensionType();
897 SDValue NewLD = DAG.getExtLoad(ExtType, PVT, dl,
898 LD->getChain(), LD->getBasePtr(),
899 LD->getPointerInfo(),
900 MemVT, LD->isVolatile(),
901 LD->isNonTemporal(), LD->getAlignment());
902 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
904 DEBUG(dbgs() << "\nPromoting ";
905 N->dump(&DAG);
906 dbgs() << "\nTo: ";
907 Result.getNode()->dump(&DAG);
908 dbgs() << '\n');
909 WorkListRemover DeadNodes(*this);
910 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
911 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
912 removeFromWorkList(N);
913 DAG.DeleteNode(N);
914 AddToWorkList(Result.getNode());
915 return true;
917 return false;
921 //===----------------------------------------------------------------------===//
922 // Main DAG Combiner implementation
923 //===----------------------------------------------------------------------===//
925 void DAGCombiner::Run(CombineLevel AtLevel) {
926 // set the instance variables, so that the various visit routines may use it.
927 Level = AtLevel;
928 LegalOperations = Level >= NoIllegalOperations;
929 LegalTypes = Level >= NoIllegalTypes;
931 // Add all the dag nodes to the worklist.
932 WorkList.reserve(DAG.allnodes_size());
933 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
934 E = DAG.allnodes_end(); I != E; ++I)
935 WorkList.push_back(I);
937 // Create a dummy node (which is not added to allnodes), that adds a reference
938 // to the root node, preventing it from being deleted, and tracking any
939 // changes of the root.
940 HandleSDNode Dummy(DAG.getRoot());
942 // The root of the dag may dangle to deleted nodes until the dag combiner is
943 // done. Set it to null to avoid confusion.
944 DAG.setRoot(SDValue());
946 // while the worklist isn't empty, inspect the node on the end of it and
947 // try and combine it.
948 while (!WorkList.empty()) {
949 SDNode *N = WorkList.back();
950 WorkList.pop_back();
952 // If N has no uses, it is dead. Make sure to revisit all N's operands once
953 // N is deleted from the DAG, since they too may now be dead or may have a
954 // reduced number of uses, allowing other xforms.
955 if (N->use_empty() && N != &Dummy) {
956 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
957 AddToWorkList(N->getOperand(i).getNode());
959 DAG.DeleteNode(N);
960 continue;
963 SDValue RV = combine(N);
965 if (RV.getNode() == 0)
966 continue;
968 ++NodesCombined;
970 // If we get back the same node we passed in, rather than a new node or
971 // zero, we know that the node must have defined multiple values and
972 // CombineTo was used. Since CombineTo takes care of the worklist
973 // mechanics for us, we have no work to do in this case.
974 if (RV.getNode() == N)
975 continue;
977 assert(N->getOpcode() != ISD::DELETED_NODE &&
978 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
979 "Node was deleted but visit returned new node!");
981 DEBUG(dbgs() << "\nReplacing.3 ";
982 N->dump(&DAG);
983 dbgs() << "\nWith: ";
984 RV.getNode()->dump(&DAG);
985 dbgs() << '\n');
986 WorkListRemover DeadNodes(*this);
987 if (N->getNumValues() == RV.getNode()->getNumValues())
988 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
989 else {
990 assert(N->getValueType(0) == RV.getValueType() &&
991 N->getNumValues() == 1 && "Type mismatch");
992 SDValue OpV = RV;
993 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
996 // Push the new node and any users onto the worklist
997 AddToWorkList(RV.getNode());
998 AddUsersToWorkList(RV.getNode());
1000 // Add any uses of the old node to the worklist in case this node is the
1001 // last one that uses them. They may become dead after this node is
1002 // deleted.
1003 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1004 AddToWorkList(N->getOperand(i).getNode());
1006 // Finally, if the node is now dead, remove it from the graph. The node
1007 // may not be dead if the replacement process recursively simplified to
1008 // something else needing this node.
1009 if (N->use_empty()) {
1010 // Nodes can be reintroduced into the worklist. Make sure we do not
1011 // process a node that has been replaced.
1012 removeFromWorkList(N);
1014 // Finally, since the node is now dead, remove it from the graph.
1015 DAG.DeleteNode(N);
1019 // If the root changed (e.g. it was a dead load, update the root).
1020 DAG.setRoot(Dummy.getValue());
1023 SDValue DAGCombiner::visit(SDNode *N) {
1024 switch (N->getOpcode()) {
1025 default: break;
1026 case ISD::TokenFactor: return visitTokenFactor(N);
1027 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1028 case ISD::ADD: return visitADD(N);
1029 case ISD::SUB: return visitSUB(N);
1030 case ISD::ADDC: return visitADDC(N);
1031 case ISD::ADDE: return visitADDE(N);
1032 case ISD::MUL: return visitMUL(N);
1033 case ISD::SDIV: return visitSDIV(N);
1034 case ISD::UDIV: return visitUDIV(N);
1035 case ISD::SREM: return visitSREM(N);
1036 case ISD::UREM: return visitUREM(N);
1037 case ISD::MULHU: return visitMULHU(N);
1038 case ISD::MULHS: return visitMULHS(N);
1039 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1040 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1041 case ISD::SDIVREM: return visitSDIVREM(N);
1042 case ISD::UDIVREM: return visitUDIVREM(N);
1043 case ISD::AND: return visitAND(N);
1044 case ISD::OR: return visitOR(N);
1045 case ISD::XOR: return visitXOR(N);
1046 case ISD::SHL: return visitSHL(N);
1047 case ISD::SRA: return visitSRA(N);
1048 case ISD::SRL: return visitSRL(N);
1049 case ISD::CTLZ: return visitCTLZ(N);
1050 case ISD::CTTZ: return visitCTTZ(N);
1051 case ISD::CTPOP: return visitCTPOP(N);
1052 case ISD::SELECT: return visitSELECT(N);
1053 case ISD::SELECT_CC: return visitSELECT_CC(N);
1054 case ISD::SETCC: return visitSETCC(N);
1055 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1056 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1057 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1058 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1059 case ISD::TRUNCATE: return visitTRUNCATE(N);
1060 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
1061 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1062 case ISD::FADD: return visitFADD(N);
1063 case ISD::FSUB: return visitFSUB(N);
1064 case ISD::FMUL: return visitFMUL(N);
1065 case ISD::FDIV: return visitFDIV(N);
1066 case ISD::FREM: return visitFREM(N);
1067 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1068 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1069 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1070 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1071 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1072 case ISD::FP_ROUND: return visitFP_ROUND(N);
1073 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1074 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1075 case ISD::FNEG: return visitFNEG(N);
1076 case ISD::FABS: return visitFABS(N);
1077 case ISD::BRCOND: return visitBRCOND(N);
1078 case ISD::BR_CC: return visitBR_CC(N);
1079 case ISD::LOAD: return visitLOAD(N);
1080 case ISD::STORE: return visitSTORE(N);
1081 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1082 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1083 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1084 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1085 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1086 case ISD::MEMBARRIER: return visitMEMBARRIER(N);
1088 return SDValue();
1091 SDValue DAGCombiner::combine(SDNode *N) {
1092 SDValue RV = visit(N);
1094 // If nothing happened, try a target-specific DAG combine.
1095 if (RV.getNode() == 0) {
1096 assert(N->getOpcode() != ISD::DELETED_NODE &&
1097 "Node was deleted but visit returned NULL!");
1099 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1100 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1102 // Expose the DAG combiner to the target combiner impls.
1103 TargetLowering::DAGCombinerInfo
1104 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1106 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1110 // If nothing happened still, try promoting the operation.
1111 if (RV.getNode() == 0) {
1112 switch (N->getOpcode()) {
1113 default: break;
1114 case ISD::ADD:
1115 case ISD::SUB:
1116 case ISD::MUL:
1117 case ISD::AND:
1118 case ISD::OR:
1119 case ISD::XOR:
1120 RV = PromoteIntBinOp(SDValue(N, 0));
1121 break;
1122 case ISD::SHL:
1123 case ISD::SRA:
1124 case ISD::SRL:
1125 RV = PromoteIntShiftOp(SDValue(N, 0));
1126 break;
1127 case ISD::SIGN_EXTEND:
1128 case ISD::ZERO_EXTEND:
1129 case ISD::ANY_EXTEND:
1130 RV = PromoteExtend(SDValue(N, 0));
1131 break;
1132 case ISD::LOAD:
1133 if (PromoteLoad(SDValue(N, 0)))
1134 RV = SDValue(N, 0);
1135 break;
1139 // If N is a commutative binary node, try commuting it to enable more
1140 // sdisel CSE.
1141 if (RV.getNode() == 0 &&
1142 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1143 N->getNumValues() == 1) {
1144 SDValue N0 = N->getOperand(0);
1145 SDValue N1 = N->getOperand(1);
1147 // Constant operands are canonicalized to RHS.
1148 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1149 SDValue Ops[] = { N1, N0 };
1150 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1151 Ops, 2);
1152 if (CSENode)
1153 return SDValue(CSENode, 0);
1157 return RV;
1160 /// getInputChainForNode - Given a node, return its input chain if it has one,
1161 /// otherwise return a null sd operand.
1162 static SDValue getInputChainForNode(SDNode *N) {
1163 if (unsigned NumOps = N->getNumOperands()) {
1164 if (N->getOperand(0).getValueType() == MVT::Other)
1165 return N->getOperand(0);
1166 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1167 return N->getOperand(NumOps-1);
1168 for (unsigned i = 1; i < NumOps-1; ++i)
1169 if (N->getOperand(i).getValueType() == MVT::Other)
1170 return N->getOperand(i);
1172 return SDValue();
1175 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1176 // If N has two operands, where one has an input chain equal to the other,
1177 // the 'other' chain is redundant.
1178 if (N->getNumOperands() == 2) {
1179 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1180 return N->getOperand(0);
1181 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1182 return N->getOperand(1);
1185 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1186 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1187 SmallPtrSet<SDNode*, 16> SeenOps;
1188 bool Changed = false; // If we should replace this token factor.
1190 // Start out with this token factor.
1191 TFs.push_back(N);
1193 // Iterate through token factors. The TFs grows when new token factors are
1194 // encountered.
1195 for (unsigned i = 0; i < TFs.size(); ++i) {
1196 SDNode *TF = TFs[i];
1198 // Check each of the operands.
1199 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1200 SDValue Op = TF->getOperand(i);
1202 switch (Op.getOpcode()) {
1203 case ISD::EntryToken:
1204 // Entry tokens don't need to be added to the list. They are
1205 // rededundant.
1206 Changed = true;
1207 break;
1209 case ISD::TokenFactor:
1210 if (Op.hasOneUse() &&
1211 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1212 // Queue up for processing.
1213 TFs.push_back(Op.getNode());
1214 // Clean up in case the token factor is removed.
1215 AddToWorkList(Op.getNode());
1216 Changed = true;
1217 break;
1219 // Fall thru
1221 default:
1222 // Only add if it isn't already in the list.
1223 if (SeenOps.insert(Op.getNode()))
1224 Ops.push_back(Op);
1225 else
1226 Changed = true;
1227 break;
1232 SDValue Result;
1234 // If we've change things around then replace token factor.
1235 if (Changed) {
1236 if (Ops.empty()) {
1237 // The entry token is the only possible outcome.
1238 Result = DAG.getEntryNode();
1239 } else {
1240 // New and improved token factor.
1241 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1242 MVT::Other, &Ops[0], Ops.size());
1245 // Don't add users to work list.
1246 return CombineTo(N, Result, false);
1249 return Result;
1252 /// MERGE_VALUES can always be eliminated.
1253 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1254 WorkListRemover DeadNodes(*this);
1255 // Replacing results may cause a different MERGE_VALUES to suddenly
1256 // be CSE'd with N, and carry its uses with it. Iterate until no
1257 // uses remain, to ensure that the node can be safely deleted.
1258 do {
1259 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1260 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1261 &DeadNodes);
1262 } while (!N->use_empty());
1263 removeFromWorkList(N);
1264 DAG.DeleteNode(N);
1265 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1268 static
1269 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1270 SelectionDAG &DAG) {
1271 EVT VT = N0.getValueType();
1272 SDValue N00 = N0.getOperand(0);
1273 SDValue N01 = N0.getOperand(1);
1274 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1276 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1277 isa<ConstantSDNode>(N00.getOperand(1))) {
1278 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1279 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1280 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1281 N00.getOperand(0), N01),
1282 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1283 N00.getOperand(1), N01));
1284 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1287 return SDValue();
1290 SDValue DAGCombiner::visitADD(SDNode *N) {
1291 SDValue N0 = N->getOperand(0);
1292 SDValue N1 = N->getOperand(1);
1293 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1294 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1295 EVT VT = N0.getValueType();
1297 // fold vector ops
1298 if (VT.isVector()) {
1299 SDValue FoldedVOp = SimplifyVBinOp(N);
1300 if (FoldedVOp.getNode()) return FoldedVOp;
1303 // fold (add x, undef) -> undef
1304 if (N0.getOpcode() == ISD::UNDEF)
1305 return N0;
1306 if (N1.getOpcode() == ISD::UNDEF)
1307 return N1;
1308 // fold (add c1, c2) -> c1+c2
1309 if (N0C && N1C)
1310 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1311 // canonicalize constant to RHS
1312 if (N0C && !N1C)
1313 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1314 // fold (add x, 0) -> x
1315 if (N1C && N1C->isNullValue())
1316 return N0;
1317 // fold (add Sym, c) -> Sym+c
1318 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1319 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1320 GA->getOpcode() == ISD::GlobalAddress)
1321 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1322 GA->getOffset() +
1323 (uint64_t)N1C->getSExtValue());
1324 // fold ((c1-A)+c2) -> (c1+c2)-A
1325 if (N1C && N0.getOpcode() == ISD::SUB)
1326 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1327 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1328 DAG.getConstant(N1C->getAPIntValue()+
1329 N0C->getAPIntValue(), VT),
1330 N0.getOperand(1));
1331 // reassociate add
1332 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1333 if (RADD.getNode() != 0)
1334 return RADD;
1335 // fold ((0-A) + B) -> B-A
1336 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1337 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1338 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1339 // fold (A + (0-B)) -> A-B
1340 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1341 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1342 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1343 // fold (A+(B-A)) -> B
1344 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1345 return N1.getOperand(0);
1346 // fold ((B-A)+A) -> B
1347 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1348 return N0.getOperand(0);
1349 // fold (A+(B-(A+C))) to (B-C)
1350 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1351 N0 == N1.getOperand(1).getOperand(0))
1352 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1353 N1.getOperand(1).getOperand(1));
1354 // fold (A+(B-(C+A))) to (B-C)
1355 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1356 N0 == N1.getOperand(1).getOperand(1))
1357 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1358 N1.getOperand(1).getOperand(0));
1359 // fold (A+((B-A)+or-C)) to (B+or-C)
1360 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1361 N1.getOperand(0).getOpcode() == ISD::SUB &&
1362 N0 == N1.getOperand(0).getOperand(1))
1363 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1364 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1366 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1367 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1368 SDValue N00 = N0.getOperand(0);
1369 SDValue N01 = N0.getOperand(1);
1370 SDValue N10 = N1.getOperand(0);
1371 SDValue N11 = N1.getOperand(1);
1373 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1374 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1375 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1376 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1379 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1380 return SDValue(N, 0);
1382 // fold (a+b) -> (a|b) iff a and b share no bits.
1383 if (VT.isInteger() && !VT.isVector()) {
1384 APInt LHSZero, LHSOne;
1385 APInt RHSZero, RHSOne;
1386 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1387 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1389 if (LHSZero.getBoolValue()) {
1390 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1392 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1393 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1394 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1395 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1396 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1400 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1401 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1402 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1403 if (Result.getNode()) return Result;
1405 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1406 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1407 if (Result.getNode()) return Result;
1410 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1411 if (N1.getOpcode() == ISD::SHL &&
1412 N1.getOperand(0).getOpcode() == ISD::SUB)
1413 if (ConstantSDNode *C =
1414 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1415 if (C->getAPIntValue() == 0)
1416 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1417 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1418 N1.getOperand(0).getOperand(1),
1419 N1.getOperand(1)));
1420 if (N0.getOpcode() == ISD::SHL &&
1421 N0.getOperand(0).getOpcode() == ISD::SUB)
1422 if (ConstantSDNode *C =
1423 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1424 if (C->getAPIntValue() == 0)
1425 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1426 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1427 N0.getOperand(0).getOperand(1),
1428 N0.getOperand(1)));
1430 if (N1.getOpcode() == ISD::AND) {
1431 SDValue AndOp0 = N1.getOperand(0);
1432 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1433 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1434 unsigned DestBits = VT.getScalarType().getSizeInBits();
1436 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1437 // and similar xforms where the inner op is either ~0 or 0.
1438 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1439 DebugLoc DL = N->getDebugLoc();
1440 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1444 return SDValue();
1447 SDValue DAGCombiner::visitADDC(SDNode *N) {
1448 SDValue N0 = N->getOperand(0);
1449 SDValue N1 = N->getOperand(1);
1450 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1451 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1452 EVT VT = N0.getValueType();
1454 // If the flag result is dead, turn this into an ADD.
1455 if (N->hasNUsesOfValue(0, 1))
1456 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1457 DAG.getNode(ISD::CARRY_FALSE,
1458 N->getDebugLoc(), MVT::Flag));
1460 // canonicalize constant to RHS.
1461 if (N0C && !N1C)
1462 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1464 // fold (addc x, 0) -> x + no carry out
1465 if (N1C && N1C->isNullValue())
1466 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1467 N->getDebugLoc(), MVT::Flag));
1469 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1470 APInt LHSZero, LHSOne;
1471 APInt RHSZero, RHSOne;
1472 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1473 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1475 if (LHSZero.getBoolValue()) {
1476 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1478 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1479 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1480 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1481 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1482 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1483 DAG.getNode(ISD::CARRY_FALSE,
1484 N->getDebugLoc(), MVT::Flag));
1487 return SDValue();
1490 SDValue DAGCombiner::visitADDE(SDNode *N) {
1491 SDValue N0 = N->getOperand(0);
1492 SDValue N1 = N->getOperand(1);
1493 SDValue CarryIn = N->getOperand(2);
1494 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1495 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1497 // canonicalize constant to RHS
1498 if (N0C && !N1C)
1499 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1500 N1, N0, CarryIn);
1502 // fold (adde x, y, false) -> (addc x, y)
1503 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1504 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1506 return SDValue();
1509 SDValue DAGCombiner::visitSUB(SDNode *N) {
1510 SDValue N0 = N->getOperand(0);
1511 SDValue N1 = N->getOperand(1);
1512 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1513 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1514 EVT VT = N0.getValueType();
1516 // fold vector ops
1517 if (VT.isVector()) {
1518 SDValue FoldedVOp = SimplifyVBinOp(N);
1519 if (FoldedVOp.getNode()) return FoldedVOp;
1522 // fold (sub x, x) -> 0
1523 if (N0 == N1)
1524 return DAG.getConstant(0, N->getValueType(0));
1525 // fold (sub c1, c2) -> c1-c2
1526 if (N0C && N1C)
1527 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1528 // fold (sub x, c) -> (add x, -c)
1529 if (N1C)
1530 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1531 DAG.getConstant(-N1C->getAPIntValue(), VT));
1532 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1533 if (N0C && N0C->isAllOnesValue())
1534 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1535 // fold (A+B)-A -> B
1536 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1537 return N0.getOperand(1);
1538 // fold (A+B)-B -> A
1539 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1540 return N0.getOperand(0);
1541 // fold ((A+(B+or-C))-B) -> A+or-C
1542 if (N0.getOpcode() == ISD::ADD &&
1543 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1544 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1545 N0.getOperand(1).getOperand(0) == N1)
1546 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1547 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1548 // fold ((A+(C+B))-B) -> A+C
1549 if (N0.getOpcode() == ISD::ADD &&
1550 N0.getOperand(1).getOpcode() == ISD::ADD &&
1551 N0.getOperand(1).getOperand(1) == N1)
1552 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1553 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1554 // fold ((A-(B-C))-C) -> A-B
1555 if (N0.getOpcode() == ISD::SUB &&
1556 N0.getOperand(1).getOpcode() == ISD::SUB &&
1557 N0.getOperand(1).getOperand(1) == N1)
1558 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1559 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1561 // If either operand of a sub is undef, the result is undef
1562 if (N0.getOpcode() == ISD::UNDEF)
1563 return N0;
1564 if (N1.getOpcode() == ISD::UNDEF)
1565 return N1;
1567 // If the relocation model supports it, consider symbol offsets.
1568 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1569 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1570 // fold (sub Sym, c) -> Sym-c
1571 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1572 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1573 GA->getOffset() -
1574 (uint64_t)N1C->getSExtValue());
1575 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1576 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1577 if (GA->getGlobal() == GB->getGlobal())
1578 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1579 VT);
1582 return SDValue();
1585 SDValue DAGCombiner::visitMUL(SDNode *N) {
1586 SDValue N0 = N->getOperand(0);
1587 SDValue N1 = N->getOperand(1);
1588 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1589 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1590 EVT VT = N0.getValueType();
1592 // fold vector ops
1593 if (VT.isVector()) {
1594 SDValue FoldedVOp = SimplifyVBinOp(N);
1595 if (FoldedVOp.getNode()) return FoldedVOp;
1598 // fold (mul x, undef) -> 0
1599 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1600 return DAG.getConstant(0, VT);
1601 // fold (mul c1, c2) -> c1*c2
1602 if (N0C && N1C)
1603 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1604 // canonicalize constant to RHS
1605 if (N0C && !N1C)
1606 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1607 // fold (mul x, 0) -> 0
1608 if (N1C && N1C->isNullValue())
1609 return N1;
1610 // fold (mul x, -1) -> 0-x
1611 if (N1C && N1C->isAllOnesValue())
1612 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1613 DAG.getConstant(0, VT), N0);
1614 // fold (mul x, (1 << c)) -> x << c
1615 if (N1C && N1C->getAPIntValue().isPowerOf2())
1616 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1617 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1618 getShiftAmountTy()));
1619 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1620 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1621 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1622 // FIXME: If the input is something that is easily negated (e.g. a
1623 // single-use add), we should put the negate there.
1624 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1625 DAG.getConstant(0, VT),
1626 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1627 DAG.getConstant(Log2Val, getShiftAmountTy())));
1629 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1630 if (N1C && N0.getOpcode() == ISD::SHL &&
1631 isa<ConstantSDNode>(N0.getOperand(1))) {
1632 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1633 N1, N0.getOperand(1));
1634 AddToWorkList(C3.getNode());
1635 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1636 N0.getOperand(0), C3);
1639 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1640 // use.
1642 SDValue Sh(0,0), Y(0,0);
1643 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1644 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1645 N0.getNode()->hasOneUse()) {
1646 Sh = N0; Y = N1;
1647 } else if (N1.getOpcode() == ISD::SHL &&
1648 isa<ConstantSDNode>(N1.getOperand(1)) &&
1649 N1.getNode()->hasOneUse()) {
1650 Sh = N1; Y = N0;
1653 if (Sh.getNode()) {
1654 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1655 Sh.getOperand(0), Y);
1656 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1657 Mul, Sh.getOperand(1));
1661 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1662 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1663 isa<ConstantSDNode>(N0.getOperand(1)))
1664 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1665 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1666 N0.getOperand(0), N1),
1667 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1668 N0.getOperand(1), N1));
1670 // reassociate mul
1671 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1672 if (RMUL.getNode() != 0)
1673 return RMUL;
1675 return SDValue();
1678 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1679 SDValue N0 = N->getOperand(0);
1680 SDValue N1 = N->getOperand(1);
1681 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1682 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1683 EVT VT = N->getValueType(0);
1685 // fold vector ops
1686 if (VT.isVector()) {
1687 SDValue FoldedVOp = SimplifyVBinOp(N);
1688 if (FoldedVOp.getNode()) return FoldedVOp;
1691 // fold (sdiv c1, c2) -> c1/c2
1692 if (N0C && N1C && !N1C->isNullValue())
1693 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1694 // fold (sdiv X, 1) -> X
1695 if (N1C && N1C->getSExtValue() == 1LL)
1696 return N0;
1697 // fold (sdiv X, -1) -> 0-X
1698 if (N1C && N1C->isAllOnesValue())
1699 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1700 DAG.getConstant(0, VT), N0);
1701 // If we know the sign bits of both operands are zero, strength reduce to a
1702 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1703 if (!VT.isVector()) {
1704 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1705 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1706 N0, N1);
1708 // fold (sdiv X, pow2) -> simple ops after legalize
1709 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1710 (isPowerOf2_64(N1C->getSExtValue()) ||
1711 isPowerOf2_64(-N1C->getSExtValue()))) {
1712 // If dividing by powers of two is cheap, then don't perform the following
1713 // fold.
1714 if (TLI.isPow2DivCheap())
1715 return SDValue();
1717 int64_t pow2 = N1C->getSExtValue();
1718 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1719 unsigned lg2 = Log2_64(abs2);
1721 // Splat the sign bit into the register
1722 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1723 DAG.getConstant(VT.getSizeInBits()-1,
1724 getShiftAmountTy()));
1725 AddToWorkList(SGN.getNode());
1727 // Add (N0 < 0) ? abs2 - 1 : 0;
1728 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1729 DAG.getConstant(VT.getSizeInBits() - lg2,
1730 getShiftAmountTy()));
1731 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1732 AddToWorkList(SRL.getNode());
1733 AddToWorkList(ADD.getNode()); // Divide by pow2
1734 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1735 DAG.getConstant(lg2, getShiftAmountTy()));
1737 // If we're dividing by a positive value, we're done. Otherwise, we must
1738 // negate the result.
1739 if (pow2 > 0)
1740 return SRA;
1742 AddToWorkList(SRA.getNode());
1743 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1744 DAG.getConstant(0, VT), SRA);
1747 // if integer divide is expensive and we satisfy the requirements, emit an
1748 // alternate sequence.
1749 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1750 !TLI.isIntDivCheap()) {
1751 SDValue Op = BuildSDIV(N);
1752 if (Op.getNode()) return Op;
1755 // undef / X -> 0
1756 if (N0.getOpcode() == ISD::UNDEF)
1757 return DAG.getConstant(0, VT);
1758 // X / undef -> undef
1759 if (N1.getOpcode() == ISD::UNDEF)
1760 return N1;
1762 return SDValue();
1765 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1766 SDValue N0 = N->getOperand(0);
1767 SDValue N1 = N->getOperand(1);
1768 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1769 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1770 EVT VT = N->getValueType(0);
1772 // fold vector ops
1773 if (VT.isVector()) {
1774 SDValue FoldedVOp = SimplifyVBinOp(N);
1775 if (FoldedVOp.getNode()) return FoldedVOp;
1778 // fold (udiv c1, c2) -> c1/c2
1779 if (N0C && N1C && !N1C->isNullValue())
1780 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1781 // fold (udiv x, (1 << c)) -> x >>u c
1782 if (N1C && N1C->getAPIntValue().isPowerOf2())
1783 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1784 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1785 getShiftAmountTy()));
1786 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1787 if (N1.getOpcode() == ISD::SHL) {
1788 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1789 if (SHC->getAPIntValue().isPowerOf2()) {
1790 EVT ADDVT = N1.getOperand(1).getValueType();
1791 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1792 N1.getOperand(1),
1793 DAG.getConstant(SHC->getAPIntValue()
1794 .logBase2(),
1795 ADDVT));
1796 AddToWorkList(Add.getNode());
1797 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1801 // fold (udiv x, c) -> alternate
1802 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1803 SDValue Op = BuildUDIV(N);
1804 if (Op.getNode()) return Op;
1807 // undef / X -> 0
1808 if (N0.getOpcode() == ISD::UNDEF)
1809 return DAG.getConstant(0, VT);
1810 // X / undef -> undef
1811 if (N1.getOpcode() == ISD::UNDEF)
1812 return N1;
1814 return SDValue();
1817 SDValue DAGCombiner::visitSREM(SDNode *N) {
1818 SDValue N0 = N->getOperand(0);
1819 SDValue N1 = N->getOperand(1);
1820 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1821 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1822 EVT VT = N->getValueType(0);
1824 // fold (srem c1, c2) -> c1%c2
1825 if (N0C && N1C && !N1C->isNullValue())
1826 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1827 // If we know the sign bits of both operands are zero, strength reduce to a
1828 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1829 if (!VT.isVector()) {
1830 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1831 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1834 // If X/C can be simplified by the division-by-constant logic, lower
1835 // X%C to the equivalent of X-X/C*C.
1836 if (N1C && !N1C->isNullValue()) {
1837 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1838 AddToWorkList(Div.getNode());
1839 SDValue OptimizedDiv = combine(Div.getNode());
1840 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1841 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1842 OptimizedDiv, N1);
1843 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1844 AddToWorkList(Mul.getNode());
1845 return Sub;
1849 // undef % X -> 0
1850 if (N0.getOpcode() == ISD::UNDEF)
1851 return DAG.getConstant(0, VT);
1852 // X % undef -> undef
1853 if (N1.getOpcode() == ISD::UNDEF)
1854 return N1;
1856 return SDValue();
1859 SDValue DAGCombiner::visitUREM(SDNode *N) {
1860 SDValue N0 = N->getOperand(0);
1861 SDValue N1 = N->getOperand(1);
1862 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1863 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1864 EVT VT = N->getValueType(0);
1866 // fold (urem c1, c2) -> c1%c2
1867 if (N0C && N1C && !N1C->isNullValue())
1868 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1869 // fold (urem x, pow2) -> (and x, pow2-1)
1870 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1871 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1872 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1873 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1874 if (N1.getOpcode() == ISD::SHL) {
1875 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1876 if (SHC->getAPIntValue().isPowerOf2()) {
1877 SDValue Add =
1878 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1879 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1880 VT));
1881 AddToWorkList(Add.getNode());
1882 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1887 // If X/C can be simplified by the division-by-constant logic, lower
1888 // X%C to the equivalent of X-X/C*C.
1889 if (N1C && !N1C->isNullValue()) {
1890 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1891 AddToWorkList(Div.getNode());
1892 SDValue OptimizedDiv = combine(Div.getNode());
1893 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1894 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1895 OptimizedDiv, N1);
1896 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1897 AddToWorkList(Mul.getNode());
1898 return Sub;
1902 // undef % X -> 0
1903 if (N0.getOpcode() == ISD::UNDEF)
1904 return DAG.getConstant(0, VT);
1905 // X % undef -> undef
1906 if (N1.getOpcode() == ISD::UNDEF)
1907 return N1;
1909 return SDValue();
1912 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1913 SDValue N0 = N->getOperand(0);
1914 SDValue N1 = N->getOperand(1);
1915 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1916 EVT VT = N->getValueType(0);
1918 // fold (mulhs x, 0) -> 0
1919 if (N1C && N1C->isNullValue())
1920 return N1;
1921 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1922 if (N1C && N1C->getAPIntValue() == 1)
1923 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1924 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1925 getShiftAmountTy()));
1926 // fold (mulhs x, undef) -> 0
1927 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1928 return DAG.getConstant(0, VT);
1930 return SDValue();
1933 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1934 SDValue N0 = N->getOperand(0);
1935 SDValue N1 = N->getOperand(1);
1936 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1937 EVT VT = N->getValueType(0);
1939 // fold (mulhu x, 0) -> 0
1940 if (N1C && N1C->isNullValue())
1941 return N1;
1942 // fold (mulhu x, 1) -> 0
1943 if (N1C && N1C->getAPIntValue() == 1)
1944 return DAG.getConstant(0, N0.getValueType());
1945 // fold (mulhu x, undef) -> 0
1946 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1947 return DAG.getConstant(0, VT);
1949 return SDValue();
1952 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1953 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1954 /// that are being performed. Return true if a simplification was made.
1956 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1957 unsigned HiOp) {
1958 // If the high half is not needed, just compute the low half.
1959 bool HiExists = N->hasAnyUseOfValue(1);
1960 if (!HiExists &&
1961 (!LegalOperations ||
1962 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1963 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1964 N->op_begin(), N->getNumOperands());
1965 return CombineTo(N, Res, Res);
1968 // If the low half is not needed, just compute the high half.
1969 bool LoExists = N->hasAnyUseOfValue(0);
1970 if (!LoExists &&
1971 (!LegalOperations ||
1972 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1973 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1974 N->op_begin(), N->getNumOperands());
1975 return CombineTo(N, Res, Res);
1978 // If both halves are used, return as it is.
1979 if (LoExists && HiExists)
1980 return SDValue();
1982 // If the two computed results can be simplified separately, separate them.
1983 if (LoExists) {
1984 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1985 N->op_begin(), N->getNumOperands());
1986 AddToWorkList(Lo.getNode());
1987 SDValue LoOpt = combine(Lo.getNode());
1988 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1989 (!LegalOperations ||
1990 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1991 return CombineTo(N, LoOpt, LoOpt);
1994 if (HiExists) {
1995 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1996 N->op_begin(), N->getNumOperands());
1997 AddToWorkList(Hi.getNode());
1998 SDValue HiOpt = combine(Hi.getNode());
1999 if (HiOpt.getNode() && HiOpt != Hi &&
2000 (!LegalOperations ||
2001 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2002 return CombineTo(N, HiOpt, HiOpt);
2005 return SDValue();
2008 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2009 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2010 if (Res.getNode()) return Res;
2012 return SDValue();
2015 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2016 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2017 if (Res.getNode()) return Res;
2019 return SDValue();
2022 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2023 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2024 if (Res.getNode()) return Res;
2026 return SDValue();
2029 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2030 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2031 if (Res.getNode()) return Res;
2033 return SDValue();
2036 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2037 /// two operands of the same opcode, try to simplify it.
2038 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2039 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2040 EVT VT = N0.getValueType();
2041 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2043 // Bail early if none of these transforms apply.
2044 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2046 // For each of OP in AND/OR/XOR:
2047 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2048 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2049 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2050 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2052 // do not sink logical op inside of a vector extend, since it may combine
2053 // into a vsetcc.
2054 EVT Op0VT = N0.getOperand(0).getValueType();
2055 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2056 N0.getOpcode() == ISD::SIGN_EXTEND ||
2057 // Avoid infinite looping with PromoteIntBinOp.
2058 (N0.getOpcode() == ISD::ANY_EXTEND &&
2059 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2060 (N0.getOpcode() == ISD::TRUNCATE &&
2061 (!TLI.isZExtFree(VT, Op0VT) ||
2062 !TLI.isTruncateFree(Op0VT, VT)) &&
2063 TLI.isTypeLegal(Op0VT))) &&
2064 !VT.isVector() &&
2065 Op0VT == N1.getOperand(0).getValueType() &&
2066 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2067 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2068 N0.getOperand(0).getValueType(),
2069 N0.getOperand(0), N1.getOperand(0));
2070 AddToWorkList(ORNode.getNode());
2071 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2074 // For each of OP in SHL/SRL/SRA/AND...
2075 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2076 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2077 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2078 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2079 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2080 N0.getOperand(1) == N1.getOperand(1)) {
2081 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2082 N0.getOperand(0).getValueType(),
2083 N0.getOperand(0), N1.getOperand(0));
2084 AddToWorkList(ORNode.getNode());
2085 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2086 ORNode, N0.getOperand(1));
2089 return SDValue();
2092 SDValue DAGCombiner::visitAND(SDNode *N) {
2093 SDValue N0 = N->getOperand(0);
2094 SDValue N1 = N->getOperand(1);
2095 SDValue LL, LR, RL, RR, CC0, CC1;
2096 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2097 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2098 EVT VT = N1.getValueType();
2099 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2101 // fold vector ops
2102 if (VT.isVector()) {
2103 SDValue FoldedVOp = SimplifyVBinOp(N);
2104 if (FoldedVOp.getNode()) return FoldedVOp;
2107 // fold (and x, undef) -> 0
2108 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2109 return DAG.getConstant(0, VT);
2110 // fold (and c1, c2) -> c1&c2
2111 if (N0C && N1C)
2112 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2113 // canonicalize constant to RHS
2114 if (N0C && !N1C)
2115 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2116 // fold (and x, -1) -> x
2117 if (N1C && N1C->isAllOnesValue())
2118 return N0;
2119 // if (and x, c) is known to be zero, return 0
2120 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2121 APInt::getAllOnesValue(BitWidth)))
2122 return DAG.getConstant(0, VT);
2123 // reassociate and
2124 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2125 if (RAND.getNode() != 0)
2126 return RAND;
2127 // fold (and (or x, C), D) -> D if (C & D) == D
2128 if (N1C && N0.getOpcode() == ISD::OR)
2129 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2130 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2131 return N1;
2132 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2133 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2134 SDValue N0Op0 = N0.getOperand(0);
2135 APInt Mask = ~N1C->getAPIntValue();
2136 Mask.trunc(N0Op0.getValueSizeInBits());
2137 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2138 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2139 N0.getValueType(), N0Op0);
2141 // Replace uses of the AND with uses of the Zero extend node.
2142 CombineTo(N, Zext);
2144 // We actually want to replace all uses of the any_extend with the
2145 // zero_extend, to avoid duplicating things. This will later cause this
2146 // AND to be folded.
2147 CombineTo(N0.getNode(), Zext);
2148 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2151 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2152 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2153 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2154 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2156 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2157 LL.getValueType().isInteger()) {
2158 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2159 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2160 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2161 LR.getValueType(), LL, RL);
2162 AddToWorkList(ORNode.getNode());
2163 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2165 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2166 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2167 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2168 LR.getValueType(), LL, RL);
2169 AddToWorkList(ANDNode.getNode());
2170 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2172 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2173 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2174 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2175 LR.getValueType(), LL, RL);
2176 AddToWorkList(ORNode.getNode());
2177 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2180 // canonicalize equivalent to ll == rl
2181 if (LL == RR && LR == RL) {
2182 Op1 = ISD::getSetCCSwappedOperands(Op1);
2183 std::swap(RL, RR);
2185 if (LL == RL && LR == RR) {
2186 bool isInteger = LL.getValueType().isInteger();
2187 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2188 if (Result != ISD::SETCC_INVALID &&
2189 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2190 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2191 LL, LR, Result);
2195 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2196 if (N0.getOpcode() == N1.getOpcode()) {
2197 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2198 if (Tmp.getNode()) return Tmp;
2201 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2202 // fold (and (sra)) -> (and (srl)) when possible.
2203 if (!VT.isVector() &&
2204 SimplifyDemandedBits(SDValue(N, 0)))
2205 return SDValue(N, 0);
2207 // fold (zext_inreg (extload x)) -> (zextload x)
2208 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2209 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2210 EVT MemVT = LN0->getMemoryVT();
2211 // If we zero all the possible extended bits, then we can turn this into
2212 // a zextload if we are running before legalize or the operation is legal.
2213 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2214 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2215 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2216 ((!LegalOperations && !LN0->isVolatile()) ||
2217 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2218 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getDebugLoc(),
2219 LN0->getChain(), LN0->getBasePtr(),
2220 LN0->getPointerInfo(), MemVT,
2221 LN0->isVolatile(), LN0->isNonTemporal(),
2222 LN0->getAlignment());
2223 AddToWorkList(N);
2224 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2225 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2228 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2229 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2230 N0.hasOneUse()) {
2231 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2232 EVT MemVT = LN0->getMemoryVT();
2233 // If we zero all the possible extended bits, then we can turn this into
2234 // a zextload if we are running before legalize or the operation is legal.
2235 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2236 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2237 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2238 ((!LegalOperations && !LN0->isVolatile()) ||
2239 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2240 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getDebugLoc(),
2241 LN0->getChain(),
2242 LN0->getBasePtr(), LN0->getPointerInfo(),
2243 MemVT,
2244 LN0->isVolatile(), LN0->isNonTemporal(),
2245 LN0->getAlignment());
2246 AddToWorkList(N);
2247 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2248 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2252 // fold (and (load x), 255) -> (zextload x, i8)
2253 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2254 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2255 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2256 (N0.getOpcode() == ISD::ANY_EXTEND &&
2257 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2258 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2259 LoadSDNode *LN0 = HasAnyExt
2260 ? cast<LoadSDNode>(N0.getOperand(0))
2261 : cast<LoadSDNode>(N0);
2262 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2263 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2264 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2265 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2266 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2267 EVT LoadedVT = LN0->getMemoryVT();
2269 if (ExtVT == LoadedVT &&
2270 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2271 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2273 SDValue NewLoad =
2274 DAG.getExtLoad(ISD::ZEXTLOAD, LoadResultTy, LN0->getDebugLoc(),
2275 LN0->getChain(), LN0->getBasePtr(),
2276 LN0->getPointerInfo(),
2277 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2278 LN0->getAlignment());
2279 AddToWorkList(N);
2280 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2281 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2284 // Do not change the width of a volatile load.
2285 // Do not generate loads of non-round integer types since these can
2286 // be expensive (and would be wrong if the type is not byte sized).
2287 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2288 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2289 EVT PtrType = LN0->getOperand(1).getValueType();
2291 unsigned Alignment = LN0->getAlignment();
2292 SDValue NewPtr = LN0->getBasePtr();
2294 // For big endian targets, we need to add an offset to the pointer
2295 // to load the correct bytes. For little endian systems, we merely
2296 // need to read fewer bytes from the same pointer.
2297 if (TLI.isBigEndian()) {
2298 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2299 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2300 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2301 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2302 NewPtr, DAG.getConstant(PtrOff, PtrType));
2303 Alignment = MinAlign(Alignment, PtrOff);
2306 AddToWorkList(NewPtr.getNode());
2308 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2309 SDValue Load =
2310 DAG.getExtLoad(ISD::ZEXTLOAD, LoadResultTy, LN0->getDebugLoc(),
2311 LN0->getChain(), NewPtr,
2312 LN0->getPointerInfo(),
2313 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2314 Alignment);
2315 AddToWorkList(N);
2316 CombineTo(LN0, Load, Load.getValue(1));
2317 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2323 return SDValue();
2326 SDValue DAGCombiner::visitOR(SDNode *N) {
2327 SDValue N0 = N->getOperand(0);
2328 SDValue N1 = N->getOperand(1);
2329 SDValue LL, LR, RL, RR, CC0, CC1;
2330 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2331 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2332 EVT VT = N1.getValueType();
2334 // fold vector ops
2335 if (VT.isVector()) {
2336 SDValue FoldedVOp = SimplifyVBinOp(N);
2337 if (FoldedVOp.getNode()) return FoldedVOp;
2340 // fold (or x, undef) -> -1
2341 if (!LegalOperations &&
2342 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2343 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2344 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2346 // fold (or c1, c2) -> c1|c2
2347 if (N0C && N1C)
2348 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2349 // canonicalize constant to RHS
2350 if (N0C && !N1C)
2351 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2352 // fold (or x, 0) -> x
2353 if (N1C && N1C->isNullValue())
2354 return N0;
2355 // fold (or x, -1) -> -1
2356 if (N1C && N1C->isAllOnesValue())
2357 return N1;
2358 // fold (or x, c) -> c iff (x & ~c) == 0
2359 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2360 return N1;
2361 // reassociate or
2362 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2363 if (ROR.getNode() != 0)
2364 return ROR;
2365 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2366 // iff (c1 & c2) == 0.
2367 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2368 isa<ConstantSDNode>(N0.getOperand(1))) {
2369 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2370 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2371 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2372 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2373 N0.getOperand(0), N1),
2374 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2376 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2377 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2378 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2379 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2381 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2382 LL.getValueType().isInteger()) {
2383 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2384 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2385 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2386 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2387 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2388 LR.getValueType(), LL, RL);
2389 AddToWorkList(ORNode.getNode());
2390 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2392 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2393 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2394 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2395 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2396 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2397 LR.getValueType(), LL, RL);
2398 AddToWorkList(ANDNode.getNode());
2399 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2402 // canonicalize equivalent to ll == rl
2403 if (LL == RR && LR == RL) {
2404 Op1 = ISD::getSetCCSwappedOperands(Op1);
2405 std::swap(RL, RR);
2407 if (LL == RL && LR == RR) {
2408 bool isInteger = LL.getValueType().isInteger();
2409 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2410 if (Result != ISD::SETCC_INVALID &&
2411 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2412 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2413 LL, LR, Result);
2417 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2418 if (N0.getOpcode() == N1.getOpcode()) {
2419 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2420 if (Tmp.getNode()) return Tmp;
2423 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2424 if (N0.getOpcode() == ISD::AND &&
2425 N1.getOpcode() == ISD::AND &&
2426 N0.getOperand(1).getOpcode() == ISD::Constant &&
2427 N1.getOperand(1).getOpcode() == ISD::Constant &&
2428 // Don't increase # computations.
2429 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2430 // We can only do this xform if we know that bits from X that are set in C2
2431 // but not in C1 are already zero. Likewise for Y.
2432 const APInt &LHSMask =
2433 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2434 const APInt &RHSMask =
2435 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2437 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2438 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2439 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2440 N0.getOperand(0), N1.getOperand(0));
2441 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2442 DAG.getConstant(LHSMask | RHSMask, VT));
2446 // See if this is some rotate idiom.
2447 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2448 return SDValue(Rot, 0);
2450 // Simplify the operands using demanded-bits information.
2451 if (!VT.isVector() &&
2452 SimplifyDemandedBits(SDValue(N, 0)))
2453 return SDValue(N, 0);
2455 return SDValue();
2458 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2459 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2460 if (Op.getOpcode() == ISD::AND) {
2461 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2462 Mask = Op.getOperand(1);
2463 Op = Op.getOperand(0);
2464 } else {
2465 return false;
2469 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2470 Shift = Op;
2471 return true;
2474 return false;
2477 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2478 // idioms for rotate, and if the target supports rotation instructions, generate
2479 // a rot[lr].
2480 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2481 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2482 EVT VT = LHS.getValueType();
2483 if (!TLI.isTypeLegal(VT)) return 0;
2485 // The target must have at least one rotate flavor.
2486 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2487 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2488 if (!HasROTL && !HasROTR) return 0;
2490 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2491 SDValue LHSShift; // The shift.
2492 SDValue LHSMask; // AND value if any.
2493 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2494 return 0; // Not part of a rotate.
2496 SDValue RHSShift; // The shift.
2497 SDValue RHSMask; // AND value if any.
2498 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2499 return 0; // Not part of a rotate.
2501 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2502 return 0; // Not shifting the same value.
2504 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2505 return 0; // Shifts must disagree.
2507 // Canonicalize shl to left side in a shl/srl pair.
2508 if (RHSShift.getOpcode() == ISD::SHL) {
2509 std::swap(LHS, RHS);
2510 std::swap(LHSShift, RHSShift);
2511 std::swap(LHSMask , RHSMask );
2514 unsigned OpSizeInBits = VT.getSizeInBits();
2515 SDValue LHSShiftArg = LHSShift.getOperand(0);
2516 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2517 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2519 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2520 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2521 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2522 RHSShiftAmt.getOpcode() == ISD::Constant) {
2523 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2524 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2525 if ((LShVal + RShVal) != OpSizeInBits)
2526 return 0;
2528 SDValue Rot;
2529 if (HasROTL)
2530 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2531 else
2532 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2534 // If there is an AND of either shifted operand, apply it to the result.
2535 if (LHSMask.getNode() || RHSMask.getNode()) {
2536 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2538 if (LHSMask.getNode()) {
2539 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2540 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2542 if (RHSMask.getNode()) {
2543 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2544 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2547 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2550 return Rot.getNode();
2553 // If there is a mask here, and we have a variable shift, we can't be sure
2554 // that we're masking out the right stuff.
2555 if (LHSMask.getNode() || RHSMask.getNode())
2556 return 0;
2558 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2559 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2560 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2561 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2562 if (ConstantSDNode *SUBC =
2563 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2564 if (SUBC->getAPIntValue() == OpSizeInBits) {
2565 if (HasROTL)
2566 return DAG.getNode(ISD::ROTL, DL, VT,
2567 LHSShiftArg, LHSShiftAmt).getNode();
2568 else
2569 return DAG.getNode(ISD::ROTR, DL, VT,
2570 LHSShiftArg, RHSShiftAmt).getNode();
2575 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2576 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2577 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2578 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2579 if (ConstantSDNode *SUBC =
2580 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2581 if (SUBC->getAPIntValue() == OpSizeInBits) {
2582 if (HasROTR)
2583 return DAG.getNode(ISD::ROTR, DL, VT,
2584 LHSShiftArg, RHSShiftAmt).getNode();
2585 else
2586 return DAG.getNode(ISD::ROTL, DL, VT,
2587 LHSShiftArg, LHSShiftAmt).getNode();
2592 // Look for sign/zext/any-extended or truncate cases:
2593 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2594 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2595 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2596 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2597 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2598 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2599 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2600 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2601 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2602 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2603 if (RExtOp0.getOpcode() == ISD::SUB &&
2604 RExtOp0.getOperand(1) == LExtOp0) {
2605 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2606 // (rotl x, y)
2607 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2608 // (rotr x, (sub 32, y))
2609 if (ConstantSDNode *SUBC =
2610 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2611 if (SUBC->getAPIntValue() == OpSizeInBits) {
2612 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2613 LHSShiftArg,
2614 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2617 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2618 RExtOp0 == LExtOp0.getOperand(1)) {
2619 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2620 // (rotr x, y)
2621 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2622 // (rotl x, (sub 32, y))
2623 if (ConstantSDNode *SUBC =
2624 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2625 if (SUBC->getAPIntValue() == OpSizeInBits) {
2626 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2627 LHSShiftArg,
2628 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2634 return 0;
2637 SDValue DAGCombiner::visitXOR(SDNode *N) {
2638 SDValue N0 = N->getOperand(0);
2639 SDValue N1 = N->getOperand(1);
2640 SDValue LHS, RHS, CC;
2641 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2642 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2643 EVT VT = N0.getValueType();
2645 // fold vector ops
2646 if (VT.isVector()) {
2647 SDValue FoldedVOp = SimplifyVBinOp(N);
2648 if (FoldedVOp.getNode()) return FoldedVOp;
2651 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2652 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2653 return DAG.getConstant(0, VT);
2654 // fold (xor x, undef) -> undef
2655 if (N0.getOpcode() == ISD::UNDEF)
2656 return N0;
2657 if (N1.getOpcode() == ISD::UNDEF)
2658 return N1;
2659 // fold (xor c1, c2) -> c1^c2
2660 if (N0C && N1C)
2661 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2662 // canonicalize constant to RHS
2663 if (N0C && !N1C)
2664 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2665 // fold (xor x, 0) -> x
2666 if (N1C && N1C->isNullValue())
2667 return N0;
2668 // reassociate xor
2669 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2670 if (RXOR.getNode() != 0)
2671 return RXOR;
2673 // fold !(x cc y) -> (x !cc y)
2674 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2675 bool isInt = LHS.getValueType().isInteger();
2676 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2677 isInt);
2679 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2680 switch (N0.getOpcode()) {
2681 default:
2682 llvm_unreachable("Unhandled SetCC Equivalent!");
2683 case ISD::SETCC:
2684 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2685 case ISD::SELECT_CC:
2686 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2687 N0.getOperand(3), NotCC);
2692 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2693 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2694 N0.getNode()->hasOneUse() &&
2695 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2696 SDValue V = N0.getOperand(0);
2697 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2698 DAG.getConstant(1, V.getValueType()));
2699 AddToWorkList(V.getNode());
2700 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2703 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2704 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2705 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2706 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2707 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2708 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2709 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2710 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2711 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2712 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2715 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2716 if (N1C && N1C->isAllOnesValue() &&
2717 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2718 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2719 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2720 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2721 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2722 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2723 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2724 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2727 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2728 if (N1C && N0.getOpcode() == ISD::XOR) {
2729 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2730 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2731 if (N00C)
2732 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2733 DAG.getConstant(N1C->getAPIntValue() ^
2734 N00C->getAPIntValue(), VT));
2735 if (N01C)
2736 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2737 DAG.getConstant(N1C->getAPIntValue() ^
2738 N01C->getAPIntValue(), VT));
2740 // fold (xor x, x) -> 0
2741 if (N0 == N1) {
2742 if (!VT.isVector()) {
2743 return DAG.getConstant(0, VT);
2744 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2745 // Produce a vector of zeros.
2746 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2747 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2748 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2749 &Ops[0], Ops.size());
2753 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2754 if (N0.getOpcode() == N1.getOpcode()) {
2755 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2756 if (Tmp.getNode()) return Tmp;
2759 // Simplify the expression using non-local knowledge.
2760 if (!VT.isVector() &&
2761 SimplifyDemandedBits(SDValue(N, 0)))
2762 return SDValue(N, 0);
2764 return SDValue();
2767 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2768 /// the shift amount is a constant.
2769 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2770 SDNode *LHS = N->getOperand(0).getNode();
2771 if (!LHS->hasOneUse()) return SDValue();
2773 // We want to pull some binops through shifts, so that we have (and (shift))
2774 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2775 // thing happens with address calculations, so it's important to canonicalize
2776 // it.
2777 bool HighBitSet = false; // Can we transform this if the high bit is set?
2779 switch (LHS->getOpcode()) {
2780 default: return SDValue();
2781 case ISD::OR:
2782 case ISD::XOR:
2783 HighBitSet = false; // We can only transform sra if the high bit is clear.
2784 break;
2785 case ISD::AND:
2786 HighBitSet = true; // We can only transform sra if the high bit is set.
2787 break;
2788 case ISD::ADD:
2789 if (N->getOpcode() != ISD::SHL)
2790 return SDValue(); // only shl(add) not sr[al](add).
2791 HighBitSet = false; // We can only transform sra if the high bit is clear.
2792 break;
2795 // We require the RHS of the binop to be a constant as well.
2796 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2797 if (!BinOpCst) return SDValue();
2799 // FIXME: disable this unless the input to the binop is a shift by a constant.
2800 // If it is not a shift, it pessimizes some common cases like:
2802 // void foo(int *X, int i) { X[i & 1235] = 1; }
2803 // int bar(int *X, int i) { return X[i & 255]; }
2804 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2805 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2806 BinOpLHSVal->getOpcode() != ISD::SRA &&
2807 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2808 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2809 return SDValue();
2811 EVT VT = N->getValueType(0);
2813 // If this is a signed shift right, and the high bit is modified by the
2814 // logical operation, do not perform the transformation. The highBitSet
2815 // boolean indicates the value of the high bit of the constant which would
2816 // cause it to be modified for this operation.
2817 if (N->getOpcode() == ISD::SRA) {
2818 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2819 if (BinOpRHSSignSet != HighBitSet)
2820 return SDValue();
2823 // Fold the constants, shifting the binop RHS by the shift amount.
2824 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2825 N->getValueType(0),
2826 LHS->getOperand(1), N->getOperand(1));
2828 // Create the new shift.
2829 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2830 VT, LHS->getOperand(0), N->getOperand(1));
2832 // Create the new binop.
2833 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2836 SDValue DAGCombiner::visitSHL(SDNode *N) {
2837 SDValue N0 = N->getOperand(0);
2838 SDValue N1 = N->getOperand(1);
2839 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2840 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2841 EVT VT = N0.getValueType();
2842 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2844 // fold (shl c1, c2) -> c1<<c2
2845 if (N0C && N1C)
2846 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2847 // fold (shl 0, x) -> 0
2848 if (N0C && N0C->isNullValue())
2849 return N0;
2850 // fold (shl x, c >= size(x)) -> undef
2851 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2852 return DAG.getUNDEF(VT);
2853 // fold (shl x, 0) -> x
2854 if (N1C && N1C->isNullValue())
2855 return N0;
2856 // if (shl x, c) is known to be zero, return 0
2857 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2858 APInt::getAllOnesValue(OpSizeInBits)))
2859 return DAG.getConstant(0, VT);
2860 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2861 if (N1.getOpcode() == ISD::TRUNCATE &&
2862 N1.getOperand(0).getOpcode() == ISD::AND &&
2863 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2864 SDValue N101 = N1.getOperand(0).getOperand(1);
2865 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2866 EVT TruncVT = N1.getValueType();
2867 SDValue N100 = N1.getOperand(0).getOperand(0);
2868 APInt TruncC = N101C->getAPIntValue();
2869 TruncC.trunc(TruncVT.getSizeInBits());
2870 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2871 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2872 DAG.getNode(ISD::TRUNCATE,
2873 N->getDebugLoc(),
2874 TruncVT, N100),
2875 DAG.getConstant(TruncC, TruncVT)));
2879 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2880 return SDValue(N, 0);
2882 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2883 if (N1C && N0.getOpcode() == ISD::SHL &&
2884 N0.getOperand(1).getOpcode() == ISD::Constant) {
2885 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2886 uint64_t c2 = N1C->getZExtValue();
2887 if (c1 + c2 > OpSizeInBits)
2888 return DAG.getConstant(0, VT);
2889 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2890 DAG.getConstant(c1 + c2, N1.getValueType()));
2892 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2893 // (srl (and x, (shl -1, c1)), (sub c1, c2))
2894 if (N1C && N0.getOpcode() == ISD::SRL &&
2895 N0.getOperand(1).getOpcode() == ISD::Constant) {
2896 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2897 if (c1 < VT.getSizeInBits()) {
2898 uint64_t c2 = N1C->getZExtValue();
2899 SDValue HiBitsMask =
2900 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2901 VT.getSizeInBits() - c1),
2902 VT);
2903 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2904 N0.getOperand(0),
2905 HiBitsMask);
2906 if (c2 > c1)
2907 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2908 DAG.getConstant(c2-c1, N1.getValueType()));
2909 else
2910 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2911 DAG.getConstant(c1-c2, N1.getValueType()));
2914 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2915 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2916 SDValue HiBitsMask =
2917 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2918 VT.getSizeInBits() -
2919 N1C->getZExtValue()),
2920 VT);
2921 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2922 HiBitsMask);
2925 if (N1C) {
2926 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
2927 if (NewSHL.getNode())
2928 return NewSHL;
2931 return SDValue();
2934 SDValue DAGCombiner::visitSRA(SDNode *N) {
2935 SDValue N0 = N->getOperand(0);
2936 SDValue N1 = N->getOperand(1);
2937 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2938 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2939 EVT VT = N0.getValueType();
2940 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2942 // fold (sra c1, c2) -> (sra c1, c2)
2943 if (N0C && N1C)
2944 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2945 // fold (sra 0, x) -> 0
2946 if (N0C && N0C->isNullValue())
2947 return N0;
2948 // fold (sra -1, x) -> -1
2949 if (N0C && N0C->isAllOnesValue())
2950 return N0;
2951 // fold (sra x, (setge c, size(x))) -> undef
2952 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2953 return DAG.getUNDEF(VT);
2954 // fold (sra x, 0) -> x
2955 if (N1C && N1C->isNullValue())
2956 return N0;
2957 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2958 // sext_inreg.
2959 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2960 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
2961 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2962 if (VT.isVector())
2963 ExtVT = EVT::getVectorVT(*DAG.getContext(),
2964 ExtVT, VT.getVectorNumElements());
2965 if ((!LegalOperations ||
2966 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
2967 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2968 N0.getOperand(0), DAG.getValueType(ExtVT));
2971 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2972 if (N1C && N0.getOpcode() == ISD::SRA) {
2973 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2974 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2975 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
2976 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2977 DAG.getConstant(Sum, N1C->getValueType(0)));
2981 // fold (sra (shl X, m), (sub result_size, n))
2982 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2983 // result_size - n != m.
2984 // If truncate is free for the target sext(shl) is likely to result in better
2985 // code.
2986 if (N0.getOpcode() == ISD::SHL) {
2987 // Get the two constanst of the shifts, CN0 = m, CN = n.
2988 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2989 if (N01C && N1C) {
2990 // Determine what the truncate's result bitsize and type would be.
2991 EVT TruncVT =
2992 EVT::getIntegerVT(*DAG.getContext(), OpSizeInBits - N1C->getZExtValue());
2993 // Determine the residual right-shift amount.
2994 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2996 // If the shift is not a no-op (in which case this should be just a sign
2997 // extend already), the truncated to type is legal, sign_extend is legal
2998 // on that type, and the truncate to that type is both legal and free,
2999 // perform the transform.
3000 if ((ShiftAmt > 0) &&
3001 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3002 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3003 TLI.isTruncateFree(VT, TruncVT)) {
3005 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
3006 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3007 N0.getOperand(0), Amt);
3008 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3009 Shift);
3010 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3011 N->getValueType(0), Trunc);
3016 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3017 if (N1.getOpcode() == ISD::TRUNCATE &&
3018 N1.getOperand(0).getOpcode() == ISD::AND &&
3019 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3020 SDValue N101 = N1.getOperand(0).getOperand(1);
3021 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3022 EVT TruncVT = N1.getValueType();
3023 SDValue N100 = N1.getOperand(0).getOperand(0);
3024 APInt TruncC = N101C->getAPIntValue();
3025 TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3026 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3027 DAG.getNode(ISD::AND, N->getDebugLoc(),
3028 TruncVT,
3029 DAG.getNode(ISD::TRUNCATE,
3030 N->getDebugLoc(),
3031 TruncVT, N100),
3032 DAG.getConstant(TruncC, TruncVT)));
3036 // Simplify, based on bits shifted out of the LHS.
3037 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3038 return SDValue(N, 0);
3041 // If the sign bit is known to be zero, switch this to a SRL.
3042 if (DAG.SignBitIsZero(N0))
3043 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3045 if (N1C) {
3046 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3047 if (NewSRA.getNode())
3048 return NewSRA;
3051 return SDValue();
3054 SDValue DAGCombiner::visitSRL(SDNode *N) {
3055 SDValue N0 = N->getOperand(0);
3056 SDValue N1 = N->getOperand(1);
3057 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3058 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3059 EVT VT = N0.getValueType();
3060 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3062 // fold (srl c1, c2) -> c1 >>u c2
3063 if (N0C && N1C)
3064 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3065 // fold (srl 0, x) -> 0
3066 if (N0C && N0C->isNullValue())
3067 return N0;
3068 // fold (srl x, c >= size(x)) -> undef
3069 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3070 return DAG.getUNDEF(VT);
3071 // fold (srl x, 0) -> x
3072 if (N1C && N1C->isNullValue())
3073 return N0;
3074 // if (srl x, c) is known to be zero, return 0
3075 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3076 APInt::getAllOnesValue(OpSizeInBits)))
3077 return DAG.getConstant(0, VT);
3079 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3080 if (N1C && N0.getOpcode() == ISD::SRL &&
3081 N0.getOperand(1).getOpcode() == ISD::Constant) {
3082 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3083 uint64_t c2 = N1C->getZExtValue();
3084 if (c1 + c2 > OpSizeInBits)
3085 return DAG.getConstant(0, VT);
3086 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3087 DAG.getConstant(c1 + c2, N1.getValueType()));
3090 // fold (srl (shl x, c), c) -> (and x, cst2)
3091 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3092 N0.getValueSizeInBits() <= 64) {
3093 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3094 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3095 DAG.getConstant(~0ULL >> ShAmt, VT));
3099 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3100 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3101 // Shifting in all undef bits?
3102 EVT SmallVT = N0.getOperand(0).getValueType();
3103 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3104 return DAG.getUNDEF(VT);
3106 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3107 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3108 N0.getOperand(0), N1);
3109 AddToWorkList(SmallShift.getNode());
3110 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3114 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3115 // bit, which is unmodified by sra.
3116 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3117 if (N0.getOpcode() == ISD::SRA)
3118 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3121 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3122 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3123 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3124 APInt KnownZero, KnownOne;
3125 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3126 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3128 // If any of the input bits are KnownOne, then the input couldn't be all
3129 // zeros, thus the result of the srl will always be zero.
3130 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3132 // If all of the bits input the to ctlz node are known to be zero, then
3133 // the result of the ctlz is "32" and the result of the shift is one.
3134 APInt UnknownBits = ~KnownZero & Mask;
3135 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3137 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3138 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3139 // Okay, we know that only that the single bit specified by UnknownBits
3140 // could be set on input to the CTLZ node. If this bit is set, the SRL
3141 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3142 // to an SRL/XOR pair, which is likely to simplify more.
3143 unsigned ShAmt = UnknownBits.countTrailingZeros();
3144 SDValue Op = N0.getOperand(0);
3146 if (ShAmt) {
3147 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3148 DAG.getConstant(ShAmt, getShiftAmountTy()));
3149 AddToWorkList(Op.getNode());
3152 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3153 Op, DAG.getConstant(1, VT));
3157 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3158 if (N1.getOpcode() == ISD::TRUNCATE &&
3159 N1.getOperand(0).getOpcode() == ISD::AND &&
3160 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3161 SDValue N101 = N1.getOperand(0).getOperand(1);
3162 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3163 EVT TruncVT = N1.getValueType();
3164 SDValue N100 = N1.getOperand(0).getOperand(0);
3165 APInt TruncC = N101C->getAPIntValue();
3166 TruncC.trunc(TruncVT.getSizeInBits());
3167 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3168 DAG.getNode(ISD::AND, N->getDebugLoc(),
3169 TruncVT,
3170 DAG.getNode(ISD::TRUNCATE,
3171 N->getDebugLoc(),
3172 TruncVT, N100),
3173 DAG.getConstant(TruncC, TruncVT)));
3177 // fold operands of srl based on knowledge that the low bits are not
3178 // demanded.
3179 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3180 return SDValue(N, 0);
3182 if (N1C) {
3183 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3184 if (NewSRL.getNode())
3185 return NewSRL;
3188 // Attempt to convert a srl of a load into a narrower zero-extending load.
3189 SDValue NarrowLoad = ReduceLoadWidth(N);
3190 if (NarrowLoad.getNode())
3191 return NarrowLoad;
3193 // Here is a common situation. We want to optimize:
3195 // %a = ...
3196 // %b = and i32 %a, 2
3197 // %c = srl i32 %b, 1
3198 // brcond i32 %c ...
3200 // into
3202 // %a = ...
3203 // %b = and %a, 2
3204 // %c = setcc eq %b, 0
3205 // brcond %c ...
3207 // However when after the source operand of SRL is optimized into AND, the SRL
3208 // itself may not be optimized further. Look for it and add the BRCOND into
3209 // the worklist.
3210 if (N->hasOneUse()) {
3211 SDNode *Use = *N->use_begin();
3212 if (Use->getOpcode() == ISD::BRCOND)
3213 AddToWorkList(Use);
3214 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3215 // Also look pass the truncate.
3216 Use = *Use->use_begin();
3217 if (Use->getOpcode() == ISD::BRCOND)
3218 AddToWorkList(Use);
3222 return SDValue();
3225 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3226 SDValue N0 = N->getOperand(0);
3227 EVT VT = N->getValueType(0);
3229 // fold (ctlz c1) -> c2
3230 if (isa<ConstantSDNode>(N0))
3231 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3232 return SDValue();
3235 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3236 SDValue N0 = N->getOperand(0);
3237 EVT VT = N->getValueType(0);
3239 // fold (cttz c1) -> c2
3240 if (isa<ConstantSDNode>(N0))
3241 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3242 return SDValue();
3245 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3246 SDValue N0 = N->getOperand(0);
3247 EVT VT = N->getValueType(0);
3249 // fold (ctpop c1) -> c2
3250 if (isa<ConstantSDNode>(N0))
3251 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3252 return SDValue();
3255 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3256 SDValue N0 = N->getOperand(0);
3257 SDValue N1 = N->getOperand(1);
3258 SDValue N2 = N->getOperand(2);
3259 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3260 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3261 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3262 EVT VT = N->getValueType(0);
3263 EVT VT0 = N0.getValueType();
3265 // fold (select C, X, X) -> X
3266 if (N1 == N2)
3267 return N1;
3268 // fold (select true, X, Y) -> X
3269 if (N0C && !N0C->isNullValue())
3270 return N1;
3271 // fold (select false, X, Y) -> Y
3272 if (N0C && N0C->isNullValue())
3273 return N2;
3274 // fold (select C, 1, X) -> (or C, X)
3275 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3276 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3277 // fold (select C, 0, 1) -> (xor C, 1)
3278 if (VT.isInteger() &&
3279 (VT0 == MVT::i1 ||
3280 (VT0.isInteger() &&
3281 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3282 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3283 SDValue XORNode;
3284 if (VT == VT0)
3285 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3286 N0, DAG.getConstant(1, VT0));
3287 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3288 N0, DAG.getConstant(1, VT0));
3289 AddToWorkList(XORNode.getNode());
3290 if (VT.bitsGT(VT0))
3291 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3292 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3294 // fold (select C, 0, X) -> (and (not C), X)
3295 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3296 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3297 AddToWorkList(NOTNode.getNode());
3298 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3300 // fold (select C, X, 1) -> (or (not C), X)
3301 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3302 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3303 AddToWorkList(NOTNode.getNode());
3304 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3306 // fold (select C, X, 0) -> (and C, X)
3307 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3308 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3309 // fold (select X, X, Y) -> (or X, Y)
3310 // fold (select X, 1, Y) -> (or X, Y)
3311 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3312 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3313 // fold (select X, Y, X) -> (and X, Y)
3314 // fold (select X, Y, 0) -> (and X, Y)
3315 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3316 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3318 // If we can fold this based on the true/false value, do so.
3319 if (SimplifySelectOps(N, N1, N2))
3320 return SDValue(N, 0); // Don't revisit N.
3322 // fold selects based on a setcc into other things, such as min/max/abs
3323 if (N0.getOpcode() == ISD::SETCC) {
3324 // FIXME:
3325 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3326 // having to say they don't support SELECT_CC on every type the DAG knows
3327 // about, since there is no way to mark an opcode illegal at all value types
3328 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3329 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3330 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3331 N0.getOperand(0), N0.getOperand(1),
3332 N1, N2, N0.getOperand(2));
3333 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3336 return SDValue();
3339 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3340 SDValue N0 = N->getOperand(0);
3341 SDValue N1 = N->getOperand(1);
3342 SDValue N2 = N->getOperand(2);
3343 SDValue N3 = N->getOperand(3);
3344 SDValue N4 = N->getOperand(4);
3345 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3347 // fold select_cc lhs, rhs, x, x, cc -> x
3348 if (N2 == N3)
3349 return N2;
3351 // Determine if the condition we're dealing with is constant
3352 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3353 N0, N1, CC, N->getDebugLoc(), false);
3354 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3356 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3357 if (!SCCC->isNullValue())
3358 return N2; // cond always true -> true val
3359 else
3360 return N3; // cond always false -> false val
3363 // Fold to a simpler select_cc
3364 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3365 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3366 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3367 SCC.getOperand(2));
3369 // If we can fold this based on the true/false value, do so.
3370 if (SimplifySelectOps(N, N2, N3))
3371 return SDValue(N, 0); // Don't revisit N.
3373 // fold select_cc into other things, such as min/max/abs
3374 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3377 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3378 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3379 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3380 N->getDebugLoc());
3383 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3384 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3385 // transformation. Returns true if extension are possible and the above
3386 // mentioned transformation is profitable.
3387 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3388 unsigned ExtOpc,
3389 SmallVector<SDNode*, 4> &ExtendNodes,
3390 const TargetLowering &TLI) {
3391 bool HasCopyToRegUses = false;
3392 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3393 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3394 UE = N0.getNode()->use_end();
3395 UI != UE; ++UI) {
3396 SDNode *User = *UI;
3397 if (User == N)
3398 continue;
3399 if (UI.getUse().getResNo() != N0.getResNo())
3400 continue;
3401 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3402 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3403 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3404 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3405 // Sign bits will be lost after a zext.
3406 return false;
3407 bool Add = false;
3408 for (unsigned i = 0; i != 2; ++i) {
3409 SDValue UseOp = User->getOperand(i);
3410 if (UseOp == N0)
3411 continue;
3412 if (!isa<ConstantSDNode>(UseOp))
3413 return false;
3414 Add = true;
3416 if (Add)
3417 ExtendNodes.push_back(User);
3418 continue;
3420 // If truncates aren't free and there are users we can't
3421 // extend, it isn't worthwhile.
3422 if (!isTruncFree)
3423 return false;
3424 // Remember if this value is live-out.
3425 if (User->getOpcode() == ISD::CopyToReg)
3426 HasCopyToRegUses = true;
3429 if (HasCopyToRegUses) {
3430 bool BothLiveOut = false;
3431 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3432 UI != UE; ++UI) {
3433 SDUse &Use = UI.getUse();
3434 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3435 BothLiveOut = true;
3436 break;
3439 if (BothLiveOut)
3440 // Both unextended and extended values are live out. There had better be
3441 // good a reason for the transformation.
3442 return ExtendNodes.size();
3444 return true;
3447 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3448 SDValue N0 = N->getOperand(0);
3449 EVT VT = N->getValueType(0);
3451 // fold (sext c1) -> c1
3452 if (isa<ConstantSDNode>(N0))
3453 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3455 // fold (sext (sext x)) -> (sext x)
3456 // fold (sext (aext x)) -> (sext x)
3457 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3458 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3459 N0.getOperand(0));
3461 if (N0.getOpcode() == ISD::TRUNCATE) {
3462 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3463 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3464 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3465 if (NarrowLoad.getNode()) {
3466 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3467 if (NarrowLoad.getNode() != N0.getNode()) {
3468 CombineTo(N0.getNode(), NarrowLoad);
3469 // CombineTo deleted the truncate, if needed, but not what's under it.
3470 AddToWorkList(oye);
3472 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3475 // See if the value being truncated is already sign extended. If so, just
3476 // eliminate the trunc/sext pair.
3477 SDValue Op = N0.getOperand(0);
3478 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3479 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3480 unsigned DestBits = VT.getScalarType().getSizeInBits();
3481 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3483 if (OpBits == DestBits) {
3484 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3485 // bits, it is already ready.
3486 if (NumSignBits > DestBits-MidBits)
3487 return Op;
3488 } else if (OpBits < DestBits) {
3489 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3490 // bits, just sext from i32.
3491 if (NumSignBits > OpBits-MidBits)
3492 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3493 } else {
3494 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3495 // bits, just truncate to i32.
3496 if (NumSignBits > OpBits-MidBits)
3497 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3500 // fold (sext (truncate x)) -> (sextinreg x).
3501 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3502 N0.getValueType())) {
3503 if (OpBits < DestBits)
3504 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3505 else if (OpBits > DestBits)
3506 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3507 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3508 DAG.getValueType(N0.getValueType()));
3512 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3513 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3514 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3515 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3516 bool DoXform = true;
3517 SmallVector<SDNode*, 4> SetCCs;
3518 if (!N0.hasOneUse())
3519 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3520 if (DoXform) {
3521 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3522 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
3523 LN0->getChain(),
3524 LN0->getBasePtr(), LN0->getPointerInfo(),
3525 N0.getValueType(),
3526 LN0->isVolatile(), LN0->isNonTemporal(),
3527 LN0->getAlignment());
3528 CombineTo(N, ExtLoad);
3529 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3530 N0.getValueType(), ExtLoad);
3531 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3533 // Extend SetCC uses if necessary.
3534 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3535 SDNode *SetCC = SetCCs[i];
3536 SmallVector<SDValue, 4> Ops;
3538 for (unsigned j = 0; j != 2; ++j) {
3539 SDValue SOp = SetCC->getOperand(j);
3540 if (SOp == Trunc)
3541 Ops.push_back(ExtLoad);
3542 else
3543 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3544 N->getDebugLoc(), VT, SOp));
3547 Ops.push_back(SetCC->getOperand(2));
3548 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3549 SetCC->getValueType(0),
3550 &Ops[0], Ops.size()));
3553 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3557 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3558 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3559 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3560 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3561 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3562 EVT MemVT = LN0->getMemoryVT();
3563 if ((!LegalOperations && !LN0->isVolatile()) ||
3564 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3565 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
3566 LN0->getChain(),
3567 LN0->getBasePtr(), LN0->getPointerInfo(),
3568 MemVT,
3569 LN0->isVolatile(), LN0->isNonTemporal(),
3570 LN0->getAlignment());
3571 CombineTo(N, ExtLoad);
3572 CombineTo(N0.getNode(),
3573 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3574 N0.getValueType(), ExtLoad),
3575 ExtLoad.getValue(1));
3576 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3580 if (N0.getOpcode() == ISD::SETCC) {
3581 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3582 // Only do this before legalize for now.
3583 if (VT.isVector() && !LegalOperations) {
3584 EVT N0VT = N0.getOperand(0).getValueType();
3585 // We know that the # elements of the results is the same as the
3586 // # elements of the compare (and the # elements of the compare result
3587 // for that matter). Check to see that they are the same size. If so,
3588 // we know that the element size of the sext'd result matches the
3589 // element size of the compare operands.
3590 if (VT.getSizeInBits() == N0VT.getSizeInBits())
3591 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3592 N0.getOperand(1),
3593 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3594 // If the desired elements are smaller or larger than the source
3595 // elements we can use a matching integer vector type and then
3596 // truncate/sign extend
3597 else {
3598 EVT MatchingElementType =
3599 EVT::getIntegerVT(*DAG.getContext(),
3600 N0VT.getScalarType().getSizeInBits());
3601 EVT MatchingVectorType =
3602 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3603 N0VT.getVectorNumElements());
3604 SDValue VsetCC =
3605 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3606 N0.getOperand(1),
3607 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3608 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
3612 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3613 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3614 SDValue NegOne =
3615 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3616 SDValue SCC =
3617 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3618 NegOne, DAG.getConstant(0, VT),
3619 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3620 if (SCC.getNode()) return SCC;
3621 if (!LegalOperations ||
3622 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3623 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3624 DAG.getSetCC(N->getDebugLoc(),
3625 TLI.getSetCCResultType(VT),
3626 N0.getOperand(0), N0.getOperand(1),
3627 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3628 NegOne, DAG.getConstant(0, VT));
3631 // fold (sext x) -> (zext x) if the sign bit is known zero.
3632 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3633 DAG.SignBitIsZero(N0))
3634 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3636 return SDValue();
3639 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3640 SDValue N0 = N->getOperand(0);
3641 EVT VT = N->getValueType(0);
3643 // fold (zext c1) -> c1
3644 if (isa<ConstantSDNode>(N0))
3645 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3646 // fold (zext (zext x)) -> (zext x)
3647 // fold (zext (aext x)) -> (zext x)
3648 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3649 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3650 N0.getOperand(0));
3652 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3653 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3654 if (N0.getOpcode() == ISD::TRUNCATE) {
3655 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3656 if (NarrowLoad.getNode()) {
3657 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3658 if (NarrowLoad.getNode() != N0.getNode()) {
3659 CombineTo(N0.getNode(), NarrowLoad);
3660 // CombineTo deleted the truncate, if needed, but not what's under it.
3661 AddToWorkList(oye);
3663 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3667 // fold (zext (truncate x)) -> (and x, mask)
3668 if (N0.getOpcode() == ISD::TRUNCATE &&
3669 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3671 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3672 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
3673 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3674 if (NarrowLoad.getNode()) {
3675 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3676 if (NarrowLoad.getNode() != N0.getNode()) {
3677 CombineTo(N0.getNode(), NarrowLoad);
3678 // CombineTo deleted the truncate, if needed, but not what's under it.
3679 AddToWorkList(oye);
3681 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3684 SDValue Op = N0.getOperand(0);
3685 if (Op.getValueType().bitsLT(VT)) {
3686 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3687 } else if (Op.getValueType().bitsGT(VT)) {
3688 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3690 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3691 N0.getValueType().getScalarType());
3694 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3695 // if either of the casts is not free.
3696 if (N0.getOpcode() == ISD::AND &&
3697 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3698 N0.getOperand(1).getOpcode() == ISD::Constant &&
3699 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3700 N0.getValueType()) ||
3701 !TLI.isZExtFree(N0.getValueType(), VT))) {
3702 SDValue X = N0.getOperand(0).getOperand(0);
3703 if (X.getValueType().bitsLT(VT)) {
3704 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3705 } else if (X.getValueType().bitsGT(VT)) {
3706 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3708 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3709 Mask.zext(VT.getSizeInBits());
3710 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3711 X, DAG.getConstant(Mask, VT));
3714 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3715 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3716 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3717 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3718 bool DoXform = true;
3719 SmallVector<SDNode*, 4> SetCCs;
3720 if (!N0.hasOneUse())
3721 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3722 if (DoXform) {
3723 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3724 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N->getDebugLoc(),
3725 LN0->getChain(),
3726 LN0->getBasePtr(), LN0->getPointerInfo(),
3727 N0.getValueType(),
3728 LN0->isVolatile(), LN0->isNonTemporal(),
3729 LN0->getAlignment());
3730 CombineTo(N, ExtLoad);
3731 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3732 N0.getValueType(), ExtLoad);
3733 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3735 // Extend SetCC uses if necessary.
3736 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3737 SDNode *SetCC = SetCCs[i];
3738 SmallVector<SDValue, 4> Ops;
3740 for (unsigned j = 0; j != 2; ++j) {
3741 SDValue SOp = SetCC->getOperand(j);
3742 if (SOp == Trunc)
3743 Ops.push_back(ExtLoad);
3744 else
3745 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3746 N->getDebugLoc(), VT, SOp));
3749 Ops.push_back(SetCC->getOperand(2));
3750 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3751 SetCC->getValueType(0),
3752 &Ops[0], Ops.size()));
3755 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3759 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3760 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3761 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3762 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3763 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3764 EVT MemVT = LN0->getMemoryVT();
3765 if ((!LegalOperations && !LN0->isVolatile()) ||
3766 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3767 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N->getDebugLoc(),
3768 LN0->getChain(),
3769 LN0->getBasePtr(), LN0->getPointerInfo(),
3770 MemVT,
3771 LN0->isVolatile(), LN0->isNonTemporal(),
3772 LN0->getAlignment());
3773 CombineTo(N, ExtLoad);
3774 CombineTo(N0.getNode(),
3775 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3776 ExtLoad),
3777 ExtLoad.getValue(1));
3778 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3782 if (N0.getOpcode() == ISD::SETCC) {
3783 if (!LegalOperations && VT.isVector()) {
3784 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
3785 // Only do this before legalize for now.
3786 EVT N0VT = N0.getOperand(0).getValueType();
3787 EVT EltVT = VT.getVectorElementType();
3788 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
3789 DAG.getConstant(1, EltVT));
3790 if (VT.getSizeInBits() == N0VT.getSizeInBits()) {
3791 // We know that the # elements of the results is the same as the
3792 // # elements of the compare (and the # elements of the compare result
3793 // for that matter). Check to see that they are the same size. If so,
3794 // we know that the element size of the sext'd result matches the
3795 // element size of the compare operands.
3796 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3797 DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3798 N0.getOperand(1),
3799 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3800 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
3801 &OneOps[0], OneOps.size()));
3802 } else {
3803 // If the desired elements are smaller or larger than the source
3804 // elements we can use a matching integer vector type and then
3805 // truncate/sign extend
3806 EVT MatchingElementType =
3807 EVT::getIntegerVT(*DAG.getContext(),
3808 N0VT.getScalarType().getSizeInBits());
3809 EVT MatchingVectorType =
3810 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3811 N0VT.getVectorNumElements());
3812 SDValue VsetCC =
3813 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3814 N0.getOperand(1),
3815 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3816 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3817 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
3818 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
3819 &OneOps[0], OneOps.size()));
3823 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3824 SDValue SCC =
3825 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3826 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3827 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3828 if (SCC.getNode()) return SCC;
3831 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3832 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3833 isa<ConstantSDNode>(N0.getOperand(1)) &&
3834 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
3835 N0.hasOneUse()) {
3836 if (N0.getOpcode() == ISD::SHL) {
3837 // If the original shl may be shifting out bits, do not perform this
3838 // transformation.
3839 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3840 unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
3841 N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
3842 if (ShAmt > KnownZeroBits)
3843 return SDValue();
3845 DebugLoc dl = N->getDebugLoc();
3846 return DAG.getNode(N0.getOpcode(), dl, VT,
3847 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
3848 DAG.getNode(ISD::ZERO_EXTEND, dl,
3849 N0.getOperand(1).getValueType(),
3850 N0.getOperand(1)));
3853 return SDValue();
3856 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3857 SDValue N0 = N->getOperand(0);
3858 EVT VT = N->getValueType(0);
3860 // fold (aext c1) -> c1
3861 if (isa<ConstantSDNode>(N0))
3862 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3863 // fold (aext (aext x)) -> (aext x)
3864 // fold (aext (zext x)) -> (zext x)
3865 // fold (aext (sext x)) -> (sext x)
3866 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3867 N0.getOpcode() == ISD::ZERO_EXTEND ||
3868 N0.getOpcode() == ISD::SIGN_EXTEND)
3869 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3871 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3872 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3873 if (N0.getOpcode() == ISD::TRUNCATE) {
3874 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3875 if (NarrowLoad.getNode()) {
3876 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3877 if (NarrowLoad.getNode() != N0.getNode()) {
3878 CombineTo(N0.getNode(), NarrowLoad);
3879 // CombineTo deleted the truncate, if needed, but not what's under it.
3880 AddToWorkList(oye);
3882 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3886 // fold (aext (truncate x))
3887 if (N0.getOpcode() == ISD::TRUNCATE) {
3888 SDValue TruncOp = N0.getOperand(0);
3889 if (TruncOp.getValueType() == VT)
3890 return TruncOp; // x iff x size == zext size.
3891 if (TruncOp.getValueType().bitsGT(VT))
3892 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3893 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3896 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3897 // if the trunc is not free.
3898 if (N0.getOpcode() == ISD::AND &&
3899 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3900 N0.getOperand(1).getOpcode() == ISD::Constant &&
3901 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3902 N0.getValueType())) {
3903 SDValue X = N0.getOperand(0).getOperand(0);
3904 if (X.getValueType().bitsLT(VT)) {
3905 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3906 } else if (X.getValueType().bitsGT(VT)) {
3907 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3909 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3910 Mask.zext(VT.getSizeInBits());
3911 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3912 X, DAG.getConstant(Mask, VT));
3915 // fold (aext (load x)) -> (aext (truncate (extload x)))
3916 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3917 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3918 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3919 bool DoXform = true;
3920 SmallVector<SDNode*, 4> SetCCs;
3921 if (!N0.hasOneUse())
3922 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3923 if (DoXform) {
3924 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3925 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
3926 LN0->getChain(),
3927 LN0->getBasePtr(), LN0->getPointerInfo(),
3928 N0.getValueType(),
3929 LN0->isVolatile(), LN0->isNonTemporal(),
3930 LN0->getAlignment());
3931 CombineTo(N, ExtLoad);
3932 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3933 N0.getValueType(), ExtLoad);
3934 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3936 // Extend SetCC uses if necessary.
3937 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3938 SDNode *SetCC = SetCCs[i];
3939 SmallVector<SDValue, 4> Ops;
3941 for (unsigned j = 0; j != 2; ++j) {
3942 SDValue SOp = SetCC->getOperand(j);
3943 if (SOp == Trunc)
3944 Ops.push_back(ExtLoad);
3945 else
3946 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3947 N->getDebugLoc(), VT, SOp));
3950 Ops.push_back(SetCC->getOperand(2));
3951 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3952 SetCC->getValueType(0),
3953 &Ops[0], Ops.size()));
3956 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3960 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3961 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3962 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3963 if (N0.getOpcode() == ISD::LOAD &&
3964 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3965 N0.hasOneUse()) {
3966 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3967 EVT MemVT = LN0->getMemoryVT();
3968 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3969 N->getDebugLoc(),
3970 LN0->getChain(), LN0->getBasePtr(),
3971 LN0->getPointerInfo(), MemVT,
3972 LN0->isVolatile(), LN0->isNonTemporal(),
3973 LN0->getAlignment());
3974 CombineTo(N, ExtLoad);
3975 CombineTo(N0.getNode(),
3976 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3977 N0.getValueType(), ExtLoad),
3978 ExtLoad.getValue(1));
3979 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3982 if (N0.getOpcode() == ISD::SETCC) {
3983 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
3984 // Only do this before legalize for now.
3985 if (VT.isVector() && !LegalOperations) {
3986 EVT N0VT = N0.getOperand(0).getValueType();
3987 // We know that the # elements of the results is the same as the
3988 // # elements of the compare (and the # elements of the compare result
3989 // for that matter). Check to see that they are the same size. If so,
3990 // we know that the element size of the sext'd result matches the
3991 // element size of the compare operands.
3992 if (VT.getSizeInBits() == N0VT.getSizeInBits())
3993 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3994 N0.getOperand(1),
3995 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3996 // If the desired elements are smaller or larger than the source
3997 // elements we can use a matching integer vector type and then
3998 // truncate/sign extend
3999 else {
4000 EVT MatchingElementType =
4001 EVT::getIntegerVT(*DAG.getContext(),
4002 N0VT.getScalarType().getSizeInBits());
4003 EVT MatchingVectorType =
4004 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4005 N0VT.getVectorNumElements());
4006 SDValue VsetCC =
4007 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4008 N0.getOperand(1),
4009 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4010 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4014 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4015 SDValue SCC =
4016 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4017 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4018 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4019 if (SCC.getNode())
4020 return SCC;
4023 return SDValue();
4026 /// GetDemandedBits - See if the specified operand can be simplified with the
4027 /// knowledge that only the bits specified by Mask are used. If so, return the
4028 /// simpler operand, otherwise return a null SDValue.
4029 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4030 switch (V.getOpcode()) {
4031 default: break;
4032 case ISD::OR:
4033 case ISD::XOR:
4034 // If the LHS or RHS don't contribute bits to the or, drop them.
4035 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4036 return V.getOperand(1);
4037 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4038 return V.getOperand(0);
4039 break;
4040 case ISD::SRL:
4041 // Only look at single-use SRLs.
4042 if (!V.getNode()->hasOneUse())
4043 break;
4044 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4045 // See if we can recursively simplify the LHS.
4046 unsigned Amt = RHSC->getZExtValue();
4048 // Watch out for shift count overflow though.
4049 if (Amt >= Mask.getBitWidth()) break;
4050 APInt NewMask = Mask << Amt;
4051 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4052 if (SimplifyLHS.getNode())
4053 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4054 SimplifyLHS, V.getOperand(1));
4057 return SDValue();
4060 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4061 /// bits and then truncated to a narrower type and where N is a multiple
4062 /// of number of bits of the narrower type, transform it to a narrower load
4063 /// from address + N / num of bits of new type. If the result is to be
4064 /// extended, also fold the extension to form a extending load.
4065 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4066 unsigned Opc = N->getOpcode();
4068 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4069 SDValue N0 = N->getOperand(0);
4070 EVT VT = N->getValueType(0);
4071 EVT ExtVT = VT;
4073 // This transformation isn't valid for vector loads.
4074 if (VT.isVector())
4075 return SDValue();
4077 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4078 // extended to VT.
4079 if (Opc == ISD::SIGN_EXTEND_INREG) {
4080 ExtType = ISD::SEXTLOAD;
4081 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4082 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
4083 return SDValue();
4084 } else if (Opc == ISD::SRL) {
4085 // Annother special-case: SRL is basically zero-extending a narrower
4086 // value.
4087 ExtType = ISD::ZEXTLOAD;
4088 N0 = SDValue(N, 0);
4089 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4090 if (!N01) return SDValue();
4091 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4092 VT.getSizeInBits() - N01->getZExtValue());
4095 unsigned EVTBits = ExtVT.getSizeInBits();
4096 unsigned ShAmt = 0;
4097 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
4098 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4099 ShAmt = N01->getZExtValue();
4100 // Is the shift amount a multiple of size of VT?
4101 if ((ShAmt & (EVTBits-1)) == 0) {
4102 N0 = N0.getOperand(0);
4103 // Is the load width a multiple of size of VT?
4104 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4105 return SDValue();
4108 // If the shift amount is larger than the input type then we're not
4109 // accessing any of the loaded bytes. If the load was a zextload/extload
4110 // then the result of the shift+trunc is zero/undef (handled elsewhere).
4111 // If the load was a sextload then the result is a splat of the sign bit
4112 // of the extended byte. This is not worth optimizing for.
4113 if (ShAmt >= VT.getSizeInBits())
4114 return SDValue();
4119 // If the load is shifted left (and the result isn't shifted back right),
4120 // we can fold the truncate through the shift.
4121 unsigned ShLeftAmt = 0;
4122 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4123 TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4124 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4125 ShLeftAmt = N01->getZExtValue();
4126 N0 = N0.getOperand(0);
4130 // Do not generate loads of non-round integer types since these can
4131 // be expensive (and would be wrong if the type is not byte sized).
4132 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
4133 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() >= EVTBits &&
4134 // Do not change the width of a volatile load.
4135 !cast<LoadSDNode>(N0)->isVolatile()) {
4136 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4137 EVT PtrType = N0.getOperand(1).getValueType();
4139 // For big endian targets, we need to adjust the offset to the pointer to
4140 // load the correct bytes.
4141 if (TLI.isBigEndian()) {
4142 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4143 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4144 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4147 uint64_t PtrOff = ShAmt / 8;
4148 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4149 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4150 PtrType, LN0->getBasePtr(),
4151 DAG.getConstant(PtrOff, PtrType));
4152 AddToWorkList(NewPtr.getNode());
4154 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
4155 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4156 LN0->getPointerInfo().getWithOffset(PtrOff),
4157 LN0->isVolatile(), LN0->isNonTemporal(), NewAlign)
4158 : DAG.getExtLoad(ExtType, VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4159 LN0->getPointerInfo().getWithOffset(PtrOff),
4160 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4161 NewAlign);
4163 // Replace the old load's chain with the new load's chain.
4164 WorkListRemover DeadNodes(*this);
4165 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4166 &DeadNodes);
4168 // Shift the result left, if we've swallowed a left shift.
4169 SDValue Result = Load;
4170 if (ShLeftAmt != 0) {
4171 EVT ShImmTy = getShiftAmountTy();
4172 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4173 ShImmTy = VT;
4174 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4175 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4178 // Return the new loaded value.
4179 return Result;
4182 return SDValue();
4185 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4186 SDValue N0 = N->getOperand(0);
4187 SDValue N1 = N->getOperand(1);
4188 EVT VT = N->getValueType(0);
4189 EVT EVT = cast<VTSDNode>(N1)->getVT();
4190 unsigned VTBits = VT.getScalarType().getSizeInBits();
4191 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4193 // fold (sext_in_reg c1) -> c1
4194 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4195 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4197 // If the input is already sign extended, just drop the extension.
4198 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4199 return N0;
4201 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4202 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4203 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4204 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4205 N0.getOperand(0), N1);
4208 // fold (sext_in_reg (sext x)) -> (sext x)
4209 // fold (sext_in_reg (aext x)) -> (sext x)
4210 // if x is small enough.
4211 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4212 SDValue N00 = N0.getOperand(0);
4213 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4214 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4215 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4218 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4219 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4220 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4222 // fold operands of sext_in_reg based on knowledge that the top bits are not
4223 // demanded.
4224 if (SimplifyDemandedBits(SDValue(N, 0)))
4225 return SDValue(N, 0);
4227 // fold (sext_in_reg (load x)) -> (smaller sextload x)
4228 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4229 SDValue NarrowLoad = ReduceLoadWidth(N);
4230 if (NarrowLoad.getNode())
4231 return NarrowLoad;
4233 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4234 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4235 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4236 if (N0.getOpcode() == ISD::SRL) {
4237 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4238 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4239 // We can turn this into an SRA iff the input to the SRL is already sign
4240 // extended enough.
4241 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4242 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4243 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4244 N0.getOperand(0), N0.getOperand(1));
4248 // fold (sext_inreg (extload x)) -> (sextload x)
4249 if (ISD::isEXTLoad(N0.getNode()) &&
4250 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4251 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4252 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4253 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4254 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4255 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4256 LN0->getChain(),
4257 LN0->getBasePtr(), LN0->getPointerInfo(),
4258 EVT,
4259 LN0->isVolatile(), LN0->isNonTemporal(),
4260 LN0->getAlignment());
4261 CombineTo(N, ExtLoad);
4262 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4263 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4265 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4266 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4267 N0.hasOneUse() &&
4268 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4269 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4270 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4271 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4272 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4273 LN0->getChain(),
4274 LN0->getBasePtr(), LN0->getPointerInfo(),
4275 EVT,
4276 LN0->isVolatile(), LN0->isNonTemporal(),
4277 LN0->getAlignment());
4278 CombineTo(N, ExtLoad);
4279 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4280 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4282 return SDValue();
4285 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4286 SDValue N0 = N->getOperand(0);
4287 EVT VT = N->getValueType(0);
4289 // noop truncate
4290 if (N0.getValueType() == N->getValueType(0))
4291 return N0;
4292 // fold (truncate c1) -> c1
4293 if (isa<ConstantSDNode>(N0))
4294 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4295 // fold (truncate (truncate x)) -> (truncate x)
4296 if (N0.getOpcode() == ISD::TRUNCATE)
4297 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4298 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4299 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4300 N0.getOpcode() == ISD::SIGN_EXTEND ||
4301 N0.getOpcode() == ISD::ANY_EXTEND) {
4302 if (N0.getOperand(0).getValueType().bitsLT(VT))
4303 // if the source is smaller than the dest, we still need an extend
4304 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4305 N0.getOperand(0));
4306 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4307 // if the source is larger than the dest, than we just need the truncate
4308 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4309 else
4310 // if the source and dest are the same type, we can drop both the extend
4311 // and the truncate.
4312 return N0.getOperand(0);
4315 // See if we can simplify the input to this truncate through knowledge that
4316 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
4317 // -> trunc y
4318 SDValue Shorter =
4319 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4320 VT.getSizeInBits()));
4321 if (Shorter.getNode())
4322 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4324 // fold (truncate (load x)) -> (smaller load x)
4325 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4326 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4327 SDValue Reduced = ReduceLoadWidth(N);
4328 if (Reduced.getNode())
4329 return Reduced;
4332 // Simplify the operands using demanded-bits information.
4333 if (!VT.isVector() &&
4334 SimplifyDemandedBits(SDValue(N, 0)))
4335 return SDValue(N, 0);
4337 return SDValue();
4340 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4341 SDValue Elt = N->getOperand(i);
4342 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4343 return Elt.getNode();
4344 return Elt.getOperand(Elt.getResNo()).getNode();
4347 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4348 /// if load locations are consecutive.
4349 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4350 assert(N->getOpcode() == ISD::BUILD_PAIR);
4352 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4353 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4354 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4355 LD1->getPointerInfo().getAddrSpace() !=
4356 LD2->getPointerInfo().getAddrSpace())
4357 return SDValue();
4358 EVT LD1VT = LD1->getValueType(0);
4360 if (ISD::isNON_EXTLoad(LD2) &&
4361 LD2->hasOneUse() &&
4362 // If both are volatile this would reduce the number of volatile loads.
4363 // If one is volatile it might be ok, but play conservative and bail out.
4364 !LD1->isVolatile() &&
4365 !LD2->isVolatile() &&
4366 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4367 unsigned Align = LD1->getAlignment();
4368 unsigned NewAlign = TLI.getTargetData()->
4369 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4371 if (NewAlign <= Align &&
4372 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4373 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4374 LD1->getBasePtr(), LD1->getPointerInfo(),
4375 false, false, Align);
4378 return SDValue();
4381 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
4382 SDValue N0 = N->getOperand(0);
4383 EVT VT = N->getValueType(0);
4385 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4386 // Only do this before legalize, since afterward the target may be depending
4387 // on the bitconvert.
4388 // First check to see if this is all constant.
4389 if (!LegalTypes &&
4390 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4391 VT.isVector()) {
4392 bool isSimple = true;
4393 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4394 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4395 N0.getOperand(i).getOpcode() != ISD::Constant &&
4396 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4397 isSimple = false;
4398 break;
4401 EVT DestEltVT = N->getValueType(0).getVectorElementType();
4402 assert(!DestEltVT.isVector() &&
4403 "Element type of vector ValueType must not be vector!");
4404 if (isSimple)
4405 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4408 // If the input is a constant, let getNode fold it.
4409 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4410 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
4411 if (Res.getNode() != N) {
4412 if (!LegalOperations ||
4413 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4414 return Res;
4416 // Folding it resulted in an illegal node, and it's too late to
4417 // do that. Clean up the old node and forego the transformation.
4418 // Ideally this won't happen very often, because instcombine
4419 // and the earlier dagcombine runs (where illegal nodes are
4420 // permitted) should have folded most of them already.
4421 DAG.DeleteNode(Res.getNode());
4425 // (conv (conv x, t1), t2) -> (conv x, t2)
4426 if (N0.getOpcode() == ISD::BIT_CONVERT)
4427 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
4428 N0.getOperand(0));
4430 // fold (conv (load x)) -> (load (conv*)x)
4431 // If the resultant load doesn't need a higher alignment than the original!
4432 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4433 // Do not change the width of a volatile load.
4434 !cast<LoadSDNode>(N0)->isVolatile() &&
4435 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4436 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4437 unsigned Align = TLI.getTargetData()->
4438 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4439 unsigned OrigAlign = LN0->getAlignment();
4441 if (Align <= OrigAlign) {
4442 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4443 LN0->getBasePtr(), LN0->getPointerInfo(),
4444 LN0->isVolatile(), LN0->isNonTemporal(),
4445 OrigAlign);
4446 AddToWorkList(N);
4447 CombineTo(N0.getNode(),
4448 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4449 N0.getValueType(), Load),
4450 Load.getValue(1));
4451 return Load;
4455 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4456 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4457 // This often reduces constant pool loads.
4458 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4459 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4460 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
4461 N0.getOperand(0));
4462 AddToWorkList(NewConv.getNode());
4464 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4465 if (N0.getOpcode() == ISD::FNEG)
4466 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4467 NewConv, DAG.getConstant(SignBit, VT));
4468 assert(N0.getOpcode() == ISD::FABS);
4469 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4470 NewConv, DAG.getConstant(~SignBit, VT));
4473 // fold (bitconvert (fcopysign cst, x)) ->
4474 // (or (and (bitconvert x), sign), (and cst, (not sign)))
4475 // Note that we don't handle (copysign x, cst) because this can always be
4476 // folded to an fneg or fabs.
4477 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4478 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4479 VT.isInteger() && !VT.isVector()) {
4480 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4481 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4482 if (isTypeLegal(IntXVT)) {
4483 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4484 IntXVT, N0.getOperand(1));
4485 AddToWorkList(X.getNode());
4487 // If X has a different width than the result/lhs, sext it or truncate it.
4488 unsigned VTWidth = VT.getSizeInBits();
4489 if (OrigXWidth < VTWidth) {
4490 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4491 AddToWorkList(X.getNode());
4492 } else if (OrigXWidth > VTWidth) {
4493 // To get the sign bit in the right place, we have to shift it right
4494 // before truncating.
4495 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4496 X.getValueType(), X,
4497 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4498 AddToWorkList(X.getNode());
4499 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4500 AddToWorkList(X.getNode());
4503 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4504 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4505 X, DAG.getConstant(SignBit, VT));
4506 AddToWorkList(X.getNode());
4508 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4509 VT, N0.getOperand(0));
4510 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4511 Cst, DAG.getConstant(~SignBit, VT));
4512 AddToWorkList(Cst.getNode());
4514 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4518 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4519 if (N0.getOpcode() == ISD::BUILD_PAIR) {
4520 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4521 if (CombineLD.getNode())
4522 return CombineLD;
4525 return SDValue();
4528 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4529 EVT VT = N->getValueType(0);
4530 return CombineConsecutiveLoads(N, VT);
4533 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
4534 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
4535 /// destination element value type.
4536 SDValue DAGCombiner::
4537 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4538 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4540 // If this is already the right type, we're done.
4541 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4543 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4544 unsigned DstBitSize = DstEltVT.getSizeInBits();
4546 // If this is a conversion of N elements of one type to N elements of another
4547 // type, convert each element. This handles FP<->INT cases.
4548 if (SrcBitSize == DstBitSize) {
4549 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4550 BV->getValueType(0).getVectorNumElements());
4552 // Due to the FP element handling below calling this routine recursively,
4553 // we can end up with a scalar-to-vector node here.
4554 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
4555 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4556 DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4557 DstEltVT, BV->getOperand(0)));
4559 SmallVector<SDValue, 8> Ops;
4560 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4561 SDValue Op = BV->getOperand(i);
4562 // If the vector element type is not legal, the BUILD_VECTOR operands
4563 // are promoted and implicitly truncated. Make that explicit here.
4564 if (Op.getValueType() != SrcEltVT)
4565 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4566 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4567 DstEltVT, Op));
4568 AddToWorkList(Ops.back().getNode());
4570 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4571 &Ops[0], Ops.size());
4574 // Otherwise, we're growing or shrinking the elements. To avoid having to
4575 // handle annoying details of growing/shrinking FP values, we convert them to
4576 // int first.
4577 if (SrcEltVT.isFloatingPoint()) {
4578 // Convert the input float vector to a int vector where the elements are the
4579 // same sizes.
4580 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4581 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4582 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
4583 SrcEltVT = IntVT;
4586 // Now we know the input is an integer vector. If the output is a FP type,
4587 // convert to integer first, then to FP of the right size.
4588 if (DstEltVT.isFloatingPoint()) {
4589 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4590 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4591 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
4593 // Next, convert to FP elements of the same size.
4594 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
4597 // Okay, we know the src/dst types are both integers of differing types.
4598 // Handling growing first.
4599 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4600 if (SrcBitSize < DstBitSize) {
4601 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4603 SmallVector<SDValue, 8> Ops;
4604 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4605 i += NumInputsPerOutput) {
4606 bool isLE = TLI.isLittleEndian();
4607 APInt NewBits = APInt(DstBitSize, 0);
4608 bool EltIsUndef = true;
4609 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4610 // Shift the previously computed bits over.
4611 NewBits <<= SrcBitSize;
4612 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4613 if (Op.getOpcode() == ISD::UNDEF) continue;
4614 EltIsUndef = false;
4616 NewBits |= APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
4617 zextOrTrunc(SrcBitSize).zext(DstBitSize);
4620 if (EltIsUndef)
4621 Ops.push_back(DAG.getUNDEF(DstEltVT));
4622 else
4623 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4626 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4627 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4628 &Ops[0], Ops.size());
4631 // Finally, this must be the case where we are shrinking elements: each input
4632 // turns into multiple outputs.
4633 bool isS2V = ISD::isScalarToVector(BV);
4634 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4635 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4636 NumOutputsPerInput*BV->getNumOperands());
4637 SmallVector<SDValue, 8> Ops;
4639 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4640 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4641 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4642 Ops.push_back(DAG.getUNDEF(DstEltVT));
4643 continue;
4646 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
4647 getAPIntValue()).zextOrTrunc(SrcBitSize);
4649 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4650 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
4651 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4652 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
4653 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4654 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4655 Ops[0]);
4656 OpVal = OpVal.lshr(DstBitSize);
4659 // For big endian targets, swap the order of the pieces of each element.
4660 if (TLI.isBigEndian())
4661 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4664 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4665 &Ops[0], Ops.size());
4668 SDValue DAGCombiner::visitFADD(SDNode *N) {
4669 SDValue N0 = N->getOperand(0);
4670 SDValue N1 = N->getOperand(1);
4671 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4672 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4673 EVT VT = N->getValueType(0);
4675 // fold vector ops
4676 if (VT.isVector()) {
4677 SDValue FoldedVOp = SimplifyVBinOp(N);
4678 if (FoldedVOp.getNode()) return FoldedVOp;
4681 // fold (fadd c1, c2) -> (fadd c1, c2)
4682 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4683 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4684 // canonicalize constant to RHS
4685 if (N0CFP && !N1CFP)
4686 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4687 // fold (fadd A, 0) -> A
4688 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4689 return N0;
4690 // fold (fadd A, (fneg B)) -> (fsub A, B)
4691 if (isNegatibleForFree(N1, LegalOperations) == 2)
4692 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4693 GetNegatedExpression(N1, DAG, LegalOperations));
4694 // fold (fadd (fneg A), B) -> (fsub B, A)
4695 if (isNegatibleForFree(N0, LegalOperations) == 2)
4696 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4697 GetNegatedExpression(N0, DAG, LegalOperations));
4699 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4700 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4701 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4702 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4703 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4704 N0.getOperand(1), N1));
4706 return SDValue();
4709 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4710 SDValue N0 = N->getOperand(0);
4711 SDValue N1 = N->getOperand(1);
4712 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4713 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4714 EVT VT = N->getValueType(0);
4716 // fold vector ops
4717 if (VT.isVector()) {
4718 SDValue FoldedVOp = SimplifyVBinOp(N);
4719 if (FoldedVOp.getNode()) return FoldedVOp;
4722 // fold (fsub c1, c2) -> c1-c2
4723 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4724 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4725 // fold (fsub A, 0) -> A
4726 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4727 return N0;
4728 // fold (fsub 0, B) -> -B
4729 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4730 if (isNegatibleForFree(N1, LegalOperations))
4731 return GetNegatedExpression(N1, DAG, LegalOperations);
4732 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4733 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4735 // fold (fsub A, (fneg B)) -> (fadd A, B)
4736 if (isNegatibleForFree(N1, LegalOperations))
4737 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4738 GetNegatedExpression(N1, DAG, LegalOperations));
4740 return SDValue();
4743 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4744 SDValue N0 = N->getOperand(0);
4745 SDValue N1 = N->getOperand(1);
4746 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4747 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4748 EVT VT = N->getValueType(0);
4750 // fold vector ops
4751 if (VT.isVector()) {
4752 SDValue FoldedVOp = SimplifyVBinOp(N);
4753 if (FoldedVOp.getNode()) return FoldedVOp;
4756 // fold (fmul c1, c2) -> c1*c2
4757 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4758 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4759 // canonicalize constant to RHS
4760 if (N0CFP && !N1CFP)
4761 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4762 // fold (fmul A, 0) -> 0
4763 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4764 return N1;
4765 // fold (fmul A, 0) -> 0, vector edition.
4766 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4767 return N1;
4768 // fold (fmul X, 2.0) -> (fadd X, X)
4769 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4770 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4771 // fold (fmul X, -1.0) -> (fneg X)
4772 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4773 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4774 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4776 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4777 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4778 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4779 // Both can be negated for free, check to see if at least one is cheaper
4780 // negated.
4781 if (LHSNeg == 2 || RHSNeg == 2)
4782 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4783 GetNegatedExpression(N0, DAG, LegalOperations),
4784 GetNegatedExpression(N1, DAG, LegalOperations));
4788 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4789 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4790 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4791 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4792 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4793 N0.getOperand(1), N1));
4795 return SDValue();
4798 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4799 SDValue N0 = N->getOperand(0);
4800 SDValue N1 = N->getOperand(1);
4801 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4802 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4803 EVT VT = N->getValueType(0);
4805 // fold vector ops
4806 if (VT.isVector()) {
4807 SDValue FoldedVOp = SimplifyVBinOp(N);
4808 if (FoldedVOp.getNode()) return FoldedVOp;
4811 // fold (fdiv c1, c2) -> c1/c2
4812 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4813 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4816 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4817 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4818 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4819 // Both can be negated for free, check to see if at least one is cheaper
4820 // negated.
4821 if (LHSNeg == 2 || RHSNeg == 2)
4822 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4823 GetNegatedExpression(N0, DAG, LegalOperations),
4824 GetNegatedExpression(N1, DAG, LegalOperations));
4828 return SDValue();
4831 SDValue DAGCombiner::visitFREM(SDNode *N) {
4832 SDValue N0 = N->getOperand(0);
4833 SDValue N1 = N->getOperand(1);
4834 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4835 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4836 EVT VT = N->getValueType(0);
4838 // fold (frem c1, c2) -> fmod(c1,c2)
4839 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4840 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4842 return SDValue();
4845 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4846 SDValue N0 = N->getOperand(0);
4847 SDValue N1 = N->getOperand(1);
4848 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4849 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4850 EVT VT = N->getValueType(0);
4852 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
4853 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4855 if (N1CFP) {
4856 const APFloat& V = N1CFP->getValueAPF();
4857 // copysign(x, c1) -> fabs(x) iff ispos(c1)
4858 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4859 if (!V.isNegative()) {
4860 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4861 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4862 } else {
4863 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4864 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4865 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4869 // copysign(fabs(x), y) -> copysign(x, y)
4870 // copysign(fneg(x), y) -> copysign(x, y)
4871 // copysign(copysign(x,z), y) -> copysign(x, y)
4872 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4873 N0.getOpcode() == ISD::FCOPYSIGN)
4874 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4875 N0.getOperand(0), N1);
4877 // copysign(x, abs(y)) -> abs(x)
4878 if (N1.getOpcode() == ISD::FABS)
4879 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4881 // copysign(x, copysign(y,z)) -> copysign(x, z)
4882 if (N1.getOpcode() == ISD::FCOPYSIGN)
4883 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4884 N0, N1.getOperand(1));
4886 // copysign(x, fp_extend(y)) -> copysign(x, y)
4887 // copysign(x, fp_round(y)) -> copysign(x, y)
4888 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4889 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4890 N0, N1.getOperand(0));
4892 return SDValue();
4895 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4896 SDValue N0 = N->getOperand(0);
4897 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4898 EVT VT = N->getValueType(0);
4899 EVT OpVT = N0.getValueType();
4901 // fold (sint_to_fp c1) -> c1fp
4902 if (N0C && OpVT != MVT::ppcf128)
4903 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4905 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4906 // but UINT_TO_FP is legal on this target, try to convert.
4907 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4908 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4909 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4910 if (DAG.SignBitIsZero(N0))
4911 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4914 return SDValue();
4917 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4918 SDValue N0 = N->getOperand(0);
4919 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4920 EVT VT = N->getValueType(0);
4921 EVT OpVT = N0.getValueType();
4923 // fold (uint_to_fp c1) -> c1fp
4924 if (N0C && OpVT != MVT::ppcf128)
4925 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4927 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4928 // but SINT_TO_FP is legal on this target, try to convert.
4929 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4930 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4931 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4932 if (DAG.SignBitIsZero(N0))
4933 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4936 return SDValue();
4939 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4940 SDValue N0 = N->getOperand(0);
4941 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4942 EVT VT = N->getValueType(0);
4944 // fold (fp_to_sint c1fp) -> c1
4945 if (N0CFP)
4946 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4948 return SDValue();
4951 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4952 SDValue N0 = N->getOperand(0);
4953 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4954 EVT VT = N->getValueType(0);
4956 // fold (fp_to_uint c1fp) -> c1
4957 if (N0CFP && VT != MVT::ppcf128)
4958 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4960 return SDValue();
4963 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4964 SDValue N0 = N->getOperand(0);
4965 SDValue N1 = N->getOperand(1);
4966 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4967 EVT VT = N->getValueType(0);
4969 // fold (fp_round c1fp) -> c1fp
4970 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4971 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4973 // fold (fp_round (fp_extend x)) -> x
4974 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4975 return N0.getOperand(0);
4977 // fold (fp_round (fp_round x)) -> (fp_round x)
4978 if (N0.getOpcode() == ISD::FP_ROUND) {
4979 // This is a value preserving truncation if both round's are.
4980 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4981 N0.getNode()->getConstantOperandVal(1) == 1;
4982 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4983 DAG.getIntPtrConstant(IsTrunc));
4986 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4987 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4988 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4989 N0.getOperand(0), N1);
4990 AddToWorkList(Tmp.getNode());
4991 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4992 Tmp, N0.getOperand(1));
4995 return SDValue();
4998 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4999 SDValue N0 = N->getOperand(0);
5000 EVT VT = N->getValueType(0);
5001 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5002 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5004 // fold (fp_round_inreg c1fp) -> c1fp
5005 if (N0CFP && isTypeLegal(EVT)) {
5006 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5007 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5010 return SDValue();
5013 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5014 SDValue N0 = N->getOperand(0);
5015 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5016 EVT VT = N->getValueType(0);
5018 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5019 if (N->hasOneUse() &&
5020 N->use_begin()->getOpcode() == ISD::FP_ROUND)
5021 return SDValue();
5023 // fold (fp_extend c1fp) -> c1fp
5024 if (N0CFP && VT != MVT::ppcf128)
5025 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5027 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5028 // value of X.
5029 if (N0.getOpcode() == ISD::FP_ROUND
5030 && N0.getNode()->getConstantOperandVal(1) == 1) {
5031 SDValue In = N0.getOperand(0);
5032 if (In.getValueType() == VT) return In;
5033 if (VT.bitsLT(In.getValueType()))
5034 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5035 In, N0.getOperand(1));
5036 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5039 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5040 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5041 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5042 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5043 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5044 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
5045 LN0->getChain(),
5046 LN0->getBasePtr(), LN0->getPointerInfo(),
5047 N0.getValueType(),
5048 LN0->isVolatile(), LN0->isNonTemporal(),
5049 LN0->getAlignment());
5050 CombineTo(N, ExtLoad);
5051 CombineTo(N0.getNode(),
5052 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5053 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5054 ExtLoad.getValue(1));
5055 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5058 return SDValue();
5061 SDValue DAGCombiner::visitFNEG(SDNode *N) {
5062 SDValue N0 = N->getOperand(0);
5063 EVT VT = N->getValueType(0);
5065 if (isNegatibleForFree(N0, LegalOperations))
5066 return GetNegatedExpression(N0, DAG, LegalOperations);
5068 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5069 // constant pool values.
5070 if (N0.getOpcode() == ISD::BIT_CONVERT &&
5071 !VT.isVector() &&
5072 N0.getNode()->hasOneUse() &&
5073 N0.getOperand(0).getValueType().isInteger()) {
5074 SDValue Int = N0.getOperand(0);
5075 EVT IntVT = Int.getValueType();
5076 if (IntVT.isInteger() && !IntVT.isVector()) {
5077 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5078 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5079 AddToWorkList(Int.getNode());
5080 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
5081 VT, Int);
5085 return SDValue();
5088 SDValue DAGCombiner::visitFABS(SDNode *N) {
5089 SDValue N0 = N->getOperand(0);
5090 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5091 EVT VT = N->getValueType(0);
5093 // fold (fabs c1) -> fabs(c1)
5094 if (N0CFP && VT != MVT::ppcf128)
5095 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5096 // fold (fabs (fabs x)) -> (fabs x)
5097 if (N0.getOpcode() == ISD::FABS)
5098 return N->getOperand(0);
5099 // fold (fabs (fneg x)) -> (fabs x)
5100 // fold (fabs (fcopysign x, y)) -> (fabs x)
5101 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5102 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5104 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5105 // constant pool values.
5106 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
5107 N0.getOperand(0).getValueType().isInteger() &&
5108 !N0.getOperand(0).getValueType().isVector()) {
5109 SDValue Int = N0.getOperand(0);
5110 EVT IntVT = Int.getValueType();
5111 if (IntVT.isInteger() && !IntVT.isVector()) {
5112 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5113 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5114 AddToWorkList(Int.getNode());
5115 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
5116 N->getValueType(0), Int);
5120 return SDValue();
5123 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5124 SDValue Chain = N->getOperand(0);
5125 SDValue N1 = N->getOperand(1);
5126 SDValue N2 = N->getOperand(2);
5128 // If N is a constant we could fold this into a fallthrough or unconditional
5129 // branch. However that doesn't happen very often in normal code, because
5130 // Instcombine/SimplifyCFG should have handled the available opportunities.
5131 // If we did this folding here, it would be necessary to update the
5132 // MachineBasicBlock CFG, which is awkward.
5134 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5135 // on the target.
5136 if (N1.getOpcode() == ISD::SETCC &&
5137 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5138 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5139 Chain, N1.getOperand(2),
5140 N1.getOperand(0), N1.getOperand(1), N2);
5143 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5144 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5145 (N1.getOperand(0).hasOneUse() &&
5146 N1.getOperand(0).getOpcode() == ISD::SRL))) {
5147 SDNode *Trunc = 0;
5148 if (N1.getOpcode() == ISD::TRUNCATE) {
5149 // Look pass the truncate.
5150 Trunc = N1.getNode();
5151 N1 = N1.getOperand(0);
5154 // Match this pattern so that we can generate simpler code:
5156 // %a = ...
5157 // %b = and i32 %a, 2
5158 // %c = srl i32 %b, 1
5159 // brcond i32 %c ...
5161 // into
5163 // %a = ...
5164 // %b = and i32 %a, 2
5165 // %c = setcc eq %b, 0
5166 // brcond %c ...
5168 // This applies only when the AND constant value has one bit set and the
5169 // SRL constant is equal to the log2 of the AND constant. The back-end is
5170 // smart enough to convert the result into a TEST/JMP sequence.
5171 SDValue Op0 = N1.getOperand(0);
5172 SDValue Op1 = N1.getOperand(1);
5174 if (Op0.getOpcode() == ISD::AND &&
5175 Op1.getOpcode() == ISD::Constant) {
5176 SDValue AndOp1 = Op0.getOperand(1);
5178 if (AndOp1.getOpcode() == ISD::Constant) {
5179 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5181 if (AndConst.isPowerOf2() &&
5182 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5183 SDValue SetCC =
5184 DAG.getSetCC(N->getDebugLoc(),
5185 TLI.getSetCCResultType(Op0.getValueType()),
5186 Op0, DAG.getConstant(0, Op0.getValueType()),
5187 ISD::SETNE);
5189 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5190 MVT::Other, Chain, SetCC, N2);
5191 // Don't add the new BRCond into the worklist or else SimplifySelectCC
5192 // will convert it back to (X & C1) >> C2.
5193 CombineTo(N, NewBRCond, false);
5194 // Truncate is dead.
5195 if (Trunc) {
5196 removeFromWorkList(Trunc);
5197 DAG.DeleteNode(Trunc);
5199 // Replace the uses of SRL with SETCC
5200 WorkListRemover DeadNodes(*this);
5201 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5202 removeFromWorkList(N1.getNode());
5203 DAG.DeleteNode(N1.getNode());
5204 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5209 if (Trunc)
5210 // Restore N1 if the above transformation doesn't match.
5211 N1 = N->getOperand(1);
5214 // Transform br(xor(x, y)) -> br(x != y)
5215 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5216 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5217 SDNode *TheXor = N1.getNode();
5218 SDValue Op0 = TheXor->getOperand(0);
5219 SDValue Op1 = TheXor->getOperand(1);
5220 if (Op0.getOpcode() == Op1.getOpcode()) {
5221 // Avoid missing important xor optimizations.
5222 SDValue Tmp = visitXOR(TheXor);
5223 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5224 DEBUG(dbgs() << "\nReplacing.8 ";
5225 TheXor->dump(&DAG);
5226 dbgs() << "\nWith: ";
5227 Tmp.getNode()->dump(&DAG);
5228 dbgs() << '\n');
5229 WorkListRemover DeadNodes(*this);
5230 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5231 removeFromWorkList(TheXor);
5232 DAG.DeleteNode(TheXor);
5233 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5234 MVT::Other, Chain, Tmp, N2);
5238 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5239 bool Equal = false;
5240 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5241 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5242 Op0.getOpcode() == ISD::XOR) {
5243 TheXor = Op0.getNode();
5244 Equal = true;
5247 EVT SetCCVT = N1.getValueType();
5248 if (LegalTypes)
5249 SetCCVT = TLI.getSetCCResultType(SetCCVT);
5250 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5251 SetCCVT,
5252 Op0, Op1,
5253 Equal ? ISD::SETEQ : ISD::SETNE);
5254 // Replace the uses of XOR with SETCC
5255 WorkListRemover DeadNodes(*this);
5256 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5257 removeFromWorkList(N1.getNode());
5258 DAG.DeleteNode(N1.getNode());
5259 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5260 MVT::Other, Chain, SetCC, N2);
5264 return SDValue();
5267 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5269 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5270 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5271 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5273 // If N is a constant we could fold this into a fallthrough or unconditional
5274 // branch. However that doesn't happen very often in normal code, because
5275 // Instcombine/SimplifyCFG should have handled the available opportunities.
5276 // If we did this folding here, it would be necessary to update the
5277 // MachineBasicBlock CFG, which is awkward.
5279 // Use SimplifySetCC to simplify SETCC's.
5280 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5281 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5282 false);
5283 if (Simp.getNode()) AddToWorkList(Simp.getNode());
5285 // fold to a simpler setcc
5286 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5287 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5288 N->getOperand(0), Simp.getOperand(2),
5289 Simp.getOperand(0), Simp.getOperand(1),
5290 N->getOperand(4));
5292 return SDValue();
5295 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5296 /// pre-indexed load / store when the base pointer is an add or subtract
5297 /// and it has other uses besides the load / store. After the
5298 /// transformation, the new indexed load / store has effectively folded
5299 /// the add / subtract in and all of its other uses are redirected to the
5300 /// new load / store.
5301 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5302 if (!LegalOperations)
5303 return false;
5305 bool isLoad = true;
5306 SDValue Ptr;
5307 EVT VT;
5308 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5309 if (LD->isIndexed())
5310 return false;
5311 VT = LD->getMemoryVT();
5312 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5313 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5314 return false;
5315 Ptr = LD->getBasePtr();
5316 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5317 if (ST->isIndexed())
5318 return false;
5319 VT = ST->getMemoryVT();
5320 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5321 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5322 return false;
5323 Ptr = ST->getBasePtr();
5324 isLoad = false;
5325 } else {
5326 return false;
5329 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5330 // out. There is no reason to make this a preinc/predec.
5331 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5332 Ptr.getNode()->hasOneUse())
5333 return false;
5335 // Ask the target to do addressing mode selection.
5336 SDValue BasePtr;
5337 SDValue Offset;
5338 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5339 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5340 return false;
5341 // Don't create a indexed load / store with zero offset.
5342 if (isa<ConstantSDNode>(Offset) &&
5343 cast<ConstantSDNode>(Offset)->isNullValue())
5344 return false;
5346 // Try turning it into a pre-indexed load / store except when:
5347 // 1) The new base ptr is a frame index.
5348 // 2) If N is a store and the new base ptr is either the same as or is a
5349 // predecessor of the value being stored.
5350 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5351 // that would create a cycle.
5352 // 4) All uses are load / store ops that use it as old base ptr.
5354 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5355 // (plus the implicit offset) to a register to preinc anyway.
5356 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5357 return false;
5359 // Check #2.
5360 if (!isLoad) {
5361 SDValue Val = cast<StoreSDNode>(N)->getValue();
5362 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5363 return false;
5366 // Now check for #3 and #4.
5367 bool RealUse = false;
5368 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5369 E = Ptr.getNode()->use_end(); I != E; ++I) {
5370 SDNode *Use = *I;
5371 if (Use == N)
5372 continue;
5373 if (Use->isPredecessorOf(N))
5374 return false;
5376 if (!((Use->getOpcode() == ISD::LOAD &&
5377 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5378 (Use->getOpcode() == ISD::STORE &&
5379 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5380 RealUse = true;
5383 if (!RealUse)
5384 return false;
5386 SDValue Result;
5387 if (isLoad)
5388 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5389 BasePtr, Offset, AM);
5390 else
5391 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5392 BasePtr, Offset, AM);
5393 ++PreIndexedNodes;
5394 ++NodesCombined;
5395 DEBUG(dbgs() << "\nReplacing.4 ";
5396 N->dump(&DAG);
5397 dbgs() << "\nWith: ";
5398 Result.getNode()->dump(&DAG);
5399 dbgs() << '\n');
5400 WorkListRemover DeadNodes(*this);
5401 if (isLoad) {
5402 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5403 &DeadNodes);
5404 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5405 &DeadNodes);
5406 } else {
5407 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5408 &DeadNodes);
5411 // Finally, since the node is now dead, remove it from the graph.
5412 DAG.DeleteNode(N);
5414 // Replace the uses of Ptr with uses of the updated base value.
5415 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5416 &DeadNodes);
5417 removeFromWorkList(Ptr.getNode());
5418 DAG.DeleteNode(Ptr.getNode());
5420 return true;
5423 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5424 /// add / sub of the base pointer node into a post-indexed load / store.
5425 /// The transformation folded the add / subtract into the new indexed
5426 /// load / store effectively and all of its uses are redirected to the
5427 /// new load / store.
5428 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5429 if (!LegalOperations)
5430 return false;
5432 bool isLoad = true;
5433 SDValue Ptr;
5434 EVT VT;
5435 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5436 if (LD->isIndexed())
5437 return false;
5438 VT = LD->getMemoryVT();
5439 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5440 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5441 return false;
5442 Ptr = LD->getBasePtr();
5443 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5444 if (ST->isIndexed())
5445 return false;
5446 VT = ST->getMemoryVT();
5447 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5448 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5449 return false;
5450 Ptr = ST->getBasePtr();
5451 isLoad = false;
5452 } else {
5453 return false;
5456 if (Ptr.getNode()->hasOneUse())
5457 return false;
5459 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5460 E = Ptr.getNode()->use_end(); I != E; ++I) {
5461 SDNode *Op = *I;
5462 if (Op == N ||
5463 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5464 continue;
5466 SDValue BasePtr;
5467 SDValue Offset;
5468 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5469 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5470 // Don't create a indexed load / store with zero offset.
5471 if (isa<ConstantSDNode>(Offset) &&
5472 cast<ConstantSDNode>(Offset)->isNullValue())
5473 continue;
5475 // Try turning it into a post-indexed load / store except when
5476 // 1) All uses are load / store ops that use it as base ptr.
5477 // 2) Op must be independent of N, i.e. Op is neither a predecessor
5478 // nor a successor of N. Otherwise, if Op is folded that would
5479 // create a cycle.
5481 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5482 continue;
5484 // Check for #1.
5485 bool TryNext = false;
5486 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5487 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5488 SDNode *Use = *II;
5489 if (Use == Ptr.getNode())
5490 continue;
5492 // If all the uses are load / store addresses, then don't do the
5493 // transformation.
5494 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5495 bool RealUse = false;
5496 for (SDNode::use_iterator III = Use->use_begin(),
5497 EEE = Use->use_end(); III != EEE; ++III) {
5498 SDNode *UseUse = *III;
5499 if (!((UseUse->getOpcode() == ISD::LOAD &&
5500 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5501 (UseUse->getOpcode() == ISD::STORE &&
5502 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5503 RealUse = true;
5506 if (!RealUse) {
5507 TryNext = true;
5508 break;
5513 if (TryNext)
5514 continue;
5516 // Check for #2
5517 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5518 SDValue Result = isLoad
5519 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5520 BasePtr, Offset, AM)
5521 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5522 BasePtr, Offset, AM);
5523 ++PostIndexedNodes;
5524 ++NodesCombined;
5525 DEBUG(dbgs() << "\nReplacing.5 ";
5526 N->dump(&DAG);
5527 dbgs() << "\nWith: ";
5528 Result.getNode()->dump(&DAG);
5529 dbgs() << '\n');
5530 WorkListRemover DeadNodes(*this);
5531 if (isLoad) {
5532 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5533 &DeadNodes);
5534 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5535 &DeadNodes);
5536 } else {
5537 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5538 &DeadNodes);
5541 // Finally, since the node is now dead, remove it from the graph.
5542 DAG.DeleteNode(N);
5544 // Replace the uses of Use with uses of the updated base value.
5545 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5546 Result.getValue(isLoad ? 1 : 0),
5547 &DeadNodes);
5548 removeFromWorkList(Op);
5549 DAG.DeleteNode(Op);
5550 return true;
5555 return false;
5558 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5559 LoadSDNode *LD = cast<LoadSDNode>(N);
5560 SDValue Chain = LD->getChain();
5561 SDValue Ptr = LD->getBasePtr();
5563 // If load is not volatile and there are no uses of the loaded value (and
5564 // the updated indexed value in case of indexed loads), change uses of the
5565 // chain value into uses of the chain input (i.e. delete the dead load).
5566 if (!LD->isVolatile()) {
5567 if (N->getValueType(1) == MVT::Other) {
5568 // Unindexed loads.
5569 if (N->hasNUsesOfValue(0, 0)) {
5570 // It's not safe to use the two value CombineTo variant here. e.g.
5571 // v1, chain2 = load chain1, loc
5572 // v2, chain3 = load chain2, loc
5573 // v3 = add v2, c
5574 // Now we replace use of chain2 with chain1. This makes the second load
5575 // isomorphic to the one we are deleting, and thus makes this load live.
5576 DEBUG(dbgs() << "\nReplacing.6 ";
5577 N->dump(&DAG);
5578 dbgs() << "\nWith chain: ";
5579 Chain.getNode()->dump(&DAG);
5580 dbgs() << "\n");
5581 WorkListRemover DeadNodes(*this);
5582 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5584 if (N->use_empty()) {
5585 removeFromWorkList(N);
5586 DAG.DeleteNode(N);
5589 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5591 } else {
5592 // Indexed loads.
5593 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5594 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5595 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5596 DEBUG(dbgs() << "\nReplacing.7 ";
5597 N->dump(&DAG);
5598 dbgs() << "\nWith: ";
5599 Undef.getNode()->dump(&DAG);
5600 dbgs() << " and 2 other values\n");
5601 WorkListRemover DeadNodes(*this);
5602 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5603 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5604 DAG.getUNDEF(N->getValueType(1)),
5605 &DeadNodes);
5606 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5607 removeFromWorkList(N);
5608 DAG.DeleteNode(N);
5609 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5614 // If this load is directly stored, replace the load value with the stored
5615 // value.
5616 // TODO: Handle store large -> read small portion.
5617 // TODO: Handle TRUNCSTORE/LOADEXT
5618 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5619 !LD->isVolatile()) {
5620 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5621 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5622 if (PrevST->getBasePtr() == Ptr &&
5623 PrevST->getValue().getValueType() == N->getValueType(0))
5624 return CombineTo(N, Chain.getOperand(1), Chain);
5628 // Try to infer better alignment information than the load already has.
5629 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5630 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5631 if (Align > LD->getAlignment())
5632 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5633 N->getDebugLoc(),
5634 Chain, Ptr, LD->getPointerInfo(),
5635 LD->getMemoryVT(),
5636 LD->isVolatile(), LD->isNonTemporal(), Align);
5640 if (CombinerAA) {
5641 // Walk up chain skipping non-aliasing memory nodes.
5642 SDValue BetterChain = FindBetterChain(N, Chain);
5644 // If there is a better chain.
5645 if (Chain != BetterChain) {
5646 SDValue ReplLoad;
5648 // Replace the chain to void dependency.
5649 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5650 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5651 BetterChain, Ptr, LD->getPointerInfo(),
5652 LD->isVolatile(), LD->isNonTemporal(),
5653 LD->getAlignment());
5654 } else {
5655 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5656 LD->getDebugLoc(),
5657 BetterChain, Ptr, LD->getPointerInfo(),
5658 LD->getMemoryVT(),
5659 LD->isVolatile(),
5660 LD->isNonTemporal(),
5661 LD->getAlignment());
5664 // Create token factor to keep old chain connected.
5665 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5666 MVT::Other, Chain, ReplLoad.getValue(1));
5668 // Make sure the new and old chains are cleaned up.
5669 AddToWorkList(Token.getNode());
5671 // Replace uses with load result and token factor. Don't add users
5672 // to work list.
5673 return CombineTo(N, ReplLoad.getValue(0), Token, false);
5677 // Try transforming N to an indexed load.
5678 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5679 return SDValue(N, 0);
5681 return SDValue();
5684 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5685 /// load is having specific bytes cleared out. If so, return the byte size
5686 /// being masked out and the shift amount.
5687 static std::pair<unsigned, unsigned>
5688 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5689 std::pair<unsigned, unsigned> Result(0, 0);
5691 // Check for the structure we're looking for.
5692 if (V->getOpcode() != ISD::AND ||
5693 !isa<ConstantSDNode>(V->getOperand(1)) ||
5694 !ISD::isNormalLoad(V->getOperand(0).getNode()))
5695 return Result;
5697 // Check the chain and pointer.
5698 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5699 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
5701 // The store should be chained directly to the load or be an operand of a
5702 // tokenfactor.
5703 if (LD == Chain.getNode())
5704 ; // ok.
5705 else if (Chain->getOpcode() != ISD::TokenFactor)
5706 return Result; // Fail.
5707 else {
5708 bool isOk = false;
5709 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5710 if (Chain->getOperand(i).getNode() == LD) {
5711 isOk = true;
5712 break;
5714 if (!isOk) return Result;
5717 // This only handles simple types.
5718 if (V.getValueType() != MVT::i16 &&
5719 V.getValueType() != MVT::i32 &&
5720 V.getValueType() != MVT::i64)
5721 return Result;
5723 // Check the constant mask. Invert it so that the bits being masked out are
5724 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
5725 // follow the sign bit for uniformity.
5726 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5727 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5728 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
5729 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5730 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
5731 if (NotMaskLZ == 64) return Result; // All zero mask.
5733 // See if we have a continuous run of bits. If so, we have 0*1+0*
5734 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5735 return Result;
5737 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5738 if (V.getValueType() != MVT::i64 && NotMaskLZ)
5739 NotMaskLZ -= 64-V.getValueSizeInBits();
5741 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5742 switch (MaskedBytes) {
5743 case 1:
5744 case 2:
5745 case 4: break;
5746 default: return Result; // All one mask, or 5-byte mask.
5749 // Verify that the first bit starts at a multiple of mask so that the access
5750 // is aligned the same as the access width.
5751 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5753 Result.first = MaskedBytes;
5754 Result.second = NotMaskTZ/8;
5755 return Result;
5759 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5760 /// provides a value as specified by MaskInfo. If so, replace the specified
5761 /// store with a narrower store of truncated IVal.
5762 static SDNode *
5763 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5764 SDValue IVal, StoreSDNode *St,
5765 DAGCombiner *DC) {
5766 unsigned NumBytes = MaskInfo.first;
5767 unsigned ByteShift = MaskInfo.second;
5768 SelectionDAG &DAG = DC->getDAG();
5770 // Check to see if IVal is all zeros in the part being masked in by the 'or'
5771 // that uses this. If not, this is not a replacement.
5772 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5773 ByteShift*8, (ByteShift+NumBytes)*8);
5774 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5776 // Check that it is legal on the target to do this. It is legal if the new
5777 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5778 // legalization.
5779 MVT VT = MVT::getIntegerVT(NumBytes*8);
5780 if (!DC->isTypeLegal(VT))
5781 return 0;
5783 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
5784 // shifted by ByteShift and truncated down to NumBytes.
5785 if (ByteShift)
5786 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5787 DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5789 // Figure out the offset for the store and the alignment of the access.
5790 unsigned StOffset;
5791 unsigned NewAlign = St->getAlignment();
5793 if (DAG.getTargetLoweringInfo().isLittleEndian())
5794 StOffset = ByteShift;
5795 else
5796 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5798 SDValue Ptr = St->getBasePtr();
5799 if (StOffset) {
5800 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5801 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5802 NewAlign = MinAlign(NewAlign, StOffset);
5805 // Truncate down to the new size.
5806 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5808 ++OpsNarrowed;
5809 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
5810 St->getPointerInfo().getWithOffset(StOffset),
5811 false, false, NewAlign).getNode();
5815 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5816 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5817 /// of the loaded bits, try narrowing the load and store if it would end up
5818 /// being a win for performance or code size.
5819 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5820 StoreSDNode *ST = cast<StoreSDNode>(N);
5821 if (ST->isVolatile())
5822 return SDValue();
5824 SDValue Chain = ST->getChain();
5825 SDValue Value = ST->getValue();
5826 SDValue Ptr = ST->getBasePtr();
5827 EVT VT = Value.getValueType();
5829 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
5830 return SDValue();
5832 unsigned Opc = Value.getOpcode();
5834 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
5835 // is a byte mask indicating a consecutive number of bytes, check to see if
5836 // Y is known to provide just those bytes. If so, we try to replace the
5837 // load + replace + store sequence with a single (narrower) store, which makes
5838 // the load dead.
5839 if (Opc == ISD::OR) {
5840 std::pair<unsigned, unsigned> MaskedLoad;
5841 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
5842 if (MaskedLoad.first)
5843 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5844 Value.getOperand(1), ST,this))
5845 return SDValue(NewST, 0);
5847 // Or is commutative, so try swapping X and Y.
5848 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
5849 if (MaskedLoad.first)
5850 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5851 Value.getOperand(0), ST,this))
5852 return SDValue(NewST, 0);
5855 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
5856 Value.getOperand(1).getOpcode() != ISD::Constant)
5857 return SDValue();
5859 SDValue N0 = Value.getOperand(0);
5860 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5861 Chain == SDValue(N0.getNode(), 1)) {
5862 LoadSDNode *LD = cast<LoadSDNode>(N0);
5863 if (LD->getBasePtr() != Ptr ||
5864 LD->getPointerInfo().getAddrSpace() !=
5865 ST->getPointerInfo().getAddrSpace())
5866 return SDValue();
5868 // Find the type to narrow it the load / op / store to.
5869 SDValue N1 = Value.getOperand(1);
5870 unsigned BitWidth = N1.getValueSizeInBits();
5871 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5872 if (Opc == ISD::AND)
5873 Imm ^= APInt::getAllOnesValue(BitWidth);
5874 if (Imm == 0 || Imm.isAllOnesValue())
5875 return SDValue();
5876 unsigned ShAmt = Imm.countTrailingZeros();
5877 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5878 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5879 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5880 while (NewBW < BitWidth &&
5881 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5882 TLI.isNarrowingProfitable(VT, NewVT))) {
5883 NewBW = NextPowerOf2(NewBW);
5884 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5886 if (NewBW >= BitWidth)
5887 return SDValue();
5889 // If the lsb changed does not start at the type bitwidth boundary,
5890 // start at the previous one.
5891 if (ShAmt % NewBW)
5892 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5893 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5894 if ((Imm & Mask) == Imm) {
5895 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5896 if (Opc == ISD::AND)
5897 NewImm ^= APInt::getAllOnesValue(NewBW);
5898 uint64_t PtrOff = ShAmt / 8;
5899 // For big endian targets, we need to adjust the offset to the pointer to
5900 // load the correct bytes.
5901 if (TLI.isBigEndian())
5902 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5904 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5905 const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
5906 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
5907 return SDValue();
5909 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5910 Ptr.getValueType(), Ptr,
5911 DAG.getConstant(PtrOff, Ptr.getValueType()));
5912 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5913 LD->getChain(), NewPtr,
5914 LD->getPointerInfo().getWithOffset(PtrOff),
5915 LD->isVolatile(), LD->isNonTemporal(),
5916 NewAlign);
5917 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5918 DAG.getConstant(NewImm, NewVT));
5919 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5920 NewVal, NewPtr,
5921 ST->getPointerInfo().getWithOffset(PtrOff),
5922 false, false, NewAlign);
5924 AddToWorkList(NewPtr.getNode());
5925 AddToWorkList(NewLD.getNode());
5926 AddToWorkList(NewVal.getNode());
5927 WorkListRemover DeadNodes(*this);
5928 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5929 &DeadNodes);
5930 ++OpsNarrowed;
5931 return NewST;
5935 return SDValue();
5938 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5939 StoreSDNode *ST = cast<StoreSDNode>(N);
5940 SDValue Chain = ST->getChain();
5941 SDValue Value = ST->getValue();
5942 SDValue Ptr = ST->getBasePtr();
5944 // If this is a store of a bit convert, store the input value if the
5945 // resultant store does not need a higher alignment than the original.
5946 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5947 ST->isUnindexed()) {
5948 unsigned OrigAlign = ST->getAlignment();
5949 EVT SVT = Value.getOperand(0).getValueType();
5950 unsigned Align = TLI.getTargetData()->
5951 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5952 if (Align <= OrigAlign &&
5953 ((!LegalOperations && !ST->isVolatile()) ||
5954 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5955 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5956 Ptr, ST->getPointerInfo(), ST->isVolatile(),
5957 ST->isNonTemporal(), OrigAlign);
5960 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5961 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5962 // NOTE: If the original store is volatile, this transform must not increase
5963 // the number of stores. For example, on x86-32 an f64 can be stored in one
5964 // processor operation but an i64 (which is not legal) requires two. So the
5965 // transform should not be done in this case.
5966 if (Value.getOpcode() != ISD::TargetConstantFP) {
5967 SDValue Tmp;
5968 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5969 default: llvm_unreachable("Unknown FP type");
5970 case MVT::f80: // We don't do this for these yet.
5971 case MVT::f128:
5972 case MVT::ppcf128:
5973 break;
5974 case MVT::f32:
5975 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
5976 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5977 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5978 bitcastToAPInt().getZExtValue(), MVT::i32);
5979 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5980 Ptr, ST->getPointerInfo(), ST->isVolatile(),
5981 ST->isNonTemporal(), ST->getAlignment());
5983 break;
5984 case MVT::f64:
5985 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
5986 !ST->isVolatile()) ||
5987 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5988 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5989 getZExtValue(), MVT::i64);
5990 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5991 Ptr, ST->getPointerInfo(), ST->isVolatile(),
5992 ST->isNonTemporal(), ST->getAlignment());
5993 } else if (!ST->isVolatile() &&
5994 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5995 // Many FP stores are not made apparent until after legalize, e.g. for
5996 // argument passing. Since this is so common, custom legalize the
5997 // 64-bit integer store into two 32-bit stores.
5998 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5999 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6000 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6001 if (TLI.isBigEndian()) std::swap(Lo, Hi);
6003 unsigned Alignment = ST->getAlignment();
6004 bool isVolatile = ST->isVolatile();
6005 bool isNonTemporal = ST->isNonTemporal();
6007 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6008 Ptr, ST->getPointerInfo(),
6009 isVolatile, isNonTemporal,
6010 ST->getAlignment());
6011 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6012 DAG.getConstant(4, Ptr.getValueType()));
6013 Alignment = MinAlign(Alignment, 4U);
6014 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6015 Ptr, ST->getPointerInfo().getWithOffset(4),
6016 isVolatile, isNonTemporal,
6017 Alignment);
6018 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6019 St0, St1);
6022 break;
6027 // Try to infer better alignment information than the store already has.
6028 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6029 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6030 if (Align > ST->getAlignment())
6031 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6032 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6033 ST->isVolatile(), ST->isNonTemporal(), Align);
6037 if (CombinerAA) {
6038 // Walk up chain skipping non-aliasing memory nodes.
6039 SDValue BetterChain = FindBetterChain(N, Chain);
6041 // If there is a better chain.
6042 if (Chain != BetterChain) {
6043 SDValue ReplStore;
6045 // Replace the chain to avoid dependency.
6046 if (ST->isTruncatingStore()) {
6047 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6048 ST->getPointerInfo(),
6049 ST->getMemoryVT(), ST->isVolatile(),
6050 ST->isNonTemporal(), ST->getAlignment());
6051 } else {
6052 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6053 ST->getPointerInfo(),
6054 ST->isVolatile(), ST->isNonTemporal(),
6055 ST->getAlignment());
6058 // Create token to keep both nodes around.
6059 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6060 MVT::Other, Chain, ReplStore);
6062 // Make sure the new and old chains are cleaned up.
6063 AddToWorkList(Token.getNode());
6065 // Don't add users to work list.
6066 return CombineTo(N, Token, false);
6070 // Try transforming N to an indexed store.
6071 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6072 return SDValue(N, 0);
6074 // FIXME: is there such a thing as a truncating indexed store?
6075 if (ST->isTruncatingStore() && ST->isUnindexed() &&
6076 Value.getValueType().isInteger()) {
6077 // See if we can simplify the input to this truncstore with knowledge that
6078 // only the low bits are being used. For example:
6079 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
6080 SDValue Shorter =
6081 GetDemandedBits(Value,
6082 APInt::getLowBitsSet(Value.getValueSizeInBits(),
6083 ST->getMemoryVT().getSizeInBits()));
6084 AddToWorkList(Value.getNode());
6085 if (Shorter.getNode())
6086 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6087 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6088 ST->isVolatile(), ST->isNonTemporal(),
6089 ST->getAlignment());
6091 // Otherwise, see if we can simplify the operation with
6092 // SimplifyDemandedBits, which only works if the value has a single use.
6093 if (SimplifyDemandedBits(Value,
6094 APInt::getLowBitsSet(
6095 Value.getValueType().getScalarType().getSizeInBits(),
6096 ST->getMemoryVT().getScalarType().getSizeInBits())))
6097 return SDValue(N, 0);
6100 // If this is a load followed by a store to the same location, then the store
6101 // is dead/noop.
6102 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6103 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6104 ST->isUnindexed() && !ST->isVolatile() &&
6105 // There can't be any side effects between the load and store, such as
6106 // a call or store.
6107 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6108 // The store is dead, remove it.
6109 return Chain;
6113 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6114 // truncating store. We can do this even if this is already a truncstore.
6115 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6116 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6117 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6118 ST->getMemoryVT())) {
6119 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6120 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6121 ST->isVolatile(), ST->isNonTemporal(),
6122 ST->getAlignment());
6125 return ReduceLoadOpStoreWidth(N);
6128 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6129 SDValue InVec = N->getOperand(0);
6130 SDValue InVal = N->getOperand(1);
6131 SDValue EltNo = N->getOperand(2);
6133 // If the inserted element is an UNDEF, just use the input vector.
6134 if (InVal.getOpcode() == ISD::UNDEF)
6135 return InVec;
6137 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
6138 // vector with the inserted element.
6139 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
6140 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6141 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
6142 InVec.getNode()->op_end());
6143 if (Elt < Ops.size())
6144 Ops[Elt] = InVal;
6145 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6146 InVec.getValueType(), &Ops[0], Ops.size());
6148 // If the invec is an UNDEF and if EltNo is a constant, create a new
6149 // BUILD_VECTOR with undef elements and the inserted element.
6150 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
6151 isa<ConstantSDNode>(EltNo)) {
6152 EVT VT = InVec.getValueType();
6153 EVT EltVT = VT.getVectorElementType();
6154 unsigned NElts = VT.getVectorNumElements();
6155 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
6157 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6158 if (Elt < Ops.size())
6159 Ops[Elt] = InVal;
6160 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6161 InVec.getValueType(), &Ops[0], Ops.size());
6163 return SDValue();
6166 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6167 // (vextract (scalar_to_vector val, 0) -> val
6168 SDValue InVec = N->getOperand(0);
6170 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6171 // Check if the result type doesn't match the inserted element type. A
6172 // SCALAR_TO_VECTOR may truncate the inserted element and the
6173 // EXTRACT_VECTOR_ELT may widen the extracted vector.
6174 SDValue InOp = InVec.getOperand(0);
6175 EVT NVT = N->getValueType(0);
6176 if (InOp.getValueType() != NVT) {
6177 assert(InOp.getValueType().isInteger() && NVT.isInteger());
6178 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6180 return InOp;
6183 // Perform only after legalization to ensure build_vector / vector_shuffle
6184 // optimizations have already been done.
6185 if (!LegalOperations) return SDValue();
6187 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6188 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6189 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6190 SDValue EltNo = N->getOperand(1);
6192 if (isa<ConstantSDNode>(EltNo)) {
6193 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6194 bool NewLoad = false;
6195 bool BCNumEltsChanged = false;
6196 EVT VT = InVec.getValueType();
6197 EVT ExtVT = VT.getVectorElementType();
6198 EVT LVT = ExtVT;
6200 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
6201 EVT BCVT = InVec.getOperand(0).getValueType();
6202 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6203 return SDValue();
6204 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6205 BCNumEltsChanged = true;
6206 InVec = InVec.getOperand(0);
6207 ExtVT = BCVT.getVectorElementType();
6208 NewLoad = true;
6211 LoadSDNode *LN0 = NULL;
6212 const ShuffleVectorSDNode *SVN = NULL;
6213 if (ISD::isNormalLoad(InVec.getNode())) {
6214 LN0 = cast<LoadSDNode>(InVec);
6215 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6216 InVec.getOperand(0).getValueType() == ExtVT &&
6217 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6218 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6219 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6220 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6221 // =>
6222 // (load $addr+1*size)
6224 // If the bit convert changed the number of elements, it is unsafe
6225 // to examine the mask.
6226 if (BCNumEltsChanged)
6227 return SDValue();
6229 // Select the input vector, guarding against out of range extract vector.
6230 unsigned NumElems = VT.getVectorNumElements();
6231 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6232 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6234 if (InVec.getOpcode() == ISD::BIT_CONVERT)
6235 InVec = InVec.getOperand(0);
6236 if (ISD::isNormalLoad(InVec.getNode())) {
6237 LN0 = cast<LoadSDNode>(InVec);
6238 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6242 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6243 return SDValue();
6245 // If Idx was -1 above, Elt is going to be -1, so just return undef.
6246 if (Elt == -1)
6247 return DAG.getUNDEF(LN0->getBasePtr().getValueType());
6249 unsigned Align = LN0->getAlignment();
6250 if (NewLoad) {
6251 // Check the resultant load doesn't need a higher alignment than the
6252 // original load.
6253 unsigned NewAlign =
6254 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6256 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6257 return SDValue();
6259 Align = NewAlign;
6262 SDValue NewPtr = LN0->getBasePtr();
6263 unsigned PtrOff = 0;
6265 if (Elt) {
6266 PtrOff = LVT.getSizeInBits() * Elt / 8;
6267 EVT PtrType = NewPtr.getValueType();
6268 if (TLI.isBigEndian())
6269 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6270 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6271 DAG.getConstant(PtrOff, PtrType));
6274 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6275 LN0->getPointerInfo().getWithOffset(PtrOff),
6276 LN0->isVolatile(), LN0->isNonTemporal(), Align);
6279 return SDValue();
6282 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6283 unsigned NumInScalars = N->getNumOperands();
6284 EVT VT = N->getValueType(0);
6286 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6287 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6288 // at most two distinct vectors, turn this into a shuffle node.
6289 SDValue VecIn1, VecIn2;
6290 for (unsigned i = 0; i != NumInScalars; ++i) {
6291 // Ignore undef inputs.
6292 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6294 // If this input is something other than a EXTRACT_VECTOR_ELT with a
6295 // constant index, bail out.
6296 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6297 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6298 VecIn1 = VecIn2 = SDValue(0, 0);
6299 break;
6302 // If the input vector type disagrees with the result of the build_vector,
6303 // we can't make a shuffle.
6304 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6305 if (ExtractedFromVec.getValueType() != VT) {
6306 VecIn1 = VecIn2 = SDValue(0, 0);
6307 break;
6310 // Otherwise, remember this. We allow up to two distinct input vectors.
6311 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6312 continue;
6314 if (VecIn1.getNode() == 0) {
6315 VecIn1 = ExtractedFromVec;
6316 } else if (VecIn2.getNode() == 0) {
6317 VecIn2 = ExtractedFromVec;
6318 } else {
6319 // Too many inputs.
6320 VecIn1 = VecIn2 = SDValue(0, 0);
6321 break;
6325 // If everything is good, we can make a shuffle operation.
6326 if (VecIn1.getNode()) {
6327 SmallVector<int, 8> Mask;
6328 for (unsigned i = 0; i != NumInScalars; ++i) {
6329 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6330 Mask.push_back(-1);
6331 continue;
6334 // If extracting from the first vector, just use the index directly.
6335 SDValue Extract = N->getOperand(i);
6336 SDValue ExtVal = Extract.getOperand(1);
6337 if (Extract.getOperand(0) == VecIn1) {
6338 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6339 if (ExtIndex > VT.getVectorNumElements())
6340 return SDValue();
6342 Mask.push_back(ExtIndex);
6343 continue;
6346 // Otherwise, use InIdx + VecSize
6347 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6348 Mask.push_back(Idx+NumInScalars);
6351 // Add count and size info.
6352 if (!isTypeLegal(VT))
6353 return SDValue();
6355 // Return the new VECTOR_SHUFFLE node.
6356 SDValue Ops[2];
6357 Ops[0] = VecIn1;
6358 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6359 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6362 return SDValue();
6365 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6366 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6367 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
6368 // inputs come from at most two distinct vectors, turn this into a shuffle
6369 // node.
6371 // If we only have one input vector, we don't need to do any concatenation.
6372 if (N->getNumOperands() == 1)
6373 return N->getOperand(0);
6375 return SDValue();
6378 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6379 EVT VT = N->getValueType(0);
6380 unsigned NumElts = VT.getVectorNumElements();
6382 SDValue N0 = N->getOperand(0);
6384 assert(N0.getValueType().getVectorNumElements() == NumElts &&
6385 "Vector shuffle must be normalized in DAG");
6387 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6389 // If it is a splat, check if the argument vector is another splat or a
6390 // build_vector with all scalar elements the same.
6391 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6392 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
6393 SDNode *V = N0.getNode();
6395 // If this is a bit convert that changes the element type of the vector but
6396 // not the number of vector elements, look through it. Be careful not to
6397 // look though conversions that change things like v4f32 to v2f64.
6398 if (V->getOpcode() == ISD::BIT_CONVERT) {
6399 SDValue ConvInput = V->getOperand(0);
6400 if (ConvInput.getValueType().isVector() &&
6401 ConvInput.getValueType().getVectorNumElements() == NumElts)
6402 V = ConvInput.getNode();
6405 if (V->getOpcode() == ISD::BUILD_VECTOR) {
6406 assert(V->getNumOperands() == NumElts &&
6407 "BUILD_VECTOR has wrong number of operands");
6408 SDValue Base;
6409 bool AllSame = true;
6410 for (unsigned i = 0; i != NumElts; ++i) {
6411 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6412 Base = V->getOperand(i);
6413 break;
6416 // Splat of <u, u, u, u>, return <u, u, u, u>
6417 if (!Base.getNode())
6418 return N0;
6419 for (unsigned i = 0; i != NumElts; ++i) {
6420 if (V->getOperand(i) != Base) {
6421 AllSame = false;
6422 break;
6425 // Splat of <x, x, x, x>, return <x, x, x, x>
6426 if (AllSame)
6427 return N0;
6430 return SDValue();
6433 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
6434 if (!TLI.getShouldFoldAtomicFences())
6435 return SDValue();
6437 SDValue atomic = N->getOperand(0);
6438 switch (atomic.getOpcode()) {
6439 case ISD::ATOMIC_CMP_SWAP:
6440 case ISD::ATOMIC_SWAP:
6441 case ISD::ATOMIC_LOAD_ADD:
6442 case ISD::ATOMIC_LOAD_SUB:
6443 case ISD::ATOMIC_LOAD_AND:
6444 case ISD::ATOMIC_LOAD_OR:
6445 case ISD::ATOMIC_LOAD_XOR:
6446 case ISD::ATOMIC_LOAD_NAND:
6447 case ISD::ATOMIC_LOAD_MIN:
6448 case ISD::ATOMIC_LOAD_MAX:
6449 case ISD::ATOMIC_LOAD_UMIN:
6450 case ISD::ATOMIC_LOAD_UMAX:
6451 break;
6452 default:
6453 return SDValue();
6456 SDValue fence = atomic.getOperand(0);
6457 if (fence.getOpcode() != ISD::MEMBARRIER)
6458 return SDValue();
6460 switch (atomic.getOpcode()) {
6461 case ISD::ATOMIC_CMP_SWAP:
6462 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6463 fence.getOperand(0),
6464 atomic.getOperand(1), atomic.getOperand(2),
6465 atomic.getOperand(3)), atomic.getResNo());
6466 case ISD::ATOMIC_SWAP:
6467 case ISD::ATOMIC_LOAD_ADD:
6468 case ISD::ATOMIC_LOAD_SUB:
6469 case ISD::ATOMIC_LOAD_AND:
6470 case ISD::ATOMIC_LOAD_OR:
6471 case ISD::ATOMIC_LOAD_XOR:
6472 case ISD::ATOMIC_LOAD_NAND:
6473 case ISD::ATOMIC_LOAD_MIN:
6474 case ISD::ATOMIC_LOAD_MAX:
6475 case ISD::ATOMIC_LOAD_UMIN:
6476 case ISD::ATOMIC_LOAD_UMAX:
6477 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6478 fence.getOperand(0),
6479 atomic.getOperand(1), atomic.getOperand(2)),
6480 atomic.getResNo());
6481 default:
6482 return SDValue();
6486 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6487 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6488 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6489 /// vector_shuffle V, Zero, <0, 4, 2, 4>
6490 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6491 EVT VT = N->getValueType(0);
6492 DebugLoc dl = N->getDebugLoc();
6493 SDValue LHS = N->getOperand(0);
6494 SDValue RHS = N->getOperand(1);
6495 if (N->getOpcode() == ISD::AND) {
6496 if (RHS.getOpcode() == ISD::BIT_CONVERT)
6497 RHS = RHS.getOperand(0);
6498 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6499 SmallVector<int, 8> Indices;
6500 unsigned NumElts = RHS.getNumOperands();
6501 for (unsigned i = 0; i != NumElts; ++i) {
6502 SDValue Elt = RHS.getOperand(i);
6503 if (!isa<ConstantSDNode>(Elt))
6504 return SDValue();
6505 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6506 Indices.push_back(i);
6507 else if (cast<ConstantSDNode>(Elt)->isNullValue())
6508 Indices.push_back(NumElts);
6509 else
6510 return SDValue();
6513 // Let's see if the target supports this vector_shuffle.
6514 EVT RVT = RHS.getValueType();
6515 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6516 return SDValue();
6518 // Return the new VECTOR_SHUFFLE node.
6519 EVT EltVT = RVT.getVectorElementType();
6520 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6521 DAG.getConstant(0, EltVT));
6522 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6523 RVT, &ZeroOps[0], ZeroOps.size());
6524 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
6525 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6526 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
6530 return SDValue();
6533 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6534 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6535 // After legalize, the target may be depending on adds and other
6536 // binary ops to provide legal ways to construct constants or other
6537 // things. Simplifying them may result in a loss of legality.
6538 if (LegalOperations) return SDValue();
6540 EVT VT = N->getValueType(0);
6541 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
6543 EVT EltType = VT.getVectorElementType();
6544 SDValue LHS = N->getOperand(0);
6545 SDValue RHS = N->getOperand(1);
6546 SDValue Shuffle = XformToShuffleWithZero(N);
6547 if (Shuffle.getNode()) return Shuffle;
6549 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6550 // this operation.
6551 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6552 RHS.getOpcode() == ISD::BUILD_VECTOR) {
6553 SmallVector<SDValue, 8> Ops;
6554 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6555 SDValue LHSOp = LHS.getOperand(i);
6556 SDValue RHSOp = RHS.getOperand(i);
6557 // If these two elements can't be folded, bail out.
6558 if ((LHSOp.getOpcode() != ISD::UNDEF &&
6559 LHSOp.getOpcode() != ISD::Constant &&
6560 LHSOp.getOpcode() != ISD::ConstantFP) ||
6561 (RHSOp.getOpcode() != ISD::UNDEF &&
6562 RHSOp.getOpcode() != ISD::Constant &&
6563 RHSOp.getOpcode() != ISD::ConstantFP))
6564 break;
6566 // Can't fold divide by zero.
6567 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6568 N->getOpcode() == ISD::FDIV) {
6569 if ((RHSOp.getOpcode() == ISD::Constant &&
6570 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6571 (RHSOp.getOpcode() == ISD::ConstantFP &&
6572 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6573 break;
6576 // If the vector element type is not legal, the BUILD_VECTOR operands
6577 // are promoted and implicitly truncated. Make that explicit here.
6578 if (LHSOp.getValueType() != EltType)
6579 LHSOp = DAG.getNode(ISD::TRUNCATE, LHS.getDebugLoc(), EltType, LHSOp);
6580 if (RHSOp.getValueType() != EltType)
6581 RHSOp = DAG.getNode(ISD::TRUNCATE, RHS.getDebugLoc(), EltType, RHSOp);
6583 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), EltType,
6584 LHSOp, RHSOp);
6585 if (FoldOp.getOpcode() != ISD::UNDEF &&
6586 FoldOp.getOpcode() != ISD::Constant &&
6587 FoldOp.getOpcode() != ISD::ConstantFP)
6588 break;
6589 Ops.push_back(FoldOp);
6590 AddToWorkList(FoldOp.getNode());
6593 if (Ops.size() == LHS.getNumOperands()) {
6594 EVT VT = LHS.getValueType();
6595 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
6596 &Ops[0], Ops.size());
6600 return SDValue();
6603 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6604 SDValue N1, SDValue N2){
6605 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6607 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6608 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6610 // If we got a simplified select_cc node back from SimplifySelectCC, then
6611 // break it down into a new SETCC node, and a new SELECT node, and then return
6612 // the SELECT node, since we were called with a SELECT node.
6613 if (SCC.getNode()) {
6614 // Check to see if we got a select_cc back (to turn into setcc/select).
6615 // Otherwise, just return whatever node we got back, like fabs.
6616 if (SCC.getOpcode() == ISD::SELECT_CC) {
6617 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6618 N0.getValueType(),
6619 SCC.getOperand(0), SCC.getOperand(1),
6620 SCC.getOperand(4));
6621 AddToWorkList(SETCC.getNode());
6622 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6623 SCC.getOperand(2), SCC.getOperand(3), SETCC);
6626 return SCC;
6628 return SDValue();
6631 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6632 /// are the two values being selected between, see if we can simplify the
6633 /// select. Callers of this should assume that TheSelect is deleted if this
6634 /// returns true. As such, they should return the appropriate thing (e.g. the
6635 /// node) back to the top-level of the DAG combiner loop to avoid it being
6636 /// looked at.
6637 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6638 SDValue RHS) {
6640 // If this is a select from two identical things, try to pull the operation
6641 // through the select.
6642 if (LHS.getOpcode() != RHS.getOpcode() ||
6643 !LHS.hasOneUse() || !RHS.hasOneUse())
6644 return false;
6646 // If this is a load and the token chain is identical, replace the select
6647 // of two loads with a load through a select of the address to load from.
6648 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6649 // constants have been dropped into the constant pool.
6650 if (LHS.getOpcode() == ISD::LOAD) {
6651 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6652 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6654 // Token chains must be identical.
6655 if (LHS.getOperand(0) != RHS.getOperand(0) ||
6656 // Do not let this transformation reduce the number of volatile loads.
6657 LLD->isVolatile() || RLD->isVolatile() ||
6658 // If this is an EXTLOAD, the VT's must match.
6659 LLD->getMemoryVT() != RLD->getMemoryVT() ||
6660 // FIXME: this discards src value information. This is
6661 // over-conservative. It would be beneficial to be able to remember
6662 // both potential memory locations. Since we are discarding
6663 // src value info, don't do the transformation if the memory
6664 // locations are not in the default address space.
6665 LLD->getPointerInfo().getAddrSpace() != 0 ||
6666 RLD->getPointerInfo().getAddrSpace() != 0)
6667 return false;
6669 // Check that the select condition doesn't reach either load. If so,
6670 // folding this will induce a cycle into the DAG. If not, this is safe to
6671 // xform, so create a select of the addresses.
6672 SDValue Addr;
6673 if (TheSelect->getOpcode() == ISD::SELECT) {
6674 SDNode *CondNode = TheSelect->getOperand(0).getNode();
6675 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
6676 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
6677 return false;
6678 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6679 LLD->getBasePtr().getValueType(),
6680 TheSelect->getOperand(0), LLD->getBasePtr(),
6681 RLD->getBasePtr());
6682 } else { // Otherwise SELECT_CC
6683 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
6684 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
6686 if ((LLD->hasAnyUseOfValue(1) &&
6687 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
6688 (LLD->hasAnyUseOfValue(1) &&
6689 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
6690 return false;
6692 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6693 LLD->getBasePtr().getValueType(),
6694 TheSelect->getOperand(0),
6695 TheSelect->getOperand(1),
6696 LLD->getBasePtr(), RLD->getBasePtr(),
6697 TheSelect->getOperand(4));
6700 SDValue Load;
6701 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6702 Load = DAG.getLoad(TheSelect->getValueType(0),
6703 TheSelect->getDebugLoc(),
6704 // FIXME: Discards pointer info.
6705 LLD->getChain(), Addr, MachinePointerInfo(),
6706 LLD->isVolatile(), LLD->isNonTemporal(),
6707 LLD->getAlignment());
6708 } else {
6709 Load = DAG.getExtLoad(LLD->getExtensionType(),
6710 TheSelect->getValueType(0),
6711 TheSelect->getDebugLoc(),
6712 // FIXME: Discards pointer info.
6713 LLD->getChain(), Addr, MachinePointerInfo(),
6714 LLD->getMemoryVT(), LLD->isVolatile(),
6715 LLD->isNonTemporal(), LLD->getAlignment());
6718 // Users of the select now use the result of the load.
6719 CombineTo(TheSelect, Load);
6721 // Users of the old loads now use the new load's chain. We know the
6722 // old-load value is dead now.
6723 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6724 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6725 return true;
6728 return false;
6731 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6732 /// where 'cond' is the comparison specified by CC.
6733 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6734 SDValue N2, SDValue N3,
6735 ISD::CondCode CC, bool NotExtCompare) {
6736 // (x ? y : y) -> y.
6737 if (N2 == N3) return N2;
6739 EVT VT = N2.getValueType();
6740 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6741 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6742 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6744 // Determine if the condition we're dealing with is constant
6745 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6746 N0, N1, CC, DL, false);
6747 if (SCC.getNode()) AddToWorkList(SCC.getNode());
6748 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6750 // fold select_cc true, x, y -> x
6751 if (SCCC && !SCCC->isNullValue())
6752 return N2;
6753 // fold select_cc false, x, y -> y
6754 if (SCCC && SCCC->isNullValue())
6755 return N3;
6757 // Check to see if we can simplify the select into an fabs node
6758 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
6759 // Allow either -0.0 or 0.0
6760 if (CFP->getValueAPF().isZero()) {
6761 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
6762 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
6763 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
6764 N2 == N3.getOperand(0))
6765 return DAG.getNode(ISD::FABS, DL, VT, N0);
6767 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
6768 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
6769 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
6770 N2.getOperand(0) == N3)
6771 return DAG.getNode(ISD::FABS, DL, VT, N3);
6775 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
6776 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
6777 // in it. This is a win when the constant is not otherwise available because
6778 // it replaces two constant pool loads with one. We only do this if the FP
6779 // type is known to be legal, because if it isn't, then we are before legalize
6780 // types an we want the other legalization to happen first (e.g. to avoid
6781 // messing with soft float) and if the ConstantFP is not legal, because if
6782 // it is legal, we may not need to store the FP constant in a constant pool.
6783 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
6784 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
6785 if (TLI.isTypeLegal(N2.getValueType()) &&
6786 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
6787 TargetLowering::Legal) &&
6788 // If both constants have multiple uses, then we won't need to do an
6789 // extra load, they are likely around in registers for other users.
6790 (TV->hasOneUse() || FV->hasOneUse())) {
6791 Constant *Elts[] = {
6792 const_cast<ConstantFP*>(FV->getConstantFPValue()),
6793 const_cast<ConstantFP*>(TV->getConstantFPValue())
6795 const Type *FPTy = Elts[0]->getType();
6796 const TargetData &TD = *TLI.getTargetData();
6798 // Create a ConstantArray of the two constants.
6799 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
6800 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
6801 TD.getPrefTypeAlignment(FPTy));
6802 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6804 // Get the offsets to the 0 and 1 element of the array so that we can
6805 // select between them.
6806 SDValue Zero = DAG.getIntPtrConstant(0);
6807 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
6808 SDValue One = DAG.getIntPtrConstant(EltSize);
6810 SDValue Cond = DAG.getSetCC(DL,
6811 TLI.getSetCCResultType(N0.getValueType()),
6812 N0, N1, CC);
6813 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
6814 Cond, One, Zero);
6815 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
6816 CstOffset);
6817 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6818 MachinePointerInfo::getConstantPool(), false,
6819 false, Alignment);
6824 // Check to see if we can perform the "gzip trick", transforming
6825 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
6826 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
6827 N0.getValueType().isInteger() &&
6828 N2.getValueType().isInteger() &&
6829 (N1C->isNullValue() || // (a < 0) ? b : 0
6830 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
6831 EVT XType = N0.getValueType();
6832 EVT AType = N2.getValueType();
6833 if (XType.bitsGE(AType)) {
6834 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
6835 // single-bit constant.
6836 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
6837 unsigned ShCtV = N2C->getAPIntValue().logBase2();
6838 ShCtV = XType.getSizeInBits()-ShCtV-1;
6839 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
6840 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
6841 XType, N0, ShCt);
6842 AddToWorkList(Shift.getNode());
6844 if (XType.bitsGT(AType)) {
6845 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6846 AddToWorkList(Shift.getNode());
6849 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6852 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
6853 XType, N0,
6854 DAG.getConstant(XType.getSizeInBits()-1,
6855 getShiftAmountTy()));
6856 AddToWorkList(Shift.getNode());
6858 if (XType.bitsGT(AType)) {
6859 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6860 AddToWorkList(Shift.getNode());
6863 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6867 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
6868 // where y is has a single bit set.
6869 // A plaintext description would be, we can turn the SELECT_CC into an AND
6870 // when the condition can be materialized as an all-ones register. Any
6871 // single bit-test can be materialized as an all-ones register with
6872 // shift-left and shift-right-arith.
6873 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
6874 N0->getValueType(0) == VT &&
6875 N1C && N1C->isNullValue() &&
6876 N2C && N2C->isNullValue()) {
6877 SDValue AndLHS = N0->getOperand(0);
6878 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6879 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
6880 // Shift the tested bit over the sign bit.
6881 APInt AndMask = ConstAndRHS->getAPIntValue();
6882 SDValue ShlAmt =
6883 DAG.getConstant(AndMask.countLeadingZeros(), getShiftAmountTy());
6884 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
6886 // Now arithmetic right shift it all the way over, so the result is either
6887 // all-ones, or zero.
6888 SDValue ShrAmt =
6889 DAG.getConstant(AndMask.getBitWidth()-1, getShiftAmountTy());
6890 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
6892 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
6896 // fold select C, 16, 0 -> shl C, 4
6897 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
6898 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
6900 // If the caller doesn't want us to simplify this into a zext of a compare,
6901 // don't do it.
6902 if (NotExtCompare && N2C->getAPIntValue() == 1)
6903 return SDValue();
6905 // Get a SetCC of the condition
6906 // FIXME: Should probably make sure that setcc is legal if we ever have a
6907 // target where it isn't.
6908 SDValue Temp, SCC;
6909 // cast from setcc result type to select result type
6910 if (LegalTypes) {
6911 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
6912 N0, N1, CC);
6913 if (N2.getValueType().bitsLT(SCC.getValueType()))
6914 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
6915 else
6916 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6917 N2.getValueType(), SCC);
6918 } else {
6919 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
6920 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6921 N2.getValueType(), SCC);
6924 AddToWorkList(SCC.getNode());
6925 AddToWorkList(Temp.getNode());
6927 if (N2C->getAPIntValue() == 1)
6928 return Temp;
6930 // shl setcc result by log2 n2c
6931 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
6932 DAG.getConstant(N2C->getAPIntValue().logBase2(),
6933 getShiftAmountTy()));
6936 // Check to see if this is the equivalent of setcc
6937 // FIXME: Turn all of these into setcc if setcc if setcc is legal
6938 // otherwise, go ahead with the folds.
6939 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
6940 EVT XType = N0.getValueType();
6941 if (!LegalOperations ||
6942 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
6943 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
6944 if (Res.getValueType() != VT)
6945 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
6946 return Res;
6949 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
6950 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
6951 (!LegalOperations ||
6952 TLI.isOperationLegal(ISD::CTLZ, XType))) {
6953 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
6954 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
6955 DAG.getConstant(Log2_32(XType.getSizeInBits()),
6956 getShiftAmountTy()));
6958 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
6959 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
6960 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
6961 XType, DAG.getConstant(0, XType), N0);
6962 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
6963 return DAG.getNode(ISD::SRL, DL, XType,
6964 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
6965 DAG.getConstant(XType.getSizeInBits()-1,
6966 getShiftAmountTy()));
6968 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6969 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6970 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6971 DAG.getConstant(XType.getSizeInBits()-1,
6972 getShiftAmountTy()));
6973 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6977 // Check to see if this is an integer abs.
6978 // select_cc setg[te] X, 0, X, -X ->
6979 // select_cc setgt X, -1, X, -X ->
6980 // select_cc setl[te] X, 0, -X, X ->
6981 // select_cc setlt X, 1, -X, X ->
6982 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6983 if (N1C) {
6984 ConstantSDNode *SubC = NULL;
6985 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6986 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
6987 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
6988 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
6989 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
6990 (N1C->isOne() && CC == ISD::SETLT)) &&
6991 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
6992 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
6994 EVT XType = N0.getValueType();
6995 if (SubC && SubC->isNullValue() && XType.isInteger()) {
6996 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6998 DAG.getConstant(XType.getSizeInBits()-1,
6999 getShiftAmountTy()));
7000 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7001 XType, N0, Shift);
7002 AddToWorkList(Shift.getNode());
7003 AddToWorkList(Add.getNode());
7004 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7008 return SDValue();
7011 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7012 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7013 SDValue N1, ISD::CondCode Cond,
7014 DebugLoc DL, bool foldBooleans) {
7015 TargetLowering::DAGCombinerInfo
7016 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7017 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7020 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7021 /// return a DAG expression to select that will generate the same value by
7022 /// multiplying by a magic number. See:
7023 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7024 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7025 std::vector<SDNode*> Built;
7026 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
7028 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7029 ii != ee; ++ii)
7030 AddToWorkList(*ii);
7031 return S;
7034 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7035 /// return a DAG expression to select that will generate the same value by
7036 /// multiplying by a magic number. See:
7037 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7038 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7039 std::vector<SDNode*> Built;
7040 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
7042 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7043 ii != ee; ++ii)
7044 AddToWorkList(*ii);
7045 return S;
7048 /// FindBaseOffset - Return true if base is a frame index, which is known not
7049 // to alias with anything but itself. Provides base object and offset as results.
7050 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7051 const GlobalValue *&GV, void *&CV) {
7052 // Assume it is a primitive operation.
7053 Base = Ptr; Offset = 0; GV = 0; CV = 0;
7055 // If it's an adding a simple constant then integrate the offset.
7056 if (Base.getOpcode() == ISD::ADD) {
7057 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7058 Base = Base.getOperand(0);
7059 Offset += C->getZExtValue();
7063 // Return the underlying GlobalValue, and update the Offset. Return false
7064 // for GlobalAddressSDNode since the same GlobalAddress may be represented
7065 // by multiple nodes with different offsets.
7066 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7067 GV = G->getGlobal();
7068 Offset += G->getOffset();
7069 return false;
7072 // Return the underlying Constant value, and update the Offset. Return false
7073 // for ConstantSDNodes since the same constant pool entry may be represented
7074 // by multiple nodes with different offsets.
7075 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7076 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7077 : (void *)C->getConstVal();
7078 Offset += C->getOffset();
7079 return false;
7081 // If it's any of the following then it can't alias with anything but itself.
7082 return isa<FrameIndexSDNode>(Base);
7085 /// isAlias - Return true if there is any possibility that the two addresses
7086 /// overlap.
7087 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7088 const Value *SrcValue1, int SrcValueOffset1,
7089 unsigned SrcValueAlign1,
7090 const MDNode *TBAAInfo1,
7091 SDValue Ptr2, int64_t Size2,
7092 const Value *SrcValue2, int SrcValueOffset2,
7093 unsigned SrcValueAlign2,
7094 const MDNode *TBAAInfo2) const {
7095 // If they are the same then they must be aliases.
7096 if (Ptr1 == Ptr2) return true;
7098 // Gather base node and offset information.
7099 SDValue Base1, Base2;
7100 int64_t Offset1, Offset2;
7101 const GlobalValue *GV1, *GV2;
7102 void *CV1, *CV2;
7103 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7104 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7106 // If they have a same base address then check to see if they overlap.
7107 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7108 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7110 // It is possible for different frame indices to alias each other, mostly
7111 // when tail call optimization reuses return address slots for arguments.
7112 // To catch this case, look up the actual index of frame indices to compute
7113 // the real alias relationship.
7114 if (isFrameIndex1 && isFrameIndex2) {
7115 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7116 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7117 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7118 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7121 // Otherwise, if we know what the bases are, and they aren't identical, then
7122 // we know they cannot alias.
7123 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7124 return false;
7126 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7127 // compared to the size and offset of the access, we may be able to prove they
7128 // do not alias. This check is conservative for now to catch cases created by
7129 // splitting vector types.
7130 if ((SrcValueAlign1 == SrcValueAlign2) &&
7131 (SrcValueOffset1 != SrcValueOffset2) &&
7132 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
7133 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
7134 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
7136 // There is no overlap between these relatively aligned accesses of similar
7137 // size, return no alias.
7138 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
7139 return false;
7142 if (CombinerGlobalAA) {
7143 // Use alias analysis information.
7144 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
7145 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
7146 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
7147 AliasAnalysis::AliasResult AAResult =
7148 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
7149 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
7150 if (AAResult == AliasAnalysis::NoAlias)
7151 return false;
7154 // Otherwise we have to assume they alias.
7155 return true;
7158 /// FindAliasInfo - Extracts the relevant alias information from the memory
7159 /// node. Returns true if the operand was a load.
7160 bool DAGCombiner::FindAliasInfo(SDNode *N,
7161 SDValue &Ptr, int64_t &Size,
7162 const Value *&SrcValue,
7163 int &SrcValueOffset,
7164 unsigned &SrcValueAlign,
7165 const MDNode *&TBAAInfo) const {
7166 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7167 Ptr = LD->getBasePtr();
7168 Size = LD->getMemoryVT().getSizeInBits() >> 3;
7169 SrcValue = LD->getSrcValue();
7170 SrcValueOffset = LD->getSrcValueOffset();
7171 SrcValueAlign = LD->getOriginalAlignment();
7172 TBAAInfo = LD->getTBAAInfo();
7173 return true;
7174 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7175 Ptr = ST->getBasePtr();
7176 Size = ST->getMemoryVT().getSizeInBits() >> 3;
7177 SrcValue = ST->getSrcValue();
7178 SrcValueOffset = ST->getSrcValueOffset();
7179 SrcValueAlign = ST->getOriginalAlignment();
7180 TBAAInfo = ST->getTBAAInfo();
7181 } else {
7182 llvm_unreachable("FindAliasInfo expected a memory operand");
7185 return false;
7188 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
7189 /// looking for aliasing nodes and adding them to the Aliases vector.
7190 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
7191 SmallVector<SDValue, 8> &Aliases) {
7192 SmallVector<SDValue, 8> Chains; // List of chains to visit.
7193 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
7195 // Get alias information for node.
7196 SDValue Ptr;
7197 int64_t Size;
7198 const Value *SrcValue;
7199 int SrcValueOffset;
7200 unsigned SrcValueAlign;
7201 const MDNode *SrcTBAAInfo;
7202 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
7203 SrcValueAlign, SrcTBAAInfo);
7205 // Starting off.
7206 Chains.push_back(OriginalChain);
7207 unsigned Depth = 0;
7209 // Look at each chain and determine if it is an alias. If so, add it to the
7210 // aliases list. If not, then continue up the chain looking for the next
7211 // candidate.
7212 while (!Chains.empty()) {
7213 SDValue Chain = Chains.back();
7214 Chains.pop_back();
7216 // For TokenFactor nodes, look at each operand and only continue up the
7217 // chain until we find two aliases. If we've seen two aliases, assume we'll
7218 // find more and revert to original chain since the xform is unlikely to be
7219 // profitable.
7221 // FIXME: The depth check could be made to return the last non-aliasing
7222 // chain we found before we hit a tokenfactor rather than the original
7223 // chain.
7224 if (Depth > 6 || Aliases.size() == 2) {
7225 Aliases.clear();
7226 Aliases.push_back(OriginalChain);
7227 break;
7230 // Don't bother if we've been before.
7231 if (!Visited.insert(Chain.getNode()))
7232 continue;
7234 switch (Chain.getOpcode()) {
7235 case ISD::EntryToken:
7236 // Entry token is ideal chain operand, but handled in FindBetterChain.
7237 break;
7239 case ISD::LOAD:
7240 case ISD::STORE: {
7241 // Get alias information for Chain.
7242 SDValue OpPtr;
7243 int64_t OpSize;
7244 const Value *OpSrcValue;
7245 int OpSrcValueOffset;
7246 unsigned OpSrcValueAlign;
7247 const MDNode *OpSrcTBAAInfo;
7248 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
7249 OpSrcValue, OpSrcValueOffset,
7250 OpSrcValueAlign,
7251 OpSrcTBAAInfo);
7253 // If chain is alias then stop here.
7254 if (!(IsLoad && IsOpLoad) &&
7255 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
7256 SrcTBAAInfo,
7257 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
7258 OpSrcValueAlign, OpSrcTBAAInfo)) {
7259 Aliases.push_back(Chain);
7260 } else {
7261 // Look further up the chain.
7262 Chains.push_back(Chain.getOperand(0));
7263 ++Depth;
7265 break;
7268 case ISD::TokenFactor:
7269 // We have to check each of the operands of the token factor for "small"
7270 // token factors, so we queue them up. Adding the operands to the queue
7271 // (stack) in reverse order maintains the original order and increases the
7272 // likelihood that getNode will find a matching token factor (CSE.)
7273 if (Chain.getNumOperands() > 16) {
7274 Aliases.push_back(Chain);
7275 break;
7277 for (unsigned n = Chain.getNumOperands(); n;)
7278 Chains.push_back(Chain.getOperand(--n));
7279 ++Depth;
7280 break;
7282 default:
7283 // For all other instructions we will just have to take what we can get.
7284 Aliases.push_back(Chain);
7285 break;
7290 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
7291 /// for a better chain (aliasing node.)
7292 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7293 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
7295 // Accumulate all the aliases to this node.
7296 GatherAllAliases(N, OldChain, Aliases);
7298 if (Aliases.size() == 0) {
7299 // If no operands then chain to entry token.
7300 return DAG.getEntryNode();
7301 } else if (Aliases.size() == 1) {
7302 // If a single operand then chain to it. We don't need to revisit it.
7303 return Aliases[0];
7306 // Construct a custom tailored token factor.
7307 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7308 &Aliases[0], Aliases.size());
7311 // SelectionDAG::Combine - This is the entry point for the file.
7313 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7314 CodeGenOpt::Level OptLevel) {
7315 /// run - This is the main entry point to this class.
7317 DAGCombiner(*this, AA, OptLevel).Run(Level);