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