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